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
|
---|---|---|---|---|---|---|
114,211 | <p>Let's say I have a container (std::vector) of pointers used by a multi-threaded application. When adding new pointers to the container, the code is protected using a critical section (boost::mutex). All well and good. The code should be able to return one of these pointers to a thread for processing, but another separate thread could choose to delete one of these pointers, which might still be in use. e.g.:</p>
<pre><code>thread1()
{
foo* p = get_pointer();
...
p->do_something();
}
thread2()
{
foo* p = get_pointer();
...
delete p;
}
</code></pre>
<p>So thread2 could delete the pointer whilst thread1 is using it. Nasty.</p>
<p>So instead I want to use a container of Boost shared ptrs. IIRC these pointers will be reference counted, so as long as I return shared ptrs instead of raw pointers, removing one from the container WON'T actually free it until the last use of it goes out of scope. i.e.</p>
<pre><code>std::vector<boost::shared_ptr<foo> > my_vec;
thread1()
{
boost::shared_ptr<foo> sp = get_ptr[0];
...
sp->do_something();
}
thread2()
{
boost::shared_ptr<foo> sp = get_ptr[0];
...
my_vec.erase(my_vec.begin());
}
boost::shared_ptr<foo> get_ptr(int index)
{
lock_my_vec();
return my_vec[index];
}
</code></pre>
<p>In the above example, if thread1 gets the pointer before thread2 calls erase, will the object pointed to still be valid? It won't actually be deleted when thread1 completes? <strong>Note that access to the global vector will be via a critical section.</strong></p>
<p>I think this is how shared_ptrs work but I need to be sure.</p>
| [
{
"answer_id": 114221,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 3,
"selected": true,
"text": "<p>For the threading safety of boost::shared_ptr you should check <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety\" rel=\"nofollow noreferrer\">this link</a>. It's not guarantied to be safe, but on many platforms it works. Modifying the std::vector is not safe AFAIK.</p>\n"
},
{
"answer_id": 114361,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 0,
"selected": false,
"text": "<p>If in addition, you synchronize the accesses to the vector (as in your original raw pointer proposal), your usage is safe. Otherwise, you may fall foul of example 4 in the link provided by the other respondent. </p>\n"
},
{
"answer_id": 114496,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>In the above example, if thread1 gets the pointer before thread2 calls erase, will the object pointed to still be valid? It won't actually be deleted when thread1 completes?</p>\n</blockquote>\n\n<p>In your example, if thread1 gets the pointer before thread2, then thread2 will have to wait at the beginning of the function (because of the lock). So, yes, the object pointed to will still be valid. However, you might want to make sure that my_vec is not empty before accessing its first element.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
| Let's say I have a container (std::vector) of pointers used by a multi-threaded application. When adding new pointers to the container, the code is protected using a critical section (boost::mutex). All well and good. The code should be able to return one of these pointers to a thread for processing, but another separate thread could choose to delete one of these pointers, which might still be in use. e.g.:
```
thread1()
{
foo* p = get_pointer();
...
p->do_something();
}
thread2()
{
foo* p = get_pointer();
...
delete p;
}
```
So thread2 could delete the pointer whilst thread1 is using it. Nasty.
So instead I want to use a container of Boost shared ptrs. IIRC these pointers will be reference counted, so as long as I return shared ptrs instead of raw pointers, removing one from the container WON'T actually free it until the last use of it goes out of scope. i.e.
```
std::vector<boost::shared_ptr<foo> > my_vec;
thread1()
{
boost::shared_ptr<foo> sp = get_ptr[0];
...
sp->do_something();
}
thread2()
{
boost::shared_ptr<foo> sp = get_ptr[0];
...
my_vec.erase(my_vec.begin());
}
boost::shared_ptr<foo> get_ptr(int index)
{
lock_my_vec();
return my_vec[index];
}
```
In the above example, if thread1 gets the pointer before thread2 calls erase, will the object pointed to still be valid? It won't actually be deleted when thread1 completes? **Note that access to the global vector will be via a critical section.**
I think this is how shared\_ptrs work but I need to be sure. | For the threading safety of boost::shared\_ptr you should check [this link](http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety). It's not guarantied to be safe, but on many platforms it works. Modifying the std::vector is not safe AFAIK. |
114,214 | <p>What is the difference between the following class methods?</p>
<p>Is it that one is static and the other is not?</p>
<pre><code>class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
</code></pre>
| [
{
"answer_id": 114232,
"author": "Justin Poliey",
"author_id": 6967,
"author_profile": "https://Stackoverflow.com/users/6967",
"pm_score": 4,
"selected": false,
"text": "<p>When you call a class member, Python automatically uses a reference to the object as the first parameter. The variable <code>self</code> actually means nothing, it's just a coding convention. You could call it <code>gargaloo</code> if you wanted. That said, the call to <code>method_two</code> would raise a <code>TypeError</code>, because Python is automatically trying to pass a parameter (the reference to its parent object) to a method that was defined as having no parameters.</p>\n\n<p>To actually make it work, you could append this to your class definition:</p>\n\n<pre><code>method_two = staticmethod(method_two)\n</code></pre>\n\n<p>or you could use the <code>@staticmethod</code> <a href=\"https://docs.python.org/2/library/functions.html#staticmethod\" rel=\"noreferrer\">function decorator</a>.</p>\n"
},
{
"answer_id": 114250,
"author": "Jon Cage",
"author_id": 15369,
"author_profile": "https://Stackoverflow.com/users/15369",
"pm_score": 2,
"selected": false,
"text": "<p>method_two won't work because you're defining a member function but not telling it what the function is a member of. If you execute the last line you'll get:</p>\n\n<pre><code>>>> a_test.method_two()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: method_two() takes no arguments (1 given)\n</code></pre>\n\n<p>If you're defining member functions for a class the first argument must always be 'self'.</p>\n"
},
{
"answer_id": 114251,
"author": "MvdD",
"author_id": 18044,
"author_profile": "https://Stackoverflow.com/users/18044",
"pm_score": 1,
"selected": false,
"text": "<p>The call to method_two will throw an exception for not accepting the self parameter the Python runtime will automatically pass it.</p>\n\n<p>If you want to create a static method in a Python class, decorate it with the <code>staticmethod decorator</code>.</p>\n\n<pre><code>Class Test(Object):\n @staticmethod\n def method_two():\n print \"Called method_two\"\n\nTest.method_two()\n</code></pre>\n"
},
{
"answer_id": 114267,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 10,
"selected": true,
"text": "<p>In Python, there is a distinction between <em>bound</em> and <em>unbound</em> methods. </p>\n\n<p>Basically, a call to a member function (like <code>method_one</code>), a bound function</p>\n\n<pre><code>a_test.method_one()\n</code></pre>\n\n<p>is translated to</p>\n\n<pre><code>Test.method_one(a_test)\n</code></pre>\n\n<p>i.e. a call to an unbound method. Because of that, a call to your version of <code>method_two</code> will fail with a <code>TypeError</code></p>\n\n<pre><code>>>> a_test = Test() \n>>> a_test.method_two()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: method_two() takes no arguments (1 given) \n</code></pre>\n\n<p>You can change the behavior of a method using a decorator</p>\n\n<pre><code>class Test(object):\n def method_one(self):\n print \"Called method_one\"\n\n @staticmethod\n def method_two():\n print \"Called method two\"\n</code></pre>\n\n<p>The decorator tells the built-in default metaclass <code>type</code> (the class of a class, cf. <a href=\"https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python\">this question</a>) to not create bound methods for <code>method_two</code>.</p>\n\n<p>Now, you can invoke static method both on an instance or on the class directly:</p>\n\n<pre><code>>>> a_test = Test()\n>>> a_test.method_one()\nCalled method_one\n>>> a_test.method_two()\nCalled method_two\n>>> Test.method_two()\nCalled method_two\n</code></pre>\n"
},
{
"answer_id": 114281,
"author": "hayalci",
"author_id": 16084,
"author_profile": "https://Stackoverflow.com/users/16084",
"pm_score": 1,
"selected": false,
"text": "<p>that is an error.</p>\n\n<p>first of all, first line should be like this (be careful of capitals)</p>\n\n<pre><code>class Test(object):\n</code></pre>\n\n<p>Whenever you call a method of a class, it gets itself as the first argument (hence the name self) and method_two gives this error </p>\n\n<pre><code>>>> a.method_two()\nTraceback (most recent call last):\nFile \"<stdin>\", line 1, in <module>\nTypeError: method_two() takes no arguments (1 given)\n</code></pre>\n"
},
{
"answer_id": 114285,
"author": "Vasil",
"author_id": 7883,
"author_profile": "https://Stackoverflow.com/users/7883",
"pm_score": 1,
"selected": false,
"text": "<p>The second one won't work because when you call it like that python internally tries to call it with the a_test instance as the first argument, but your method_two doesn't accept any arguments, so it wont work, you'll get a runtime error.\nIf you want the equivalent of a static method you can use a class method.\nThere's much less need for class methods in Python than static methods in languages like Java or C#. Most often the best solution is to use a method in the module, outside a class definition, those work more efficiently than class methods.</p>\n"
},
{
"answer_id": 114289,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 8,
"selected": false,
"text": "<p>Methods in Python are a very, very simple thing once you understood the basics of the descriptor system. Imagine the following class:</p>\n\n<pre><code>class C(object):\n def foo(self):\n pass\n</code></pre>\n\n<p>Now let's have a look at that class in the shell:</p>\n\n<pre><code>>>> C.foo\n<unbound method C.foo>\n>>> C.__dict__['foo']\n<function foo at 0x17d05b0>\n</code></pre>\n\n<p>As you can see if you access the <code>foo</code> attribute on the class you get back an unbound method, however inside the class storage (the dict) there is a function. Why's that? The reason for this is that the class of your class implements a <code>__getattribute__</code> that resolves descriptors. Sounds complex, but is not. <code>C.foo</code> is roughly equivalent to this code in that special case:</p>\n\n<pre><code>>>> C.__dict__['foo'].__get__(None, C)\n<unbound method C.foo>\n</code></pre>\n\n<p>That's because functions have a <code>__get__</code> method which makes them descriptors. If you have an instance of a class it's nearly the same, just that <code>None</code> is the class instance:</p>\n\n<pre><code>>>> c = C()\n>>> C.__dict__['foo'].__get__(c, C)\n<bound method C.foo of <__main__.C object at 0x17bd4d0>>\n</code></pre>\n\n<p>Now why does Python do that? Because the method object binds the first parameter of a function to the instance of the class. That's where self comes from. Now sometimes you don't want your class to make a function a method, that's where <code>staticmethod</code> comes into play:</p>\n\n<pre><code> class C(object):\n @staticmethod\n def foo():\n pass\n</code></pre>\n\n<p>The <code>staticmethod</code> decorator wraps your class and implements a dummy <code>__get__</code> that returns the wrapped function as function and not as a method:</p>\n\n<pre><code>>>> C.__dict__['foo'].__get__(None, C)\n<function foo at 0x17d0c30>\n</code></pre>\n\n<p>Hope that explains it.</p>\n"
},
{
"answer_id": 2696019,
"author": "kzh",
"author_id": 143739,
"author_profile": "https://Stackoverflow.com/users/143739",
"pm_score": 4,
"selected": false,
"text": "<pre><code>>>> class Class(object):\n... def __init__(self):\n... self.i = 0\n... def instance_method(self):\n... self.i += 1\n... print self.i\n... c = 0\n... @classmethod\n... def class_method(cls):\n... cls.c += 1\n... print cls.c\n... @staticmethod\n... def static_method(s):\n... s += 1\n... print s\n... \n>>> a = Class()\n>>> a.class_method()\n1\n>>> Class.class_method() # The class shares this value across instances\n2\n>>> a.instance_method()\n1\n>>> Class.instance_method() # The class cannot use an instance method\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unbound method instance_method() must be called with Class instance as first argument (got nothing instead)\n>>> Class.instance_method(a)\n2\n>>> b = 0\n>>> a.static_method(b)\n1\n>>> a.static_method(a.c) # Static method does not have direct access to \n>>> # class or instance properties.\n3\n>>> Class.c # a.c above was passed by value and not by reference.\n2\n>>> a.c\n2\n>>> a.c = 5 # The connection between the instance\n>>> Class.c # and its class is weak as seen here.\n2\n>>> Class.class_method()\n3\n>>> a.c\n5\n</code></pre>\n"
},
{
"answer_id": 21213848,
"author": "James Sapam",
"author_id": 2062973,
"author_profile": "https://Stackoverflow.com/users/2062973",
"pm_score": 1,
"selected": false,
"text": "<p>Please read this docs from the Guido <a href=\"http://python-history.blogspot.in/2009/02/first-class-everything.html\" rel=\"nofollow\">First Class everything</a> Clearly explained how Unbound, Bound methods are born.</p>\n"
},
{
"answer_id": 39563369,
"author": "supi",
"author_id": 923372,
"author_profile": "https://Stackoverflow.com/users/923372",
"pm_score": 2,
"selected": false,
"text": "<p>Accurate explanation from Armin Ronacher above, expanding on his answers so that beginners like me understand it well:</p>\n\n<p>Difference in the methods defined in a class, whether static or instance method(there is yet another type - class method - not discussed here so skipping it), lay in the fact whether they are somehow bound to the class instance or not. For example, say whether the method receives a reference to the class instance during runtime</p>\n\n<pre><code>class C:\n a = [] \n def foo(self):\n pass\n\nC # this is the class object\nC.a # is a list object (class property object)\nC.foo # is a function object (class property object)\nc = C() \nc # this is the class instance\n</code></pre>\n\n<p>The <code>__dict__</code> dictionary property of the class object holds the reference to all the properties and methods of a class object and thus </p>\n\n<pre><code>>>> C.__dict__['foo']\n<function foo at 0x17d05b0>\n</code></pre>\n\n<p>the method foo is accessible as above. An important point to note here is that everything in python is an object and so references in the dictionary above are themselves pointing to other objects. Let me call them Class Property Objects - or as CPO within the scope of my answer for brevity.</p>\n\n<p>If a CPO is a descriptor, then python interpretor calls the <code>__get__()</code> method of the CPO to access the value it contains.</p>\n\n<p>In order to determine if a CPO is a descriptor, python interpretor checks if it implements the descriptor protocol. To implement descriptor protocol is to implement 3 methods</p>\n\n<pre><code>def __get__(self, instance, owner)\ndef __set__(self, instance, value)\ndef __delete__(self, instance)\n</code></pre>\n\n<p>for e.g. </p>\n\n<pre><code>>>> C.__dict__['foo'].__get__(c, C)\n</code></pre>\n\n<p>where </p>\n\n<ul>\n<li><code>self</code> is the CPO (it could be an instance of list, str, function etc) and is supplied by the runtime</li>\n<li><code>instance</code> is the instance of the class where this CPO is defined (the object 'c' above) and needs to be explicity supplied by us</li>\n<li><code>owner</code> is the class where this CPO is defined(the class object 'C' above) and needs to be supplied by us. However this is because we are calling it on the CPO. when we call it on the instance, we dont need to supply this since the runtime can supply the instance or its class(polymorphism)</li>\n<li><code>value</code> is the intended value for the CPO and needs to be supplied by us</li>\n</ul>\n\n<p>Not all CPO are descriptors. For example </p>\n\n<pre><code>>>> C.__dict__['foo'].__get__(None, C)\n<function C.foo at 0x10a72f510> \n>>> C.__dict__['a'].__get__(None, C)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'list' object has no attribute '__get__'\n</code></pre>\n\n<p>This is because the list class doesnt implement the descriptor protocol.</p>\n\n<p>Thus the argument self in <code>c.foo(self)</code> is required because its method signature is actually this <code>C.__dict__['foo'].__get__(c, C)</code> (as explained above, C is not needed as it can be found out or polymorphed)\nAnd this is also why you get a TypeError if you dont pass that required instance argument.</p>\n\n<p>If you notice the method is still referenced via the class Object C and the binding with the class instance is achieved via passing a context in the form of the instance object into this function. </p>\n\n<p>This is pretty awesome since if you chose to keep no context or no binding to the instance, all that was needed was to write a class to wrap the descriptor CPO and override its <code>__get__()</code> method to require no context. \nThis new class is what we call a decorator and is applied via the keyword <code>@staticmethod</code></p>\n\n<pre><code>class C(object):\n @staticmethod\n def foo():\n pass\n</code></pre>\n\n<p>The absence of context in the new wrapped CPO <code>foo</code> doesnt throw an error and can be verified as follows:</p>\n\n<pre><code>>>> C.__dict__['foo'].__get__(None, C)\n<function foo at 0x17d0c30>\n</code></pre>\n\n<p>Use case of a static method is more of a namespacing and code maintainability one(taking it out of a class and making it available throughout the module etc). </p>\n\n<p>It maybe better to write static methods rather than instance methods whenever possible, unless ofcourse you need to contexualise the methods(like access instance variables, class variables etc). One reason is to ease garbage collection by not keeping unwanted reference to objects.</p>\n"
},
{
"answer_id": 54260080,
"author": "Yossarian42",
"author_id": 9905745,
"author_profile": "https://Stackoverflow.com/users/9905745",
"pm_score": 0,
"selected": false,
"text": "<p>The definition of <code>method_two</code> is invalid. When you call <code>method_two</code>, you'll get <code>TypeError: method_two() takes 0 positional arguments but 1 was given</code> from the interpreter. </p>\n\n<p>An instance method is a bounded function when you call it like <code>a_test.method_two()</code>. It automatically accepts <code>self</code>, which points to an instance of <code>Test</code>, as its first parameter. Through the <code>self</code> parameter, an instance method can freely access attributes and modify them on the same object.</p>\n"
},
{
"answer_id": 60205635,
"author": "Öykü",
"author_id": 9616459,
"author_profile": "https://Stackoverflow.com/users/9616459",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Unbound Methods</strong></p>\n\n<p>Unbound methods are methods that are not bound to any particular class instance yet.</p>\n\n<p><strong>Bound Methods</strong></p>\n\n<p>Bound methods are the ones which are bound to a specific instance of a class. </p>\n\n<p>As its documented <a href=\"https://medium.com/@gumussoyku/bound-unbound-methods-in-python-cb4f124a6482\" rel=\"nofollow noreferrer\">here</a>, self can refer to different things depending on the function is bound, unbound or static. </p>\n\n<p>Take a look at the following example: </p>\n\n<pre><code>class MyClass: \n def some_method(self):\n return self # For the sake of the example\n\n>>> MyClass().some_method()\n<__main__.MyClass object at 0x10e8e43a0># This can also be written as:>>> obj = MyClass()\n\n>>> obj.some_method()\n<__main__.MyClass object at 0x10ea12bb0>\n\n# Bound method call:\n>>> obj.some_method(10)\nTypeError: some_method() takes 1 positional argument but 2 were given\n\n# WHY IT DIDN'T WORK?\n# obj.some_method(10) bound call translated as\n# MyClass.some_method(obj, 10) unbound method and it takes 2 \n# arguments now instead of 1 \n\n# ----- USING THE UNBOUND METHOD ------\n>>> MyClass.some_method(10)\n10\n</code></pre>\n\n<p>Since we did not use the class instance — <code>obj</code> — on the last call, we can kinda say it looks like a static method.</p>\n\n<p>If so, what is the difference between <code>MyClass.some_method(10)</code> call and a call to a static function decorated with a <code>@staticmethod</code> decorator?</p>\n\n<p>By using the decorator, we explicitly make it clear that the method will be used without creating an instance for it first. Normally one would not expect the class member methods to be used without the instance and accesing them can cause possible errors depending on the structure of the method.</p>\n\n<p>Also, by adding the <code>@staticmethod</code> decorator, we are making it possible to be reached through an object as well.</p>\n\n<pre><code>class MyClass: \n def some_method(self):\n return self \n\n @staticmethod\n def some_static_method(number):\n return number\n\n>>> MyClass.some_static_method(10) # without an instance\n10\n>>> MyClass().some_static_method(10) # Calling through an instance\n10\n</code></pre>\n\n<p>You can’t do the above example with the instance methods. You may survive the first one (as we did before) but the second one will be translated into an unbound call <code>MyClass.some_method(obj, 10)</code> which will raise a <code>TypeError</code> since the instance method takes one argument and you unintentionally tried to pass two.</p>\n\n<p>Then, you might say, “if I can call static methods through both an instance and a class, <code>MyClass.some_static_method</code> and <code>MyClass().some_static_method</code> should be the same methods.” Yes!</p>\n"
},
{
"answer_id": 61545304,
"author": "Python Newbie",
"author_id": 13448231,
"author_profile": "https://Stackoverflow.com/users/13448231",
"pm_score": 1,
"selected": false,
"text": "<p>Bound method = instance method</p>\n\n<p>Unbound method = static method.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16070/"
]
| What is the difference between the following class methods?
Is it that one is static and the other is not?
```
class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
``` | In Python, there is a distinction between *bound* and *unbound* methods.
Basically, a call to a member function (like `method_one`), a bound function
```
a_test.method_one()
```
is translated to
```
Test.method_one(a_test)
```
i.e. a call to an unbound method. Because of that, a call to your version of `method_two` will fail with a `TypeError`
```
>>> a_test = Test()
>>> a_test.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)
```
You can change the behavior of a method using a decorator
```
class Test(object):
def method_one(self):
print "Called method_one"
@staticmethod
def method_two():
print "Called method two"
```
The decorator tells the built-in default metaclass `type` (the class of a class, cf. [this question](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python)) to not create bound methods for `method_two`.
Now, you can invoke static method both on an instance or on the class directly:
```
>>> a_test = Test()
>>> a_test.method_one()
Called method_one
>>> a_test.method_two()
Called method_two
>>> Test.method_two()
Called method_two
``` |
114,222 | <p>With the introduction of .NET 3.5 and the <code>IQueryable<T></code> interface, new patterns will emerge. While I have seen a number of implementations of the Specification pattern, I have not seen many other patterns using this technology. Rob Conery's Storefront application is another concrete example using <code>IQueryable<T></code> which may lead to some new patterns.</p>
<p><strong>What patterns have emerged from the useful <code>IQueryable<T></code> interface?</strong></p>
| [
{
"answer_id": 114609,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 3,
"selected": false,
"text": "<p>It has certainly made the repository pattern much simpler to implement as well. You can essentially create a generic repository:</p>\n\n<pre><code>public class LinqToSqlRepository : IRepository\n{\n private readonly DataContext _context;\n\n public LinqToSqlRepository(DataContext context)\n {\n _context = context;\n }\n\n public IQueryable<T> Find<T>()\n {\n return _dataContext.GetTable<T>(); // linq 2 sql\n }\n\n /** snip: Insert, Update etc.. **/\n}\n</code></pre>\n\n<p>and then use it with linq:</p>\n\n<pre><code>var query = from customers in _repository.Find<Customer>() \n select customers;\n</code></pre>\n"
},
{
"answer_id": 645970,
"author": "BC.",
"author_id": 54838,
"author_profile": "https://Stackoverflow.com/users/54838",
"pm_score": 3,
"selected": false,
"text": "<p>I like the repository-filter pattern. It allows you to separate concerns from the middle and data end tier without sacrificing performance.</p>\n\n<p>Your data layer can concentrate on simple list-get-save style operations, while your middle tier can utilize extensions to IQueryable to provide more robust functionality:</p>\n\n<p>Repository (Data layer):</p>\n\n<pre><code>public class ThingRepository : IThingRepository\n{\n public IQueryable<Thing> GetThings()\n {\n return from m in context.Things\n select m; // Really simple!\n }\n}\n</code></pre>\n\n<p>Filter (Service layer):</p>\n\n<pre><code>public static class ServiceExtensions\n{\n public static IQueryable<Thing> ForUserID(this IQueryable<Thing> qry, int userID)\n {\n return from a in qry\n where a.UserID == userID\n select a;\n }\n}\n</code></pre>\n\n<p>Service:</p>\n\n<pre><code>public GetThingsForUserID(int userID)\n{\n return repository.GetThings().ForUserID(userID);\n}\n</code></pre>\n\n<p>This is a simple example, but filters can be safely combined to build more complicated queries. The performance is saved because the list isn't materialized until all the filters have been built into the query.</p>\n\n<p>I love it because I dislike application-specific repositories!</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
]
| With the introduction of .NET 3.5 and the `IQueryable<T>` interface, new patterns will emerge. While I have seen a number of implementations of the Specification pattern, I have not seen many other patterns using this technology. Rob Conery's Storefront application is another concrete example using `IQueryable<T>` which may lead to some new patterns.
**What patterns have emerged from the useful `IQueryable<T>` interface?** | It has certainly made the repository pattern much simpler to implement as well. You can essentially create a generic repository:
```
public class LinqToSqlRepository : IRepository
{
private readonly DataContext _context;
public LinqToSqlRepository(DataContext context)
{
_context = context;
}
public IQueryable<T> Find<T>()
{
return _dataContext.GetTable<T>(); // linq 2 sql
}
/** snip: Insert, Update etc.. **/
}
```
and then use it with linq:
```
var query = from customers in _repository.Find<Customer>()
select customers;
``` |
114,242 | <p>Previously I have asked to strip text from a field and convert it to an int, this works successfully. But now, I would like to do an INNER JOIN on this new value.</p>
<p>So I have this:</p>
<pre><code>SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999))
AS 'memId', userDetails.title, userDetails.lname
FROM accountingTab INNER JOIN
(SELECT id, title, first, last FROM memDetTab) AS userDetails ON memID = userDetails.id
</code></pre>
<p>And then I get the Invalid Column Name <code>memID</code> error.</p>
<p>How can I fix this?</p>
| [
{
"answer_id": 114253,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 2,
"selected": false,
"text": "<p>Instead of memId, repeat the whole expression.</p>\n"
},
{
"answer_id": 114265,
"author": "Remi Despres-Smyth",
"author_id": 8169,
"author_profile": "https://Stackoverflow.com/users/8169",
"pm_score": 1,
"selected": true,
"text": "<p>If you have to do this, you have design problems. If you're able, I would suggest you need to refactor your table or relationships.</p>\n"
},
{
"answer_id": 114280,
"author": "Chris Shaffer",
"author_id": 6744,
"author_profile": "https://Stackoverflow.com/users/6744",
"pm_score": 3,
"selected": false,
"text": "<p>You can either repeat the whole expression or reverse your join:</p>\n\n<pre><code>\nSELECT *\nFROM memDetTab\n JOIN (SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999)) AS 'memId', userDetails.title, userDetails.lname\nFROM accountingTab) subquery\n ON subquery.memID = memDetTab.ID\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841427/"
]
| Previously I have asked to strip text from a field and convert it to an int, this works successfully. But now, I would like to do an INNER JOIN on this new value.
So I have this:
```
SELECT CONVERT(int, SUBSTRING(accountingTab.id, PATINDEX('%[0-9]%', accountingTab.id), 999))
AS 'memId', userDetails.title, userDetails.lname
FROM accountingTab INNER JOIN
(SELECT id, title, first, last FROM memDetTab) AS userDetails ON memID = userDetails.id
```
And then I get the Invalid Column Name `memID` error.
How can I fix this? | If you have to do this, you have design problems. If you're able, I would suggest you need to refactor your table or relationships. |
114,266 | <p>I am getting the following error whenever I click on a postbacking control</p>
<pre><code>HttpException (0x80004005): Validation
of viewstate MAC failed. If this
application is hosted by a Web Farm
or cluster, ensure that configuration
specifies the same validationKey and
validation algorithm. AutoGenerate
cannot be used in a cluster.
</code></pre>
<p>I am not using a Web Farm or cluster server. I have even tried setting the page property <strong><em>EnableViewStateMac</em></strong> to false but it changes the error message stating</p>
<pre><code>The state information is invalid for
this page and might be corrupted.
</code></pre>
<p>What could possibly be wrong?</p>
| [
{
"answer_id": 114292,
"author": "user20259",
"author_id": 20259,
"author_profile": "https://Stackoverflow.com/users/20259",
"pm_score": 3,
"selected": true,
"text": "<p>There is an article about this here: <a href=\"http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx</a> .</p>\n\n<p>The basic problem is that Your page hasn't completed loading before You perform the postback.</p>\n\n<p>A few different solutions are in the article listed above: \n1. Set enableEventValidation to false and viewStateEncryptionMode to Never\n2. Mark the form as disabled and then enable it in script once the load is complete.\n3. override the Render Event of the page to place the hidden fields for Encrypted Viewstate and Event validation on the top of the form.</p>\n\n<p>But the main problem is that the page load slow, which should be fixed (if possible ASAP). It can also be good to apply solution 2 above as well as there will always be trigger happy users that will click faster that the page loads no matter how fast it loads :-).</p>\n\n<p>/Andreas</p>\n"
},
{
"answer_id": 114347,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 0,
"selected": false,
"text": "<p>I have encountered the same problem with a custom build ASP.NET control which was dynamically reloaded and rebuild on every POST / GET request. Thus the page sending the POST request was not the same as the one recieving the response.\nIf you use any custom or databound controls look closly how they behave on a POST back.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4021/"
]
| I am getting the following error whenever I click on a postbacking control
```
HttpException (0x80004005): Validation
of viewstate MAC failed. If this
application is hosted by a Web Farm
or cluster, ensure that configuration
specifies the same validationKey and
validation algorithm. AutoGenerate
cannot be used in a cluster.
```
I am not using a Web Farm or cluster server. I have even tried setting the page property ***EnableViewStateMac*** to false but it changes the error message stating
```
The state information is invalid for
this page and might be corrupted.
```
What could possibly be wrong? | There is an article about this here: <http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx> .
The basic problem is that Your page hasn't completed loading before You perform the postback.
A few different solutions are in the article listed above:
1. Set enableEventValidation to false and viewStateEncryptionMode to Never
2. Mark the form as disabled and then enable it in script once the load is complete.
3. override the Render Event of the page to place the hidden fields for Encrypted Viewstate and Event validation on the top of the form.
But the main problem is that the page load slow, which should be fixed (if possible ASAP). It can also be good to apply solution 2 above as well as there will always be trigger happy users that will click faster that the page loads no matter how fast it loads :-).
/Andreas |
114,284 | <p>First of all, this question regards MySQL 3.23.58, so be advised.</p>
<p>I have 2 tables with the following definition:</p>
<pre><code>Table A: id INT (primary), customer_id INT, offlineid INT
Table B: id INT (primary), name VARCHAR(255)
</code></pre>
<p>Now, table A contains in the range of 65k+ records, while table B contains ~40 records. In addition to the 2 primary key indexes, there is also an index on the <em>offlineid</em> field in table A. There are more fields in each table, but they are not relevant (as I see it, ask if necessary) for this query.</p>
<p>I was first presented with the following query (<em>query time: ~22 seconds</em>):</p>
<pre><code>SELECT b.name, COUNT(*) AS orders, COUNT(DISTINCT(a.kundeid)) AS leads
FROM katalogbestilling_katalog a, medie b
WHERE a.offlineid = b.id
GROUP BY b.name
</code></pre>
<p>Now, each id in medie is associated with a different name, meaning you could group by id as well as name. A bit of testing back and forth settled me on this (<em>query time: ~6 seconds</em>):</p>
<pre><code>SELECT a.name, COUNT(*) AS orders, COUNT(DISTINCT(b.kundeid)) AS leads
FROM medie a
INNER JOIN katalogbestilling_katalog b ON a.id = b.offline
GROUP BY b.offline;
</code></pre>
<p>Is there any way to crank it down to "instant" time (max 1 second at worst)? I added the index on offlineid, but besides that and the re-arrangement of the query, I am at a loss for what to do. The EXPLAIN query shows me the query is using fileshort (the original query also used temp tables). All suggestions are welcome!</p>
| [
{
"answer_id": 114345,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 1,
"selected": false,
"text": "<p>I'm going to guess that your main problem is that you are using such an old version of MySQL. Maybe MySQL 3 doesn't like the COUNT(DISTINCT()).</p>\n\n<p>Alternately, it might just be system performance. How much memory do you have?</p>\n\n<p>Still, MySQL 3 is really old. I would at least put together a test system to see if a newer version ran that query faster.</p>\n"
},
{
"answer_id": 114350,
"author": "tpk",
"author_id": 8437,
"author_profile": "https://Stackoverflow.com/users/8437",
"pm_score": 0,
"selected": false,
"text": "<p>How is kundeid defined? It would be helpful to see the full schema for both tables (as generated by MySQL, ie. with indexes) as well as the output of EXPLAIN with the queries above.</p>\n\n<p>The easiest way to debug this and find out what is your bottleneck would be to start removing fields, one by one, from the query and measure how long does it take to run (remember to run RESET QUERY CACHE before running each query). At some point you'll see a significant drop in the execution time and then you've identified your bottleneck. For example:</p>\n\n<pre><code>SELECT b.name, COUNT(*) AS orders, COUNT(DISTINCT(a.kundeid)) AS leads\nFROM katalogbestilling_katalog a, medie b\nWHERE a.offlineid = b.id\nGROUP BY b.name\n</code></pre>\n\n<p>may become</p>\n\n<pre><code>SELECT b.name, COUNT(DISTINCT(a.kundeid)) AS leads\nFROM katalogbestilling_katalog a, medie b\nWHERE a.offlineid = b.id\nGROUP BY b.name\n</code></pre>\n\n<p>to eliminate the possibility of \"orders\" being the bottleneck, or</p>\n\n<pre><code>SELECT b.name, COUNT(*) AS orders\nFROM katalogbestilling_katalog a, medie b\nWHERE a.offlineid = b.id\nGROUP BY b.name\n</code></pre>\n\n<p>to eliminate \"leads\" from the equasion. This will lead you in the right direction.</p>\n\n<p><strong><em>update</em></strong>: I'm not suggesting removing any of the data from the final query. Just remove them to reduce the number of variables while looking for the bottleneck. Given your comment, I understand</p>\n\n<pre><code>SELECT b.name\nFROM katalogbestilling_katalog a, medie b\nWHERE a.offlineid = b.id\nGROUP BY b.name\n</code></pre>\n\n<p>is still performing badly? This clearly means it's either the join that is not optimized or the group by (which you can test by removing the group by - either the JOIN will be still slow, in which case that's the problem you need to fix, or it won't - in which case it's obviously the GROUP BY). Can you post the output of</p>\n\n<pre><code>EXPLAIN SELECT b.name\nFROM katalogbestilling_katalog a, medie b\nWHERE a.offlineid = b.id\nGROUP BY b.name\n</code></pre>\n\n<p>as well as the table schemas (to make it easier to debug)?</p>\n\n<p><strong><em>update #2</em></strong></p>\n\n<p>there's also a possibility that all of your indeces are created correctly but you have you mysql installation misconfigured when it comes to max memory usage or something along those lines which forces it to use disk sortation.</p>\n"
},
{
"answer_id": 114423,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 0,
"selected": false,
"text": "<p>You may get a small increase in performance if you remove the inner join and replace it with a nested select statement also remove the count(*) and replace it with the PK.</p>\n\n<p><code>SELECT a.name, COUNT(*) AS orders, COUNT(DISTINCT(b.kundeid)) AS leads\nFROM medie aINNER JOIN katalogbestilling_katalog b ON a.id = b.offline \nGROUP BY b.offline;</code></p>\n\n<p>would be</p>\n\n<p><code>SELECT a.name, \n COUNT(a.id) AS orders, \n (SELECT COUNT(kundeid) FROM katalogbestilling_katalog b WHERE b.offline = a.id) AS Leads\nFROM medie a;</code></p>\n"
},
{
"answer_id": 114476,
"author": "Christian P.",
"author_id": 9479,
"author_profile": "https://Stackoverflow.com/users/9479",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately, mysql 3 doesn't support sub-queries. I suspect that the old version in general is what's causing the slow performance.</p>\n"
},
{
"answer_id": 114486,
"author": "TrevorD",
"author_id": 12492,
"author_profile": "https://Stackoverflow.com/users/12492",
"pm_score": 0,
"selected": false,
"text": "<p>Well if the query is run often enough to warrant the overhead, create an index on table A containing the fields used in the query. Then all the results can be read from an index and it wont have to scan the table.</p>\n\n<p>That said, all my experience is based on MSSQL, so might not work.</p>\n"
},
{
"answer_id": 114798,
"author": "Jonathan",
"author_id": 19272,
"author_profile": "https://Stackoverflow.com/users/19272",
"pm_score": 0,
"selected": false,
"text": "<p>Your second query is fine and 65k+40k rows is not very large :)</p>\n\n<p>Put an new index on katalogbestilling_katalog.offline column and it will run faster for you.</p>\n"
},
{
"answer_id": 115320,
"author": "tyshock",
"author_id": 16448,
"author_profile": "https://Stackoverflow.com/users/16448",
"pm_score": 1,
"selected": true,
"text": "<p>You could try making sure there are covering indexes defined on each table. A covering index is just an index where each column requested in the select or used in a join is included in the index. This way, the engine only has to read the index entry and doesn't have to also do the corresponding row lookup to get any requested columns not included in the index. I've used this technique with great success in Oracle and MS SqlServer.</p>\n\n<p>Looking at your query, you could try:</p>\n\n<p>one index for medie.id, medie.name<br>\none index for katalogbestilling_katalog.offlineid, katalogbestilling_katalog.kundeid</p>\n\n<p>The columns should be defined in these orders for the index. That makes a difference whether the index can be used or not.</p>\n\n<p>More info here:</p>\n\n<p><a href=\"http://peter-zaitsev.livejournal.com/6949.html\" rel=\"nofollow noreferrer\">Covering Index Info</a> </p>\n"
},
{
"answer_id": 115409,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 0,
"selected": false,
"text": "<p>Try adding an index to (offlineid, kundeid)</p>\n\n<p>I added 180,000 BS rows to katalog and 30,000 BS rows to medie (with katalog offlineid's corresponding to medie id's and with a few overlapping kundeid's to make sure the disinct counts work). Mind you this is on mysql 5, so if you don't have similar results, mysql 3 may be your culprit, but from what I recall mysql 3 should be able to handle this just fine.</p>\n\n<p>My tables:</p>\n\n<pre><code>CREATE TABLE `katalogbestilling_katalog` (\n `id` int(11) NOT NULL auto_increment,\n `offlineid` int(11) NOT NULL,\n `kundeid` int(11) NOT NULL,\n PRIMARY KEY (`id`),\n KEY `offline_id` (`offlineid`,`kundeid`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=60001 ;\n\nCREATE TABLE `medie` (\n `id` int(11) NOT NULL auto_increment,\n `name` varchar(255) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=30001 ;\n</code></pre>\n\n<p>My query:</p>\n\n<pre><code>SELECT b.name, COUNT(*) AS orders, COUNT(DISTINCT(a.kundeid)) AS leads\nFROM medie b\nINNER JOIN katalogbestilling_katalog a ON b.id = a.offlineid\nGROUP BY a.offlineid\nLIMIT 0 , 30\n\n\n\"Showing rows 0 - 29 (30,000 total, Query took 0.0018 sec)\"\n</code></pre>\n\n<p>And the explain:</p>\n\n<pre><code>id: 1\nselect_type: SIMPLE\ntable: a\ntype: index\npossible_keys: NULL\nkey: offline_id\nkey_len: 8\nref: NULL\nrows: 180000\nExtra: Using index\n\nid: 1\nselect_type: SIMPLE\ntable: b\ntype: eq_ref\npossible_keys: PRIMARY\nkey: PRIMARY\nkey_len: 4\nref: test.a.offlineid\nrows: 1\nExtra:\n</code></pre>\n"
},
{
"answer_id": 116068,
"author": "Shinhan",
"author_id": 18219,
"author_profile": "https://Stackoverflow.com/users/18219",
"pm_score": 0,
"selected": false,
"text": "<p>Try optimizing the server itself. See <a href=\"http://www.mysqlperformanceblog.com/2006/09/29/what-to-tune-in-mysql-server-after-installation/\" rel=\"nofollow noreferrer\" title=\"What to tune in MySQL Server after installation\">this post by Peter Zaitsev</a> for the most important variables. Some are InnoDB specific, while others are for MyISAM. You didnt mention which engine you were using which might be relevant in this case (count(*) is much faster in MyISAM than in InnoDB for example).\n<a href=\"http://www.mysqlperformanceblog.com/2006/06/08/mysql-server-variables-sql-layer-or-storage-engine-specific/\" rel=\"nofollow noreferrer\" title=\"MySQL Server Variables - SQL layer or Storage Engine specific.\">Here is another post from same blog</a>, and an article from <a href=\"http://forge.mysql.com/wiki/ServerVariables\" rel=\"nofollow noreferrer\" title=\"Server Variables\">MySQL Forge</a></p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9479/"
]
| First of all, this question regards MySQL 3.23.58, so be advised.
I have 2 tables with the following definition:
```
Table A: id INT (primary), customer_id INT, offlineid INT
Table B: id INT (primary), name VARCHAR(255)
```
Now, table A contains in the range of 65k+ records, while table B contains ~40 records. In addition to the 2 primary key indexes, there is also an index on the *offlineid* field in table A. There are more fields in each table, but they are not relevant (as I see it, ask if necessary) for this query.
I was first presented with the following query (*query time: ~22 seconds*):
```
SELECT b.name, COUNT(*) AS orders, COUNT(DISTINCT(a.kundeid)) AS leads
FROM katalogbestilling_katalog a, medie b
WHERE a.offlineid = b.id
GROUP BY b.name
```
Now, each id in medie is associated with a different name, meaning you could group by id as well as name. A bit of testing back and forth settled me on this (*query time: ~6 seconds*):
```
SELECT a.name, COUNT(*) AS orders, COUNT(DISTINCT(b.kundeid)) AS leads
FROM medie a
INNER JOIN katalogbestilling_katalog b ON a.id = b.offline
GROUP BY b.offline;
```
Is there any way to crank it down to "instant" time (max 1 second at worst)? I added the index on offlineid, but besides that and the re-arrangement of the query, I am at a loss for what to do. The EXPLAIN query shows me the query is using fileshort (the original query also used temp tables). All suggestions are welcome! | You could try making sure there are covering indexes defined on each table. A covering index is just an index where each column requested in the select or used in a join is included in the index. This way, the engine only has to read the index entry and doesn't have to also do the corresponding row lookup to get any requested columns not included in the index. I've used this technique with great success in Oracle and MS SqlServer.
Looking at your query, you could try:
one index for medie.id, medie.name
one index for katalogbestilling\_katalog.offlineid, katalogbestilling\_katalog.kundeid
The columns should be defined in these orders for the index. That makes a difference whether the index can be used or not.
More info here:
[Covering Index Info](http://peter-zaitsev.livejournal.com/6949.html) |
114,302 | <p>I'm looking for a list of win32 API in some "database"/XML format. </p>
<p>I'd need it to easily create a "conversion layer" between win32 API and the higher level language I'm using (harbour/xharbour). Since this runs Pcode, it is necessary to transform parameters to C standard...</p>
<p>Instead of doing manual code write, I'd like to automate the process...</p>
<p>just for example, the windows API definition (taken from MSDN)</p>
<pre><code>DWORD WINAPI GetSysColor(
__in int nIndex
);
</code></pre>
<p>should be transformed in</p>
<pre><code>HB_FUNC( GETSYSCOLOR )
{
hb_retnl( (LONG) GetSysColor( hb_parni( 1 ) ) );
}
</code></pre>
| [
{
"answer_id": 114307,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 0,
"selected": false,
"text": "<p>About the closest thing I know of would be: <a href=\"http://pinvoke.net/\" rel=\"nofollow noreferrer\">http://pinvoke.net/</a>\nMaybe they would share their data with you?\nThey have a VS tool that accesses this data, so it may be a webservice. You might even be able to sniff that out.</p>\n"
},
{
"answer_id": 114370,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 1,
"selected": false,
"text": "<p>AFAIK, pinvoke.net only stores text data with the PInvoke definition for the call. Not very useful if what you want is something to use as a pre-parsed database of APIs.</p>\n\n<p>Probably you could create an small parser that will take the include file and translate it to what you need. In that case, I'd recommend using <a href=\"http://www.cs.virginia.edu/~lcc-win32/\" rel=\"nofollow noreferrer\">lcc-win32</a>'s include files, as they are pretty much fat-free/no-BS version of the SDK headers (they don't come with a bunch of special reserved words you'd have to ignore, etc.)</p>\n"
},
{
"answer_id": 114455,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>Of course, you have Microsoft Platform SDK, but it is in raw .h C code, so hard to parse!</p>\n\n<p>Similar work have been done by VB users (and Delphi users and probably for some other languages), for example <a href=\"http://www.activevb.de/rubriken/apiviewer/index-apiviewereng.html\" rel=\"nofollow noreferrer\" title=\"ActiveVB - ApiViewer (en)\">ApiViewer</a> has such database, but in some proprietary binary format (.apv extension), so you might have to reverse-engineer it.<br>\nSimilarly, there is an API-Guide, which was hosted at Allapi.net but the later seems to be a parking site now. It used .api files (again binary-proprietary).</p>\n"
},
{
"answer_id": 41434051,
"author": "akavel",
"author_id": 98528,
"author_profile": "https://Stackoverflow.com/users/98528",
"pm_score": 0,
"selected": false,
"text": "<p>There seems to be some database (and an app for using it, named \"<a href=\"https://github.com/jaredpar/pinvoke\" rel=\"nofollow noreferrer\">PInvoke Interop Assistant</a>\") at:</p>\n\n<p><a href=\"https://github.com/jaredpar/pinvoke/tree/master/StorageGenerator/Data\" rel=\"nofollow noreferrer\">https://github.com/jaredpar/pinvoke/tree/master/StorageGenerator/Data</a> </p>\n\n<p>although I'm not sure what's the license for now — thus <a href=\"https://github.com/jaredpar/pinvoke/issues/19\" rel=\"nofollow noreferrer\">I've asked the authors</a>.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm looking for a list of win32 API in some "database"/XML format.
I'd need it to easily create a "conversion layer" between win32 API and the higher level language I'm using (harbour/xharbour). Since this runs Pcode, it is necessary to transform parameters to C standard...
Instead of doing manual code write, I'd like to automate the process...
just for example, the windows API definition (taken from MSDN)
```
DWORD WINAPI GetSysColor(
__in int nIndex
);
```
should be transformed in
```
HB_FUNC( GETSYSCOLOR )
{
hb_retnl( (LONG) GetSysColor( hb_parni( 1 ) ) );
}
``` | AFAIK, pinvoke.net only stores text data with the PInvoke definition for the call. Not very useful if what you want is something to use as a pre-parsed database of APIs.
Probably you could create an small parser that will take the include file and translate it to what you need. In that case, I'd recommend using [lcc-win32](http://www.cs.virginia.edu/~lcc-win32/)'s include files, as they are pretty much fat-free/no-BS version of the SDK headers (they don't come with a bunch of special reserved words you'd have to ignore, etc.) |
114,339 | <p>If I want to manipulate an HTML tag's properties on the server within an aspx page based on a master page i.e. </p>
<pre><code><a href="#" runat="server" ID="myLink">My Link</a>
</code></pre>
<p>For example to give the link a different class depending on the current page i.e.</p>
<pre><code>if (Path.GetFileName(Request.PhysicalPath) == "MyPage")
{
myLink.Attributes.Add("class","active");
}
</code></pre>
<p>.NET changes the ID property of the link to something like</p>
<pre><code><a href="#" ID="ct100-foo-myLink">My Link</a>
</code></pre>
<p>Is there any way of stopping this from happening and keeping the original ID?</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 114357,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think so. </p>\n\n<p>However, you probably want to keep the original name so that you can manipulate the control with javascript.... if that's the case, you should look into ClientID; it will return the assigned ID at runtime.</p>\n\n<p><strong>EDIT:</strong> </p>\n\n<p>It looks like there is a way to do it, but with some work... take a look at <a href=\"http://weblogs.asp.net/nunogomes/archive/2008/06/04/asp-net-controls-improving-automatic-id-generation-architectural-changes-part-3.aspx\" rel=\"nofollow noreferrer\">ASP.NET Controls - Improving automatic ID generation : Architectural Changes ( Part 3)</a></p>\n\n<p>I didn't read the full post, but it looks like he created his own container and own naming provider. I think that if you wanted to leave your control's name untouched, you would just return the name back in </p>\n\n<pre><code>public abstract string SetControlID(string name, System.Web.UI.Control control);\n</code></pre>\n"
},
{
"answer_id": 114363,
"author": "Rahul",
"author_id": 16308,
"author_profile": "https://Stackoverflow.com/users/16308",
"pm_score": 0,
"selected": false,
"text": "<p>I never figured out how to prevent .NET from doing this, but what I did start doing was placing asp:Literals and using c# to add a WebControl to them. If you write a WebControl you can set various properties without it getting .NET's unique ID.\nFor instance:</p>\n\n<pre><code><asp:Literal ID=\"myLink\" />\n</code></pre>\n\n<p>...</p>\n\n<pre><code>WebControl a = new WebControl(HtmlTextWriterTag.A);\na.CssClass = \"active\";\na.Attributes[\"href\"] = \"#\";\nLiteral text = new Literal();\ntext.Text = \"click here\";\na.Controls.Add(text);\nmyLink.Controls.Add(a);\n</code></pre>\n\n<p>Which will result in the following html:</p>\n\n<pre><code><a href=\"#\" class=\"active\">click here</a>\n</code></pre>\n\n<p>Overall, a pretty dirty solution, but I didn't know what else to do at the time and I had a deadline to meet. ;)</p>\n"
},
{
"answer_id": 114367,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 3,
"selected": true,
"text": "<p>AFAIK there is no way.</p>\n\n<p>It shows the actual control tree, which is in this case masterpage-content-control.</p>\n\n<p>However if you add an ID to the masterpage (this.ID = \"whatever\") then you will see \"whatever\" instead of ctl00 (which means control index 0).</p>\n"
},
{
"answer_id": 114371,
"author": "Nick Allen",
"author_id": 12918,
"author_profile": "https://Stackoverflow.com/users/12918",
"pm_score": 0,
"selected": false,
"text": "<p>Yep exactly, we will need to persist the original ID for JavaScript and CSS reasons. I noticed the ClientId property but it's read only and can't be assigned, so i'm not sure how I would use it?</p>\n"
},
{
"answer_id": 114375,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 0,
"selected": false,
"text": "<p>This <strong>blog post</strong> could be helpful:\n<a href=\"http://gathadams.com/2008/08/18/remove-name-mangling-from-aspnet-master-pages-get-your-id-back/\" rel=\"nofollow noreferrer\">Remove Name Mangling from ASP.Net Master Pages (get your ID back!)</a></p>\n\n<p>The solution in the post overwrites the <code>.getElementById</code> method, allowing you to search for the element just using the normal ID. Maybe you can adapt it to your needings.</p>\n\n<p><strong>Disclaimer:</strong> That ASP.NET behaviour is by design and it is good that way, even for HTML Server Controls like the control in your example. Server-ID and Client-ID are two very different things, which should not be mixed. Using Master Pages or User Controls you could end with identical Client-IDs if there wasn't that mechanism.</p>\n"
},
{
"answer_id": 114381,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 2,
"selected": false,
"text": "<p>It's not possible directly. You could make a new control that inherits the link and override its ClientID to return directly the ID. But this seems to be overkill. You can simply use HTML markup and use <%# GetClass() %> to add the class when you need it.</p>\n\n<p>Regarding the usage of ClientID for Javascript:</p>\n\n<pre><code><a ID=\"myLink\" runat=\"server\">....\n\n\nvar ctrl = document.getElementById('<%# myLink.ClientID %>');\n</code></pre>\n\n<p>Of course you need a DataBind somewhere in the code.</p>\n"
},
{
"answer_id": 125690,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just use a standard a tag, and use render blocks to modify it, and then you have its behavior locked in on client.</p>\n"
},
{
"answer_id": 219730,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 1,
"selected": false,
"text": "<p>I just discovered an easy way to do it if you are using jQuery.</p>\n\n<pre><code>var mangled_name = $(\"[id$=original_name]\").attr(\"id\");\n</code></pre>\n\n<p>So if you have a server control like this:</p>\n\n<pre><code><asp:TextBox ID=\"txtStartDate\" runat=\"server\" />\n</code></pre>\n\n<p>You can get the mangled name in your jQuery/Javascript with:</p>\n\n<pre><code>var start_date_id = $(\"[id$=txtStartDate]\").attr(\"id\");\n</code></pre>\n\n<p>Since it is a string, you can also use it \"inline\" instead of assigning it, e.g. concatenating it with other elements for selectors.</p>\n"
},
{
"answer_id": 6579985,
"author": "Lisetsky Val",
"author_id": 694502,
"author_profile": "https://Stackoverflow.com/users/694502",
"pm_score": 0,
"selected": false,
"text": "<p>ASP.NET 4 has property <em>ClientIDMode</em> that controls ClientID rendering.</p>\n\n<p>Also, there is a <a href=\"http://clientidless.codeplex.com/\" rel=\"nofollow\">trick how to disable ClientID rendering for any non-postback control</a> (ASP.NET 2.0+).</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12918/"
]
| If I want to manipulate an HTML tag's properties on the server within an aspx page based on a master page i.e.
```
<a href="#" runat="server" ID="myLink">My Link</a>
```
For example to give the link a different class depending on the current page i.e.
```
if (Path.GetFileName(Request.PhysicalPath) == "MyPage")
{
myLink.Attributes.Add("class","active");
}
```
.NET changes the ID property of the link to something like
```
<a href="#" ID="ct100-foo-myLink">My Link</a>
```
Is there any way of stopping this from happening and keeping the original ID?
Thanks in advance | AFAIK there is no way.
It shows the actual control tree, which is in this case masterpage-content-control.
However if you add an ID to the masterpage (this.ID = "whatever") then you will see "whatever" instead of ctl00 (which means control index 0). |
114,419 | <p>The following two C# code snippets produce different results (assuming the variable level is used both before and after the recursive call). Why?</p>
<pre><code>public DoStuff(int level)
{
// ...
DoStuff(level++);
// ...
}
</code></pre>
<p>,</p>
<pre><code>public DoStuff(int level)
{
// ...
DoStuff(level+1);
// ...
}
</code></pre>
<p>After reading some of the responses below I thought it would be worthwhile posting the stack traces for level++, ++level and level+1 to highlight how deceiving this problem is.</p>
<p>I've simplified them for this post. The recursive call sequence starts with DoStuff(1). </p>
<p>// level++</p>
<pre><code>DoStuff(int level = 1)
DoStuff(int level = 2)
DoStuff(int level = 2)
DoStuff(int level = 2)
</code></pre>
<p>// ++level</p>
<pre><code>DoStuff(int level = 4)
DoStuff(int level = 4)
DoStuff(int level = 3)
DoStuff(int level = 2)
</code></pre>
<p>// level+1</p>
<pre><code>DoStuff(int level = 4)
DoStuff(int level = 3)
DoStuff(int level = 2)
DoStuff(int level = 1)
</code></pre>
| [
{
"answer_id": 114427,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 5,
"selected": false,
"text": "<p><strong>level++</strong> will pass <strong>level</strong> into <strong>DoStuff</strong> and then increment <strong>level</strong> for use in the rest of the function. This could be a fairly nasty bug as the recursion will never end (from what is shown <strong>DoStuff</strong> is always being passed the same value). Perhaps <strong>++level</strong> is meant instead, as this is the opposite of <strong>level++</strong> (increments level and passes the incremented value into <strong>DoStuff</strong>)?</p>\n\n<p><strong>level+1</strong> will pass <strong>level+1</strong> into <strong>DoStuff</strong> and leave <strong>level</strong> unchanged for the rest of the function.</p>\n"
},
{
"answer_id": 114435,
"author": "Henry B",
"author_id": 6414,
"author_profile": "https://Stackoverflow.com/users/6414",
"pm_score": 2,
"selected": false,
"text": "<p>The first is using the value in level and THEN incrmenting it.</p>\n\n<p>The latter is using level+1 as a passed variable.</p>\n"
},
{
"answer_id": 114436,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 0,
"selected": false,
"text": "<p>The first code snippet uses the post-operation increment operator, so the call is made as DoStuff(level);. If you want to use an increment operator here, use DoStuff(++level);.</p>\n"
},
{
"answer_id": 114441,
"author": "Markus Schnell",
"author_id": 20668,
"author_profile": "https://Stackoverflow.com/users/20668",
"pm_score": 1,
"selected": false,
"text": "<p><code>level++</code> returns the current value of <code>level</code>, then increments <code>level</code>.\n<code>level+1</code> doesn't change <code>level</code> at all, but <code>DoStuff</code> is called with the value of <code>(level + 1)</code>.</p>\n"
},
{
"answer_id": 114446,
"author": "Frederik Slijkerman",
"author_id": 12416,
"author_profile": "https://Stackoverflow.com/users/12416",
"pm_score": 5,
"selected": false,
"text": "<p>Because the first example is really equivalent to:</p>\n\n<pre><code>public DoStuff(int level)\n{ \n // ...\n int temp = level;\n level = level + 1;\n DoStuff(temp);\n // ...\n}\n</code></pre>\n\n<p>Note that you can also write ++level; that would be equivalent to:</p>\n\n<pre><code>public DoStuff(int level)\n{ \n // ...\n level = level + 1;\n DoStuff(level);\n // ...\n}\n</code></pre>\n\n<p>It's best not to overuse the ++ and -- operators in my opinion; it quickly gets confusing and/or undefined what's really happening, and modern C++ compilers don't generate more efficient code with these operators anyway.</p>\n"
},
{
"answer_id": 114452,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 0,
"selected": false,
"text": "<p>level+1 sends whatever level+1 is to the function.\nlevel++ sends level to the function and then increments it. </p>\n\n<p>You could do ++level and that would likely give you the results you want.</p>\n"
},
{
"answer_id": 114453,
"author": "paul",
"author_id": 11249,
"author_profile": "https://Stackoverflow.com/users/11249",
"pm_score": 0,
"selected": false,
"text": "<p>The first example uses the value of 'index', increments the value and <strong>updates</strong> 'index'.</p>\n\n<p>The second example uses the value of 'index' plus 1 but does not change the content of 'index'.</p>\n\n<p>So, depending on what you are wanting to do here, there could be some surprises in store!</p>\n"
},
{
"answer_id": 114458,
"author": "rep_movsd",
"author_id": 20392,
"author_profile": "https://Stackoverflow.com/users/20392",
"pm_score": -1,
"selected": false,
"text": "<p>As far as my experience goes, the parameter expression is evaluated first, and gets a value of level. \nThe variable itself is incremented before the function is called, because the compiler doesnt care whether you are using the expression as a parameter or otherwise... All it knows is that it should increment the value and get the old value as the result of the expression.</p>\n\n<p>However in my opinion, code like this is really sloppy, since by trying to be clever, it makes you have to think twice about what is really happening.</p>\n"
},
{
"answer_id": 114468,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 4,
"selected": false,
"text": "<p>the return value of <code>level++</code> will be <code>level</code> and <code>therefore</code> pass <code>level</code> into <code>DoStuff</code>. This could be a fairly nasty bug as the recursion will never end (from what is shown <code>DoStuff</code> is always being passed with the same value). Perhaps <code>++level</code> or <code>level + 1</code> is meant instead?</p>\n\n<p><code>level + 1</code> will pass <code>level + 1</code> into <code>DoStuff</code> and leave <code>level</code> unchanged for the rest of the function.</p>\n\n<hr>\n\n<p>The post-increment operator (variable++) is precisely equivalent to the function</p>\n\n<pre><code>int post_increment(ref int value)\n{\n int temp = value;\n value = value + 1\n return temp;\n}\n</code></pre>\n\n<p>while the pre-increment operator (++variable) is precisely equivalent to the function</p>\n\n<pre><code>int pre_increment(ref int value)\n{\n value = value + 1;\n return value;\n}\n</code></pre>\n\n<hr>\n\n<p>Therefore, if you expand the operator inline into the code, the operators are equivalent to:</p>\n\n<pre><code>DoStuff(a + 1)\n\nint temp = a + 1;\nDoStuff(temp);\n</code></pre>\n\n<hr>\n\n<pre><code>DoStuff(++a)\n\na = a + 1;\nDoStuff(a);\n</code></pre>\n\n<hr>\n\n<pre><code>DoStuff(a++);\n\nint temp = a;\na = a + 1;\nDoStuff(temp);\n</code></pre>\n\n<hr>\n\n<p>It is important to note that post-increment is <strong>not</strong> equivalent to:</p>\n\n<pre><code>DoStuff(a);\na = a + 1;\n</code></pre>\n\n<hr>\n\n<p>Additionally, as a point of style, one shouldn't increment a value unless the intention is to use the incremented value (a specific version of the rule, \"don't assign a value to a variable unless you plan on using that value\"). If the value <code>i + 1</code> is never used again, then the preferred usage should be <code>DoStuff(i + 1)</code> and not <code>DoStuff(++i)</code>.</p>\n"
},
{
"answer_id": 114471,
"author": "Matt",
"author_id": 17759,
"author_profile": "https://Stackoverflow.com/users/17759",
"pm_score": 5,
"selected": false,
"text": "<p>To clarify all the other responses:</p>\n\n<p>+++++++++++++++++++++</p>\n\n<pre><code>DoStuff(a++);\n</code></pre>\n\n<p>Is equivalent to:</p>\n\n<pre><code>DoStuff(a);\na = a + 1;\n</code></pre>\n\n<p>+++++++++++++++++++++</p>\n\n<pre><code>DoStuff(++a);\n</code></pre>\n\n<p>Is equivalent to:</p>\n\n<pre><code>a = a + 1;\nDoStuff(a);\n</code></pre>\n\n<p>+++++++++++++++++++++</p>\n\n<pre><code>DoStuff(a + 1);\n</code></pre>\n\n<p>Is equivalent to:</p>\n\n<pre><code>b = a + 1;\nDoStuff(b);\n</code></pre>\n\n<p>+++++++++++++++++++++</p>\n"
},
{
"answer_id": 114482,
"author": "Wes P",
"author_id": 13611,
"author_profile": "https://Stackoverflow.com/users/13611",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public DoStuff(int level)\n{\n\n // DoStuff(level);\n DoStuff(level++);\n // level = level + 1;\n // here, level's value is 1 greater than when it came in\n}\n</code></pre>\n\n<p>It actually increments the value of level.</p>\n\n<pre><code>public DoStuff(int level)\n{\n // int iTmp = level + 1;\n // DoStuff(iTmp);\n DoStuff(level+1);\n // here, level's value hasn't changed\n}\n</code></pre>\n\n<p>doesn't actually increment the value of level.</p>\n\n<p>Not a huge problem before the function call, but after the function call, the values will be different.</p>\n"
},
{
"answer_id": 114487,
"author": "Chris Ballard",
"author_id": 18782,
"author_profile": "https://Stackoverflow.com/users/18782",
"pm_score": 0,
"selected": false,
"text": "<p>Whilst it is tempting to rewrite as:</p>\n\n<pre><code>DoStuff(++level);\n</code></pre>\n\n<p>I personally think this is less readable than incrementing the variable prior to the method call. As noted by a couple of the answers above, the following would be clearer:</p>\n\n<pre><code>level++;\nDoStuff(level);\n</code></pre>\n"
},
{
"answer_id": 114665,
"author": "Christoffer",
"author_id": 15514,
"author_profile": "https://Stackoverflow.com/users/15514",
"pm_score": 0,
"selected": false,
"text": "<p>When you use a language that allows operator overloading, and '+ <integer>' has been defined to do something other than post- and prefix '++'. </p>\n\n<p>Then again, I have only seen such abominations in school projects*, if you encounter that in the wild you probably have a really good, well-documented, reason. </p>\n\n<p>[* a stack of integers, if I'm not mistaken. '++' and '--' pushed and popped, while '+' and '-' performed normal arithmetics]</p>\n"
},
{
"answer_id": 114743,
"author": "TheVillageIdiot",
"author_id": 13198,
"author_profile": "https://Stackoverflow.com/users/13198",
"pm_score": 1,
"selected": false,
"text": "<p>In level++ you are using postfix operator. This operator works after the variable is used. That is after it is put on the stack for the called function, it is incremented. On the other hand level + 1 is simple mathematical expression and it is evaluated and the result is passed to called function. \nIf you want to increment the variable first and then pass it to called function, you can use prefix operator: ++level</p>\n"
},
{
"answer_id": 12432401,
"author": "MarioDS",
"author_id": 1313143,
"author_profile": "https://Stackoverflow.com/users/1313143",
"pm_score": 0,
"selected": false,
"text": "<p>To put it in the most simple way, <code>++var</code> is a prefix operator and will increment the variables <strong>before</strong> the rest of the expression is evaluated. <code>var++</code>, a postfix operator, increments a variable <strong>after</strong> the rest of the expression is evaluated. And as others have mentioned of course, <code>var+1</code> creates just a temporary variable (seperate in memory) which is initiated with <code>var</code> and incremented with constant <code>1</code>.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199234/"
]
| The following two C# code snippets produce different results (assuming the variable level is used both before and after the recursive call). Why?
```
public DoStuff(int level)
{
// ...
DoStuff(level++);
// ...
}
```
,
```
public DoStuff(int level)
{
// ...
DoStuff(level+1);
// ...
}
```
After reading some of the responses below I thought it would be worthwhile posting the stack traces for level++, ++level and level+1 to highlight how deceiving this problem is.
I've simplified them for this post. The recursive call sequence starts with DoStuff(1).
// level++
```
DoStuff(int level = 1)
DoStuff(int level = 2)
DoStuff(int level = 2)
DoStuff(int level = 2)
```
// ++level
```
DoStuff(int level = 4)
DoStuff(int level = 4)
DoStuff(int level = 3)
DoStuff(int level = 2)
```
// level+1
```
DoStuff(int level = 4)
DoStuff(int level = 3)
DoStuff(int level = 2)
DoStuff(int level = 1)
``` | **level++** will pass **level** into **DoStuff** and then increment **level** for use in the rest of the function. This could be a fairly nasty bug as the recursion will never end (from what is shown **DoStuff** is always being passed the same value). Perhaps **++level** is meant instead, as this is the opposite of **level++** (increments level and passes the incremented value into **DoStuff**)?
**level+1** will pass **level+1** into **DoStuff** and leave **level** unchanged for the rest of the function. |
114,431 | <p>I am trying to display a live word count in the vim statusline. I do this by setting my status line in my .vimrc and inserting a function into it. The idea of this function is to return the number of words in the current buffer. This number is then displayed on the status line. This should work nicely as the statusline is updated at just about every possible opportunity so the count will always remain 'live'. </p>
<p>The problem is that the function I have currently defined is slow and so vim is obviously sluggish when it is used for all but the smallest files; due to this function being executed so frequently.</p>
<p>In summary, does anyone have a clever trick for producing a function that is blazingly fast at calculating the number of words in the current buffer and returning the result?</p>
| [
{
"answer_id": 114474,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 3,
"selected": false,
"text": "<p>Keep a count for the current line and a separate count for the rest of the buffer. As you type (or delete) words on the current line, update only that count, but display the sum of the current line count and the rest of the buffer count.</p>\n\n<p>When you change lines, add the current line count to the buffer count, count the words in the current line and a) set the current line count and b) subtract it from the buffer count.</p>\n\n<p>It would also be wise to recount the buffer periodically (note that you don't have to count the whole buffer at once, since you know where editing is occurring).</p>\n"
},
{
"answer_id": 114684,
"author": "Rodrigo Queiro",
"author_id": 20330,
"author_profile": "https://Stackoverflow.com/users/20330",
"pm_score": 2,
"selected": false,
"text": "<p>So I've written:</p>\n\n<pre>\nfunc CountWords()\n exe \"normal g\\\"\n let words = substitute(v:statusmsg, \"^.*Word [^ ]* of \", \"\", \"\")\n let words = substitute(words, \";.*\", \"\", \"\")\n return words\nendfunc\n</pre>\n\n<p>But it prints out info to the statusbar, so I don't think it will be suitable for your use-case. It's very fast, though!</p>\n"
},
{
"answer_id": 116454,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 2,
"selected": false,
"text": "<p>This will recalculate the number of words whenever you stop typing for a while (specifically, <code>updatetime</code> ms).</p>\n\n<pre><code>let g:word_count=\"<unknown>\"\nfun! WordCount()\n return g:word_count\nendfun\nfun! UpdateWordCount()\n let s = system(\"wc -w \".expand(\"%p\"))\n let parts = split(s, ' ')\n if len(parts) > 1\n let g:word_count = parts[0]\n endif\nendfun\n\naugroup WordCounter\n au! CursorHold * call UpdateWordCount()\n au! CursorHoldI * call UpdateWordCount()\naugroup END\n\n\" how eager are you? (default is 4000 ms)\nset updatetime=500\n\n\" modify as you please...\nset statusline=%{WordCount()}\\ words\n</code></pre>\n\n<p>Enjoy!</p>\n"
},
{
"answer_id": 120386,
"author": "Greg Sexton",
"author_id": 20388,
"author_profile": "https://Stackoverflow.com/users/20388",
"pm_score": 0,
"selected": false,
"text": "<p>Using the method in the answer provided by Steve Moyer I was able to produce the following solution. It is a rather inelegant hack I'm afraid and I feel that there must be a neater solution, but it works, and is much faster than simply counting all of the words in a buffer every time the status line is updated. I should note also that this solution is platform independent and does not assume a system has 'wc' or something similar.</p>\n\n<p>My solution does not periodically update the buffer, but the answer provided by Mikael Jansson would be able to provide this functionality. I have not, as of yet, found an instance where my solution becomes out of sync. However I have only tested this briefly as an accurate live word count is not essential to my needs. The pattern I use for matching words is also simple and is intended for simple text documents. If anyone has a better idea for a pattern or any other suggestions please feel free to post an answer or edit this post.</p>\n\n<p>My solution:</p>\n\n<pre><code>\"returns the count of how many words are in the entire file excluding the current line \n\"updates the buffer variable Global_Word_Count to reflect this\nfu! OtherLineWordCount() \n let data = []\n \"get lines above and below current line unless current line is first or last\n if line(\".\") > 1\n let data = getline(1, line(\".\")-1)\n endif \n if line(\".\") < line(\"$\")\n let data = data + getline(line(\".\")+1, \"$\") \n endif \n let count_words = 0\n let pattern = \"\\\\<\\\\(\\\\w\\\\|-\\\\|'\\\\)\\\\+\\\\>\"\n for str in data\n let count_words = count_words + NumPatternsInString(str, pattern)\n endfor \n let b:Global_Word_Count = count_words\n return count_words\nendf \n\n\"returns the word count for the current line\n\"updates the buffer variable Current_Line_Number \n\"updates the buffer variable Current_Line_Word_Count \nfu! CurrentLineWordCount()\n if b:Current_Line_Number != line(\".\") \"if the line number has changed then add old count\n let b:Global_Word_Count = b:Global_Word_Count + b:Current_Line_Word_Count\n endif \n \"calculate number of words on current line\n let line = getline(\".\")\n let pattern = \"\\\\<\\\\(\\\\w\\\\|-\\\\|'\\\\)\\\\+\\\\>\"\n let count_words = NumPatternsInString(line, pattern)\n let b:Current_Line_Word_Count = count_words \"update buffer variable with current line count\n if b:Current_Line_Number != line(\".\") \"if the line number has changed then subtract current line count\n let b:Global_Word_Count = b:Global_Word_Count - b:Current_Line_Word_Count\n endif \n let b:Current_Line_Number = line(\".\") \"update buffer variable with current line number\n return count_words\nendf \n\n\"returns the word count for the entire file using variables defined in other procedures\n\"this is the function that is called repeatedly and controls the other word\n\"count functions.\nfu! WordCount()\n if exists(\"b:Global_Word_Count\") == 0 \n let b:Global_Word_Count = 0\n let b:Current_Line_Word_Count = 0\n let b:Current_Line_Number = line(\".\")\n call OtherLineWordCount()\n endif \n call CurrentLineWordCount()\n return b:Global_Word_Count + b:Current_Line_Word_Count\nendf\n\n\"returns the number of patterns found in a string \nfu! NumPatternsInString(str, pat)\n let i = 0\n let num = -1\n while i != -1\n let num = num + 1\n let i = matchend(a:str, a:pat, i)\n endwhile\n return num\nendf\n</code></pre>\n\n<p>This is then added to the status line by:</p>\n\n<pre><code>:set statusline=wc:%{WordCount()}\n</code></pre>\n\n<p>I hope this helps anyone looking for a live word count in Vim. Albeit one that isn't always exact. Alternatively of course g ctrl-g will provide you with Vim's word count!</p>\n"
},
{
"answer_id": 553257,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<p>Here's a usable version of Rodrigo Queiro's idea. It doesn't change the status bar, and it restores the statusmsg variable.</p>\n\n<pre><code>function WordCount()\n let s:old_status = v:statusmsg\n exe \"silent normal g\\<c-g>\"\n let s:word_count = str2nr(split(v:statusmsg)[11])\n let v:statusmsg = s:old_status\n return s:word_count\nendfunction\n</code></pre>\n\n<p>This seems to be fast enough to include directly in the status line, e.g.:</p>\n\n<pre><code>:set statusline=wc:%{WordCount()}\n</code></pre>\n"
},
{
"answer_id": 2796006,
"author": "dahu",
"author_id": 336429,
"author_profile": "https://Stackoverflow.com/users/336429",
"pm_score": 1,
"selected": false,
"text": "<p>I took the bulk of this from the vim help pages on writing functions.</p>\n\n<pre><code>function! WordCount()\n let lnum = 1\n let n = 0\n while lnum <= line('$')\n let n = n + len(split(getline(lnum)))\n let lnum = lnum + 1\n endwhile\n return n\nendfunction\n</code></pre>\n\n<p>Of course, like the others, you'll need to:</p>\n\n<pre><code>:set statusline=wc:%{WordCount()}\n</code></pre>\n\n<p>I'm sure this can be cleaned up by somebody to make it more vimmy (s:n instead of just n?), but I believe the basic functionality is there.</p>\n\n<p>Edit:</p>\n\n<p>Looking at this again, I really like Mikael Jansson's solution. I don't like shelling out to <code>wc</code> (not portable and perhaps slow). If we replace his <code>UpdateWordCount</code> function with the code I have above (renaming my function to <code>UpdateWordCount</code>), then I think we have a better solution.</p>\n"
},
{
"answer_id": 2808113,
"author": "godlygeek",
"author_id": 337899,
"author_profile": "https://Stackoverflow.com/users/337899",
"pm_score": 1,
"selected": false,
"text": "<p>My suggestion:</p>\n\n<pre><code>function! UpdateWordCount()\n let b:word_count = eval(join(map(getline(\"1\", \"$\"), \"len(split(v:val, '\\\\s\\\\+'))\"), \"+\"))\nendfunction\n\naugroup UpdateWordCount\n au!\n autocmd BufRead,BufNewFile,BufEnter,CursorHold,CursorHoldI,InsertEnter,InsertLeave * call UpdateWordCount()\naugroup END\n\nlet &statusline='wc:%{get(b:, \"word_count\", 0)}'\n</code></pre>\n\n<p>I'm not sure how this compares in speed to some of the other solutions, but it's certainly a lot simpler than most.</p>\n"
},
{
"answer_id": 4588161,
"author": "Abslom Daak",
"author_id": 561702,
"author_profile": "https://Stackoverflow.com/users/561702",
"pm_score": 5,
"selected": false,
"text": "<p>I really like Michael Dunn's answer above but I found that when I was editing it was causing me to be unable to access the last column. So I have a minor change for the function:</p>\n\n<pre><code>function! WordCount()\n let s:old_status = v:statusmsg\n let position = getpos(\".\")\n exe \":silent normal g\\<c-g>\"\n let stat = v:statusmsg\n let s:word_count = 0\n if stat != '--No lines in buffer--'\n let s:word_count = str2nr(split(v:statusmsg)[11])\n let v:statusmsg = s:old_status\n end\n call setpos('.', position)\n return s:word_count \nendfunction\n</code></pre>\n\n<p>I've included it in my status line without any issues:</p>\n\n<p><code>:set statusline=wc:%{WordCount()}</code></p>\n"
},
{
"answer_id": 8773451,
"author": "nth",
"author_id": 1136450,
"author_profile": "https://Stackoverflow.com/users/1136450",
"pm_score": 1,
"selected": false,
"text": "<p>I'm new to Vim scripting, but I might suggest</p>\n\n<pre><code>function WordCount()\n redir => l:status\n exe \"silent normal g\\<c-g>\"\n redir END\n return str2nr(split(l:status)[11])\nendfunction\n</code></pre>\n\n<p>as being a bit cleaner since it does not overwrite the existing status line.</p>\n\n<p>My reason for posting is to point out that this function has a puzzling bug: namely, it breaks the append command. Hitting <kbd>A</kbd> should drop you into insert mode with the cursor positioned to the right of the final character on the line. However, with this custom status bar enabled it will put you to the left of the final character. </p>\n\n<p>Anyone have any idea what causes this?</p>\n"
},
{
"answer_id": 11993678,
"author": "Felipe Morales",
"author_id": 1604120,
"author_profile": "https://Stackoverflow.com/users/1604120",
"pm_score": 1,
"selected": false,
"text": "<p>This is an improvement on <a href=\"https://stackoverflow.com/a/553257/1604120\">Michael Dunn's version</a>, caching the word count so even less processing is needed.</p>\n\n<pre><code>function! WC()\n if &modified || !exists(\"b:wordcount\") \n let l:old_status = v:statusmsg \n execute \"silent normal g\\<c-g>\"\n let b:wordcount = str2nr(split(v:statusmsg)[11])\n let v:statusmsg = l:old_status \n return b:wordcount\n else\n return b:wordcount\n endif\nendfunction \n</code></pre>\n"
},
{
"answer_id": 13539953,
"author": "Leo",
"author_id": 926705,
"author_profile": "https://Stackoverflow.com/users/926705",
"pm_score": 2,
"selected": false,
"text": "<p>I used a slightly different approach for this. Rather than make sure the word count function is especially fast, I only call it when the cursor stops moving. These commands will do it:</p>\n\n<pre><code>:au CursorHold * exe \"normal g\\<c-g>\"\n:au CursorHoldI * exe \"normal g\\<c-g>\"\n</code></pre>\n\n<p>Perhaps not quite what the questioner wanted, but much simpler than some of the answers here, and good enough for my use-case (glance down to see word count after typing a sentence or two).</p>\n\n<p>Setting <code>updatetime</code> to a smaller value also helps here:</p>\n\n<pre><code>set updatetime=300\n</code></pre>\n\n<p>There isn't a huge overhead polling for the word count because <code>CursorHold</code> and <code>CursorHoldI</code> only fire <em>once</em> when the cursor stops moving, not every <code>updatetime</code> ms.</p>\n"
},
{
"answer_id": 18895724,
"author": "Guy Gur-Ari",
"author_id": 563237,
"author_profile": "https://Stackoverflow.com/users/563237",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a refinement of Abslom Daak's answer that also works in visual mode.</p>\n\n<pre><code>function! WordCount()\n let s:old_status = v:statusmsg\n let position = getpos(\".\")\n exe \":silent normal g\\<c-g>\"\n let stat = v:statusmsg\n let s:word_count = 0\n if stat != '--No lines in buffer--'\n <strong>if stat =~ \"^Selected\"\n let s:word_count = str2nr(split(v:statusmsg)[5])\n else\n let s:word_count = str2nr(split(v:statusmsg)[11])\n end</strong>\n let v:statusmsg = s:old_status\n end\n call setpos('.', position)\n return s:word_count \nendfunction\n</code></pre>\n\n<p>Included in the status line as before. Here is a right-aligned status line:</p>\n\n<p><code>set statusline=%=%{WordCount()}\\ words\\ </code></p>\n"
},
{
"answer_id": 24560728,
"author": "Dan Sheffler",
"author_id": 3769180,
"author_profile": "https://Stackoverflow.com/users/3769180",
"pm_score": 0,
"selected": false,
"text": "<p>In case someone else is coming here from Google, I modified Abslom Daak's answer to work with <a href=\"https://github.com/bling/vim-airline\" rel=\"nofollow\">Airline</a>. I saved the following as</p>\n\n<p><code>~/.vim/bundle/vim-airline/autoload/airline/extensions/pandoc.vim</code></p>\n\n<p>and added</p>\n\n<p><code>call airline#extensions#pandoc#init(s:ext)</code></p>\n\n<p>to <code>extensions.vim</code> </p>\n\n<pre><code>let s:spc = g:airline_symbols.space\n\nfunction! airline#extensions#pandoc#word_count()\nif mode() == \"s\"\n return 0\nelse\n let s:old_status = v:statusmsg\n let position = getpos(\".\")\n let s:word_count = 0\n exe \":silent normal g\\<c-g>\"\n let stat = v:statusmsg\n let s:word_count = 0\n if stat != '--No lines in buffer--'\n let s:word_count = str2nr(split(v:statusmsg)[11])\n let v:statusmsg = s:old_status\n end\n call setpos('.', position)\n return s:word_count \nend\nendfunction\n\nfunction! airline#extensions#pandoc#apply(...)\nif &ft == \"pandoc\"\n let w:airline_section_x = \"%{airline#extensions#pandoc#word_count()} Words\"\nendif\nendfunction\n\nfunction! airline#extensions#pandoc#init(ext)\ncall a:ext.add_statusline_func('airline#extensions#pandoc#apply')\nendfunction\n</code></pre>\n"
},
{
"answer_id": 56586860,
"author": "Enno",
"author_id": 3528522,
"author_profile": "https://Stackoverflow.com/users/3528522",
"pm_score": 0,
"selected": false,
"text": "<p>A variation of Guy Gur-Ari's <a href=\"https://stackoverflow.com/a/18895724/3528522\">refinement</a> that</p>\n\n<ul>\n<li>only counts words if spell checking is enabled,</li>\n<li>counts the number of selected words in visual mode</li>\n<li>keeps mute outside of insert and normal mode, and</li>\n<li>hopefully is more agnostic to the system language (when different from english)</li>\n</ul>\n\n<pre><code>function! StatuslineWordCount()\n if !&l:spell\n return ''\n endif\n\n if empty(getline(line('$')))\n return ''\n endif\n let mode = mode()\n if !(mode ==# 'v' || mode ==# 'V' || mode ==# \"\\<c-v>\" || mode =~# '[ni]')\n return ''\n endif\n\n let s:old_status = v:statusmsg\n let position = getpos('.')\n let stat = v:statusmsg\n let s:word_count = 0\n exe \":silent normal g\\<c-g>\"\n try\n if mode ==# 'v' || mode ==# 'V'\n let s:word_count = split(split(v:statusmsg, ';')[1])[0]\n elseif mode ==# \"\\<c-v>\"\n let s:word_count = split(split(v:statusmsg, ';')[2])[0]\n elseif mode =~# '[ni]'\n let s:word_count = split(split(v:statusmsg, ';')[2])[3]\n end\n \" index out of range\n catch /^Vim\\%((\\a\\+)\\)\\=:E\\%(684\\|116\\)/\n return ''\n endtry\n let v:statusmsg = s:old_status\n call setpos('.', position)\n\n return \"\\ \\|\\ \" . s:word_count . 'w'\nendfunction\n</code></pre>\n\n<p>that can be appended to the statusline by, say,</p>\n\n<pre><code> set statusline+=%.10{StatuslineWordCount()} \" wordcount\n</code></pre>\n"
},
{
"answer_id": 60310471,
"author": "Serge Stroobandt",
"author_id": 2192488,
"author_profile": "https://Stackoverflow.com/users/2192488",
"pm_score": 2,
"selected": false,
"text": "<h1>Since <code>vim</code> version 7.4.1042</h1>\n\n<p>Since <code>vim</code> version 7.4.1042, one can simply alter the <code>statusline</code> as follows:</p>\n\n<pre><code>set statusline+=%{wordcount().words}\\ words\nset laststatus=2 \" enables the statusline.\n</code></pre>\n\n<h1>Word count in <code>vim-airline</code></h1>\n\n<p>Word count is provided standard by <a href=\"https://github.com/vim-airline/vim-airline#vim-airline---\" rel=\"nofollow noreferrer\"><code>vim-airline</code></a> for a number of file types, being at the time of writing:\n<a href=\"https://github.com/vim-airline/vim-airline/blob/master/autoload/airline/extensions/wordcount.vim#L90\" rel=\"nofollow noreferrer\"><code>asciidoc, help, mail, markdown, org, rst, tex ,text</code></a></p>\n\n<p>If word count is not shown in the <code>vim-airline</code>, more often this is due to an unrecognised file type. For example, <a href=\"https://github.com/vim-airline/vim-airline/pull/2075\" rel=\"nofollow noreferrer\">at least for now</a>, the compound file type <a href=\"https://github.com/vim-pandoc/vim-pandoc-syntax#standalone\" rel=\"nofollow noreferrer\"><code>markdown.pandoc</code></a> is not being recognised by <code>vim-airline</code> for word count. This can easily be remedied by amending the <code>.vimrc</code> as follows:</p>\n\n<pre><code>let g:airline#extensions#wordcount#filetypes = '\\vasciidoc|help|mail|markdown|markdown.pandoc|org|rst|tex|text'\nset laststatus=2 \" enables vim-airline.\n</code></pre>\n\n<p>The <code>\\v</code> statement overrides the default <code>g:airline#extensions#wordcount#filetypes</code> variable. The last line ensures <code>vim-airline</code> is enabled.</p>\n\n<p>In case of doubt, the <code>&filetype</code> of an opened file is returned upon issuing the following command:</p>\n\n<pre><code>:echo &filetype\n</code></pre>\n\n<p>Here is a meta-example:</p>\n\n<p><img src=\"https://i.imgur.com/9RynwBY.png\" alt=\"vim-airline word count\"></p>\n"
},
{
"answer_id": 60326395,
"author": "D. Ben Knoble",
"author_id": 4400820,
"author_profile": "https://Stackoverflow.com/users/4400820",
"pm_score": 1,
"selected": false,
"text": "<p>Since vim now supports this natively:</p>\n\n<pre><code>:echo wordcount().words\n</code></pre>\n"
},
{
"answer_id": 67723154,
"author": "Iuri Gavronski",
"author_id": 11001018,
"author_profile": "https://Stackoverflow.com/users/11001018",
"pm_score": 0,
"selected": false,
"text": "<p>Building upon <a href=\"https://stackoverflow.com/a/60310471/11001018\">https://stackoverflow.com/a/60310471/11001018</a>, my suggestion is:</p>\n<pre><code>"new in vim 7.4.1042\nlet g:word_count=wordcount().words\nfunction WordCount()\n if has_key(wordcount(),'visual_words')\n let g:word_count=wordcount().visual_words."/".wordcount().words\n else\n let g:word_count=wordcount().cursor_words."/".wordcount().words\n endif\n return g:word_count\nendfunction\n</code></pre>\n<p>And then:</p>\n<pre><code>set statusline+=\\ w:%{WordCount()},\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20388/"
]
| I am trying to display a live word count in the vim statusline. I do this by setting my status line in my .vimrc and inserting a function into it. The idea of this function is to return the number of words in the current buffer. This number is then displayed on the status line. This should work nicely as the statusline is updated at just about every possible opportunity so the count will always remain 'live'.
The problem is that the function I have currently defined is slow and so vim is obviously sluggish when it is used for all but the smallest files; due to this function being executed so frequently.
In summary, does anyone have a clever trick for producing a function that is blazingly fast at calculating the number of words in the current buffer and returning the result? | Here's a usable version of Rodrigo Queiro's idea. It doesn't change the status bar, and it restores the statusmsg variable.
```
function WordCount()
let s:old_status = v:statusmsg
exe "silent normal g\<c-g>"
let s:word_count = str2nr(split(v:statusmsg)[11])
let v:statusmsg = s:old_status
return s:word_count
endfunction
```
This seems to be fast enough to include directly in the status line, e.g.:
```
:set statusline=wc:%{WordCount()}
``` |
114,493 | <p>I know the range name of the start of a list - <code>1</code> column wide and <code>x</code> rows deep.</p>
<p>How do I calculate <code>x</code>?</p>
<p>There is more data in the column than just this list. However, this list is contiguous - there is nothing in any of the cells above or below or either side beside it.</p>
| [
{
"answer_id": 114513,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 5,
"selected": true,
"text": "<pre><code>Function ListRowCount(ByVal FirstCellName as String) as Long\n With thisworkbook.Names(FirstCellName).RefersToRange\n If isempty(.Offset(1,0).value) Then \n ListRowCount = 1\n Else\n ListRowCount = .End(xlDown).row - .row + 1\n End If\n End With\nEnd Function\n</code></pre>\n\n<p>But if you are damn sure there's nothing around the list, then just <code>thisworkbook.Names(FirstCellName).RefersToRange.CurrentRegion.rows.count</code></p>\n"
},
{
"answer_id": 114598,
"author": "wcm",
"author_id": 2173,
"author_profile": "https://Stackoverflow.com/users/2173",
"pm_score": 2,
"selected": false,
"text": "<p>I am sure that you probably wanted the answer that @GSerg gave. There is also a worksheet function called <code>rows</code> that will give you the number of rows. </p>\n\n<p>So, if you have a named data range called <code>Data</code> that has 7 rows, then <code>=ROWS(Data)</code> will show 7 in that cell.</p>\n"
},
{
"answer_id": 114615,
"author": "SpyJournal",
"author_id": 10326,
"author_profile": "https://Stackoverflow.com/users/10326",
"pm_score": 1,
"selected": false,
"text": "<p>That single last line worked perfectly @GSerg.</p>\n\n<p>The other function was what I had been working on but I don't like having to resort to UDF's unless absolutely necessary.</p>\n\n<p>I had been trying a combination of excel and vba and had got this to work - but its clunky compared with your answer.</p>\n\n<pre><code>strArea = Sheets(\"Oper St Report CC\").Range(\"cc_rev\").CurrentRegion.Address\ncc_rev_rows = \"=ROWS(\" & strArea & \")\"\nRange(\"cc_rev_count\").Formula = cc_rev_rows\n</code></pre>\n"
},
{
"answer_id": 115091,
"author": "Jon Fournier",
"author_id": 5106,
"author_profile": "https://Stackoverflow.com/users/5106",
"pm_score": 3,
"selected": false,
"text": "<p>You can also use:</p>\n\n<pre><code>Range( RangeName ).end(xlDown).row\n</code></pre>\n\n<p>to find the last row with data in it starting at your named range.</p>\n"
},
{
"answer_id": 1233664,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<pre><code>Sheet1.Range(\"myrange\").Rows.Count\n</code></pre>\n"
},
{
"answer_id": 10737390,
"author": "user1371038",
"author_id": 1371038,
"author_profile": "https://Stackoverflow.com/users/1371038",
"pm_score": 3,
"selected": false,
"text": "<p>Why not use an Excel formula to determine the rows? For instance, if you are looking for how many cells contain data in Column A use this:</p>\n\n<p>=COUNTIFS(A:A,\"<>\")</p>\n\n<p>You can replace <> with any value to get how many rows have that value in it.</p>\n\n<p>=COUNTIFS(A:A,\"2008\")</p>\n\n<p>This can be used for finding filled cells in a row too.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10326/"
]
| I know the range name of the start of a list - `1` column wide and `x` rows deep.
How do I calculate `x`?
There is more data in the column than just this list. However, this list is contiguous - there is nothing in any of the cells above or below or either side beside it. | ```
Function ListRowCount(ByVal FirstCellName as String) as Long
With thisworkbook.Names(FirstCellName).RefersToRange
If isempty(.Offset(1,0).value) Then
ListRowCount = 1
Else
ListRowCount = .End(xlDown).row - .row + 1
End If
End With
End Function
```
But if you are damn sure there's nothing around the list, then just `thisworkbook.Names(FirstCellName).RefersToRange.CurrentRegion.rows.count` |
114,501 | <p>I want to set a background image for a div, in a way that it is in the upper <strong>RIGHT</strong> of the div, but with a fixed <code>10px</code> distance from top and right.</p>
<p>Here is how I would do that if wanted it in the upper <strong>LEFT</strong> of the div:</p>
<pre>background: url(images/img06.gif) no-repeat 10px 10px;</pre>
<p>Is there anyway to achieve the same result, but showing the background on the upper <strong>RIGHT</strong>?</p>
| [
{
"answer_id": 114517,
"author": "mathieu",
"author_id": 971,
"author_profile": "https://Stackoverflow.com/users/971",
"pm_score": 3,
"selected": false,
"text": "<p>I don't know if it is possible in pure css, so you can try </p>\n\n<pre><code>background: url(images/img06.gif) no-repeat top right;\n</code></pre>\n\n<p>and modify your image to incorporate a 10px border on the top and right in a transparent color</p>\n"
},
{
"answer_id": 114522,
"author": "Justin Poliey",
"author_id": 6967,
"author_profile": "https://Stackoverflow.com/users/6967",
"pm_score": 3,
"selected": false,
"text": "<p>There are a few ways you can do this.</p>\n\n<ol>\n<li><p>Do the math yourself, if possible. You already know the dimensions of your image. If you know the dimensions of the div, you can just put the image at (div width - image width - 10, div height - image height - 10).</p></li>\n<li><p>Use Javascript to do the heavy lifting for you. Pretty much the same method as above, except you don't need to know the dimensions of the div itself. Javascript can tell you.</p></li>\n<li><p>A more hackish way would be to put a 10px transparent border around the top and right of your image, and set the position to <code>top right</code>.</p></li>\n</ol>\n"
},
{
"answer_id": 114523,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 0,
"selected": false,
"text": "<p>One solution is to absolutely position an empty <code>div</code>, and give that the background. I don't believe there's a way to do it purely with CSS, no changes to the image, and no extra markup in a fluid layout.</p>\n"
},
{
"answer_id": 114653,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": 5,
"selected": true,
"text": "<p>Use the previously mentioned rule along with a top and right margin:</p>\n\n<pre><code>background: url(images/img06.gif) no-repeat top right;\nmargin-top: 10px;\nmargin-right: 10px;\n</code></pre>\n\n<p>Background images only appear within padding, not margins. If adding the margin isn't an option you may have to resort to another div, although I'd recommend you only use that as a last resort to try and keep your markup as lean and sementic as possible.</p>\n"
},
{
"answer_id": 114661,
"author": "Rahul",
"author_id": 16308,
"author_profile": "https://Stackoverflow.com/users/16308",
"pm_score": 1,
"selected": false,
"text": "<p>You can use percentages:</p>\n\n<pre><code>background: url(...) top 98% no-repeat;\n</code></pre>\n\n<p>If you know the width of the parent div it should be pretty easy to determine what percentage you need to use.</p>\n"
},
{
"answer_id": 9133530,
"author": "Teatra.co",
"author_id": 1188186,
"author_profile": "https://Stackoverflow.com/users/1188186",
"pm_score": -1,
"selected": false,
"text": "<p>The correct format is:</p>\n\n<pre><code>background: url(YourUrl) 0px -50px no-repeat;\n</code></pre>\n\n<p>Where <code>0px</code> is the horizontal position and <code>-50px</code> is the vertical position.</p>\n\n<p>CSS <code>background-position</code> accepts negative values.</p>\n"
},
{
"answer_id": 9943032,
"author": "Boldewyn",
"author_id": 113195,
"author_profile": "https://Stackoverflow.com/users/113195",
"pm_score": 5,
"selected": false,
"text": "<p>In all modern browsers and IE down even to version 9 you can use a four-value syntax, <a href=\"http://www.w3.org/TR/css3-background/#background-position\" rel=\"noreferrer\">specified in CSS3</a>:</p>\n\n<pre><code>background-position: right 10px top 10px;\n</code></pre>\n\n<p>Source: <a href=\"https://developer.mozilla.org/en/CSS/background-position\" rel=\"noreferrer\">MDN</a></p>\n"
},
{
"answer_id": 32929143,
"author": "Hichem ben chaabene",
"author_id": 2079148,
"author_profile": "https://Stackoverflow.com/users/2079148",
"pm_score": 0,
"selected": false,
"text": "<p>You can fake the space on the right hand side with a border in pixels (white most of the time or maybe something else)</p>\n\n<pre><code> background-image: url(../images/calender.svg) center right\n border-right: 5px white solid\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6476/"
]
| I want to set a background image for a div, in a way that it is in the upper **RIGHT** of the div, but with a fixed `10px` distance from top and right.
Here is how I would do that if wanted it in the upper **LEFT** of the div:
```
background: url(images/img06.gif) no-repeat 10px 10px;
```
Is there anyway to achieve the same result, but showing the background on the upper **RIGHT**? | Use the previously mentioned rule along with a top and right margin:
```
background: url(images/img06.gif) no-repeat top right;
margin-top: 10px;
margin-right: 10px;
```
Background images only appear within padding, not margins. If adding the margin isn't an option you may have to resort to another div, although I'd recommend you only use that as a last resort to try and keep your markup as lean and sementic as possible. |
114,504 | <p>Eg. can I write something like this code:</p>
<pre><code>public void InactiveCustomers(IEnumerable<Guid> customerIDs)
{
//...
myAdoCommand.CommandText =
"UPDATE Customer SET Active = 0 WHERE CustomerID in (@CustomerIDs)";
myAdoCommand.Parameters["@CustomerIDs"].Value = customerIDs;
//...
}
</code></pre>
<p>The only way I know is to Join my IEnumerable and then use string concatenation to build my SQL string.</p>
| [
{
"answer_id": 114548,
"author": "Pontus Gagge",
"author_id": 20402,
"author_profile": "https://Stackoverflow.com/users/20402",
"pm_score": -1,
"selected": false,
"text": "<p>Nope. Parameters are like SQL values in obeying <a href=\"http://www.anaesthetist.com/mnm/sql/normal.htm\" rel=\"nofollow noreferrer\">first normal form</a>, basically, there can only be one...</p>\n\n<p>As you are probably aware, generating SQL strings is risky business: you leave yourself open to an <a href=\"http://en.wikipedia.org/wiki/Sql_injection\" rel=\"nofollow noreferrer\">SQL injection attack</a>. As long as you're dealing with bona fide GUID's you should be fine, but otherwise you need to be sure to cleanse your input. </p>\n"
},
{
"answer_id": 114562,
"author": "hollystyles",
"author_id": 2083160,
"author_profile": "https://Stackoverflow.com/users/2083160",
"pm_score": -1,
"selected": false,
"text": "<p>You cannot pass a list as a single SQl Parameter. You could string.Join(',') the GUIDS such as \"0000-0000-0000-0000, 1111-1111-1111-1111\" but this would be high on database overhead and sub-optimal really. And you have to pass the whole string as single concatenated dynamic statement, you can't add it as a parameter.</p>\n\n<p>Question:</p>\n\n<p>Where are you getting your list of ID's that represent inactive customers from?</p>\n\n<p>My suggestion is to approach the problem a little differently. Move all that logic into the database, something like:</p>\n\n<pre><code> Create procedure usp_DeactivateCustomers \n @inactive varchar(50) /*or whatever values are required to identify inactive customers*/\n AS \n UPDATE Customer SET c.Active = 0 \n FROM Customer c JOIN tableB b ON c.CustomerID = b.CustomerID \n WHERE b.someField = @inactive\n</code></pre>\n\n<p>And call it as a stored procedure:</p>\n\n<pre><code>public void InactiveCustomers(string inactive)\n{\n //...\n myAdoCommand.CommandText =\n \"usp_DeactivateCustomers\";\n myAdoCommand.Parameters[\"@inactive\"].Value = inactive;\n //...\n}\n</code></pre>\n\n<hr>\n\n<p>If a list of GUID's exist in a database, why do I need to: find them; put them in a generic list; unwind the list into a CSV/XML/Table variable, just to present them back to the DB again ????? They're already there! Am I missing something?</p>\n"
},
{
"answer_id": 114685,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 5,
"selected": true,
"text": "<p>Generally the way that you do this is to pass in a comma-separated list of values, and within your stored procedure, parse the list out and insert it into a temp table, which you can then use for joins. As of <strong>Sql Server 2005</strong>, this is standard practice for dealing with parameters that need to hold arrays.</p>\n\n<p>Here's a good article on various ways to deal with this problem:</p>\n\n<p><a href=\"http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm\" rel=\"noreferrer\">Passing a list/array to an SQL Server stored procedure</a></p>\n\n<p>But for <strong>Sql Server 2008</strong>, we finally get to pass table variables into procedures, by first defining the table as a custom type.</p>\n\n<p>There is a good description of this (and more 2008 features) in this article:</p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/cc721270.aspx\" rel=\"noreferrer\">Introduction to New T-SQL Programmability Features in SQL Server 2008</a></p>\n"
},
{
"answer_id": 114703,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 3,
"selected": false,
"text": "<p>You can with <a href=\"http://blog.benhall.me.uk/2007/07/sql-server-2008-table-value-parameters.html\" rel=\"noreferrer\">SQL 2008</a>. It hasn't been out very long, but it is available.</p>\n"
},
{
"answer_id": 114724,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 1,
"selected": false,
"text": "<p>You can use xml parameter type:</p>\n\n<pre><code>CREATE PROCEDURE SelectByIdList(@productIds xml) AS\n\nDECLARE @Products TABLE (ID int) \n\nINSERT INTO @Products (ID) SELECT ParamValues.ID.value('.','VARCHAR(20)')\nFROM @productIds.nodes('/Products/id') as ParamValues(ID) \n\nSELECT * FROM \n Products\nINNER JOIN \n @Products p\nON Products.ProductID = p.ID\n</code></pre>\n\n<p><a href=\"http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing-lists-to-sql-server-2005-with-xml-parameters.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing-lists-to-sql-server-2005-with-xml-parameters.aspx</a></p>\n"
},
{
"answer_id": 31110710,
"author": "stakx - no longer contributing",
"author_id": 240733,
"author_profile": "https://Stackoverflow.com/users/240733",
"pm_score": 2,
"selected": false,
"text": "<p>As was mentioned <a href=\"https://stackoverflow.com/questions/114504/is-it-possible-to-send-a-collection-of-ids-as-a-ado-net-sql-parameter#comment1039858_114685\">in a comment</a>, Erland Sommarskog wrote a series of articles on this topic (linked-to below). The articles are very thorough and can serve as reference material. While they are specific to SQL Server (T-SQL), some of the techniques mentioned might also work for other RDBMS (such as using an <code>XML</code> data type):</p>\n\n<ul>\n<li><p><strong><a href=\"http://www.sommarskog.se/arrays-in-sql-2008.html\" rel=\"nofollow noreferrer\">Arrays and Lists in SQL Server 2008 Using Table-Valued Parameters</a></strong>:</p>\n\n<ul>\n<li>Table-Valued Parameters (TVPs)</li>\n</ul></li>\n<li><p><strong><a href=\"http://www.sommarskog.se/arrays-in-sql-2005.html\" rel=\"nofollow noreferrer\">Arrays and Lists in SQL Server 2005 and Beyond When TVPs Do Not Cut it</a></strong>:</p>\n\n<ul>\n<li>string serialization and de-serialization of scalar values</li>\n<li>SQLCLR</li>\n<li>passing structured list data via the XML data type</li>\n<li>Dynamic SQL</li>\n</ul></li>\n<li><p><strong><a href=\"http://www.sommarskog.se/arrays-in-sql-2000.html\" rel=\"nofollow noreferrer\">Arrays and Lists in SQL Server 2000 and Earlier</a></strong></p></li>\n</ul>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8547/"
]
| Eg. can I write something like this code:
```
public void InactiveCustomers(IEnumerable<Guid> customerIDs)
{
//...
myAdoCommand.CommandText =
"UPDATE Customer SET Active = 0 WHERE CustomerID in (@CustomerIDs)";
myAdoCommand.Parameters["@CustomerIDs"].Value = customerIDs;
//...
}
```
The only way I know is to Join my IEnumerable and then use string concatenation to build my SQL string. | Generally the way that you do this is to pass in a comma-separated list of values, and within your stored procedure, parse the list out and insert it into a temp table, which you can then use for joins. As of **Sql Server 2005**, this is standard practice for dealing with parameters that need to hold arrays.
Here's a good article on various ways to deal with this problem:
[Passing a list/array to an SQL Server stored procedure](http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm)
But for **Sql Server 2008**, we finally get to pass table variables into procedures, by first defining the table as a custom type.
There is a good description of this (and more 2008 features) in this article:
[Introduction to New T-SQL Programmability Features in SQL Server 2008](http://technet.microsoft.com/en-us/library/cc721270.aspx) |
114,521 | <p>I am creating a <code>gridView</code> that allows adding new rows by adding the controls necessary for the insert into the <code>FooterTemplate</code>, but when the <code>ObjectDataSource</code> has no records, I add a dummy row as the <code>FooterTemplate</code> is only displayed when there is data.</p>
<p>How can I hide this dummy row? I have tried setting <code>e.row.visible = false</code> on <code>RowDataBound</code> but the row is still visible.</p>
| [
{
"answer_id": 114589,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 0,
"selected": false,
"text": "<p>This is the incorrect usage of the GridView control. The GridView control has a special InsertRow which is where your controls should go.</p>\n"
},
{
"answer_id": 114612,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe try:</p>\n\n<pre><code>e.Row.Height = Unit.Pixel(0);\n</code></pre>\n\n<p>This isnt the right answer but it might work in the meantime until you get the right answer.</p>\n"
},
{
"answer_id": 114638,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe use CSS to set display none?!</p>\n"
},
{
"answer_id": 114699,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 1,
"selected": false,
"text": "<p>I think this is what you need:</p>\n\n<pre><code><asp:GridView ID=\"grid\" runat=\"server\" AutoGenerateColumns=\"false\" ShowFooter=\"true\" OnRowDataBound=\"OnRowDataBound\">\n <Columns>\n <asp:TemplateField HeaderText=\"headertext\">\n <ItemTemplate>\n itemtext\n </ItemTemplate>\n <FooterTemplate>\n insert controls\n </FooterTemplate>\n </asp:TemplateField>\n </Columns>\n</asp:GridView>\n</code></pre>\n\n<p>and the codebehind:</p>\n\n<pre><code>protected void OnRowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n e.Row.Attributes[\"style\"] = \"display:none\";\n }\n}\n</code></pre>\n\n<p>But I do not understand why you are adding your \"insert controls\" to the footer instead of placing them below the grid.</p>\n"
},
{
"answer_id": 114737,
"author": "John Miller",
"author_id": 17623,
"author_profile": "https://Stackoverflow.com/users/17623",
"pm_score": 2,
"selected": false,
"text": "<p>You could handle the gridview's databound event and hide the dummy row. (Don't forget to assign the event property in the aspx code):</p>\n\n<pre><code>protected void GridView1_DataBound(object sender, EventArgs e)\n {\n if (GridView1.Rows.Count == 1)\n GridView1.Rows[0].Visible = false;\n }\n</code></pre>\n"
},
{
"answer_id": 115047,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 0,
"selected": false,
"text": "<p>GridView has a special property to access Footer Row, named \"FooterRow\"</p>\n\n<p>Then, you cold try yourGrid.FooterRow.Visible = false;</p>\n"
},
{
"answer_id": 115097,
"author": "Rob",
"author_id": 12413,
"author_profile": "https://Stackoverflow.com/users/12413",
"pm_score": 0,
"selected": false,
"text": "<p>I did this on a previous job, but since you can add rows, I always had it visible in the footer row. To make it so that the grid shows up, I bound an empty row of the type that is normally bound </p>\n\n<pre><code>dim row as Datarow = table.NewRow()\ntable.AddRow(row)\ngridView.DataSource = table\ngridView.Databind()\n</code></pre>\n\n<p>then it has all the columns and then you need. You can access the footer by pulling this:</p>\n\n<pre><code>'this will get the footer no matter how many rows there are in the grid.\n\nDim footer as Control = gridView.Controls(0).Controls(gridView.Controls(0).Controls.Count -1)\n</code></pre>\n\n<p>then to access any of the controls in the footer you would go and do a:</p>\n\n<pre><code>Dim cntl as Control = footer.FindControl(<Insert Control Name Here>)\n</code></pre>\n\n<p>I'd assume you'd be able to do a:</p>\n\n<pre><code>footer.Visible = false\n</code></pre>\n\n<p>to make the footer row invisible.</p>\n\n<p>I hope this helps!</p>\n\n<p><em>Edit</em> I just figured out what you said. I basically delete the row when I add a new one, but to do this you need to check to see if there are any other rows, and if there are, check to see if there are values in it. </p>\n\n<p>To delete the dummy row do something like this: </p>\n\n<pre><code>If mTable.Rows.Count = 1 AndAlso mTable.Rows(0)(<first column to check for null value>) Is DBNull.Value AndAlso mTable.Rows(0)(<second column>) Is DBNull.Value AndAlso mTable.Rows(0)(<thrid column>) Is DBNull.Value Then \nmTable.Rows.Remove(mTable.Rows(0)) \nEnd If\nmTable.Rows.Add(row)\ngridView.Datasource = mTable\ngridView.Databind()\n</code></pre>\n"
},
{
"answer_id": 594536,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>To make it visible, just use:</p>\n\n<pre><code>Gridview.Rows.Item(i).Attributes.Add(\"style\", \"display:block\")\n</code></pre>\n\n<p>And to make it invisible</p>\n\n<pre><code>Gridview.Rows.Item(i).Attributes.Add(\"style\", \"display:none\")\n</code></pre>\n"
},
{
"answer_id": 1492628,
"author": "DiningPhilanderer",
"author_id": 30934,
"author_profile": "https://Stackoverflow.com/users/30934",
"pm_score": 0,
"selected": false,
"text": "<p>Why are you not using the EmptyDataTemplate? It seems to work great even though I have only been using it for a couple days...</p>\n"
},
{
"answer_id": 3353093,
"author": "Davidson Sousa",
"author_id": 296437,
"author_profile": "https://Stackoverflow.com/users/296437",
"pm_score": 0,
"selected": false,
"text": "<p>You should use DataKeyNames in your GridView:</p>\n\n<p><code><asp:GridView ID=\"GridView1\" runat=\"server\" DataKeyNames=\"FooID\"></code></p>\n\n<p>And then retrieve it on your code:\n<code>GridView1.DataKeys[0].Value.ToString()</code></p>\n\n<p>Where \"0\" is the number of the row you want to get the \"FooID\"</p>\n"
},
{
"answer_id": 8025100,
"author": "Harshal",
"author_id": 1031824,
"author_profile": "https://Stackoverflow.com/users/1031824",
"pm_score": 2,
"selected": false,
"text": "<p>Please try the following</p>\n\n<pre><code> protected void GridView1_DataBound(object sender, EventArgs e)\n {\n GridView1.Rows[0].Visible = false;\n }\n</code></pre>\n"
},
{
"answer_id": 9844658,
"author": "Anto SJ",
"author_id": 1288930,
"author_profile": "https://Stackoverflow.com/users/1288930",
"pm_score": -1,
"selected": false,
"text": "<p>It can easily be done by SQL </p>\n\n<pre><code>USE YourdatabaseName select * from TableName where Column_Name <> ''\n</code></pre>\n"
},
{
"answer_id": 32940462,
"author": "user5408227",
"author_id": 5408227,
"author_profile": "https://Stackoverflow.com/users/5408227",
"pm_score": 0,
"selected": false,
"text": "<p>If you do not want to display data when the column/row is null: </p>\n\n<pre><code>if (!String.IsNullOrEmpty(item.DataName))\n{\n e.Row.Visible = false;\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2808/"
]
| I am creating a `gridView` that allows adding new rows by adding the controls necessary for the insert into the `FooterTemplate`, but when the `ObjectDataSource` has no records, I add a dummy row as the `FooterTemplate` is only displayed when there is data.
How can I hide this dummy row? I have tried setting `e.row.visible = false` on `RowDataBound` but the row is still visible. | You could handle the gridview's databound event and hide the dummy row. (Don't forget to assign the event property in the aspx code):
```
protected void GridView1_DataBound(object sender, EventArgs e)
{
if (GridView1.Rows.Count == 1)
GridView1.Rows[0].Visible = false;
}
``` |
114,525 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname">JavaScript: var functionName = function() {} vs function functionName() {}</a> </p>
</blockquote>
<p>What's the difference between:</p>
<pre><code>function sum(x, y) {
return x+y;
}
// and
var sum = function (x, y) {
return x+y;
}
</code></pre>
<p>Why is one used over the other?</p>
| [
{
"answer_id": 114573,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 3,
"selected": false,
"text": "<p>The first one is a named function statement, the second one assigns an anonymous function expression to a variable.</p>\n\n<p>The function statement is added to its scope immediately - you don't need to run it before being able to call it, so this works:</p>\n\n<pre><code>var y = sum(1, 2);\n\nfunction sum(x, y) {\n return x + y;\n}\n</code></pre>\n\n<p>But the function expression is only assigned to the variable when the code is executed, so this doesn't work:</p>\n\n<pre><code>// Error here because the function hasn't been assigned to sum yet.\nvar y = sum(1, 2);\n\nvar sum = function(x, y) {\n return x + y;\n}\n</code></pre>\n\n<p>An advantage of the expression form is that you can use it to assign different functions to the expression at different points - so you can change the function, or use a different one under different conditions (such as depending on the browser being used).</p>\n\n<p>An advantage of a named function statement, is that debuggers will be able to display the name. Although, you can name function expressions:</p>\n\n<pre><code>var sum = function sum(x, y) {\n return x + y;\n}\n</code></pre>\n\n<p>But this can be confusing since the two names are actually in different scopes and refer to different things.</p>\n"
},
{
"answer_id": 114579,
"author": "niXar",
"author_id": 19979,
"author_profile": "https://Stackoverflow.com/users/19979",
"pm_score": -1,
"selected": false,
"text": "<p>They mean the exact same thing. It's just syntactic sugar. The latter is IMO more revealing of what JavaScript is really doing; i.e. \"sum\" is just a variable, initialised with a function object, which can then be replaced by something else:</p>\n\n<pre><code>$ js\njs> function sum(x,y) { return x+y; }\njs> sum(1,2);\n3\njs> sum=3\n3\njs> sum(1,2);\ntypein:4: TypeError: sum is not a function\njs> sum\n3\n</code></pre>\n"
},
{
"answer_id": 114593,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 7,
"selected": true,
"text": "<p>The first is known as a named function where the second is known as an anonymous function.</p>\n\n<p>The key practical difference is in when you can use the sum function. For example:-</p>\n\n<pre><code>var z = sum(2, 3);\nfunction sum(x, y) {\n return x+y;\n}\n</code></pre>\n\n<p><code>z</code> is assigned 5 whereas this:-</p>\n\n<pre><code>var z = sum(2, 3);\nvar sum = function(x, y) {\n return x+y;\n}\n</code></pre>\n\n<p>Will fail since at the time the first line has executed the variable sum has not yet been assigned the function.</p>\n\n<p>Named functions are parsed and assigned to their names before execution begins which is why a named function can be utilized in code that precedes its definition.</p>\n\n<p>Variables assigned a function by code can clearly only be used as function once execution has proceeded past the assignment.</p>\n"
},
{
"answer_id": 114596,
"author": "Mike Samuel",
"author_id": 20394,
"author_profile": "https://Stackoverflow.com/users/20394",
"pm_score": 4,
"selected": false,
"text": "<p>The first tends to be used for a few reasons:</p>\n\n<ol>\n<li>The name \"sum\" shows up in the\nstacktrace which makes debugging\neasier in many browsers.</li>\n<li>The name\n\"sum\" can be used inside the\nfunction body which makes it easier\nto use for recursive functions.</li>\n<li>function declarations are \"hoisted\"\nin javascript, so in the first case,\nthe function is guaranteed to be\ndefined exactly once.</li>\n<li><p>Semicolon insertion causes</p>\n\n<pre><code>var f = function (x) { return 4; }\n\n(f)\n</code></pre>\n\n<p>to assign 4 to <code>f</code>.</p></li>\n</ol>\n\n<p>There are a few caveats to keep in mind though.\nDo not do </p>\n\n<pre><code> var sum = function sum(x, y) { ... };\n</code></pre>\n\n<p>on IE 6 since it will result in two function objects being created. Especially confusing if you do</p>\n\n<pre><code> var sum = function mySym(x, y) { ... };\n</code></pre>\n\n<p>According to the standard, \n function sum(x, y) { ... }\ncannot appear inside an if block or a loop body, so different interpreters will treat</p>\n\n<pre><code> if (0) {\n function foo() { return 1; }\n } else {\n function foo() { return 2; }\n }\n return foo();\n</code></pre>\n\n<p>differently.\nIn this case, you should do</p>\n\n<pre><code> var foo;\n if (0) {\n foo = function () { return 1; }\n } ...\n</code></pre>\n"
},
{
"answer_id": 114654,
"author": "user19745",
"author_id": 19745,
"author_profile": "https://Stackoverflow.com/users/19745",
"pm_score": 1,
"selected": false,
"text": "<p>The difference is...</p>\n\n<p>This is a nameless function</p>\n\n<pre><code>var sum = function (x, y) {\n return x+y;\n}\n</code></pre>\n\n<p>So if you alert(sum); you get \"function (x, y) { return x + y; }\" (nameless)\nWhile this is a named function:</p>\n\n<pre><code>function sum(x, y) {\n return x+y;\n}\n</code></pre>\n\n<p>If you alert(sum); now you get \"function <strong>sum</strong>(x, y) { return x + y; }\" (name is sum)</p>\n\n<p>Having named functions help if you are using a profiler because the profiler can tell you function <strong>sum</strong>'s execution time...etcetera instead of an unknown functions's execution time...etcetera </p>\n"
},
{
"answer_id": 114959,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 0,
"selected": false,
"text": "<p>here's an other example:\nfunction sayHello(name) { alert('hello' + name) }</p>\n\n<p>now,suppose you want modify onclick event of a button, such as it says \"hello world\"</p>\n\n<p>you can not write:</p>\n\n<p>yourBtn.onclik = sayHello('world'), because you must provide a function reference.</p>\n\n<p>then you can use second form:\nyourBtn.onclick = function() { sayHello('workld'); }</p>\n\n<p>Ps: sorry for my bad english!</p>\n"
},
{
"answer_id": 2672548,
"author": "thomasrutter",
"author_id": 53212,
"author_profile": "https://Stackoverflow.com/users/53212",
"pm_score": 2,
"selected": false,
"text": "<p>The two code snippets you've posted there will, for almost all purposes, behave the same way.</p>\n\n<p>However, the difference in behaviour is that with the second variant, that function can only be called after that point in the code.</p>\n\n<p>With the first variant, the function is available to code that runs above where the function is declared.</p>\n\n<p>This is because with the second variant, the function is assigned to the variable foo at run time. In the first, the function is assigned to that identifier foo at parse time.</p>\n\n<p><strong>More technical info</strong></p>\n\n<p>Javascript has three ways of defining functions.</p>\n\n<ol>\n<li>Your first example is a <strong>function declaration</strong>. This uses the <em>\"function\" statement</em> to create a function. The function is made available at parse time and can be called anywhere in that scope. You can still store it in a variable or object property later.</li>\n<li>Your second snippet shows a <strong>function expression</strong>. This involves using the <em>\"function\" operator</em> to create a function - the result of that operator can be stored in any variable or object property. The function expression is powerful that way. The function expression is often called an \"anonymous function\" because it does not have to have a name,</li>\n<li>The third way of defining a function is the <strong>\"Function()\" constructor</strong>, which is not shown in your original post. It's not recommended to use this as it works the same way as eval(), which has its problems.</li>\n</ol>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3983/"
]
| >
> **Possible Duplicate:**
>
> [JavaScript: var functionName = function() {} vs function functionName() {}](https://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname)
>
>
>
What's the difference between:
```
function sum(x, y) {
return x+y;
}
// and
var sum = function (x, y) {
return x+y;
}
```
Why is one used over the other? | The first is known as a named function where the second is known as an anonymous function.
The key practical difference is in when you can use the sum function. For example:-
```
var z = sum(2, 3);
function sum(x, y) {
return x+y;
}
```
`z` is assigned 5 whereas this:-
```
var z = sum(2, 3);
var sum = function(x, y) {
return x+y;
}
```
Will fail since at the time the first line has executed the variable sum has not yet been assigned the function.
Named functions are parsed and assigned to their names before execution begins which is why a named function can be utilized in code that precedes its definition.
Variables assigned a function by code can clearly only be used as function once execution has proceeded past the assignment. |
114,527 | <p>I'm really new to .NET, and I still didn't get the hang about how configuration files work.</p>
<p>Every time I search on Google about it I get results about web.config, but I'm writing a Windows Forms application.</p>
<p>I figured out that I need to use the System.Configuration namespace, but the documentation isn't helping.</p>
<p>How do I define that my configuration file is XYZ.xml? Or does it have a "default" name for the configuration file? I still didn't get that.</p>
<p>Also, how do I define a new section? Do I really need to create a class which inherits from ConfigurationSection?</p>
<p>I would like to just have a configuration file with some values like this:</p>
<pre><code><MyCustomValue>1</MyCustomValue>
<MyCustomPath>C:\Some\Path\Here</MyCustomPath>
</code></pre>
<p>Is there a simple way to do it? Can you explain in a simple way how to read and write from/to a simple configuration file?</p>
| [
{
"answer_id": 114551,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 0,
"selected": false,
"text": "<p>What version of .NET and Visual Studio are you using?</p>\n\n<p>When you created the new project, you should have a file in your solution called <em>app.config</em>. That is the default configuration file.</p>\n"
},
{
"answer_id": 114552,
"author": "Chris James",
"author_id": 3193,
"author_profile": "https://Stackoverflow.com/users/3193",
"pm_score": 8,
"selected": true,
"text": "<p>You want to use an App.Config.</p>\n\n<p>When you add a new item to a project there is something called Applications Configuration file. Add that.</p>\n\n<p>Then you add keys in the configuration/appsettings section</p>\n\n<p>Like:</p>\n\n<pre><code><configuration>\n <appSettings>\n <add key=\"MyKey\" value=\"false\"/>\n</code></pre>\n\n<p>Access the members by doing</p>\n\n<pre><code>System.Configuration.ConfigurationSettings.AppSettings[\"MyKey\"];\n</code></pre>\n\n<p>This works in .NET 2 and above.</p>\n"
},
{
"answer_id": 114554,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 3,
"selected": false,
"text": "<p>The best (IMHO) article about .NET Application configuration is on CodeProject, <em><a href=\"http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx\" rel=\"nofollow noreferrer\">Unraveling the Mysteries of .NET 2.0 Configuration</a></em>. And my next favorite (shorter) article about sections in the .NET configuration files is <em><a href=\"http://www.codeproject.com/KB/aspnet/ConfigSections.aspx\" rel=\"nofollow noreferrer\">Understanding Section Handlers - App.config File</a></em>.</p>\n"
},
{
"answer_id": 114578,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 2,
"selected": false,
"text": "<p>In Windows Forms, you have the <code>app.config</code> file, which is very similar to the <code>web.config</code> file. But since what I see you need it for are custom values, I suggest using <em>Settings</em>.</p>\n\n<p>To do that, open your project properties, and then go to settings. If a settings file does not exist you will have a link to create one. Then, you can add the settings to the table you see there, which would generate both the appropriate XML, and a <em>Settings</em> class that can be used to load and save the settings.</p>\n\n<p>The settings class will be named something like <code>DefaultNamespace.Properties.Settings</code>. Then, you can use code similar to:</p>\n\n<pre><code>using DefaultNamespace.Properties;\n\nnamespace DefaultNamespace {\n class Class {\n public int LoadMySettingValue() {\n return Settings.Default.MySettingValue;\n }\n public void SaveMySettingValue(int value) {\n Settings.Default.MySettingValue = value;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 114607,
"author": "Nathan Koop",
"author_id": 18821,
"author_profile": "https://Stackoverflow.com/users/18821",
"pm_score": 3,
"selected": false,
"text": "<p>You should create an <em>App.config</em> file (very similar to <em>web.config</em>).</p>\n\n<p>You should right click on your project, add new item, and choose new <em>\"Application Configuration File\"</em>.</p>\n\n<p>Ensure that you add using System.Configuration in your project.</p>\n\n<p>Then you can add values to it:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <appSettings>\n <add key=\"setting1\" value=\"key\"/>\n </appSettings>\n <connectionStrings>\n <add name=\"prod\" connectionString=\"YourConnectionString\"/>\n </connectionStrings>\n</configuration>\n</code></pre>\n\n<hr>\n\n<pre><code> private void Form1_Load(object sender, EventArgs e)\n {\n string setting = ConfigurationManager.AppSettings[\"setting1\"];\n string conn = ConfigurationManager.ConnectionStrings[\"prod\"].ConnectionString;\n }\n</code></pre>\n\n<hr>\n\n<p>Just a note: <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationsettings.aspx\" rel=\"nofollow noreferrer\">According to Microsoft</a>, you should use ConfigurationManager instead of ConfigurationSettings (see the remarks section):</p>\n\n<blockquote>\n <p>\"The ConfigurationSettings class provides backward compatibility only. For new applications you should use the ConfigurationManager class or WebConfigurationManager class instead. \"</p>\n</blockquote>\n"
},
{
"answer_id": 114649,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 3,
"selected": false,
"text": "<p>The default name for a configuration file is [yourexe].exe.config. So notepad.exe will have a configuration file named notepad.exe.config, in the same folder as the program. This is a general configuration file for all aspects of the CLR and Framework, but it can contain your own settings under an <code><appSettings></code> node.</p>\n\n<p>The <code><appSettings></code> element creates a collection of name-value pairs which can be accessed as <code>System.Configuration.ConfigurationSettings.AppSettings</code>. There is no way to save changes back to the configuration file, however.</p>\n\n<p>It is also possible to add your own custom elements to a configuration file - for example, to define a structured setting - by creating a class that implements <code>IConfigurationSectionHandler</code> and adding it to the <code><configSections></code> element of the configuration file. You can then access it by calling <code>ConfigurationSettings.GetConfig</code>.</p>\n\n<p>.NET 2.0 adds a new class, <code>System.Configuration.ConfigurationManager</code>, which supports multiple files, with per-user overrides of per-system data. It also supports saving modified configurations back to settings files.</p>\n\n<p>Visual Studio creates a file called <code>App.config</code>, which it copies to the EXE folder, with the correct name, when the project is built.</p>\n"
},
{
"answer_id": 114691,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 6,
"selected": false,
"text": "<p>Clarification of previous answers...</p>\n\n<ol>\n<li><p>Add a new file to your project (<em>Add</em> → <em>New Item</em> → <em>Application Configuration File</em>)</p></li>\n<li><p>The new configuration file will appear in Solution Explorer as <em>App.Config</em>.</p></li>\n<li><p>Add your settings into this file using the following as a template</p>\n\n<pre><code><configuration>\n <appSettings>\n <add key=\"setting1\" value=\"key\"/>\n </appSettings>\n <connectionStrings>\n <add name=\"prod\" connectionString=\"YourConnectionString\"/>\n </connectionStrings>\n</configuration>\n</code></pre></li>\n<li><p>Retrieve them like this:</p>\n\n<pre><code>private void Form1_Load(object sender, EventArgs e)\n{\n string setting = ConfigurationManager.AppSettings[\"setting1\"];\n string conn = ConfigurationManager.ConnectionStrings[\"prod\"].ConnectionString;\n}\n</code></pre></li>\n<li><p>When built, your output folder will contain a file called <assemblyname>.exe.config. This will be a copy of the <em>App.Config</em> file. No further work should need to be done by the developer to create this file.</p></li>\n</ol>\n"
},
{
"answer_id": 114800,
"author": "Jamie Ide",
"author_id": 12752,
"author_profile": "https://Stackoverflow.com/users/12752",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with the other answers that point you to app.config. However, rather than reading values directly from app.config, you should create a utility class (AppSettings is the name I use) to read them and expose them as properties. The AppSettings class can be used to aggregate settings from several stores, such as values from app.config and application version info from the assembly (AssemblyVersion and AssemblyFileVersion). </p>\n"
},
{
"answer_id": 118510,
"author": "maxfurni",
"author_id": 20832,
"author_profile": "https://Stackoverflow.com/users/20832",
"pm_score": 5,
"selected": false,
"text": "<p>From a quick read of the previous answers, they look correct, but it doesn't look like anyone mentioned the new configuration facilities in Visual Studio 2008. It still uses <em>app.config</em> (copied at compile time to YourAppName.exe.config), but there is a UI widget to set properties and specify their types. Double-click <em>Settings.settings</em> in your project's \"Properties\" folder.</p>\n\n<p>The best part is that accessing this property from code is typesafe - the compiler will catch obvious mistakes like mistyping the property name. For example, a property called MyConnectionString in <em>app.config</em> would be accessed like:</p>\n\n<pre><code>string s = Properties.Settings.Default.MyConnectionString;\n</code></pre>\n"
},
{
"answer_id": 326066,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code>System.Configuration.ConfigurationSettings.AppSettings[\"MyKey\"];\n</code></pre>\n\n<p>AppSettings has been deprecated and is now considered obsolete\n(<a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationsettings.appsettings(VS.80).aspx\" rel=\"nofollow noreferrer\">link</a>).</p>\n\n<p>In addition, the appSettings section of the <em>app.config</em> has been replaced by the <em>applicationSettings</em> section.</p>\n\n<p>As someone else mentioned, you should be using System.Configuration.ConfigurationManager (<a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(VS.80).aspx\" rel=\"nofollow noreferrer\">link</a>) which is new for .NET 2.0.</p>\n"
},
{
"answer_id": 599116,
"author": "Protagonist",
"author_id": 460006,
"author_profile": "https://Stackoverflow.com/users/460006",
"pm_score": 2,
"selected": false,
"text": "<p>A very simple way of doing this is to use your <a href=\"https://stackoverflow.com/questions/577782/where-to-store-configuration-information/597835#597835\">your own custom <code>Settings</code> class</a>.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
]
| I'm really new to .NET, and I still didn't get the hang about how configuration files work.
Every time I search on Google about it I get results about web.config, but I'm writing a Windows Forms application.
I figured out that I need to use the System.Configuration namespace, but the documentation isn't helping.
How do I define that my configuration file is XYZ.xml? Or does it have a "default" name for the configuration file? I still didn't get that.
Also, how do I define a new section? Do I really need to create a class which inherits from ConfigurationSection?
I would like to just have a configuration file with some values like this:
```
<MyCustomValue>1</MyCustomValue>
<MyCustomPath>C:\Some\Path\Here</MyCustomPath>
```
Is there a simple way to do it? Can you explain in a simple way how to read and write from/to a simple configuration file? | You want to use an App.Config.
When you add a new item to a project there is something called Applications Configuration file. Add that.
Then you add keys in the configuration/appsettings section
Like:
```
<configuration>
<appSettings>
<add key="MyKey" value="false"/>
```
Access the members by doing
```
System.Configuration.ConfigurationSettings.AppSettings["MyKey"];
```
This works in .NET 2 and above. |
114,541 | <p>I want to write a <a href="http://getsongbird.com/" rel="noreferrer">Songbird</a> extension binds the multimedia keys available on all Apple Mac OS X platforms. Unfortunately this isn't an easy google search and I can't find any docs.</p>
<p>Can anyone point me resources on accessing these keys or tell me how to do it?</p>
<p>I have extensive programming experience, but this will be my first time coding in both MacOSX and <a href="http://wiki.songbirdnest.com/Developer/Developer_Intro/Extensions" rel="noreferrer">XUL</a> (Firefox, etc), so any tips on either are welcome.</p>
<p>Please note that these are not regular key events. I assume it must be a different type of system event that I will need to hook or subscribe to.</p>
| [
{
"answer_id": 115333,
"author": "rami",
"author_id": 9629,
"author_profile": "https://Stackoverflow.com/users/9629",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.manpagez.com/man/1/xev/\" rel=\"nofollow noreferrer\"><code>xev</code></a> might help you if you want to find out which codes are being sent by multimedia keys.</p>\n"
},
{
"answer_id": 135259,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 1,
"selected": false,
"text": "<p>Are you sure your multimedia keys are working in your installation? Every single key generates a scan code which is translated into a key code by the kernel. If xev doesn't show you any keycodes I guess those scan codes aren't mapped and so the kernel has no knowledge of them. </p>\n\n<p><a href=\"http://gentoo-wiki.com/HOWTO_Use_Multimedia_Keys\" rel=\"nofollow noreferrer\">http://gentoo-wiki.com/HOWTO_Use_Multimedia_Keys</a> has a nice explanation of finding key codes and offers help on how you can find raw scan codes and translate them into key codes.</p>\n"
},
{
"answer_id": 423534,
"author": "Rhythmic Fistman",
"author_id": 22147,
"author_profile": "https://Stackoverflow.com/users/22147",
"pm_score": 3,
"selected": true,
"text": "<p>This blog post has a solution:</p>\n\n<p><a href=\"http://www.rogueamoeba.com/utm/posts/Article/mediaKeys-2007-09-29-17-00.html\" rel=\"nofollow noreferrer\">http://www.rogueamoeba.com/utm/posts/Article/mediaKeys-2007-09-29-17-00.html</a></p>\n\n<p>You basically need to subclass <code>NSApplication</code> and override <code>sendEvent</code>,<br>\nlooking for special scan codes. I don't know what songbird is, but if it's<br>\nnot a real application then I doubt you'll be able to do this.</p>\n\n<p>Or maybe you can, a simple category may suffice:</p>\n\n<pre><code>@implementation NSApplication(WantMediaKeysCategoryKBye)\n- (void)sendEvent: (NSEvent*)event\n{\n // intercept media keys here\n}\n@end\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15948/"
]
| I want to write a [Songbird](http://getsongbird.com/) extension binds the multimedia keys available on all Apple Mac OS X platforms. Unfortunately this isn't an easy google search and I can't find any docs.
Can anyone point me resources on accessing these keys or tell me how to do it?
I have extensive programming experience, but this will be my first time coding in both MacOSX and [XUL](http://wiki.songbirdnest.com/Developer/Developer_Intro/Extensions) (Firefox, etc), so any tips on either are welcome.
Please note that these are not regular key events. I assume it must be a different type of system event that I will need to hook or subscribe to. | This blog post has a solution:
<http://www.rogueamoeba.com/utm/posts/Article/mediaKeys-2007-09-29-17-00.html>
You basically need to subclass `NSApplication` and override `sendEvent`,
looking for special scan codes. I don't know what songbird is, but if it's
not a real application then I doubt you'll be able to do this.
Or maybe you can, a simple category may suffice:
```
@implementation NSApplication(WantMediaKeysCategoryKBye)
- (void)sendEvent: (NSEvent*)event
{
// intercept media keys here
}
@end
``` |
114,543 | <p>How can I horizontally center a <code><div></code> within another <code><div></code> using CSS?</p>
<pre class="lang-html prettyprint-override"><code><div id="outer">
<div id="inner">Foo foo</div>
</div>
</code></pre>
| [
{
"answer_id": 114549,
"author": "Justin Poliey",
"author_id": 6967,
"author_profile": "https://Stackoverflow.com/users/6967",
"pm_score": 13,
"selected": true,
"text": "<p>You can apply this CSS to the inner <code><div></code>:</p>\n<pre class=\"lang-css prettyprint-override\"><code>#inner {\n width: 50%;\n margin: 0 auto;\n}\n</code></pre>\n<p>Of course, you don't have to set the <code>width</code> to <code>50%</code>. Any width less than the containing <code><div></code> will work. The <code>margin: 0 auto</code> is what does the actual centering.</p>\n<p>If you are targeting <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_8\" rel=\"noreferrer\">Internet Explorer 8</a> (and later), it might be better to have this instead:</p>\n<pre class=\"lang-css prettyprint-override\"><code>#inner {\n display: table;\n margin: 0 auto;\n}\n</code></pre>\n<p>It will make the inner element center horizontally and it works without setting a specific <code>width</code>.</p>\n<p>Working example here:</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-css lang-css prettyprint-override\"><code>#inner {\n display: table;\n margin: 0 auto;\n border: 1px solid black;\n}\n\n#outer {\n border: 1px solid red;\n width:100%\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h2>EDIT</h2>\n<p>With <code>flexbox</code> it is very easy to style the div horizontally and vertically centered.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#inner { \n border: 0.05em solid black;\n}\n\n#outer {\n border: 0.05em solid red;\n width:100%;\n display: flex;\n justify-content: center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>To align the div vertically centered, use the property <code>align-items: center</code>.</p>\n"
},
{
"answer_id": 114553,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 7,
"selected": false,
"text": "<p>It cannot be centered if you don't give it a width. Otherwise, it will take, by default, the whole horizontal space.</p>\n"
},
{
"answer_id": 1180400,
"author": "Sneakyness",
"author_id": 142632,
"author_profile": "https://Stackoverflow.com/users/142632",
"pm_score": 7,
"selected": false,
"text": "<p>Set the <code>width</code> and set <code>margin-left</code> and <code>margin-right</code> to <code>auto</code>. That's <strong>for horizontal only</strong>, though. If you want both ways, you'd just do it both ways. Don't be afraid to experiment; it's not like you'll break anything.</p>\n"
},
{
"answer_id": 4753609,
"author": "Alfred",
"author_id": 291727,
"author_profile": "https://Stackoverflow.com/users/291727",
"pm_score": 10,
"selected": false,
"text": "<p>If you don't want to set a fixed width on the inner <code>div</code> you could do something 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-css lang-css prettyprint-override\"><code>#outer {\r\n width: 100%;\r\n text-align: center;\r\n}\r\n\r\n#inner {\r\n display: inline-block;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\"> \r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>That makes the inner <code>div</code> into an inline element that can be centered with <code>text-align</code>.</p>\n"
},
{
"answer_id": 6460947,
"author": "James Moberg",
"author_id": 693068,
"author_profile": "https://Stackoverflow.com/users/693068",
"pm_score": 6,
"selected": false,
"text": "<p>I recently had to center a \"hidden\" div (i.e., <code>display:none;</code>) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery code to display the hidden div and then update the CSS content to the automatic generated width of the table and change the margin to center it. (The display toggle is triggered by clicking on a link, but this code wasn't necessary to display.)</p>\n\n<p><strong>NOTE:</strong> I'm sharing this code, because Google brought me to this Stack Overflow solution and everything would have worked except that hidden elements don't have any width and can't be resized/centered until after they are displayed.</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>$(function(){\r\n $('#inner').show().width($('#innerTable').width()).css('margin','0 auto');\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\r\n<div id=\"inner\" style=\"display:none;\">\r\n <form action=\"\">\r\n <table id=\"innerTable\">\r\n <tr><td>Name:</td><td><input type=\"text\"></td></tr>\r\n <tr><td>Email:</td><td><input type=\"text\"></td></tr>\r\n <tr><td>Email:</td><td><input type=\"submit\"></td></tr>\r\n </table>\r\n </form>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 8347427,
"author": "Nuno",
"author_id": 501066,
"author_profile": "https://Stackoverflow.com/users/501066",
"pm_score": 8,
"selected": false,
"text": "<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-css lang-css prettyprint-override\"><code>#centered {\n position: absolute;\n left: 50%;\n margin-left: -100px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\" style=\"width:200px\">\n <div id=\"centered\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Make sure the parent element is <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/position\" rel=\"noreferrer\">positioned</a>, i.e., relative, fixed, absolute, or sticky.</p>\n<p>If you don't know the width of your div, you can use <code>transform:translateX(-50%);</code> instead of the negative margin.</p>\n<p>With <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/calc\" rel=\"noreferrer\">CSS calc()</a>, the code can get even simpler:</p>\n<br>\n<pre class=\"lang-css prettyprint-override\"><code>.centered {\n width: 200px;\n position: absolute;\n left: calc(50% - 100px);\n}\n</code></pre>\n<p>The principle is still the same; put the item in the middle and compensate for the width.</p>\n"
},
{
"answer_id": 9655404,
"author": "neoneye",
"author_id": 78336,
"author_profile": "https://Stackoverflow.com/users/78336",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"http://www.w3schools.com/cssref/css3_pr_box-align.asp\" rel=\"noreferrer\">CSS 3's box-align property</a></p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#outer {\n width: 100%;\n height: 100%;\n display: box;\n box-orient: horizontal;\n box-pack: center;\n box-align: center;\n}\n</code></pre>\n"
},
{
"answer_id": 10568273,
"author": "Salman von Abbas",
"author_id": 362006,
"author_profile": "https://Stackoverflow.com/users/362006",
"pm_score": 7,
"selected": false,
"text": "<p>If you don't want to set a fixed width and don't want the extra margin, add <code>display: inline-block</code> to your element.</p>\n\n<p>You can use:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#element {\n display: table;\n margin: 0 auto;\n}\n</code></pre>\n"
},
{
"answer_id": 10836683,
"author": "ch2o",
"author_id": 982488,
"author_profile": "https://Stackoverflow.com/users/982488",
"pm_score": 6,
"selected": false,
"text": "<p>For Firefox and Chrome:</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-html lang-html prettyprint-override\"><code><div style=\"width:100%;\">\r\n <div style=\"width: 50%; margin: 0px auto;\">Text</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>For Internet Explorer, Firefox, and Chrome:</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-html lang-html prettyprint-override\"><code><div style=\"width:100%; text-align:center;\">\r\n <div style=\"width: 50%; margin: 0px auto; text-align:left;\">Text</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The <code>text-align:</code> property is optional for modern browsers, but it is necessary in Internet Explorer Quirks Mode for legacy browsers support.</p>\n"
},
{
"answer_id": 12196466,
"author": "kongaraju",
"author_id": 1307915,
"author_profile": "https://Stackoverflow.com/users/1307915",
"pm_score": 9,
"selected": false,
"text": "<p>The best approaches are with CSS3.</p>\n<h2>The old box model (deprecated)</h2>\n<p><code>display: box</code> and its properties <code>box-pack</code>, <code>box-align</code>, <code>box-orient</code>, <code>box-direction</code> etc. have been replaced by flexbox. While they may still work, they are not recommended to be used in production.</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-css lang-css prettyprint-override\"><code>#outer {\n width: 100%;\n /* Firefox */\n display: -moz-box;\n -moz-box-pack: center;\n -moz-box-align: center;\n /* Safari and Chrome */\n display: -webkit-box;\n -webkit-box-pack: center;\n -webkit-box-align: center;\n /* W3C */\n display: box;\n box-pack: center;\n box-align: center;\n}\n\n#inner {\n width: 50%;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>According to your usability you may also use the <code>box-orient, box-flex, box-direction</code> properties.</p>\n<h2>The modern box model with Flexbox</h2>\n<pre class=\"lang-css prettyprint-override\"><code>#outer {\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n justify-content: center;\n align-items: center;\n}\n</code></pre>\n<h3>Read more about centering the child elements</h3>\n<ul>\n<li><p><a href=\"http://www.w3.org/TR/css3-box/\" rel=\"noreferrer\">Link 2</a></p>\n</li>\n<li><p><a href=\"http://www.w3.org/TR/CSS2/box.html\" rel=\"noreferrer\">Link 3</a></p>\n</li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/box-align\" rel=\"noreferrer\">Link 4</a></p>\n</li>\n</ul>\n<p>And <strong>this explains why the box model is the best approach</strong>:</p>\n<ul>\n<li><em><a href=\"https://stackoverflow.com/questions/2429819/why-is-the-w3c-box-model-considered-better\">Why is the W3C box model considered better?</a></em></li>\n</ul>\n"
},
{
"answer_id": 15412749,
"author": "Ray",
"author_id": 1372225,
"author_profile": "https://Stackoverflow.com/users/1372225",
"pm_score": -1,
"selected": false,
"text": "<p>Centering: Auto-width Margins</p>\n\n<p>This box is horizontally centered by setting its right and left margin widths to \"auto\". This is the preferred way to accomplish horizontal centering with CSS and works very well in most browsers with CSS 2 support. Unfortunately, Internet Explorer 5/Windows does not respond to this method - a shortcoming of that browser, not the technique.</p>\n\n<p>There is a simple workaround. (A pause while you fight back the nausea induced by that word.) Ready? Internet Explorer 5/Windows incorrectly applies the CSS \"text-align\" attribute to block-level elements. Declaring \"text-align:center\" for the containing block-level element (often the BODY element) horizontally centers the box in Internet Explorer 5/Windows.</p>\n\n<p>There is a side effect of this workaround: the CSS \"text-align\" attribute is inherited, centering inline content. It is often necessary to explicitly set the \"text-align\" attribute for the centered box, counteracting the effects of the Internet Explorer 5/Windows workaround. The relevant CSS follows.</p>\n\n<pre><code>body {\n margin: 50px 0px;\n padding: 0px;\n text-align: center;\n}\n\n#Content {\n width: 500px;\n margin: 0px auto;\n text-align: left;\n padding: 15px;\n border: 1px dashed #333;\n background-color: #EEE;\n}\n</code></pre>\n\n<p><a href=\"http://bluerobot.com/web/css/center1.html\" rel=\"nofollow noreferrer\">http://bluerobot.com/web/css/center1.html</a></p>\n"
},
{
"answer_id": 15860345,
"author": "william44isme",
"author_id": 2075466,
"author_profile": "https://Stackoverflow.com/users/2075466",
"pm_score": 6,
"selected": false,
"text": "<p>The way I usually do it is using absolute position:</p>\n<pre class=\"lang-css prettyprint-override\"><code>#inner{\n left: 0;\n right: 0;\n margin-left: auto;\n margin-right: auto;\n position: absolute;\n}\n</code></pre>\n<p>The outer div doesn't need any extra properties for this to work.</p>\n"
},
{
"answer_id": 16144913,
"author": "Danield",
"author_id": 703717,
"author_profile": "https://Stackoverflow.com/users/703717",
"pm_score": 8,
"selected": false,
"text": "<p>Some posters have mentioned the CSS 3 way to center using <code>display:box</code>.</p>\n\n<p>This syntax is outdated and shouldn't be used anymore. [See also <a href=\"http://css-tricks.com/old-flexbox-and-new-flexbox/\" rel=\"noreferrer\">this post]</a>.</p>\n\n<p>So just for completeness here is the latest way to center in CSS 3 using the <strong><a href=\"http://www.w3.org/TR/css3-flexbox/\" rel=\"noreferrer\">Flexible Box Layout Module</a></strong>.</p>\n\n<p>So if you have simple markup like:</p>\n\n<pre><code><div class=\"box\">\n <div class=\"item1\">A</div>\n <div class=\"item2\">B</div>\n <div class=\"item3\">C</div>\n</div>\n</code></pre>\n\n<p>...and you want to center your items within the box, here's what you need on the parent element (.box):</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.box {\n display: flex;\n flex-wrap: wrap; /* Optional. only if you want the items to wrap */\n justify-content: center; /* For horizontal alignment */\n align-items: center; /* For vertical alignment */\n}\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.box {\r\n display: flex;\r\n flex-wrap: wrap;\r\n /* Optional. only if you want the items to wrap */\r\n justify-content: center;\r\n /* For horizontal alignment */\r\n align-items: center;\r\n /* For vertical alignment */\r\n}\r\n* {\r\n margin: 0;\r\n padding: 0;\r\n}\r\nhtml,\r\nbody {\r\n height: 100%;\r\n}\r\n.box {\r\n height: 200px;\r\n display: flex;\r\n flex-wrap: wrap;\r\n justify-content: center;\r\n align-items: center;\r\n border: 2px solid tomato;\r\n}\r\n.box div {\r\n margin: 0 10px;\r\n width: 100px;\r\n}\r\n.item1 {\r\n height: 50px;\r\n background: pink;\r\n}\r\n.item2 {\r\n background: brown;\r\n height: 100px;\r\n}\r\n.item3 {\r\n height: 150px;\r\n background: orange;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"box\">\r\n <div class=\"item1\">A</div>\r\n <div class=\"item2\">B</div>\r\n <div class=\"item3\">C</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>If you need to support older browsers which use older syntax for flexbox <a href=\"http://the-echoplex.net/flexyboxes/\" rel=\"noreferrer\">here's</a> a good place to look.</p>\n"
},
{
"answer_id": 16776988,
"author": "BenjaminRH",
"author_id": 941158,
"author_profile": "https://Stackoverflow.com/users/941158",
"pm_score": 6,
"selected": false,
"text": "<p>I recently found an approach:</p>\n\n<pre><code>#outer {\n position: absolute;\n left: 50%;\n}\n\n#inner {\n position: relative;\n left: -50%;\n}\n</code></pre>\n\n<p>Both elements must be the same width to function correctly.</p>\n"
},
{
"answer_id": 16954310,
"author": "aamirha",
"author_id": 949033,
"author_profile": "https://Stackoverflow.com/users/949033",
"pm_score": 4,
"selected": false,
"text": "<p>I have applied the inline style to the inner div. Use this one:</p>\n\n<pre><code><div id=\"outer\" style=\"width:100%\"> \n <div id=\"inner\" style=\"display:table;margin:0 auto;\">Foo foo</div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 17743761,
"author": "Ankit Jain",
"author_id": 2594679,
"author_profile": "https://Stackoverflow.com/users/2594679",
"pm_score": 6,
"selected": false,
"text": "<p>Use:</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-css lang-css prettyprint-override\"><code>#outerDiv {\r\n width: 500px;\r\n}\r\n\r\n#innerDiv {\r\n width: 200px;\r\n margin: 0 auto;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outerDiv\">\r\n <div id=\"innerDiv\">Inner Content</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 18739996,
"author": "Tom Maton",
"author_id": 911553,
"author_profile": "https://Stackoverflow.com/users/911553",
"pm_score": 8,
"selected": false,
"text": "<p>I've created <a href=\"http://codepen.io/tom-maton/pen/oqsEJ\" rel=\"noreferrer\">this example</a> to show how to <strong>vertically</strong> and <strong>horizontally</strong> <code>align</code>.</p>\n<p>The code is basically this:</p>\n<pre class=\"lang-css prettyprint-override\"><code>#outer {\n position: relative;\n}\n</code></pre>\n<p>and...</p>\n<pre class=\"lang-css prettyprint-override\"><code>#inner {\n margin: auto;\n position: absolute;\n left:0;\n right: 0;\n top: 0;\n bottom: 0;\n}\n</code></pre>\n<p>And it will stay in the <code>center</code> even when you <strong>resize</strong> your screen.</p>\n"
},
{
"answer_id": 19123062,
"author": "Rajesh",
"author_id": 1114506,
"author_profile": "https://Stackoverflow.com/users/1114506",
"pm_score": 3,
"selected": false,
"text": "<p>Use the below CSS content for <code>#inner</code> div:</p>\n\n<pre><code>#inner {\n width: 50%;\n margin-left: 25%;\n}\n</code></pre>\n\n<p>I mostly use this CSS content to center <em>div</em>s.</p>\n"
},
{
"answer_id": 19359956,
"author": "Kenma",
"author_id": 1460756,
"author_profile": "https://Stackoverflow.com/users/1460756",
"pm_score": 5,
"selected": false,
"text": "<p>You can do something like this</p>\n\n<pre><code>#container {\n display: table;\n width: <width of your container>;\n height: <height of your container>;\n}\n\n#inner {\n width: <width of your center div>;\n display: table-cell;\n margin: 0 auto;\n text-align: center;\n vertical-align: middle;\n}\n</code></pre>\n\n<p>This will also align the <code>#inner</code> vertically. If you don't want to, remove the <code>display</code> and <code>vertical-align</code> properties;</p>\n"
},
{
"answer_id": 19589133,
"author": "Willem de Wit",
"author_id": 1474739,
"author_profile": "https://Stackoverflow.com/users/1474739",
"pm_score": 6,
"selected": false,
"text": "<p>Chris Coyier who wrote an <a href=\"http://css-tricks.com/centering-in-the-unknown/\" rel=\"noreferrer\">excellent post</a> on 'Centering in the Unknown' on his blog. It's a roundup of multiple solutions. I posted one that isn't posted in this question. It has more browser support than the <a href=\"https://en.wikipedia.org/wiki/CSS_Flexible_Box_Layout\" rel=\"noreferrer\">Flexbox</a> solution, and you're not using <code>display: table;</code> which could break other things.</p>\n\n<pre><code>/* This parent can be any width and height */\n.outer {\n text-align: center;\n}\n\n/* The ghost, nudged to maintain perfect centering */\n.outer:before {\n content: '.';\n display: inline-block;\n height: 100%;\n vertical-align: middle;\n width: 0;\n overflow: hidden;\n}\n\n/* The element to be centered, can\n also be of any width and height */\n.inner {\n display: inline-block;\n vertical-align: middle;\n width: 300px;\n}\n</code></pre>\n"
},
{
"answer_id": 19715517,
"author": "Josh Mc",
"author_id": 685404,
"author_profile": "https://Stackoverflow.com/users/685404",
"pm_score": 3,
"selected": false,
"text": "<p>A nice thing I recently found, mixing the use of <code>line-height</code>+<code>vertical-align</code> and the <code>50%</code> left trick, you can <code>center</code> a dynamically sized box inside another dynamically sized box, on both the horizontal and vertical using pure CSS.</p>\n<p>Note you must use spans (and <code>inline-block</code>), tested in modern browsers + Internet Explorer 8.\n<strong>HTML:</strong></p>\n<pre class=\"lang-html prettyprint-override\"><code><h1>Center dynamic box using only css test</h1>\n<div class="container">\n <div class="center">\n <div class="center-container">\n <span class="dyn-box">\n <div class="dyn-head">This is a head</div>\n <div class="dyn-body">\n This is a body<br />\n Content<br />\n Content<br />\n Content<br />\n Content<br />\n </div>\n </span>\n </div>\n </div>\n</div>\n</code></pre>\n<p><strong>CSS:</strong></p>\n<pre class=\"lang-css prettyprint-override\"><code>.container {\n position: absolute;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n overflow: hidden;\n}\n\n.center {\n position: absolute;\n left: 50%;\n top: 50%;\n}\n\n.center-container {\n position: absolute;\n left: -2500px;\n top: -2500px;\n width: 5000px;\n height: 5000px;\n line-height: 5000px;\n text-align: center;\n overflow: hidden;\n}\n\n.dyn-box {\n display: inline-block;\n vertical-align: middle;\n line-height: 100%;\n /* Purely asthetic below this point */\n background: #808080;\n padding: 13px;\n border-radius: 11px;\n font-family: arial;\n}\n\n.dyn-head {\n background: red;\n color: white;\n min-width: 300px;\n padding: 20px;\n font-size: 23px;\n}\n\n.dyn-body {\n padding: 10px;\n background: white;\n color: red;\n}\n</code></pre>\n<p><a href=\"http://jsfiddle.net/7mQS5/16/\" rel=\"nofollow noreferrer\">See example here</a>.</p>\n"
},
{
"answer_id": 19792397,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Try playing around with </p>\n\n<pre><code>margin: 0 auto;\n</code></pre>\n\n<p>If you want to center your text too, try using:</p>\n\n<pre><code>text-align: center;\n</code></pre>\n"
},
{
"answer_id": 20023094,
"author": "Pnsadeghy",
"author_id": 2148893,
"author_profile": "https://Stackoverflow.com/users/2148893",
"pm_score": 5,
"selected": false,
"text": "<p>One option existed that I found:</p>\n\n<p>Everybody says to use:</p>\n\n<pre><code>margin: auto 0;\n</code></pre>\n\n<p>But there is another option. Set this property for the parent div. It\nworks perfectly anytime:</p>\n\n<pre><code>text-align: center;\n</code></pre>\n\n<p>And see, child go center.</p>\n\n<p>And finally CSS for you:</p>\n\n<pre><code>#outer{\n text-align: center;\n display: block; /* Or inline-block - base on your need */\n}\n\n#inner\n{\n position: relative;\n margin: 0 auto; /* It is good to be */\n}\n</code></pre>\n"
},
{
"answer_id": 20339458,
"author": "user2952495",
"author_id": 2952495,
"author_profile": "https://Stackoverflow.com/users/2952495",
"pm_score": -1,
"selected": false,
"text": "<pre><code><center>\n</code></pre>\n\n<p>I am spoiled with the most simple center known?</p>\n\n<pre><code></center>\n</code></pre>\n"
},
{
"answer_id": 20369553,
"author": "Lalit Kumar Maurya",
"author_id": 1637683,
"author_profile": "https://Stackoverflow.com/users/1637683",
"pm_score": 6,
"selected": false,
"text": "<p>For example, see <a href=\"http://jsfiddle.net/uCdPK/\" rel=\"noreferrer\">this link</a> and the snippet below:</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-css lang-css prettyprint-override\"><code>div#outer {\r\n height: 120px;\r\n background-color: red;\r\n}\r\n\r\ndiv#inner {\r\n width: 50%;\r\n height: 100%;\r\n background-color: green;\r\n margin: 0 auto;\r\n text-align: center; /* For text alignment to center horizontally. */\r\n line-height: 120px; /* For text alignment to center vertically. */\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\" style=\"width:100%;\">\r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>If you have a lot of children under a parent, so your CSS content must be like this <a href=\"http://jsfiddle.net/uCdPK/2/\" rel=\"noreferrer\">example on fiddle</a>.</p>\n\n<p>The HTML content look likes this:</p>\n\n<pre><code><div id=\"outer\" style=\"width:100%;\">\n <div class=\"inner\"> Foo Text </div>\n <div class=\"inner\"> Foo Text </div>\n <div class=\"inner\"> Foo Text </div>\n <div class=\"inner\"> </div>\n <div class=\"inner\"> </div>\n <div class=\"inner\"> </div>\n <div class=\"inner\"> </div>\n <div class=\"inner\"> </div>\n <div class=\"inner\"> Foo Text </div>\n</div>\n</code></pre>\n\n<p>Then see this <a href=\"http://jsfiddle.net/uCdPK/2/\" rel=\"noreferrer\">example on fiddle</a>.</p>\n"
},
{
"answer_id": 21193027,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 5,
"selected": false,
"text": "<p><strong>If width of the content is unknown you can use the following method</strong>. Suppose we have these two elements:</p>\n\n<ul>\n<li><code>.outer</code> -- full width</li>\n<li><code>.inner</code> -- no width set (but a max-width could be specified)</li>\n</ul>\n\n<p>Suppose the computed width of the elements are 1000 pixels and 300 pixels respectively. Proceed as follows:</p>\n\n<ol>\n<li>Wrap <code>.inner</code> inside <code>.center-helper</code></li>\n<li>Make <code>.center-helper</code> an inline block; it becomes the same size as <code>.inner</code> making it 300 pixels wide.</li>\n<li>Push <code>.center-helper</code> 50% right relative to its parent; this places its left at 500 pixels wrt. outer.</li>\n<li>Push <code>.inner</code> 50% left relative to its parent; this places its left at -150 pixels wrt. center helper which means its left is at 500 - 150 = 350 pixels wrt. outer.</li>\n<li>Set overflow on <code>.outer</code> to hidden to prevent horizontal scrollbar.</li>\n</ol>\n\n<p>Demo:</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-css lang-css prettyprint-override\"><code>body {\r\n font: medium sans-serif;\r\n}\r\n\r\n.outer {\r\n overflow: hidden;\r\n background-color: papayawhip;\r\n}\r\n\r\n.center-helper {\r\n display: inline-block;\r\n position: relative;\r\n left: 50%;\r\n background-color: burlywood;\r\n}\r\n\r\n.inner {\r\n display: inline-block;\r\n position: relative;\r\n left: -50%;\r\n background-color: wheat;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\r\n <div class=\"center-helper\">\r\n <div class=\"inner\">\r\n <h1>A div with no defined width</h1>\r\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br>\r\n Duis condimentum sem non turpis consectetur blandit.<br>\r\n Donec dictum risus id orci ornare tempor.<br>\r\n Proin pharetra augue a lorem elementum molestie.<br>\r\n Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p>\r\n </div>\r\n </div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 21402241,
"author": "caniz",
"author_id": 3178923,
"author_profile": "https://Stackoverflow.com/users/3178923",
"pm_score": 5,
"selected": false,
"text": "<p>Here is what you want in the shortest way.</p>\n<p><strong><a href=\"http://jsfiddle.net/8qYcn/\" rel=\"nofollow noreferrer\">JSFIDDLE</a></strong></p>\n<pre class=\"lang-css prettyprint-override\"><code>#outer {\n margin - top: 100 px;\n height: 500 px; /* you can set whatever you want */\n border: 1 px solid# ccc;\n}\n\n#inner {\n border: 1 px solid# f00;\n position: relative;\n top: 50 % ;\n transform: translateY(-50 % );\n}\n</code></pre>\n"
},
{
"answer_id": 21706557,
"author": "Miguel Leite",
"author_id": 1732465,
"author_profile": "https://Stackoverflow.com/users/1732465",
"pm_score": 5,
"selected": false,
"text": "<p>Well, I managed to find a solution that maybe will fit all situations, but uses JavaScript:</p>\n\n<p>Here's the structure:</p>\n\n<pre><code><div class=\"container\">\n <div class=\"content\">Your content goes here!</div>\n <div class=\"content\">Your content goes here!</div>\n <div class=\"content\">Your content goes here!</div>\n</div>\n</code></pre>\n\n<p>And here's the JavaScript snippet:</p>\n\n<pre><code>$(document).ready(function() {\n $('.container .content').each( function() {\n container = $(this).closest('.container');\n content = $(this);\n\n containerHeight = container.height();\n contentHeight = content.height();\n\n margin = (containerHeight - contentHeight) / 2;\n content.css('margin-top', margin);\n })\n});\n</code></pre>\n\n<p>If you want to use it in a responsive approach, you can add the following:</p>\n\n<pre><code>$(window).resize(function() {\n $('.container .content').each( function() {\n container = $(this).closest('.container');\n content = $(this);\n\n containerHeight = container.height();\n contentHeight = content.height();\n\n margin = (containerHeight - contentHeight) / 2;\n content.css('margin-top', margin);\n })\n});\n</code></pre>\n"
},
{
"answer_id": 22273883,
"author": "uSeRnAmEhAhAhAhAhA",
"author_id": 2645707,
"author_profile": "https://Stackoverflow.com/users/2645707",
"pm_score": 1,
"selected": false,
"text": "<p>I know I'm a bit late to answering this question, and I haven't bothered to read every single answer so this <em>may</em> be a duplicate. <a href=\"http://jsfiddle.net/spikey/FLL5Z/\" rel=\"nofollow\">Here's my take</a>:</p>\n\n<pre><code>inner { width: 50%; background-color: Khaki; margin: 0 auto; }\n</code></pre>\n"
},
{
"answer_id": 23714832,
"author": "iamnotsam",
"author_id": 362477,
"author_profile": "https://Stackoverflow.com/users/362477",
"pm_score": 7,
"selected": false,
"text": "<h2>Centering a div of unknown height and width</h2>\n<p>Horizontally and vertically. It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet & Explorer & 10, Opera, etc.)</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-css lang-css prettyprint-override\"><code>.content {\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"content\">This works with any content</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Tinker with it further on <a href=\"http://codepen.io/storypixel/pen/Dbdiq\" rel=\"noreferrer\">Codepen</a> or on <a href=\"http://jsbin.com/zureq/1\" rel=\"noreferrer\">JSBin</a>.</p>\n"
},
{
"answer_id": 25287376,
"author": "hossein ketabi",
"author_id": 2757573,
"author_profile": "https://Stackoverflow.com/users/2757573",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code><div id=\"a\">\n <div id=\"b\"></div>\n</div>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>#a{\n border: 1px solid red;\n height: 120px;\n width: 400px\n}\n\n#b{\n border: 1px solid blue;\n height: 90px;\n width: 300px;\n position: relative;\n margin-left: auto;\n margin-right: auto;\n}\n</code></pre>\n"
},
{
"answer_id": 25446740,
"author": "joan16v",
"author_id": 1398876,
"author_profile": "https://Stackoverflow.com/users/1398876",
"pm_score": 5,
"selected": false,
"text": "<p>The easiest way:</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-css lang-css prettyprint-override\"><code>#outer {\r\n width: 100%;\r\n text-align: center;\r\n}\r\n#inner {\r\n margin: auto;\r\n width: 200px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\r\n <div id=\"inner\">Blabla</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 25942594,
"author": "Gerald Goshorn",
"author_id": 4056805,
"author_profile": "https://Stackoverflow.com/users/4056805",
"pm_score": 2,
"selected": false,
"text": "<p>I just use the simplest solution, but it works in all browsers:</p>\n\n<pre><code><!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <title>center a div within a div?</title>\n <style type=\"text/css\">\n *{\n margin: 0;\n padding: 0;\n }\n\n #outer{\n width: 80%;\n height: 500px;\n background-color: #003;\n margin: 0 auto;\n }\n\n #outer p{\n color: #FFF;\n text-align: center;\n }\n\n #inner{\n background-color: #901;\n width: 50%;\n height: 100px;\n margin: 0 auto;\n\n }\n\n #inner p{\n color: #FFF;\n text-align: center;\n }\n </style>\n </head>\n\n <body>\n <div id=\"outer\"><p>this is the outer div</p>\n <div id=\"inner\">\n <p>this is the inner div</p>\n </div>\n </div>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 25946329,
"author": "sarath",
"author_id": 2614847,
"author_profile": "https://Stackoverflow.com/users/2614847",
"pm_score": 4,
"selected": false,
"text": "<p>If anyone would like a jQuery solution for center align these divs:</p>\n\n<pre><code>$(window).bind(\"load\", function() {\n var wwidth = $(\"#outer\").width();\n var width = $('#inner').width();\n $('#inner').attr(\"style\", \"padding-left: \" + wwidth / 2 + \"px; margin-left: -\" + width / 2 + \"px;\");\n});\n</code></pre>\n"
},
{
"answer_id": 26072829,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>First of all: You need to give a width to the second div:</p>\n\n<p>For example:</p>\n\n<h3>HTML</h3>\n\n<pre><code><div id=\"outter\">\n <div id=\"inner\"Centered content\">\n </div\n</div>\n</code></pre>\n\n<h3>CSS:</h3>\n\n<pre><code> #inner{\n width: 50%;\n margin: auto;\n}\n</code></pre>\n\n<p>Note that if you don't give it a width, it will take the whole width of the line.</p>\n"
},
{
"answer_id": 27965715,
"author": "Cees Timmerman",
"author_id": 819417,
"author_profile": "https://Stackoverflow.com/users/819417",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of multiple wrappers and/or auto margins, this simple solution works for me:</p>\n\n<pre><code><div style=\"top: 50%; left: 50%;\n height: 100px; width: 100px;\n margin-top: -50px; margin-left: -50px;\n background: url('lib/loading.gif') no-repeat center #fff;\n text-align: center;\n position: fixed; z-index: 9002;\">Loading...</div>\n</code></pre>\n\n<p>It puts the div at the center of the view (vertical and horizontal), sizes and adjusts for size, centers background image (vertical and horizontal), centers text (horizontal), and keeps div in the view and on top of the content. Simply place in the HTML <code>body</code> and enjoy.</p>\n"
},
{
"answer_id": 29011864,
"author": "Kilian Stinson",
"author_id": 2345972,
"author_profile": "https://Stackoverflow.com/users/2345972",
"pm_score": 6,
"selected": false,
"text": "<p>Another solution for this without having to set a width for one of the elements is using the CSS 3 <code>transform</code> attribute.</p>\n\n<pre><code>#outer {\n position: relative;\n}\n\n#inner {\n position: absolute;\n left: 50%;\n\n transform: translateX(-50%);\n}\n</code></pre>\n\n<p>The trick is that <code>translateX(-50%)</code> sets the <code>#inner</code> element 50 percent to the left of its own width. You can use the same trick for vertical alignment.</p>\n\n<p>Here's a <a href=\"http://jsfiddle.net/bfedqjz4/\" rel=\"noreferrer\" title=\"Fiddle\"><strong>Fiddle</strong></a> showing horizontal and vertical alignment.</p>\n\n<p>More information is on <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/transform\" rel=\"noreferrer\" title=\"MDN\">Mozilla Developer Network</a>.</p>\n"
},
{
"answer_id": 30257156,
"author": "anand jothi",
"author_id": 4247052,
"author_profile": "https://Stackoverflow.com/users/4247052",
"pm_score": 3,
"selected": false,
"text": "<pre><code>#inner {\n width: 50%;\n margin: 0 auto;\n}\n</code></pre>\n"
},
{
"answer_id": 32328992,
"author": "Ajay Gupta",
"author_id": 2663073,
"author_profile": "https://Stackoverflow.com/users/2663073",
"pm_score": 2,
"selected": false,
"text": "<p>Try out this below CSS code:</p>\n<pre class=\"lang-html prettyprint-override\"><code><style>\n #outer {\n display: inline-block;\n width: 100%;\n height: 100%;\n text-align: center;\n vertical-align: middle;\n }\n\n #outer > #inner {\n display: inline-block;\n font-size: 19px;\n margin: 20px;\n max-width: 320px;\n min-height: 20px;\n min-width: 30px;\n padding: 14px;\n vertical-align: middle;\n }\n</style>\n</code></pre>\n<p>Apply above CSS via below HTML code, to center horizontally and to center vertically (aka: align vertically in middle)<b>:</b></p>\n<pre class=\"lang-html prettyprint-override\"><code><div id="outer">\n <div id="inner">\n ...These <div>ITEMS</div> <img src="URL"/> are in center...\n </div>\n</div>\n</code></pre>\n<p>After applying CSS & using above HTML, that section in webpage would look like this:</p>\n<pre><code>BEFORE applying code:\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃V..Middle & H..Center ┣━1\n┃ ┣━2\n┃ ┣━3\n┗┳━━━━━━┳━━━━━━┳━━━━━━┳━━━━━━┳┛\n 1 2 3 4 5\n\nAFTER:\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃ ┣━1\n┃ V..Middle & H..Center ┣━2\n┃ ┣━3\n┗┳━━━━━━┳━━━━━━┳━━━━━━┳━━━━━━┳┛\n 1 2 3 4 5\n</code></pre>\n<br>\nTo center \"inner\" elements horizontally inside the \"outer\" wrapper, the \"inner\" elements (of type DIV, IMG, etc) need to have \"inline\" CSS properties, such as these: display:inline or display:inline-block, etc, THEN \"outer\" CSS property text-align:center can work on \"inner\" elements. \n<br><br>\n<p>So near to minimum CSS code are these:</p>\n<pre class=\"lang-html prettyprint-override\"><code><style>\n #outer {\n width: 100%;\n text-align: center;\n }\n\n #outer > .inner2 {\n display: inline-block;\n }\n</style>\n</code></pre>\n<p>Apply above CSS via below HTML code, to center (horizontally)<b>:</b></p>\n<pre class=\"lang-html prettyprint-override\"><code><div id="outer">\n <img class="inner2" src="URL-1"> <img class="inner2" src="URL-2">\n</div>\n</code></pre>\n<p>After applying CSS & using above HTML, that line in webpage would look like this:</p>\n<pre><code>BEFORE applying code:\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃┍━━━━━━━━━━┑ ┃\n┃│ img URL1 │ ┃\n┃┕━━━━━━━━━━┙ ┃\n┃┍━━━━━━━━━━┑ ┃\n┃│ img URL2 │ ┃\n┃┕━━━━━━━━━━┙ ┃\n┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n\nAFTER:\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃ ┍━━━━━━━━━━┑ ┍━━━━━━━━━━┑ ┣━1\n┃ │ img URL1 │ │ img URL2 │ ┣━2\n┃ ┕━━━━━━━━━━┙ ┕━━━━━━━━━━┙ ┣━3\n┗┳━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━┳┛\n 1 2 3 4 5\n</code></pre>\n<br>\nIf you want to avoid specifying class=\"inner2\" attribute everytime for each \"inner\" elements, then use such CSS in early: \n<pre class=\"lang-html prettyprint-override\"><code><style>\n #outer {\n width: 100%;\n text-align: center;\n }\n\n #outer > img, #outer > div {\n display: inline-block;\n }\n</style>\n</code></pre>\n<p>So above CSS can be applied like below, to center items (horizontally) inside the "outer" wrapper:</p>\n<pre class=\"lang-html prettyprint-override\"><code><div id="outer">\n <img src="URL-1"> Text1 <img src="URL-2"> Text2\n</div>\n</code></pre>\n<p>After applying CSS & using above HTML, that line in webpage would look like this:</p>\n<pre><code>BEFORE applying code:\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃┍━━━━━━━━┑ ┃\n┃│img URL1│ ┃\n┃┕━━━━━━━━┙ ┃\n┃Text1 ┃\n┃┍━━━━━━━━┑ ┃\n┃│img URL2│ ┃\n┃┕━━━━━━━━┙ ┃\n┃Text2 ┃\n┗━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n\nAFTER:\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃ ┍━━━━━━━━━┑ ┍━━━━━━━━┑ ┣━1\n┃ │img URL1 │ │img URL2│ ┣━2\n┃ ┕━━━━━━━━━┙Text1┕━━━━━━━━┙Text2 ┣━3\n┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛\n 1 2 3 4 5\n</code></pre>\n<br>\nThe \"id\" attribute's unique name/value should be used only once for only one HTML element in one webpage, So CSS properties of same \"id\" name cannot be repeatedly used on multiple HTML elements, (some web-browser incorrectly allows to use same id on multiple elements).<br>\nSo when you need many lines in same webpage, that need to show internal elements/items in center (horizontally) in that line, then you may use such CSS \"class\" (aka: CSS group, CSS repeater)<b>:</b> \n<pre class=\"lang-html prettyprint-override\"><code><style>\n .outer2 {\n width: 100%;\n text-align: center;\n }\n\n .outer2 > div, .outer2 > div > img {\n display: inline-block;\n }\n</style>\n</code></pre>\n<p>So above CSS can be applied like below, to center items (horizontally) inside the "outer2" wrapper:</p>\n<pre class=\"lang-html prettyprint-override\"><code><div class="outer2">\n <div>\n Line1: <img src="URL-1"> Text1 <img src="URL-2">\n </div>\n</div>\n...\n<div class="outer2">\n <div>\n Line2: <img src="URL-3"> Text2 <img src="URL-4">\n </div>\n</div>\n</code></pre>\n<p>After applying CSS & using above HTML, those lines in webpage would look like this:</p>\n<pre><code>BEFORE applying code:\n┏━━━━━━━━━━━━━━━━━━━━━━┓\n┃Line1: ┃\n┃┍━━━━━━━━┑ ┃\n┃│img URL1│ ┃\n┃┕━━━━━━━━┙ ┃\n┃Text1 ┃\n┃┍━━━━━━━━┑ ┃\n┃│img URL2│ ┃\n┃┕━━━━━━━━┙ ┃\n┗━━━━━━━━━━━━━━━━━━━━━━┛\n........................\n┏━━━━━━━━━━━━━━━━━━━━━━┓\n┃Line2: ┃\n┃┍━━━━━━━━┑ ┃\n┃│img URL3│ ┃\n┃┕━━━━━━━━┙ ┃\n┃Text2 ┃\n┃┍━━━━━━━━┑ ┃\n┃│img URL4│ ┃\n┃┕━━━━━━━━┙ ┃\n┗━━━━━━━━━━━━━━━━━━━━━━┛\n\nAFTER:\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃ ┍━━━━━━━━┑ ┍━━━━━━━━┑ ┣━1\n┃ │img URL1│ │img URL2│ ┣━2\n┃ Line1:┕━━━━━━━━┙Text1┕━━━━━━━━┙ ┣━3\n┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛\n 1 2 3 4 5\n.......................................\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃ ┍━━━━━━━━┑ ┍━━━━━━━━┑ ┣━1\n┃ │img URL3│ │img URL4│ ┣━2\n┃ Line2:┕━━━━━━━━┙Text2┕━━━━━━━━┙ ┣━3\n┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛\n 1 2 3 4 5\n</code></pre>\n<br>\nTo vertically align in middle, we would need to use below CSS code<b>:</b> \n<pre class=\"lang-html prettyprint-override\"><code><style>\n .outer2 {\n width: 100%;\n text-align: center;\n vertical-align: middle;\n }\n\n .outer2 > div, .outer2 > div > img {\n display: inline-block;\n vertical-align: middle;\n }\n</style>\n</code></pre>\n<p>So above CSS can be applied like below, to center items horizontally and to vertically align in middle of the "outer2" wrapper:</p>\n<pre class=\"lang-html prettyprint-override\"><code><div class="outer2">\n <div>\n Line1: <img src="URL-1"> Text1 <img src="URL-2">\n </div>\n</div>\n...\n<div class="outer2">\n <div>\n Line2: <img src="URL-3"> Text2 <img src="URL-4">\n </div>\n</div>\n</code></pre>\n<p>After applying CSS & using above HTML, those lines in webpage would look like this:</p>\n<pre><code>BEFORE applying code:\n┏━━━━━━━━━━━━━━━━━━━━━━┓\n┃Line1: ┃\n┃┍━━━━━━━━┑ ┃\n┃│img URL1│ ┃\n┃┕━━━━━━━━┙ ┃\n┃Text1 ┃\n┃┍━━━━━━━━┑ ┃\n┃│img URL2│ ┃\n┃┕━━━━━━━━┙ ┃\n┗━━━━━━━━━━━━━━━━━━━━━━┛\n........................\n┏━━━━━━━━━━━━━━━━━━━━━━┓\n┃Line2: ┃\n┃┍━━━━━━━━┑ ┃\n┃│img URL3│ ┃\n┃┕━━━━━━━━┙ ┃\n┃Text2 ┃\n┃┍━━━━━━━━┑ ┃\n┃│img URL4│ ┃\n┃┕━━━━━━━━┙ ┃\n┗━━━━━━━━━━━━━━━━━━━━━━┛\n\nAFTER:\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃ ┍━━━━━━━━┑ ┍━━━━━━━━┑ ┣━1\n┃ Line1:│img URL1│Text1│img URL2│ ┣━2\n┃ ┕━━━━━━━━┙ ┕━━━━━━━━┙ ┣━3\n┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛\n 1 2 3 4 5\n.......................................\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n┃ ┍━━━━━━━━┑ ┍━━━━━━━━┑ ┣━1\n┃ Line2:│img URL3│Text2│img URL4│ ┣━2\n┃ ┕━━━━━━━━┙ ┕━━━━━━━━┙ ┣━3\n┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛\n 1 2 3 4 5\n</code></pre>\n"
},
{
"answer_id": 33708242,
"author": "Majid Sadr",
"author_id": 3789730,
"author_profile": "https://Stackoverflow.com/users/3789730",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#outer {postion: relative}\n#inner {\n width: 100px; \n height: 40px; \n position: absolute;\n top: 50%;\n margin-top: -20px; /* Half of your height */\n}\n</code></pre>\n"
},
{
"answer_id": 34386220,
"author": "Justin Munce",
"author_id": 4780578,
"author_profile": "https://Stackoverflow.com/users/4780578",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on your circumstances, the simplest solution could be:</p>\n\n<pre><code>margin: 0 auto; float: none;\n</code></pre>\n"
},
{
"answer_id": 34432583,
"author": "Banti Mathur",
"author_id": 4300993,
"author_profile": "https://Stackoverflow.com/users/4300993",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, this is short and clean code for horizontal align.</p>\n\n<pre><code>.classname {\n display: box;\n margin: 0 auto;\n width: 500px /* Width set as per your requirement. */;\n}\n</code></pre>\n"
},
{
"answer_id": 35357708,
"author": "nyn05",
"author_id": 5758188,
"author_profile": "https://Stackoverflow.com/users/5758188",
"pm_score": 1,
"selected": false,
"text": "<p>The best way is using table-cell display (inner) that come exactly after a div with the display table (outer) and set vertical align for the inner div (with table-cell display) and every tag you use in the inner div placed in the center of div or page.</p>\n\n<p>Note: you must set a specified height to outer</p>\n\n<p>It is the best way you know without position relative or absolute, and you can use it in every browser as same.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#outer{\r\n display: table;\r\n height: 100vh;\r\n width: 100%;\r\n}\r\n\r\n\r\n#inner{\r\n display: table-cell;\r\n vertical-align: middle;\r\n text-align: center;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\r\n <div id=\"inner\">\r\n <h1>\r\n set content center\r\n </h1>\r\n <div>\r\n hi this is the best way to align your items center\r\n </div>\r\n </div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 35510639,
"author": "John Slegers",
"author_id": 1946501,
"author_profile": "https://Stackoverflow.com/users/1946501",
"pm_score": 5,
"selected": false,
"text": "<h1>Centering only horizontally</h1>\n<p>In my experience, the best way to center a box horizontally is to apply the following properties:</p>\n<h2>The container:</h2>\n<ul>\n<li>should have <code>text-align: center;</code></li>\n</ul>\n<h2>The content box:</h2>\n<ul>\n<li>should have <code>display: inline-block;</code></li>\n</ul>\n<h2>Demo:</h2>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.container {\n width: 100%;\n height: 120px;\n background: #CCC;\n text-align: center;\n}\n\n.centered-content {\n display: inline-block;\n background: #FFF;\n padding: 20px;\n border: 1px solid #000;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"container\">\n <div class=\"centered-content\">\n Center this!\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>See also <a href=\"https://jsfiddle.net/zmw77awd/1/\" rel=\"noreferrer\"><strong>this Fiddle</strong></a>!</p>\n<hr />\n<h1>Centering both horizontally & vertically</h1>\n<p>In my experience, the best way to center a box <strong>both</strong> vertically and horizontally is to use an additional container and apply the following properties:</p>\n<h2>The outer container:</h2>\n<ul>\n<li>should have <code>display: table;</code></li>\n</ul>\n<h2>The inner container:</h2>\n<ul>\n<li>should have <code>display: table-cell;</code></li>\n<li>should have <code>vertical-align: middle;</code></li>\n<li>should have <code>text-align: center;</code></li>\n</ul>\n<h2>The content box:</h2>\n<ul>\n<li>should have <code>display: inline-block;</code></li>\n</ul>\n<h2>Demo:</h2>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.outer-container {\n display: table;\n width: 100%;\n height: 120px;\n background: #CCC;\n}\n\n.inner-container {\n display: table-cell;\n vertical-align: middle;\n text-align: center;\n}\n\n.centered-content {\n display: inline-block;\n background: #FFF;\n padding: 20px;\n border: 1px solid #000;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer-container\">\n <div class=\"inner-container\">\n <div class=\"centered-content\">\n Center this!\n </div>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>See also <a href=\"https://jsfiddle.net/zmw77awd/2/\" rel=\"noreferrer\"><strong>this Fiddle</strong></a>!</p>\n"
},
{
"answer_id": 36259732,
"author": "Gaurav Aggarwal",
"author_id": 4119808,
"author_profile": "https://Stackoverflow.com/users/4119808",
"pm_score": 2,
"selected": false,
"text": "<p>It is so simple.</p>\n<p>Just decide what width you want to give to the inner div and use the following CSS.</p>\n<h3>CSS</h3>\n<pre><code>.inner{\n width: 500px; /* Assumed width */\n margin: 0 auto;\n}\n</code></pre>\n"
},
{
"answer_id": 37096327,
"author": "Qmr",
"author_id": 2681049,
"author_profile": "https://Stackoverflow.com/users/2681049",
"pm_score": 2,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\" style=\"width:100%;margin: 0 auto; text-align: center;\"> \r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 37735442,
"author": "Mardok",
"author_id": 3170976,
"author_profile": "https://Stackoverflow.com/users/3170976",
"pm_score": 2,
"selected": false,
"text": "<p>After reading all the answers I did not see the one I prefer. This is how you can center an element in another. </p>\n\n<p>jsfiddle - <a href=\"http://jsfiddle.net/josephtveter/w3sksu1w/\" rel=\"nofollow\">http://jsfiddle.net/josephtveter/w3sksu1w/</a> </p>\n\n<pre><code><p>Horz Center</p>\n<div class=\"outterDiv\">\n <div class=\"innerDiv horzCenter\"></div>\n</div>\n<p>Vert Center</p>\n<div class=\"outterDiv\">\n <div class=\"innerDiv vertCenter\"></div>\n</div>\n<p>True Center</p>\n<div class=\"outterDiv\">\n <div class=\"innerDiv trueCenter\"></div>\n</div>\n.vertCenter\n{\n position: absolute;\n top:50%;\n -ms-transform: translateY(-50%);\n -moz-transform: translateY(-50%);\n -webkit-transform: translateY(-50%);\n transform: translateY(-50%);\n}\n\n.horzCenter\n{\n position: absolute;\n left: 50%;\n -ms-transform: translateX(-50%);\n -moz-transform: translateX(-50%);\n -webkit-transform: translateX(-50%);\n transform: translateX(-50%);\n}\n\n.trueCenter\n{\n position: absolute;\n left: 50%;\n top: 50%;\n -ms-transform: translate(-50%, -50%);\n -moz-transform: translate(-50%, -50%);\n -webkit-transform: translate(-50%, -50%);\n transform: translate(-50%, -50%);\n}\n\n.outterDiv\n{\n position: relative;\n background-color: blue;\n width: 10rem;\n height: 10rem;\n margin: 2rem;\n}\n.innerDiv\n{\n background-color: red;\n width: 5rem;\n height: 5rem;\n}\n</code></pre>\n"
},
{
"answer_id": 38170372,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>HTML:</p>\n\n<pre><code><div id=\"outer\">\n <div id=\"inner\">\n </div>\n</div>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>#outer{\n width: 500px;\n background-color: #000;\n height: 500px\n}\n#inner{\n background-color: #333;\n margin: 0 auto;\n width: 50%;\n height: 250px;\n}\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/78gu7vwv/\" rel=\"nofollow noreferrer\">Fiddle</a>.</p>\n"
},
{
"answer_id": 38673523,
"author": "Friend",
"author_id": 6284236,
"author_profile": "https://Stackoverflow.com/users/6284236",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Add <code>text-align:center;</code> to parent div</strong> </p>\n\n<pre><code>#outer {\n text-align: center;\n}\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/7qwxx9rs/\" rel=\"nofollow\">https://jsfiddle.net/7qwxx9rs/</a></p>\n\n<p>or </p>\n\n<pre><code>#outer > div {\n margin: auto;\n width: 100px;\n}\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/f8su1fLz/\" rel=\"nofollow\">https://jsfiddle.net/f8su1fLz/</a></p>\n"
},
{
"answer_id": 39654350,
"author": "Billal Begueradj",
"author_id": 3329664,
"author_profile": "https://Stackoverflow.com/users/3329664",
"pm_score": 5,
"selected": false,
"text": "<p>This method also works just fine:</p>\n<pre class=\"lang-css prettyprint-override\"><code>div.container {\n display: flex;\n justify-content: center; /* For horizontal alignment */\n align-items: center; /* For vertical alignment */\n}\n</code></pre>\n<p>For the inner <code><div></code>, the only condition is that its <code>height</code> and <code>width</code> must not be larger than the ones of its container.</p>\n"
},
{
"answer_id": 40361272,
"author": "Saurav Rastogi",
"author_id": 1687746,
"author_profile": "https://Stackoverflow.com/users/1687746",
"pm_score": 3,
"selected": false,
"text": "<p>You can attain this using the <strong>CSS Flexbox</strong>. You just need to apply 3 properties to the parent element to get everything working.</p>\n\n<pre><code>#outer {\n display: flex;\n align-content: center;\n justify-content: center;\n}\n</code></pre>\n\n<p>Have a look at the code below this will make you understand the properties much better.</p>\n\n<p>Get to know more about <strong><a href=\"https://css-tricks.com/snippets/css/a-guide-to-flexbox/\" rel=\"noreferrer\">CSS Flexbox</a></strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#outer {\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n border: 1px solid #ddd;\r\n width: 100%;\r\n height: 200px;\r\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\"> \r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 40480047,
"author": "Mr.Pandya",
"author_id": 6554624,
"author_profile": "https://Stackoverflow.com/users/6554624",
"pm_score": 2,
"selected": false,
"text": "<p>Give some <code>width</code> to the inner <code>div</code> and add <code>margin:0 auto;</code> in the CSS property.</p>\n"
},
{
"answer_id": 41059156,
"author": "amit bende",
"author_id": 6374688,
"author_profile": "https://Stackoverflow.com/users/6374688",
"pm_score": -1,
"selected": false,
"text": "<pre><code>.outer {\n text-align: center;\n width: 100%\n}\n</code></pre>\n"
},
{
"answer_id": 41237712,
"author": "Cyan Baltazar",
"author_id": 6665604,
"author_profile": "https://Stackoverflow.com/users/6665604",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"https://en.wikipedia.org/wiki/CSS_Flexible_Box_Layout\" rel=\"nofollow noreferrer\">CSS Flexbox</a>.</p>\n\n<pre><code>#inner {\n display: flex;\n justify-content: center;\n}\n</code></pre>\n\n<p>You can learn more about it on this link: <a href=\"https://css-tricks.com/snippets/css/a-guide-to-flexbox/\" rel=\"nofollow noreferrer\">https://css-tricks.com/snippets/css/a-guide-to-flexbox/</a></p>\n"
},
{
"answer_id": 41634428,
"author": "ADH - THE TECHIE GUY",
"author_id": 6677244,
"author_profile": "https://Stackoverflow.com/users/6677244",
"pm_score": 3,
"selected": false,
"text": "<p>It's possible using <strong>CSS 3 Flexbox</strong>. You have two methods when using Flexbox.</p>\n<ol>\n<li>Set the parent <code>display:flex;</code> and add properties <code>{justify-content:center; ,align-items:center;}</code> to your parent element.</li>\n</ol>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#outer {\n display: flex;\n justify-content: center;\n align-items: center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\" style=\"width:100%\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<ol start=\"2\">\n<li>Set the parent <code>display:flex</code> and add <code>margin:auto;</code> to the child.</li>\n</ol>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#outer {\n display: flex;\n}\n\n#inner {\n margin: auto;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\" style=\"width:100%\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 41644871,
"author": "bonyem",
"author_id": 6921594,
"author_profile": "https://Stackoverflow.com/users/6921594",
"pm_score": 0,
"selected": false,
"text": "<p>Add CSS to your inner div. Set <code>margin: 0 auto</code> and set its width less than 100%, which is the width of the outer div.</p>\n\n<pre><code><div id=\"outer\" style=\"width:100%\"> \n <div id=\"inner\" style=\"margin:0 auto;width:50%\">Foo foo</div> \n</div>\n</code></pre>\n\n<p>This will give the desired result.</p>\n"
},
{
"answer_id": 41713418,
"author": "Abdul Ghaffar",
"author_id": 5324262,
"author_profile": "https://Stackoverflow.com/users/5324262",
"pm_score": 2,
"selected": false,
"text": "<p><strong>CSS</strong></p>\n\n<pre><code>#inner {\n display: table;\n margin: 0 auto; \n}\n</code></pre>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><div id=\"outer\" style=\"width:100%\"> \n <div id=\"inner\">Foo foo</div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 41952200,
"author": "sneha",
"author_id": 7445431,
"author_profile": "https://Stackoverflow.com/users/7445431",
"pm_score": -1,
"selected": false,
"text": "<pre><code><div id=\"outer\" style=\"width:100%\"> \n <div id=\"inner\" style=\"text-align:center\">Foo foo</div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 42173742,
"author": "Faizal Munna",
"author_id": 7434879,
"author_profile": "https://Stackoverflow.com/users/7434879",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest answer: Add <strong>margin:auto;</strong> to inner.</p>\n\n<pre><code><div class=\"outer\">\n <div class=\"inner\">\n Foo foo\n </div>\n</div>\n</code></pre>\n\n<h3>CSS code</h3>\n\n<pre><code>.outer{\n width: 100%;\n height: 300px;\n background: yellow;\n}\n\n.inner{\n width: 30%;\n height: 200px;\n margin: auto;\n background: red;\n text-align: center\n}\n</code></pre>\n\n<p>Check my <a href=\"https://en.wikipedia.org/wiki/CodePen\" rel=\"nofollow noreferrer\">CodePen</a> link: <a href=\"http://codepen.io/feizel/pen/QdJJrK\" rel=\"nofollow noreferrer\">http://codepen.io/feizel/pen/QdJJrK</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/IeKcF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IeKcF.png\" alt=\"Enter image description here\"></a></p>\n"
},
{
"answer_id": 42345578,
"author": "Sankar",
"author_id": 2131576,
"author_profile": "https://Stackoverflow.com/users/2131576",
"pm_score": 1,
"selected": false,
"text": "<p>Just simply <code>Margin:0px auto</code>:</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-css lang-css prettyprint-override\"><code>#inner{\r\n display: block;\r\n margin: 0px auto;\r\n width: 100px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\" style=\"width:100%\"> \r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 42736256,
"author": "Legends",
"author_id": 2581562,
"author_profile": "https://Stackoverflow.com/users/2581562",
"pm_score": 3,
"selected": false,
"text": "<p><strong>CSS 3:</strong></p>\n\n<p>You can use the following style on the parent container to distribute child elements evenly horizontally:</p>\n\n<pre><code>display: flex;\njustify-content: space-between; // <-- space-between or space-around\n</code></pre>\n\n<p>A nice <a href=\"https://www.w3schools.com/cssref/playit.asp?filename=playcss_justify-content&preval=space-between\" rel=\"nofollow noreferrer\">DEMO</a> regarding the different values for <code>justify-content</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/H3tJq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/H3tJq.png\" alt=\"Enter image description here\"></a></p>\n\n<p>CanIUse: <a href=\"http://caniuse.com/#search=justify-content\" rel=\"nofollow noreferrer\">Browser-Compatability</a></p>\n\n<p><strong>Try it!:</strong></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-css lang-css prettyprint-override\"><code>#containerdiv {\r\n display: flex;\r\n justify-content: space-between;\r\n}\r\n\r\n#containerdiv > div {\r\n background-color: blue;\r\n width: 50px;\r\n color: white;\r\n text-align: center;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\r\n<html>\r\n<head>\r\n <meta charset=\"utf-8\">\r\n <meta name=\"viewport\" content=\"width=device-width\">\r\n <title>JS Bin</title>\r\n</head>\r\n<body>\r\n <div id=\"containerdiv\">\r\n <div>88</div>\r\n <div>77</div>\r\n <div>55</div>\r\n <div>33</div>\r\n <div>40</div>\r\n <div>45</div>\r\n </div>\r\n</body>\r\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 43193443,
"author": "Sandesh Damkondwar",
"author_id": 3589104,
"author_profile": "https://Stackoverflow.com/users/3589104",
"pm_score": 5,
"selected": false,
"text": "<p>Flex have more than 97% browser support coverage and might be the best way to solve these kind of problems within few lines:</p>\n<pre class=\"lang-css prettyprint-override\"><code>#outer {\n display: flex;\n justify-content: center;\n}\n</code></pre>\n"
},
{
"answer_id": 43882882,
"author": "Agu Dondo",
"author_id": 936703,
"author_profile": "https://Stackoverflow.com/users/936703",
"pm_score": 2,
"selected": false,
"text": "<p>It can also be centered horizontally and vertically using absolute positioning, like this:</p>\n\n<pre><code>#outer{\n position: relative;\n}\n\n#inner{\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%)\n}\n</code></pre>\n"
},
{
"answer_id": 44020300,
"author": "Faizal",
"author_id": 8012850,
"author_profile": "https://Stackoverflow.com/users/8012850",
"pm_score": 2,
"selected": false,
"text": "<p>Use the below code.</p>\n\n<h3>HTML</h3>\n\n<pre><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div>\n</code></pre>\n\n<h3>CSS</h3>\n\n<pre><code>#outer {\n text-align: center;\n}\n#inner{\n display: inline-block;\n}\n</code></pre>\n"
},
{
"answer_id": 44084783,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 2,
"selected": false,
"text": "<p>The best known way which is used widely and work in <strong>many browsers</strong> including the old ones, is using <code>margin</code> as below:</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-css lang-css prettyprint-override\"><code>#parent {\r\n width: 100%;\r\n background-color: #CCCCCC;\r\n}\r\n\r\n#child {\r\n width: 30%; /* We need the width */\r\n margin: 0 auto; /* This does the magic */\r\n color: #FFFFFF;\r\n background-color: #000000;\r\n padding: 10px;\r\n text-align: center;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"parent\">\r\n <div id=\"child\">I'm the child and I'm horizontally centered! My daddy is a greyish div dude!</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Run the code to see how it works. Also, there are two important things you shouldn't forget in your CSS when you try to center this way: <code>margin: 0 auto;</code>. That makes it the div center as wanted. Plus don't forget <code>width</code> of the child, otherwise it won't get centered as expected!</p>\n"
},
{
"answer_id": 44338349,
"author": "Yahya Essam",
"author_id": 6471803,
"author_profile": "https://Stackoverflow.com/users/6471803",
"pm_score": 2,
"selected": false,
"text": "<p>You can use one line of code, just <code>text-align:center</code>.</p>\n\n<p>Here's an example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#inner {\r\n text-align: center;\r\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\" style=\"width:100%\">\r\n <div id=\"inner\"><button>hello</button></div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 44453030,
"author": "Paolo Forgia",
"author_id": 1685157,
"author_profile": "https://Stackoverflow.com/users/1685157",
"pm_score": 5,
"selected": false,
"text": "<h1>Flexbox</h1>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/display?v=control\" rel=\"noreferrer\"><strong><code>display: flex</code></strong></a> behaves like a block element and lays out its content according to the flexbox model. It works with <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content?v=control\" rel=\"noreferrer\"><strong><code>justify-content: center</code></strong></a>.</p>\n<p><strong>Please note:</strong> Flexbox is compatible all browsers exept Internet Explorer. See <a href=\"https://stackoverflow.com/questions/43979702/display-flex-not-working-on-internet-explorer/43979973#43979973\">display: flex not working on Internet Explorer</a> for a complete and up to date list of browsers compatibility.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#inner {\n display: inline-block;\n}\n\n#outer {\n display: flex;\n justify-content: center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h1>Text-align: center</h1>\n<p>Applying <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/text-align?v=control\" rel=\"noreferrer\"><strong><code>text-align: center</code></strong></a> the inline contents are centered within the line box. However since the inner div has by default <code>width: 100%</code> you have to set a specific width or use one of the following:</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/display?v=control\" rel=\"noreferrer\"><strong><code>display: block</code></strong></a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/display?v=control\" rel=\"noreferrer\"><strong><code>display: inline</code></strong></a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/display?v=control\" rel=\"noreferrer\"><strong><code>display: inline-block</code></strong></a></li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#inner {\n display: inline-block;\n}\n\n#outer {\n text-align: center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h1>Margin: 0 auto</h1>\n<p>Using <a href=\"https://developer.mozilla.org/en/docs/Web/CSS/margin?v=example\" rel=\"noreferrer\"><strong><code>margin: 0 auto</code></strong></a> is another option and it is more suitable for older browsers compatibility. It works together with <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/display?v=control\" rel=\"noreferrer\"><strong><code>display: table</code></strong></a>.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#inner {\n display: table;\n margin: 0 auto;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h1>Transform</h1>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/transform?v=control\" rel=\"noreferrer\"><strong><code>transform: translate</code></strong></a> lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed. To center horizontally it require <a href=\"https://developer.mozilla.org/en/docs/Web/CSS/position?v=example\" rel=\"noreferrer\"><strong><code>position: absolute</code></strong></a> and <a href=\"https://developer.mozilla.org/en/docs/Web/CSS/left\" rel=\"noreferrer\"><strong><code>left: 50%</code></strong></a>.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#inner {\n position: absolute;\n left: 50%;\n transform: translate(-50%, 0%);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h1><code><center></code> (Deprecated)</h1>\n<p>The tag <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center\" rel=\"noreferrer\"><strong><code><center></code></strong></a> is the HTML alternative to <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/text-align?v=control\" rel=\"noreferrer\"><strong><code>text-align: center</code></strong></a>. It works on older browsers and most of the new ones but it is not considered a good practice since this feature is <a href=\"https://www.w3.org/TR/html5/obsolete.html\" rel=\"noreferrer\">obsolete</a> and has been removed from the Web standards.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#inner {\n display: inline-block;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <center>\n <div id=\"inner\">Foo foo</div>\n </center>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 45251566,
"author": "Heitor",
"author_id": 3063226,
"author_profile": "https://Stackoverflow.com/users/3063226",
"pm_score": 2,
"selected": false,
"text": "<p>I'm sorry but this baby from the 1990s just <em>worked</em> for me:</p>\n\n<pre><code><div id=\"outer\"> \n <center>Foo foo</center>\n</div>\n</code></pre>\n\n<p>Am I going to hell for this sin?</p>\n"
},
{
"answer_id": 45322869,
"author": "sibaspage",
"author_id": 5241734,
"author_profile": "https://Stackoverflow.com/users/5241734",
"pm_score": -1,
"selected": false,
"text": "<p>You can use the link <a href=\"https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview\" rel=\"nofollow noreferrer\">https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview</a></p>\n\n<pre><code>.outer{\n display: table;\n width: 100%;\n height: 100%;\n}\n.inner {\n vertical-align: middle;\n}\n</code></pre>\n\n<p>Refer to <a href=\"https://v4-alpha.getbootstrap.com/examples/cover/\" rel=\"nofollow noreferrer\">https://v4-alpha.getbootstrap.com/examples/cover/</a></p>\n"
},
{
"answer_id": 45510181,
"author": "Rafiqul Islam",
"author_id": 4788956,
"author_profile": "https://Stackoverflow.com/users/4788956",
"pm_score": 2,
"selected": false,
"text": "<p>You can add this code:</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-css lang-css prettyprint-override\"><code>#inner {\r\n width: 90%;\r\n margin: 0 auto;\r\n text-align:center;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\"> \r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 46382081,
"author": "antelove",
"author_id": 7656367,
"author_profile": "https://Stackoverflow.com/users/7656367",
"pm_score": 2,
"selected": false,
"text": "<h3>Center a div in a div</h3>\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-css lang-css prettyprint-override\"><code>.outer {\r\n display: -webkit-flex;\r\n display: flex;\r\n\r\n //-webkit-justify-content: center; \r\n //justify-content: center;\r\n \r\n //align-items: center;\r\n\r\n width: 100%;\r\n height: 100px;\r\n background-color: lightgrey;\r\n}\r\n\r\n.inner {\r\n background-color: cornflowerblue;\r\n padding: 2rem;\r\n margin: auto; \r\n \r\n //align-self: center; \r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\"> \r\n <div class=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 46382588,
"author": "Elias MP",
"author_id": 5770216,
"author_profile": "https://Stackoverflow.com/users/5770216",
"pm_score": 2,
"selected": false,
"text": "<p>We could use the next CSS's class which allow center vertically and horizontally any element against its parent:</p>\n\n<pre><code>.centerElement{\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n}\n</code></pre>\n"
},
{
"answer_id": 46449757,
"author": "Руслан",
"author_id": 7546060,
"author_profile": "https://Stackoverflow.com/users/7546060",
"pm_score": 2,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code><div id=\"parent\">\n <div class=\"child\"></div>\n</div>\n</code></pre>\n\n<p>Style:</p>\n\n<pre><code>#parent {\n display: flex;\n justify-content: center;\n}\n</code></pre>\n\n<p>If you want to center it horizontally you should write as below:</p>\n\n<pre><code>#parent {\n display: flex;\n justify-content: center;\n align-items: center;\n}\n</code></pre>\n"
},
{
"answer_id": 46604060,
"author": "sed",
"author_id": 1483143,
"author_profile": "https://Stackoverflow.com/users/1483143",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the calc method. The usage is for the div you're centering. If you know its width, let's say it's 1200 pixels, go for:</p>\n\n<pre><code>.container {\n width:1200px;\n margin-left: calc(50% - 600px);\n}\n</code></pre>\n\n<p>So basically it'll add a left margin of 50% minus half the known width.</p>\n"
},
{
"answer_id": 46741879,
"author": "Husain Ahmed",
"author_id": 5218509,
"author_profile": "https://Stackoverflow.com/users/5218509",
"pm_score": 2,
"selected": false,
"text": "<p>Use this code:</p>\n\n<pre><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div>\n\n#inner {\n width: 50%;\n margin: 0 auto;\n text-align: center;\n}\n</code></pre>\n"
},
{
"answer_id": 46807365,
"author": "SUNIL KUMAR E.U",
"author_id": 4688232,
"author_profile": "https://Stackoverflow.com/users/4688232",
"pm_score": 2,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code><style>\n #outer{\n text-align: center;\n width: 100%;\n }\n #inner{\n text-align: center;\n }\n</style>\n</code></pre>\n"
},
{
"answer_id": 47604928,
"author": "Gaurang Sondagar",
"author_id": 6152004,
"author_profile": "https://Stackoverflow.com/users/6152004",
"pm_score": 1,
"selected": false,
"text": "<p>You can do it in a different way. See the below examples:</p>\n\n<pre><code>1. First Method\n#outer {\n text-align: center;\n width: 100%;\n}\n#inner {\n display: inline-block;\n}\n\n\n2. Second method\n#outer {\n position: relative;\n overflow: hidden;\n}\n.centered {\n position: absolute;\n left: 50%;\n}\n</code></pre>\n"
},
{
"answer_id": 47885563,
"author": "Temani Afif",
"author_id": 8620333,
"author_profile": "https://Stackoverflow.com/users/8620333",
"pm_score": 2,
"selected": false,
"text": "<p>Here is another way to center horizontally using <strong><a href=\"https://en.wikipedia.org/wiki/CSS_Flexible_Box_Layout\" rel=\"nofollow noreferrer\">Flexbox</a></strong> and without specifying any width to the inner container. The idea is to use pseudo elements that will push the inner content from the right and the left.</p>\n\n<p>Using <code>flex:1</code> on pseudo element will make them fill the remaining spaces and take equal size and the inner container will get centered.</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-css lang-css prettyprint-override\"><code>.container {\r\n display: flex;\r\n border: 1px solid;\r\n}\r\n\r\n.container:before,\r\n.container:after {\r\n content: \"\";\r\n flex: 1;\r\n}\r\n\r\n.inner {\r\n border: 1px solid red;\r\n padding: 5px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"container\">\r\n <div class=\"inner\">\r\n Foo content\r\n </div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>We can also consider the same situation for vertical alignment by simply changing the direction of flex to column:</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-css lang-css prettyprint-override\"><code>.container {\r\n display: flex;\r\n flex-direction: column;\r\n border: 1px solid;\r\n min-height: 200px;\r\n}\r\n\r\n.container:before,\r\n.container:after {\r\n content: \"\";\r\n flex: 1;\r\n}\r\n\r\n.inner {\r\n border: 1px solid red;\r\n padding: 5px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"container\">\r\n <div class=\"inner\">\r\n Foo content\r\n </div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48437064,
"author": "Anu",
"author_id": 7635131,
"author_profile": "https://Stackoverflow.com/users/7635131",
"pm_score": 1,
"selected": false,
"text": "<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-css lang-css prettyprint-override\"><code>#inner {\r\n display: table;\r\n margin: 0 auto;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\" style=\"width:100%\">\r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48437400,
"author": "Anu",
"author_id": 7635131,
"author_profile": "https://Stackoverflow.com/users/7635131",
"pm_score": 1,
"selected": false,
"text": "<p>The main attributes for centering the div are <code>margin: auto</code> and <code>width:</code> according to requirements:</p>\n\n<pre><code>.DivCenter{\n width: 50%;\n margin: auto;\n border: 3px solid #000;\n padding: 10px;\n}\n</code></pre>\n"
},
{
"answer_id": 49306625,
"author": "Shivam Chhetri",
"author_id": 9138195,
"author_profile": "https://Stackoverflow.com/users/9138195",
"pm_score": 2,
"selected": false,
"text": "<p>This centralizes your inner div horizontally and vertically:</p>\n\n<pre><code>#outer{\n display: flex;\n}\n#inner{\n margin: auto;\n}\n</code></pre>\n\n<p>For only horizontal align, change</p>\n\n<pre><code>margin: 0 auto;\n</code></pre>\n\n<p>and for vertical, change</p>\n\n<pre><code>margin: auto 0;\n</code></pre>\n"
},
{
"answer_id": 50785476,
"author": "Milan Panigrahi",
"author_id": 9121968,
"author_profile": "https://Stackoverflow.com/users/9121968",
"pm_score": 5,
"selected": false,
"text": "<p>You can use <code>display: flex</code> for your outer div and to horizontally center you have to add <code>justify-content: center</code></p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#outer{\n display: flex;\n justify-content: center;\n}\n</code></pre>\n\n<p>or you can visit <a href=\"https://www.w3schools.com/cssref/css3_pr_flex.asp\" rel=\"noreferrer\">w3schools - CSS flex Property</a> for more ideas.</p>\n"
},
{
"answer_id": 51349575,
"author": "MANGESH SUPE",
"author_id": 9857446,
"author_profile": "https://Stackoverflow.com/users/9857446",
"pm_score": -1,
"selected": false,
"text": "<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-html lang-html prettyprint-override\"><code><!DOCTYPE html>\r\n<html>\r\n <head>\r\n <title>Center</title>\r\n <style>\r\n .outer{\r\n text-align: center;\r\n }\r\n .inner{\r\n width: 500px;\r\n margin: 0 auto;\r\n background: brown;\r\n color: red;\r\n }\r\n\r\n</style>\r\n\r\n </head>\r\n\r\n <body>\r\n\r\n <div class=\"outer\">\r\n <div class=\"inner\">This DIV is centered</div>\r\n </div>\r\n\r\n </body>\r\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Please try this. It will work without the HTML center tag.</p>\n"
},
{
"answer_id": 51724022,
"author": "Jaison James",
"author_id": 1374554,
"author_profile": "https://Stackoverflow.com/users/1374554",
"pm_score": 2,
"selected": false,
"text": "<p>The best I have used in my various projects is </p>\n\n<pre><code><div class=\"outer\">\n <div class=\"inner\"></div>\n</div>\n.outer{\n width: 500px;\n height: 500px;\n position: relative;\n background: yellow;\n}\n.inner{\n width: 100px;\n height: 100px;\n background:red;\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n}\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/jaisonjjames/phacnvf4/\" rel=\"nofollow noreferrer\">fiddle link</a></p>\n"
},
{
"answer_id": 51844248,
"author": "Galarist",
"author_id": 10123520,
"author_profile": "https://Stackoverflow.com/users/10123520",
"pm_score": 1,
"selected": false,
"text": "<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-css lang-css prettyprint-override\"><code>#outer {\r\n width: 160px;\r\n padding: 5px;\r\n border-style: solid;\r\n border-width: thin;\r\n display: block;\r\n}\r\n\r\n#inner {\r\n margin: auto;\r\n background-color: lightblue;\r\n border-style: solid;\r\n border-width: thin;\r\n width: 80px;\r\n padding: 10px;\r\n text-align: center;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 52230054,
"author": "Mark Salvania",
"author_id": 10326622,
"author_profile": "https://Stackoverflow.com/users/10326622",
"pm_score": 2,
"selected": false,
"text": "<p>This will surely center your <code>#inner</code> both horizontally and vertically. This is also compatible in all browsers. I just added extra styling just to show how it is centered.</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-css lang-css prettyprint-override\"><code>#outer {\r\n background: black;\r\n position: relative;\r\n width:150px;\r\n height:150px;\r\n}\r\n\r\n#inner { \r\n background:white;\r\n position: absolute;\r\n left:50%;\r\n top: 50%;\r\n transform: translate(-50%,-50%);\r\n -webkit-transform: translate(-50%,-50%);\r\n -moz-transform: translate(-50%,-50%); \r\n -o-transform: translate(-50%,-50%);\r\n} </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\"> \r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>But of course if you only want it horizontally aligned, This may help you.</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-css lang-css prettyprint-override\"><code>#outer {\r\n background: black;\r\n position: relative;\r\n width:150px;\r\n height:150px;\r\n}\r\n\r\n#inner { \r\n background:white;\r\n position: absolute;\r\n left:50%;\r\n transform: translate(-50%,0);\r\n -webkit-transform: translate(-50%,0);\r\n -moz-transform: translate(-50%,0); \r\n -o-transform: translate(-50%,0);\r\n} </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\"> \r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 52230061,
"author": "drewkiimon",
"author_id": 8249594,
"author_profile": "https://Stackoverflow.com/users/8249594",
"pm_score": 2,
"selected": false,
"text": "<p>One of the easiest ways you can do it is by using <code>display: flex</code>. The outer div just needs to have display flex, and the inner needs <code>margin: 0 auto</code> to make it centered horizontally.</p>\n\n<p>To center vertically and just center a div within another div, please look at the comments of the .inner class below</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-css lang-css prettyprint-override\"><code>.wrapper {\r\n display: flex;\r\n /* Adding whatever height & width we want */\r\n height: 300px;\r\n width: 300px;\r\n /* Just so you can see it is centered */\r\n background: peachpuff;\r\n}\r\n\r\n.inner {\r\n /* center horizontally */\r\n margin: 0 auto;\r\n /* center vertically */\r\n /* margin: auto 0; */\r\n /* center */\r\n /* margin: 0 auto; */\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"wrapper\">\r\n <div class=\"inner\">\r\n I am horizontally!\r\n </div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 52266619,
"author": "Morteza Sadri",
"author_id": 7707724,
"author_profile": "https://Stackoverflow.com/users/7707724",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it by using <a href=\"https://en.wikipedia.org/wiki/CSS_Flexible_Box_Layout\" rel=\"nofollow noreferrer\">Flexbox</a> which is a good technique these days.</p>\n\n<p>For using Flexbox you should give <code>display: flex;</code> and <code>align-items: center;</code> to your parent or <code>#outer</code> div element. The code should be 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-css lang-css prettyprint-override\"><code>#outer {\r\n display: flex;\r\n align-items: center;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This should center your child or <code>#inner</code> div horizontally. But you can't actually see any changes. Because our <code>#outer</code> div has no height or in other words, its height is set to auto, so it has the same height as all of its child elements. So after a little of visual styling, the result code should be 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-css lang-css prettyprint-override\"><code>#outer {\r\n height: 500px;\r\n display: flex;\r\n align-items: center;\r\n background-color: blue;\r\n}\r\n\r\n#inner {\r\n height: 100px;\r\n background: yellow;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>You can see <code>#inner</code> div is now centered. Flexbox is the new method of positioning elements in horizontal or vertical stacks with CSS and it's got 96% of global browsers compatibility. So you are free to use it and if you want to find out more about Flexbox visit <a href=\"https://css-tricks.com/snippets/css/a-guide-to-flexbox/\" rel=\"nofollow noreferrer\">CSS-Tricks</a> article. That is the best place to learn using Flexbox in my opinion.</p>\n"
},
{
"answer_id": 53296801,
"author": "Mohammed Rabiulla RABI",
"author_id": 9321142,
"author_profile": "https://Stackoverflow.com/users/9321142",
"pm_score": 2,
"selected": false,
"text": "<pre><code>div{\n width: 100px;\n height: 100px;\n margin: 0 auto;\n}\n</code></pre>\n\n<p>For the normal thing if you are using div in a static way.</p>\n\n<p>If you want a div to be centered when div is absolute to its parent, here is example:</p>\n\n<pre><code>.parentdiv{\n position: relative;\n height: 500px;\n}\n\n.child_div{\n position: absolute;\n height: 200px;\n width: 500px;\n left: 0;\n right: 0;\n margin: 0 auto;\n}\n</code></pre>\n"
},
{
"answer_id": 53465902,
"author": "Fatemeh Khosravi Farsani",
"author_id": 2370039,
"author_profile": "https://Stackoverflow.com/users/2370039",
"pm_score": 2,
"selected": false,
"text": "<p>This worked for me:</p>\n<pre class=\"lang-css prettyprint-override\"><code>#inner {\n position: absolute;\n margin: 0 auto;\n left: 0;\n width: 7%;\n right: 0;\n}\n</code></pre>\n<p>In this code, you determine the width of the element.</p>\n"
},
{
"answer_id": 53973313,
"author": "orghu",
"author_id": 2817442,
"author_profile": "https://Stackoverflow.com/users/2817442",
"pm_score": 1,
"selected": false,
"text": "<p>I found a similar way with <code>margin-left</code>, but it can be <code>left</code> as well.</p>\n\n<pre><code>#inner {\n width: 100%;\n max-width: 65px; /* To adapt to screen width. It can be whatever you want. */\n left: 65px; /* This has to be approximately the same as the max-width. */\n}\n</code></pre>\n"
},
{
"answer_id": 54642130,
"author": "Ady Ngom",
"author_id": 2074138,
"author_profile": "https://Stackoverflow.com/users/2074138",
"pm_score": 4,
"selected": false,
"text": "<p>A very simple and cross-browser answer to horizontal center is to apply this rule to the parent element:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.parentBox {\n display: flex;\n justify-content: center\n}\n</code></pre>\n"
},
{
"answer_id": 55045803,
"author": "pavelbere",
"author_id": 11129768,
"author_profile": "https://Stackoverflow.com/users/11129768",
"pm_score": 2,
"selected": false,
"text": "<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-css lang-css prettyprint-override\"><code>.outer\r\n{\r\n background-color: rgb(230,230,255);\r\n width: 100%;\r\n height: 50px;\r\n}\r\n.inner\r\n{\r\n background-color: rgb(200,200,255);\r\n width: 50%;\r\n height: 50px;\r\n margin: 0 auto;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\r\n <div class=\"inner\">\r\n margin 0 auto\r\n </div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 55360820,
"author": "Hassan Siddiqui",
"author_id": 3169136,
"author_profile": "https://Stackoverflow.com/users/3169136",
"pm_score": 3,
"selected": false,
"text": "<p>Make it simple!</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-css lang-css prettyprint-override\"><code>#outer {\r\n display: flex;\r\n justify-content: center;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\"> \r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 55515508,
"author": "Shashin Bhayani",
"author_id": 10429035,
"author_profile": "https://Stackoverflow.com/users/10429035",
"pm_score": 5,
"selected": false,
"text": "<p>You can just simply use <a href=\"https://en.wikipedia.org/wiki/CSS_Flexible_Box_Layout\" rel=\"noreferrer\">Flexbox</a> 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-css lang-css prettyprint-override\"><code>#outer {\r\n display: flex;\r\n justify-content: center\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Apply Autoprefixer for all browser support:</p>\n\n<pre><code>#outer {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n width: 100%;\n -webkit-box-pack: center;\n -ms-flex-pack: center;\n justify-content: center\n}\n</code></pre>\n\n<h1>Or else</h1>\n\n<p>Use <strong>transform</strong>:</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-css lang-css prettyprint-override\"><code>#inner {\r\n position: absolute;\r\n left: 50%;\r\n transform: translate(-50%)\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\r\n <div id=\"inner\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>With Autoprefixer:</p>\n\n<pre><code>#inner {\n position: absolute;\n left: 50%;\n -webkit-transform: translate(-50%);\n -ms-transform: translate(-50%);\n transform: translate(-50%)\n}\n</code></pre>\n"
},
{
"answer_id": 56275647,
"author": "Riddhi Busa",
"author_id": 5440324,
"author_profile": "https://Stackoverflow.com/users/5440324",
"pm_score": -1,
"selected": false,
"text": "<p>For a horizontally centered DIV:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#outer {\n width: 100%;\n text-align: center;\n}\n#inner {\n display: inline-block;\n}\n</code></pre>\n\n<pre class=\"lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div>\n</code></pre>\n\n\n"
},
{
"answer_id": 56361573,
"author": "Javed Khan",
"author_id": 9704900,
"author_profile": "https://Stackoverflow.com/users/9704900",
"pm_score": 1,
"selected": false,
"text": "<pre><code>#inner {\n width: 50%;\n margin: 0 auto;\n}\n</code></pre>\n"
},
{
"answer_id": 57012108,
"author": "Appy Sharma",
"author_id": 7802577,
"author_profile": "https://Stackoverflow.com/users/7802577",
"pm_score": 4,
"selected": false,
"text": "<p>We can use <strong><a href=\"https://en.wikipedia.org/wiki/CSS_Flexible_Box_Layout\" rel=\"noreferrer\">Flexbox</a></strong> to achieve this really easily:</p>\n\n<pre><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div>\n</code></pre>\n\n<p>Center a div inside a div <em>horizontally</em>:</p>\n\n<pre><code>#outer {\n display: flex;\n justify-content: center;\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/sT5Rb.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/sT5Rb.png\" alt=\"Enter image description here\"></a></p>\n\n<p>Center a div inside a div <em>vertically</em>:</p>\n\n<pre><code>#outer {\n display: flex;\n align-items: center;\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/a7vse.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/a7vse.png\" alt=\"Enter image description here\"></a></p>\n\n<p>And, to completely middle the div vertically and horizontally:</p>\n\n<pre><code>#outer{\n display: flex;\n justify-content: center;\n align-items: center;\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/0J9dv.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0J9dv.png\" alt=\"Enter image description here\"></a></p>\n"
},
{
"answer_id": 57100359,
"author": "SB3NDER",
"author_id": 9350702,
"author_profile": "https://Stackoverflow.com/users/9350702",
"pm_score": 2,
"selected": false,
"text": "<p>You can add another div which has the same size of #inner and move it to the left by -50% (half of the width of #inner) and #inner by 50%.</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-css lang-css prettyprint-override\"><code>#inner {\r\n position: absolute;\r\n left: 50%;\r\n}\r\n\r\n#inner > div {\r\n position: relative;\r\n left: -50%;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\r\n <div id=\"inner\"><div>Foo foo</div></div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 57272025,
"author": "Asmit",
"author_id": 10721198,
"author_profile": "https://Stackoverflow.com/users/10721198",
"pm_score": 3,
"selected": false,
"text": "<p><strong>One of the easiest ways...</strong></p>\n\n<pre><code><!DOCTYPE html>\n<html>\n <head>\n <style>\n #outer-div {\n width: 100%;\n text-align: center;\n background-color: #000\n }\n #inner-div {\n display: inline-block;\n margin: 0 auto;\n padding: 3px;\n background-color: #888\n }\n </style>\n </head>\n\n <body>\n <div id =\"outer-div\" width=\"100%\">\n <div id =\"inner-div\"> I am a easy horizontally centered div.</div>\n <div>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 59006837,
"author": "Sawan mishra",
"author_id": 3454233,
"author_profile": "https://Stackoverflow.com/users/3454233",
"pm_score": 3,
"selected": false,
"text": "<p><strong>This is the best example to horizontally center a <div></strong></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-css lang-css prettyprint-override\"><code>#outer {\r\n display: flex;\r\n align-items: center;\r\n justify-content: center;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\r\n<html>\r\n <head>\r\n\r\n </head>\r\n\r\n <body>\r\n <div id=\"outer\">\r\n <div id=\"inner\">Foo foo</div>\r\n </div>\r\n </body>\r\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 59263638,
"author": "Shoma",
"author_id": 7901403,
"author_profile": "https://Stackoverflow.com/users/7901403",
"pm_score": 3,
"selected": false,
"text": "<p>If you have a parent of some height say, <code>body{height: 200px}</code>\nor like the below has parent div#outer with height 200px, then add CSS content as below</p>\n\n<p>HTML:</p>\n\n<pre><code><div id=\"outer\">\n <div id=\"centered\">Foo foo</div>\n</div>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>#outer{\n display: flex;\n width: 100%;\n height: 200px;\n}\n#centered {\n margin: auto;\n}\n</code></pre>\n\n<p>Then child content, say div#centered content, will be vertically or horizontally middle, without using any position CSS. To remove vertically middle behavior then just modify to below CSS code:</p>\n\n<pre><code>#centered {\n margin: 0px auto;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>#outer{\n display: flex;\n width: 100%;\n height: 200px;\n}\n#centered {\n margin: auto;\n}\n\n<div id=\"outer\">\n <div id=\"centered\">Foo foo</div>\n</div>\n</code></pre>\n\n<p>Demo: <a href=\"https://jsfiddle.net/jinny/p3x5jb81/5/\" rel=\"noreferrer\">https://jsfiddle.net/jinny/p3x5jb81/5/</a></p>\n\n<p>To add only a border to show the inner div is not 100% by default:</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-css lang-css prettyprint-override\"><code>#outer{\r\n display: flex;\r\n width: 100%;\r\n height: 200px;\r\n border: 1px solid #000000;\r\n}\r\n#centered {\r\n margin: auto;\r\n border: 1px solid #000000;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\r\n <div id=\"centered\">Foo foo</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>DEMO: <a href=\"http://jsfiddle.net/jinny/p3x5jb81/9\" rel=\"noreferrer\">http://jsfiddle.net/jinny/p3x5jb81/9</a></p>\n"
},
{
"answer_id": 59607763,
"author": "ChandanK",
"author_id": 9826412,
"author_profile": "https://Stackoverflow.com/users/9826412",
"pm_score": 4,
"selected": false,
"text": "<p>Just add this CSS content into your CSS file. It will automatically center the content.</p>\n\n<p>Align horizontally to center in CSS:</p>\n\n<pre><code>#outer {\n display: flex;\n justify-content: center;\n}\n</code></pre>\n\n<p>Align-vertically + horizontal to center in CSS:</p>\n\n<pre><code>#outer {\n display: flex;\n justify-content: center;\n align-items: center;\n}\n</code></pre>\n"
},
{
"answer_id": 60116165,
"author": "Alessandro_Russo",
"author_id": 2893733,
"author_profile": "https://Stackoverflow.com/users/2893733",
"pm_score": 3,
"selected": false,
"text": "<p>With <a href=\"https://sass-lang.com/\" rel=\"nofollow noreferrer\">Sass</a> (SCSS syntax) you can do this with a <a href=\"https://sass-lang.com/documentation/at-rules/mixin\" rel=\"nofollow noreferrer\">mixin</a>:</p>\n<h2>With <em>translate</em></h2>\n<pre><code>// Center horizontal mixin\n@mixin center-horizontally {\n position: absolute;\n left: 50%;\n transform: translate(-50%, -50%);\n}\n\n// Center horizontal class\n.center-horizontally {\n @include center-horizontally;\n}\n</code></pre>\n<p>In an HTML tag:</p>\n<pre><code><div class="center-horizontally">\n I'm centered!\n</div>\n</code></pre>\n<p><strong>Remember</strong> to add <code>position: relative;</code> to the parent HTML element.</p>\n<hr />\n<h2>With Flexbox</h2>\n<p>Using <em>flex</em>, you can do this:</p>\n<pre><code>@mixin center-horizontally {\n display: flex;\n justify-content: center;\n}\n\n// Center horizontal class\n.center-horizontally {\n @include center-horizontally;\n}\n</code></pre>\n<p>In an HTML tag:</p>\n<pre><code><div class="center-horizontally">\n <div>I'm centered!</div>\n</div>\n</code></pre>\n<p>Try <a href=\"https://codepen.io/alessandroinfo/pen/oNXgXyM\" rel=\"nofollow noreferrer\">this CodePen</a>!</p>\n"
},
{
"answer_id": 60301181,
"author": "jual ahmed",
"author_id": 9797396,
"author_profile": "https://Stackoverflow.com/users/9797396",
"pm_score": 2,
"selected": false,
"text": "<p>I used <a href=\"https://en.wikipedia.org/wiki/CSS_Flexible_Box_Layout\" rel=\"nofollow noreferrer\">Flexbox</a> or <a href=\"https://en.wikipedia.org/wiki/CSS_grid_layout\" rel=\"nofollow noreferrer\">CSS grid</a></p>\n\n<ol>\n<li><p>Flexbox</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-html lang-html prettyprint-override\"><code>#outer{\r\n display: flex;\r\n justify-content: center;\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p></li>\n<li><p>CSS grid</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-css lang-css prettyprint-override\"><code>#outer {\r\n display: inline-grid;\r\n grid-template-rows: 100px 100px 100px;\r\n grid-template-columns: 100px 100px 100px;\r\n grid-gap: 3px;\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p></li>\n</ol>\n\n<p>You can solve the issue in many ways.</p>\n"
},
{
"answer_id": 61367209,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In the previous examples they used <code>margin: 0 auto</code>, <code>display:table</code> and other answers used "with transform and translate".</p>\n<p>And what about just with a tag? Everyone knows there is a <code><center></code> tag which is just not supported by HTML5. But it works in HTML5. For instance, in my old projects.</p>\n<p>And it is working, but now not only <a href=\"https://en.wikipedia.org/wiki/MDN_Web_Docs\" rel=\"nofollow noreferrer\">MDN Web Docs</a>, but other websites are advising not to use it any more. Here in <em><a href=\"https://caniuse.com/#info_about\" rel=\"nofollow noreferrer\">Can I use</a></em> you can see notes from MDN Web Docs. But whatever, there is such a way. This is just to know. Always being noticed about something is so useful.</p>\n<p><a href=\"https://i.stack.imgur.com/aNDMQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aNDMQ.png\" alt=\"Enter image description here\" /></a></p>\n"
},
{
"answer_id": 62515727,
"author": "Utkarsh Tyagi",
"author_id": 13779469,
"author_profile": "https://Stackoverflow.com/users/13779469",
"pm_score": 3,
"selected": false,
"text": "<p>To align a div within a div in middle -</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-css lang-css prettyprint-override\"><code>.outer{\n width: 300px; /* For example */\n height: 300px; /* For example */\n background: red;\n}\n.inner{\n position: relative;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 200px;\n height: 200px;\n background: yellow;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body>\n <div class='outer'>\n <div class='inner'></div>\n </div>\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This will align the internal div in the middle, both vertically and horizontally.</p>\n"
},
{
"answer_id": 63123622,
"author": "air5",
"author_id": 7764088,
"author_profile": "https://Stackoverflow.com/users/7764088",
"pm_score": 4,
"selected": false,
"text": "<p><strong>With Grid</strong></p>\n<p>A pretty simple and modern way is to use <code>display: grid</code>:</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-css lang-css prettyprint-override\"><code>div {\n border: 1px dotted grey;\n}\n\n#outer {\n display: grid;\n place-items: center;\n height: 50px; /* not necessary */\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html>\n <head>\n </head>\n\n <body>\n <div id=\"outer\">\n <div>Foo foo</div>\n </div>\n </body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 63469234,
"author": "Priya jain",
"author_id": 6076863,
"author_profile": "https://Stackoverflow.com/users/6076863",
"pm_score": 2,
"selected": false,
"text": "<h3>CSS <em>justify-content</em> property</h3>\n<p>It <em>aligns</em> the Flexbox items at the center of the container:</p>\n<pre><code>#outer {\n display: flex;\n justify-content: center;\n}\n</code></pre>\n"
},
{
"answer_id": 63746323,
"author": "sabban",
"author_id": 13435350,
"author_profile": "https://Stackoverflow.com/users/13435350",
"pm_score": 2,
"selected": false,
"text": "<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-css lang-css prettyprint-override\"><code>#outer\n{\n display: grid;\n justify-content: center;\n\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">hello</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n<code>enter code here</code></p>\n"
},
{
"answer_id": 64015413,
"author": "mdmundo",
"author_id": 11720321,
"author_profile": "https://Stackoverflow.com/users/11720321",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n<pre class=\"lang-html prettyprint-override\"><code><div style="position: absolute;left: 50%;top: 50%;-webkit-transform: translate(-50%, -50%);transform: translate(-50%, -50%);"><div>Example</div></div>\n</code></pre>\n"
},
{
"answer_id": 64672383,
"author": "John T",
"author_id": 9403953,
"author_profile": "https://Stackoverflow.com/users/9403953",
"pm_score": 2,
"selected": false,
"text": "<p>In my case I needed to center(on screen) a dropdown menu(using flexbox for it's items) below a button that could have various locations vertically. None of the suggestions worked until I changed position from absolute to fixed, like this:</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-css lang-css prettyprint-override\"><code>#outer {\n margin: auto;\n left: 0;\n right: 0;\n position: fixed;\n}\n#inner {\n text-align: center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The above codes makes the dropdown to always center on the screen for devices of all sizes, no matter where the dropdown button is located vertically.</p>\n"
},
{
"answer_id": 65804173,
"author": "Jone",
"author_id": 14769063,
"author_profile": "https://Stackoverflow.com/users/14769063",
"pm_score": 0,
"selected": false,
"text": "<p>Flexbox Center Horizontally and Vertically Center Align an Element</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-css lang-css prettyprint-override\"><code>.wrapper {border: 1px solid #678596; max-width: 350px; margin: 30px auto;} \n \n.parentClass { display: flex; justify-content: center; align-items: center; height: 300px;}\n \n.parentClass div {margin: 5px; background: #678596; width: 50px; line-height: 50px; text-align: center; font-size: 30px; color: #fff;}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><h1>Flexbox Center Horizontally and Vertically Center Align an Element</h1>\n<h2>justify-content: center; align-items: center;</h2>\n\n<div class=\"wrapper\">\n\n<div class=\"parentClass\">\n <div>c</div>\n</div>\n\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 66435423,
"author": "proseosoc",
"author_id": 5225541,
"author_profile": "https://Stackoverflow.com/users/5225541",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Center an Element Without Need of a Wrapper/Parent with Dynamic Height & Width</strong></p>\n<p><strong>No side effect:</strong> It will not limit a centered element's width less than the viewport width, when using margins in Flexbox inside a centered element</p>\n<pre><code>position: fixed;\ntop: 0; left: 0;\ntransform: translate(calc(50vw - 50%));\n</code></pre>\n<p>Horizontally + vertically center, if its height is same as the width:</p>\n<pre><code>position: fixed;\ntop: 0; left: 0;\ntransform: translate(calc(50vw - 50%), calc(50vh - 50%));\n</code></pre>\n"
},
{
"answer_id": 66739798,
"author": "Satish Chandra Gupta",
"author_id": 9445290,
"author_profile": "https://Stackoverflow.com/users/9445290",
"pm_score": 3,
"selected": false,
"text": "<h1>To centre an element horizontally you can use these methods:</h1>\n<h2><strong>Method 1: Using margin property</strong></h2>\n<p>If the element is a block-level element then you can centre the element by using margin property. Set <code>margin-left</code> and <code>margin-right</code> is to auto (Shorthand - <code>margin: 0 auto</code>).</p>\n<p>This will align the element to the centre horizontally.\nIf the element is not a block-level element then add <code>display: block</code> property to it.</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-css lang-css prettyprint-override\"><code>#outer {\n background-color: silver;\n}\n#inner {\n width: max-content;\n margin: 0 auto;\n background-color: #f07878;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2><strong>Method 2: Using CSS flexbox</strong></h2>\n<p>Create a flexbox container and use <code>justify-content</code> property and set it to <code>center</code>. This will align all elements horizontally to the centre of the webpage.</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-css lang-css prettyprint-override\"><code>#outer {\n display: flex;\n justify-content: center;\n background-color: silver;\n}\n#inner {\n background-color: #f07878;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Method 3: Using position absolute technique</h2>\n<p>This is a classic method to centre the element. Set <code>postion:relative</code> to the outer element. Set the inner element's position to absolute and <code>left: 50%</code>. This will push the inner element to start from the centre of the outer element. Now use the transform property and set <code>transform: translateX(-50%)</code> this will make the element centre horizontally.</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-css lang-css prettyprint-override\"><code>#outer {\n position: relative;\n background-color: silver;\n}\n#inner {\n position: absolute;\n left: 50%;\n transform: translateX(-50%);\n background-color: #f07878;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <center>\n <div id=\"inner\">Foo foo</div>\n </center>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 66866694,
"author": "Vasyl Gutnyk",
"author_id": 3277216,
"author_profile": "https://Stackoverflow.com/users/3277216",
"pm_score": 0,
"selected": false,
"text": "<pre><code>button {\n margin: 0 auto;\n width: fit-content;\n display: block;\n}\n// container should have set width (for example 100%)\n</code></pre>\n"
},
{
"answer_id": 67053491,
"author": "Abdullah Ch",
"author_id": 13708712,
"author_profile": "https://Stackoverflow.com/users/13708712",
"pm_score": 3,
"selected": false,
"text": "<p>Just do this:</p>\n<pre><code><div id="outer">\n <div id="inner">Foo foo</div>\n</div>\n</code></pre>\n<p>CSS</p>\n<pre><code>#outer{\n display: grid;\n place-items: center;\n}\n\n</code></pre>\n"
},
{
"answer_id": 67132637,
"author": "Egon Stetmann.",
"author_id": 7238789,
"author_profile": "https://Stackoverflow.com/users/7238789",
"pm_score": 2,
"selected": false,
"text": "<p>I've seen lots and lots of answers and they are all outdated. Google already implemented a solution for this common problem, which centers the object literally in the middle no matter what happens, and YES it's responsive. So never do <code>transform()</code> or <code>position</code> manually ever again.</p>\n<h2>.HTML</h2>\n<pre><code>...\n<div class="parent">\n <form> ... </form>\n <div> ... </div>\n</div>\n</code></pre>\n<h2>.CSS</h2>\n<pre><code>.parent {\n display: grid;\n place-items: center;\n}\n</code></pre>\n"
},
{
"answer_id": 67390020,
"author": "Tharindu Lakshan",
"author_id": 11384233,
"author_profile": "https://Stackoverflow.com/users/11384233",
"pm_score": 3,
"selected": false,
"text": "<p>This can be done by using lots of methods. Many guys'/gals' given answers are correct and working properly. I'll give one more different pattern.</p>\n<p>In the <strong>HTML</strong> file</p>\n<pre><code><div id="outer">\n <div id="inner">Foo foo</div>\n</div>\n</code></pre>\n<p>In the <strong>CSS</strong> file</p>\n<pre><code>#outer{\n width: 100%;\n}\n\n#inner{\n margin: auto;\n}\n</code></pre>\n"
},
{
"answer_id": 67547259,
"author": "Krutik Raut",
"author_id": 13613400,
"author_profile": "https://Stackoverflow.com/users/13613400",
"pm_score": 0,
"selected": false,
"text": "<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-css lang-css prettyprint-override\"><code>#outer {\ndisplay:grid;\nplace-items:center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"inner\">Foo foo</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 69733298,
"author": "Ismoil Shokirov",
"author_id": 12924484,
"author_profile": "https://Stackoverflow.com/users/12924484",
"pm_score": 2,
"selected": false,
"text": "<p>There are several ways to achieve it: using "flex", "positioning", "margin" and others. Assuming <code>#outer</code> and <code>#inner</code> divs given in the question:</p>\n<p><strong>I would recommend using "flex"</strong></p>\n<pre class=\"lang-css prettyprint-override\"><code>#outer {\n display: flex;\n justify-content: center;\n align-items: center; /* if you also need vertical center */\n}\n</code></pre>\n<p>Horizontal align using positioning</p>\n<pre class=\"lang-css prettyprint-override\"><code>#outer {\n position: relative;\n}\n#inner {\n position: absolute;\n left: 50%;\n translate: transformX(-50%)\n}\n</code></pre>\n<p>Horizontal and vertical-align using positioning</p>\n<pre class=\"lang-css prettyprint-override\"><code>#outer {\n position: relative;\n}\n#inner {\n position: absolute;\n left: 50%;\n top: 50%;\n translate: transform(-50%, -50%)\n}\n</code></pre>\n<p>Horizontal align using margin</p>\n<pre class=\"lang-css prettyprint-override\"><code>#inner {\n width: fit-content;\n margin: 0 auto;\n}\n</code></pre>\n"
},
{
"answer_id": 69778212,
"author": "Anil Parshi",
"author_id": 15405352,
"author_profile": "https://Stackoverflow.com/users/15405352",
"pm_score": 0,
"selected": false,
"text": "<p>I'd simply suggest using <code>justify-content: center;</code> when the container is displayed as flex.\nand <code>text-align: center;</code> when it is about a text element.</p>\n<p>check the code below and modify as per the requirements.</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-css lang-css prettyprint-override\"><code>#content_block {\n border: 1px solid black;\n padding: 10px;\n width: 50%;\n text-align: center;\n}\n\n#container {\n border: 1px solid red;\n width:100%;\n padding: 20px;\n display: flex;\n justify-content: center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"container\">\n <div id=\"content_block\">Foo foo check</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 70569854,
"author": "Rounin - Standing with Ukraine",
"author_id": 3897775,
"author_profile": "https://Stackoverflow.com/users/3897775",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n<p>How can I horizontally center a <code><div></code> within another <code><div></code> using CSS?</p>\n</blockquote>\n<p>Here's a non-exhaustive list of centering approaches, using:</p>\n<ul>\n<li><code>margin</code> and <code>auto</code></li>\n<li><code>margin</code> and <code>calc()</code></li>\n<li><code>padding</code> and <code>box-sizing</code> and <code>calc()</code></li>\n<li><code>position: absolute</code> and <em>negative</em> <code>margin-left</code></li>\n<li><code>position: absolute</code> and <em>negative</em> <code>transform: translateX()</code></li>\n<li><code>display: inline-block</code> and <code>text-align: center</code></li>\n<li><code>display: table</code> and <code>display: table-cell</code></li>\n<li><code>display: flex</code> and <code>justify-content: center</code></li>\n<li><code>display: grid</code> and <code>justify-items: center</code></li>\n</ul>\n<h2>1. Center a block-level element using <code>auto</code> for horizontal margins</h2>\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-css lang-css prettyprint-override\"><code>.outer {\n width: 300px;\n height: 180px;\n background-color: rgb(255, 0, 0);\n}\n\n.inner {\n width: 150px;\n height: 180px;\n margin: 0 auto;\n background-color: rgb(255, 255, 0);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\n <div class=\"inner\"></div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>2. Center a block-level element using <code>calc</code> with horizontal margins</h2>\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-css lang-css prettyprint-override\"><code>.outer {\n width: 300px;\n height: 180px;\n background-color: rgb(255, 0, 0);\n}\n\n.inner {\n width: 150px;\n height: 180px;\n margin: 0 calc((300px - 150px) / 2);\n background-color: rgb(255, 255, 0);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\n <div class=\"inner\"></div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>3. Center a block-level element using <code>calc</code> with horizontal padding + <code>box-sizing</code></h2>\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-css lang-css prettyprint-override\"><code>.outer {\n width: 300px;\n height: 180px;\n padding: 0 calc((300px - 150px) / 2);\n background-color: rgb(255, 0, 0);\n box-sizing: border-box;\n}\n\n.inner {\n width: 150px;\n height: 180px;\n background-color: rgb(255, 255, 0);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\n <div class=\"inner\"></div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>4. Center a block-level element using <code>position: absolute</code> with <code>left: 50%</code> and <em>negative</em> <code>margin-left</code></h2>\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-css lang-css prettyprint-override\"><code>.outer {\n position: relative;\n width: 300px;\n height: 180px;\n background-color: rgb(255, 0, 0);\n}\n\n.inner {\n position: absolute;\n left: 50%;\n width: 150px;\n height: 180px;\n margin-left: -75px;\n background-color: rgb(255, 255, 0);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\n <div class=\"inner\"></div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>5. Center a block-level element using <code>position: absolute</code> with <code>left: 50%</code> and <em>negative</em> <code>transform: translateX()</code></h2>\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-css lang-css prettyprint-override\"><code>.outer {\n position: relative;\n width: 300px;\n height: 180px;\n background-color: rgb(255, 0, 0);\n}\n\n.inner {\n position: absolute;\n left: 50%;\n width: 150px;\n height: 180px;\n background-color: rgb(255, 255, 0);\n transform: translateX(-75px);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\n <div class=\"inner\"></div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>6. Center an element using <code>display: inline-block</code> and <code>text-align: center</code></h2>\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-css lang-css prettyprint-override\"><code>.outer {\n position: relative;\n width: 300px;\n height: 180px;\n text-align: center;\n background-color: rgb(255, 0, 0);\n}\n\n.inner {\n display: inline-block;\n width: 150px;\n height: 180px;\n background-color: rgb(255, 255, 0);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\n <div class=\"inner\"></div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>7. Center an element using <code>display: table</code>, <code>padding</code> and <code>box-sizing</code></h2>\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-css lang-css prettyprint-override\"><code>.outer {\n display: table;\n width: 300px;\n height: 180px;\n padding: 0 75px;\n background-color: rgb(255, 0, 0);\n box-sizing: border-box;\n}\n\n.inner {\n display: table-cell;\n background-color: rgb(255, 255, 0);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\n <div class=\"inner\"></div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>8. Center an element using <code>display: flex</code> and <code>justify-content: center</code></h2>\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-css lang-css prettyprint-override\"><code>.outer {\n display: flex;\n justify-content: center;\n width: 300px;\n height: 180px;\n background-color: rgb(255, 0, 0);\n}\n\n.inner {\n flex: 0 0 150px;\n background-color: rgb(255, 255, 0);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\n <div class=\"inner\"></div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>9. Center an element using <code>display: grid</code> and <code>justify-items: center</code></h2>\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-css lang-css prettyprint-override\"><code>.outer {\n display: grid;\n justify-items: center;\n width: 300px;\n height: 180px;\n background-color: rgb(255, 0, 0);\n}\n\n.inner {\n width: 150px;\n background-color: rgb(255, 255, 0);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"outer\">\n <div class=\"inner\"></div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 70785617,
"author": "Ali Hamza Yaseen",
"author_id": 10144242,
"author_profile": "https://Stackoverflow.com/users/10144242",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#outer{\n display: flex;\n width: 100%;\n height: 200px;\n justify-content:center;\n align-items:center;\n}\n</code></pre>\n"
},
{
"answer_id": 71138412,
"author": "Vishal Kardam",
"author_id": 16431434,
"author_profile": "https://Stackoverflow.com/users/16431434",
"pm_score": 0,
"selected": false,
"text": "<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-html lang-html prettyprint-override\"><code><html></code></pre>\r\n</div>\r\n</div>\r\n</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-css lang-css prettyprint-override\"><code>*{\n margin: 0;\n padding: 0;\n }\n #outer{\n background: red;\n width: 100%;\n height: 100vh;\n display: flex;\n /*center For vertically*/\n justify-content: center;\n flex-direction: column;\n /*center for horizontally*/\n align-items: center;\n }\n #inner{\n width: 80%;\n height: 40px;\n background: grey;\n margin-top:5px;\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>horizontally center an element</title>\n</head>\n\n<body>\n<div id=\"outer\">\n <div id=\"inner\">1</div>\n <div id=\"inner\" style=\"background: green;\">2</div>\n <div id=\"inner\" style=\"background: yellow;\">3</div>\n</div>\n</body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 72238157,
"author": "mirazimi",
"author_id": 6742006,
"author_profile": "https://Stackoverflow.com/users/6742006",
"pm_score": 0,
"selected": false,
"text": "<pre><code><div class="container">\n<div class="res-banner">\n<img class="imgmelk" src="~/File/opt_img.jpg" >\n</div>\n</div>\n</code></pre>\n<blockquote>\n<p>css code</p>\n</blockquote>\n<pre><code>.res-banner{\n width:309px;\n margin: auto;\n height:309px;\n }\n</code></pre>\n"
},
{
"answer_id": 72375591,
"author": "dkellner",
"author_id": 1892607,
"author_profile": "https://Stackoverflow.com/users/1892607",
"pm_score": 2,
"selected": false,
"text": "<h2>Recap 2022</h2>\n<p>This is a very old question so I'm just trying to report the situation today:</p>\n<ul>\n<li>CSS grid and flexbox are the best options you have for centering, horizontal or vertical;</li>\n<li>margin:auto method works well if the inner content is not a box (inline-block is okay);</li>\n<li>margin 50% with transform:translateX(-50%) is brute force but works allright;</li>\n<li>same thing with absolute positions and translateX/Y is good for horizontal and vertical centering too, many dialogs use that, stretching height to 100vh;</li>\n<li>the good old text-align:center with inline-block still works</li>\n<li>the ancient demon called "center tag" still works, actually it's the easiest way for horizontal centering. Deprecated, feared & hated by many but still;</li>\n<li>tables (td tags, actually) can center beautifully, horizontal and vertical, but they're also called old hat;</li>\n<li>these last 2 will work in email templates too (they're HTML4) if you're unlucky enough to work on one.</li>\n</ul>\n<p>That's what it looks like in 2022, and I hope we'll never need more than grids and flexboxes. Those guys are the answer to all our prayers in 1999.</p>\n"
},
{
"answer_id": 72403665,
"author": "Mubeen Ahmad",
"author_id": 17344570,
"author_profile": "https://Stackoverflow.com/users/17344570",
"pm_score": 1,
"selected": false,
"text": "<p>You can horizontally center a <code><div></code> within another <code><div></code> by using <code>text-align</code> Property in CSS.</p>\n<p><code>text-align: center</code> is used to center the text of the outer div horizontally.</p>\n<p><code>text-align: right</code> is used to align the text to the right.</p>\n<p><code>text-align: left</code> is used to align the text to the left.</p>\n<p><code>text-align: justify</code> is used to stretch the lines so that each line has equal width.</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-css lang-css prettyprint-override\"><code>div.a {\n text-align: center;\n}\n\ndiv.b {\n text-align: left;\n}\n\ndiv.c {\n text-align: right;\n} \n\ndiv.d {\n text-align: justify;\n} </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><h1>The text-align Property</h1>\n\n<div class=\"a\">\n<h2>text-align: center:</h2>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p>\n</div>\n\n<div class=\"b\">\n<h2>text-align: left:</h2>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p>\n</div>\n\n<div class=\"c\">\n<h2>text-align: right:</h2>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p>\n</div>\n\n<div class=\"d\">\n<h2>text-align: justify:</h2>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 73393666,
"author": "Chathuranga CPM",
"author_id": 2913984,
"author_profile": "https://Stackoverflow.com/users/2913984",
"pm_score": 0,
"selected": false,
"text": "<pre><code><div id="outer">\n <div id="inner">Foo foo</div>\n</div>\n\n\n\n#outer{\n display:flex;\n align-items:center;\n}\n</code></pre>\n"
},
{
"answer_id": 73449205,
"author": "legend",
"author_id": 19670872,
"author_profile": "https://Stackoverflow.com/users/19670872",
"pm_score": -1,
"selected": false,
"text": "<p>You can horizontally align any element using:</p>\n<pre><code><div align=center>\n (code goes here)\n</div>\n</code></pre>\n<p>Or:</p>\n<pre><code><!-- css here -->\n .center-me {\n margin: 0 auto;\n }\n\n<!-- html here -->\n <div class="center-me">\n (code goes here)\n </div>\n</code></pre>\n"
},
{
"answer_id": 74247962,
"author": "A. Ravindu Silva",
"author_id": 18738231,
"author_profile": "https://Stackoverflow.com/users/18738231",
"pm_score": -1,
"selected": false,
"text": "<p>I think this will be a solution:</p>\n<pre><code>#outer {\n position: absolute;\n left: 50%;\n}\n\n#inner {\n position: relative;\n left: -50%;\n}\n</code></pre>\n<p>Both elements must be the same width to function separately.</p>\n"
},
{
"answer_id": 74567666,
"author": "Harvir",
"author_id": 16195196,
"author_profile": "https://Stackoverflow.com/users/16195196",
"pm_score": -1,
"selected": false,
"text": "<p>can use a center tag for convenience</p>\n<pre><code> <div id="outer">\n <center> \n<div id="inner">Foo foo</div> \n</center> \n</div>\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20403/"
]
| How can I horizontally center a `<div>` within another `<div>` using CSS?
```html
<div id="outer">
<div id="inner">Foo foo</div>
</div>
``` | You can apply this CSS to the inner `<div>`:
```css
#inner {
width: 50%;
margin: 0 auto;
}
```
Of course, you don't have to set the `width` to `50%`. Any width less than the containing `<div>` will work. The `margin: 0 auto` is what does the actual centering.
If you are targeting [Internet Explorer 8](https://en.wikipedia.org/wiki/Internet_Explorer_8) (and later), it might be better to have this instead:
```css
#inner {
display: table;
margin: 0 auto;
}
```
It will make the inner element center horizontally and it works without setting a specific `width`.
Working example here:
```css
#inner {
display: table;
margin: 0 auto;
border: 1px solid black;
}
#outer {
border: 1px solid red;
width:100%
}
```
```html
<div id="outer">
<div id="inner">Foo foo</div>
</div>
```
---
EDIT
----
With `flexbox` it is very easy to style the div horizontally and vertically centered.
```css
#inner {
border: 0.05em solid black;
}
#outer {
border: 0.05em solid red;
width:100%;
display: flex;
justify-content: center;
}
```
```html
<div id="outer">
<div id="inner">Foo foo</div>
</div>
```
To align the div vertically centered, use the property `align-items: center`. |
114,619 | <p>I have defined a Delphi TTable object with calculated fields, and it is used in a grid on a form. I would like to make a copy of the TTable object, including the calculated fields, open that copy, do some changes to the data with the copy, close the copy, and then refresh the original copy and thusly the grid view. Is there an easy way to get a copy of a TTable object to be used in such a way?</p>
<p>The ideal answer would be one that solves the problem as generically as possible, i.e., a way of getting something like this:</p>
<pre><code>newTable:=getACopyOf(existingTable);
</code></pre>
| [
{
"answer_id": 114803,
"author": "mj2008",
"author_id": 5544,
"author_profile": "https://Stackoverflow.com/users/5544",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to select the table on the form, copy it using <kbd>Ctrl</kbd>-<kbd>C</kbd>, then paste it into any text editor. You will get the text version of the object's properties which you can then edit as needed. When you are done, select all the text again and you can copy it to the clipboard and paste it back onto a form.</p>\n"
},
{
"answer_id": 114933,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 1,
"selected": false,
"text": "<p>Let me propose several things:</p>\n\n<p>Let us suppose that you want to make changes programmatically. You could then use DisableControls and EnableControls methods of the TTable to disallow screen updates during that time.</p>\n\n<p>If you want to have two screens with the same data (f.e. to compare data during online changes), you could actually create the same screen twice, with the TTable object being on the screen itself. It will have the exact same configuration (but not carry over previously made changes on the first screen but read the data from the database). Changes made on one screen will not be automatically refreshed on the other.</p>\n\n<p>Another way: Try using TDataSetProvider with TTable as Dataset (source) feeding a TClientDataSet. ApplyUpdates would feed back the changes to the TTable. Since the calculated fields are read only, they are not affected. (untested, but should work)</p>\n"
},
{
"answer_id": 115079,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that the second approach (TClientDataset) is probably the best method to use in this scenario. An alternative would be to use a memory table (<a href=\"http://www.components4programmers.com/products/kbmmemtable/index.htm\" rel=\"nofollow noreferrer\">kbmMemTable</a> for instance). Either way, you would clone your original table and then after making your changes loop thru the memory version of your dataset and update your original table.</p>\n"
},
{
"answer_id": 118661,
"author": "Tim Knipe",
"author_id": 10493,
"author_profile": "https://Stackoverflow.com/users/10493",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <strong>TBatchMove</strong> component to copy a table and its structure.</p>\n\n<p>Set the Mode property to specify the desired operation. The Source and Destination properties indicate the datasets whose records are added, deleted, or copied. The online help has additional details.</p>\n\n<p>(Although I reckon you should investigate a TClientDataSet approach - it's certainly more scalable and faster).</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20408/"
]
| I have defined a Delphi TTable object with calculated fields, and it is used in a grid on a form. I would like to make a copy of the TTable object, including the calculated fields, open that copy, do some changes to the data with the copy, close the copy, and then refresh the original copy and thusly the grid view. Is there an easy way to get a copy of a TTable object to be used in such a way?
The ideal answer would be one that solves the problem as generically as possible, i.e., a way of getting something like this:
```
newTable:=getACopyOf(existingTable);
``` | You can use the **TBatchMove** component to copy a table and its structure.
Set the Mode property to specify the desired operation. The Source and Destination properties indicate the datasets whose records are added, deleted, or copied. The online help has additional details.
(Although I reckon you should investigate a TClientDataSet approach - it's certainly more scalable and faster). |
114,658 | <p>I keep hearing that </p>
<pre><code>catch (Exception ex)
</code></pre>
<p>Is bad practise, however, I often use it in event handlers where an operation may for example go to network, allowing the possibility of many different types of failure. In this case, I catch all exceptions and display the error message to the user in a message box.</p>
<p>Is this considered bad practise? There's nothing more I can do with the exception: I don't want it to halt the application, the user needs to know what happened, and I'm at the top level of my code. What else should I be doing?</p>
<p>EDIT:</p>
<p>People are saying that I should look through the stack of calls and handle errors specifically, because for example a StackOverflow exception cannot be handled meaningfully. However, halting the process is the <b>worst</b> outcome, I want to prevent that at all costs. If I can't handle a StackOverflow, so be it - the outcome will be no worse than not catching exceptions at all, and in 99% of cases, informing the user is the least bad option as far as I'm concerned.</p>
<p>Also, despite my best efforts to work out all of the possible exceptions that can be thrown, in a large code-base it's likely that I would miss some. And for most of them the best defense is still to inform the user.</p>
| [
{
"answer_id": 114678,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 2,
"selected": false,
"text": "<p>It's perfectly okay if you re-raise exceptions you can't handle properly. If you just catch the exceptions you could hide bugs in the code you don't expect. If you catch exceptions to display them (and bypass the die-and-print-traceback-to-stderr behavior) that's perfectly acceptable.</p>\n"
},
{
"answer_id": 114681,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "<p>It is bad practice in the sense that you shouldn't do it everywhere.</p>\n\n<p>In this case, I would consider it the only reasonable solution as your exception could be truly anything. The only possible improvement would be to add extra handlers before your catch everything for specific error cases where you could do something about the exception.</p>\n"
},
{
"answer_id": 114682,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 0,
"selected": false,
"text": "<p>No; in that case if you don't want to halt the program there's nothing else you can do and at the top level is the right place to do it, as long as you're logging properly and not hiding it away in hope <em>grin</em></p>\n"
},
{
"answer_id": 114693,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 6,
"selected": true,
"text": "<p>The bad practice is</p>\n\n<pre><code>catch (Exception ex){}\n</code></pre>\n\n<p>and variants:</p>\n\n<pre><code>catch (Exception ex){ return false; }\n</code></pre>\n\n<p>etc.</p>\n\n<p>Catching all exceptions on the top-level and passing them on to the user (by either logging them or displaying them in a message-box, depending on whether you are writing a server- or a client-application), is exactly the right thing to do.</p>\n"
},
{
"answer_id": 114697,
"author": "brock.holum",
"author_id": 15860,
"author_profile": "https://Stackoverflow.com/users/15860",
"pm_score": 3,
"selected": false,
"text": "<p>It makes complete sense to catch the exception at the highest level in your code. Catching the base Exception type is fine as long as you don't need to do any different logic based on the exception's type.</p>\n\n<p><strong>Also, make sure you're displaying a friendly, general error message and not showing the actual exception's message. That may lead to security vulnerabilities.</strong></p>\n"
},
{
"answer_id": 114718,
"author": "Ben Fulton",
"author_id": 6902,
"author_profile": "https://Stackoverflow.com/users/6902",
"pm_score": 0,
"selected": false,
"text": "<p>The important thing is to understand the path of exceptions through your application, and not just throw or catch them arbitrarily. For example, what if the exception you catch is Out-Of-Memory? Are you sure that your dialog box is going to display in that case? But it is certainly fine to define a last-ditch exception point and say that you <em>never</em> want errors to propagate past that point. </p>\n"
},
{
"answer_id": 114726,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": false,
"text": "<p>When I see</p>\n\n<pre><code>catch (Exception ex)\n</code></pre>\n\n<p>my hand starts to groping for a hammer. There are almost no excuses to catch base Exception. Only valid cases that come to my mind are:<br>\n1) 3rd party component throws Exception (be damned it's author)<br>\n2) Very top level exceptions handling (as a last resort) (for example handle \"unhandled\" exceptions in WinForms app)</p>\n\n<p>If you find a case where many different types of exceptions can happen it's a good sign of bad design.</p>\n\n<p>I would disagree with Armin Ronacher. How would you behave if StackOverflow exception raised? Trying to perform additional actions can lead to even worse consequences. Catch exception only if you can handle it in meaningful and safe way. Catching System.Exception to cover <em>range</em> of possible exceptions is terribly wrong. Even when you are re-throwing it.</p>\n"
},
{
"answer_id": 114751,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You should catch the exceptions related to what you are doing. If you look at the methods you call, you will see what exceptions they throw, and you want to stay more specific to those. You should have access to know what exceptions may be thrown by the methods you call, and handle them appropriately.</p>\n\n<p>And... better than having one big try catch, do your try and catch where you need the catch.</p>\n\n<pre><code>try {\n myThing.DoStuff();\n}\ncatch (StuffGoneWrongException ex) {\n //figure out what you need to do or bail\n}\n</code></pre>\n\n<p>Maybe not quite this closely packed, but it depends on what you are doing. Remember, the job isn't just to compile it and put it on someones desktop, you want to know what breaks if something did and how to fix it. (Insert rant about tracing here)</p>\n"
},
{
"answer_id": 114869,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 2,
"selected": false,
"text": "<p>I think the poster is referring to exception handling like this:</p>\n\n<pre><code>try {something} catch (SqlException) {do stuff} catch (Exception) {do other stuff}\n</code></pre>\n\n<p>The idea here is that you want to catch the more specific errors (like SqlException) first and handle them appropriately, rather than always relying on the catch-all general Exception.</p>\n\n<p>The conventional wisdom says that this is the proper way to do exception handling (and that a solo Catch (Exception ex) is bad). In practice this approach doesn't always work, especially when you're working with components and libraries written by someone else. </p>\n\n<p>These components will often throw a different type of exception in production than the one your code was expecting based on how the component behaved in your development environment, even though the underlying problem is the same in both environments. This is an amazingly common problem in ASP.NET, and has often led me to use a naked Catch (Exception ex) block, which doesn't care what type of exception is thrown.</p>\n\n<p>Structured exception handling is a great idea in theory. In practice, it can still be a great idea within the code domain that you control. Once you introduce third party stuff, it <em>sometimes</em> doesn't work very well.</p>\n"
},
{
"answer_id": 114922,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 2,
"selected": false,
"text": "<p>We use Catch ex as Exception (VB.Net variant) quite a bit. We log it, and examine our logs regularly. Track down the causes, and resolve.</p>\n\n<p>I think Catch ex as Exception is completely acceptabile <em>once</em> you are dealing with production code, AND you have a general way to handle unknown exceptions gracefully. Personally I don't put the generic catch in until I've completed a module / new functionality and put in specialized handling for any exceptions I found in testing. That seems to be the best of both worlds.</p>\n"
},
{
"answer_id": 114986,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 4,
"selected": false,
"text": "<p>I find the arguments that generic catches are always bad to be overly dogmatic. They, like everything else, have a place.</p>\n\n<p>That place is <strong>not</strong> your library code, nor the classes you custom-develop for your app. That place is, as many have mentioned, the very top level of the app, where if <strong>any</strong> exception is raised, it is most likely unexpected. </p>\n\n<p>Here's my general rule (and like all rules, it's designed to be broken when appropriate):</p>\n\n<p>I use classes and custom-built libraries for the majority of the lifting in an app. This is basic app architecture -- really basic, mind you. These guys try to handle as many exceptions as possible, and if they really can't continue, throw the most specific kind available back up to the UI.</p>\n\n<p>At the UI, I tend to always catch all from event handlers. If there is a reasonable expectation of catching a specific exception, <strong>and</strong> I can do something about it, then I catch the specific exception and handle it gracefully. This must come before the catch all, however, as .NET will only use the very first exception handler which matches your exception. (Always order from most specific to most generic!) </p>\n\n<p>If I can't do anything about the exception other than error out (say, the database is offline), or if the exception truly is unexpected, catch all will take it, log it, and fail safe quickly, with a general error message displayed to the user before dying. (Of course, there are certain classes of errors which will almost always fail ungracefully -- OutOfMemory, StackOverflow, etc. I'm fortunate enough to have not had to deal with those in prod-level code ... so far!)</p>\n\n<p>Catch all has its place. That place is not to hide the exception, that place is not to try and recover (because if you don't know what you caught, how can you possibly recover), that place is not to prevent errors from showing to the user while allowing your app to continue executing in an unknown and bad state.</p>\n\n<p>Catch all's place is to be a last resort, a trap to ensure that if anything makes it through your well-designed and well-guarded defenses, that at a minimum it's logged appropriately and a clean exit can be made. It <strong>is</strong> bad practice if you don't have well-designed and well-guarded defenses in place at lower levels, and it is <strong>very</strong> bad practice at lower levels, but done as a last resort it is (in my mind) not only acceptable, but often the right thing to do.</p>\n"
},
{
"answer_id": 115018,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, it is fine to catch the base Execption <strong>at the top level of the application</strong>, which is what you are doing.</p>\n\n<p>The strong reactions you are getting is probably because at <em>any other level</em>, its almost always wrong to catch the Base exception. Specifically in an a library it would be very bad practice.</p>\n"
},
{
"answer_id": 115119,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 0,
"selected": false,
"text": "<p>a lot of times exception are catched to free resources, it' s not important if exception is (re)thrown. in these cases you can avoid try catch:</p>\n\n<p>1) for Disposable object you can use \"using\" keyword:\n using(SqlConnection conn = new SqlConnection(connStr)) \n {\n //code\n }\nonce you are out of the using scope (normally or by a return statement or by exception), Dispsose method is automatically called on object. in other word, it' s like try/finally construct.</p>\n\n<p>2) in asp.net, you can intercept Error or UnLoad event of Page object to free your resource.</p>\n\n<p>i hope i help you!</p>\n"
},
{
"answer_id": 337556,
"author": "MatthewMartin",
"author_id": 33264,
"author_profile": "https://Stackoverflow.com/users/33264",
"pm_score": 0,
"selected": false,
"text": "<p>I'm responding to \"However, halting the process is the <strong>worst</strong> outcome...\"</p>\n\n<p>If you can handle an exception by running different code (using try/catch as control flow), retrying, waiting and retrying, retrying with an different but equivalent technique (ie fallback method) then by all means do so.</p>\n\n<p>It is also nice to do error message replacement and logging, unless it is that pseudo-polite-passive-aggressive \"contact your administrator\" (when you know there is no administrator and if there was the administrator can't do anything about it!) But after you do that, the application should end, i.e. same behavior you get with an unhandled exception.</p>\n\n<p><em>On the other hand, if you intend to handle the exception by returning the user to a code thread that has potentially trashed its state, I'd say that is worse</em> than ending the application and letting the user start over. Is it better for the user to have to restart at the beginning or better to let the user destroy data?</p>\n\n<p>If I get an unexpected exception in the module that determines which accounts I can withdraw money from, do I really want to log and report an Exception and return the user to the withdraw money screen? For all we know we just granted him the right to withdraw money from all accounts!</p>\n"
},
{
"answer_id": 704116,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This is all good of catching exceptions that you can handled. But sometimes it also happens that due to unstable environment or users just do the process correctly, the application runs into unexpected exception. Which you haven't been listed or handled in code. Is there a way that the unhandled exception is captured from app.config file and displays a common error? </p>\n\n<p>Also puts that details exception message in a log file.</p>\n"
},
{
"answer_id": 1194825,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>I've been working a fair bit with exceptions, and here's the implementation structure I'm currently following:</p>\n\n<ol>\n<li>Dim everything to Nothing / String.Empty / 0 etc. outside of Try / Catch.</li>\n<li>Initialise everything inside Try / Catch to desired values.</li>\n<li>Catch the most specific exceptions first, e.g. FormatException but leave in base Exception handling as a last resort (you can have multiple catch blocks, remember)</li>\n<li>Almost always Throw exceptions</li>\n<li>Let Application_Error sub in global.asax handle errors gracefully, e.g. call a custom function to log the details of the error to a file and redirect to some error page</li>\n<li>Kill all objects you Dim'd in a Finally block</li>\n</ol>\n\n<p>One example where I thought it was acceptable to not process an exception 'properly' recently was working with a GUID string (strGuid) passed via HTTP GET to a page. I <em>could</em> have implemented a function to check the GUID string for validity before calling New Guid(strGuid), but it seemed fairly reasonable to:</p>\n\n<pre><code>Dim myGuid As Guid = Nothing\n\nTry\n myGuid = New Guid(strGuid)\n 'Some processing here...\n\nCatch ex As FormatException\n lblError.Text = \"Invalid ID\"\n\nCatch ex As Exception \n Throw\n\nFinally\n If myGuid IsNot Nothing Then\n myGuid = Nothing\n End If\n\nEnd Try\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6448/"
]
| I keep hearing that
```
catch (Exception ex)
```
Is bad practise, however, I often use it in event handlers where an operation may for example go to network, allowing the possibility of many different types of failure. In this case, I catch all exceptions and display the error message to the user in a message box.
Is this considered bad practise? There's nothing more I can do with the exception: I don't want it to halt the application, the user needs to know what happened, and I'm at the top level of my code. What else should I be doing?
EDIT:
People are saying that I should look through the stack of calls and handle errors specifically, because for example a StackOverflow exception cannot be handled meaningfully. However, halting the process is the **worst** outcome, I want to prevent that at all costs. If I can't handle a StackOverflow, so be it - the outcome will be no worse than not catching exceptions at all, and in 99% of cases, informing the user is the least bad option as far as I'm concerned.
Also, despite my best efforts to work out all of the possible exceptions that can be thrown, in a large code-base it's likely that I would miss some. And for most of them the best defense is still to inform the user. | The bad practice is
```
catch (Exception ex){}
```
and variants:
```
catch (Exception ex){ return false; }
```
etc.
Catching all exceptions on the top-level and passing them on to the user (by either logging them or displaying them in a message-box, depending on whether you are writing a server- or a client-application), is exactly the right thing to do. |
114,725 | <p>I’ve got a problem with Visual Basic (6) in combination with LDAP. When I try to connect to an LDAP store, I always get errors like ‘Bad Pathname’ or ‘Table does not exist’ (depending on what the code looks like).</p>
<p>This is the part of the code I wrote to connect:</p>
<pre><code>path = "LDAP://xx.xxx.xxx.xxx:xxx/"
Logging.WriteToLogFile "Test1", logINFO
Set conn = CreateObject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Properties("User ID") = "USER_ID"
conn.Properties("Password") = "PASSWORD"
conn.Properties("Encrypt Password") = True
conn.Properties("ADSI Flag") = 34
Logging.WriteToLogFile "Test2", logINFO
conn.Open "Active Directory Provider"
Logging.WriteToLogFile "Test3", logINFO
Set rs = conn.Execute("<" & path & "ou=Some,ou=Kindof,o=Searchbase>;(objectclass=*);name;subtree")
Logging.WriteToLogFile "Test4", logINFO
</code></pre>
<p>The logfile shows “Test1” , “Test2”, “Test3” and then “Table does not exist”, so it’s the line “Set rs = conn.Execute(…)” where things go wrong (pretty obvious…).</p>
<p>In my code, I try to connect in a secure way. I found out it has nothing to do with SSL/certificates though, because it’s also not possible to establish an anonymous unsecured connection. Funny thing is: I wrote a small test app in .NET in five minutes. With that app I was able to connect (anonymously) and read results from the LDAP store, no problems at all.</p>
<p>Does anyone have any experience with the combination LDAP and VB6 and maybe know what could be the problem? I googled and saw some example code snippets, but unfortunately none of them worked (same error messages as result). Thanks in advance!</p>
| [
{
"answer_id": 114790,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure how much help this will be, but I use this code to access Active Directory objects.</p>\n\n<pre><code> Set oinfo = New ADSystemInfo\n sDomain = Split(oinfo.DomainDNSName, \".\")\n '-- Get Datasets from the Active Directory\n\n '-- Connect to Active Directory in logged in domain\n con.Open \"Provider=ADsDSOObject;Encrypt Password=False;Integrated Security=SSPI;Data Source=ADSDSOObject;Mode=Read;Bind Flags=0;ADSI Flag=-2147483648\"\n\n '-- Query all serviceConnectionPoints in the Active Directory \n '-- that contain the keyword \"urn://tavis.net/TM/Database\" \n '-- and return the full path to the object\n\n Set rst = con.Execute(\"<LDAP://DC=\" & sDomain(0) & \",DC=\" & sDomain(1) & \">;(&(objectCategory=serviceConnectionPoint)(keywords=urn://tavis.net/TM/Database));Name, AdsPath;subTree\")\n</code></pre>\n"
},
{
"answer_id": 642661,
"author": "AviD",
"author_id": 10080,
"author_profile": "https://Stackoverflow.com/users/10080",
"pm_score": 1,
"selected": false,
"text": "<p>2 things: </p>\n\n<ul>\n<li>The <code>Open()</code> method call takes additional parameters, server/username/password</li>\n<li><p>The LDAP query you passed to <code>Execute()</code> should be: </p>\n\n<pre><code>\"<\" & path & \"ou=Some/ou=Kindof/o=Searchbase>;(objectclass=*);name;subtree\"\n</code></pre></li>\n</ul>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I’ve got a problem with Visual Basic (6) in combination with LDAP. When I try to connect to an LDAP store, I always get errors like ‘Bad Pathname’ or ‘Table does not exist’ (depending on what the code looks like).
This is the part of the code I wrote to connect:
```
path = "LDAP://xx.xxx.xxx.xxx:xxx/"
Logging.WriteToLogFile "Test1", logINFO
Set conn = CreateObject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Properties("User ID") = "USER_ID"
conn.Properties("Password") = "PASSWORD"
conn.Properties("Encrypt Password") = True
conn.Properties("ADSI Flag") = 34
Logging.WriteToLogFile "Test2", logINFO
conn.Open "Active Directory Provider"
Logging.WriteToLogFile "Test3", logINFO
Set rs = conn.Execute("<" & path & "ou=Some,ou=Kindof,o=Searchbase>;(objectclass=*);name;subtree")
Logging.WriteToLogFile "Test4", logINFO
```
The logfile shows “Test1” , “Test2”, “Test3” and then “Table does not exist”, so it’s the line “Set rs = conn.Execute(…)” where things go wrong (pretty obvious…).
In my code, I try to connect in a secure way. I found out it has nothing to do with SSL/certificates though, because it’s also not possible to establish an anonymous unsecured connection. Funny thing is: I wrote a small test app in .NET in five minutes. With that app I was able to connect (anonymously) and read results from the LDAP store, no problems at all.
Does anyone have any experience with the combination LDAP and VB6 and maybe know what could be the problem? I googled and saw some example code snippets, but unfortunately none of them worked (same error messages as result). Thanks in advance! | I'm not sure how much help this will be, but I use this code to access Active Directory objects.
```
Set oinfo = New ADSystemInfo
sDomain = Split(oinfo.DomainDNSName, ".")
'-- Get Datasets from the Active Directory
'-- Connect to Active Directory in logged in domain
con.Open "Provider=ADsDSOObject;Encrypt Password=False;Integrated Security=SSPI;Data Source=ADSDSOObject;Mode=Read;Bind Flags=0;ADSI Flag=-2147483648"
'-- Query all serviceConnectionPoints in the Active Directory
'-- that contain the keyword "urn://tavis.net/TM/Database"
'-- and return the full path to the object
Set rst = con.Execute("<LDAP://DC=" & sDomain(0) & ",DC=" & sDomain(1) & ">;(&(objectCategory=serviceConnectionPoint)(keywords=urn://tavis.net/TM/Database));Name, AdsPath;subTree")
``` |
114,728 | <p>One of my DBs have grown closer to permitted size.</p>
<p>Inorder to find out the table containing the max data, i used the following query:</p>
<pre><code>exec sp_MSforeachtable @command1="print '?' exec sp_spaceused '?'"
</code></pre>
<p>It returned the culprit table comprising the max data.</p>
<p>As a next step, i want to cleanup the rows based on the size. For this, i would like to order the rows based on size.</p>
<p>How to achieve this using a query? Are there any tools to do this?</p>
| [
{
"answer_id": 114827,
"author": "Casper",
"author_id": 18729,
"author_profile": "https://Stackoverflow.com/users/18729",
"pm_score": 1,
"selected": false,
"text": "<p>An easier approach for all table sizes is to use the stored procedure at <a href=\"http://www.mitchelsellers.com/blogs/articletype/articleview/articleid/121/determing-sql-server-table-size.aspx\" rel=\"nofollow noreferrer\">this site</a>.\nYou could alter the select statement of that stored procedure to:</p>\n\n<pre><code>SELECT * \nFROM #TempTable\nOrder by dataSize desc\n</code></pre>\n\n<p>to have it ordered by size.</p>\n\n<p>How do you want to cleanup? Cleanup the biggest row of a specific table? Not sure I understand the question.</p>\n\n<p><strong>EDIT</strong> (response to comment)</p>\n\n<p>Assuming your eventlog has the same layout as mine (DNN eventlog): </p>\n\n<pre><code>SELECT LEN(CONVERT(nvarchar(MAX), LogProperties)) AS length\nFROM EventLog\nORDER BY length DESC\n</code></pre>\n"
},
{
"answer_id": 114856,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe something like this will work </p>\n\n<pre><code>delete table where id in \n(\n select top 100 id\n from table\n order by datalength(event_text) + length(varchar_column) desc\n) \n</code></pre>\n\n<p>(since you are dealing with an event table its probably a text column you are looking at ordering on so the datalength sql command is key here)</p>\n"
},
{
"answer_id": 114886,
"author": "Christopher Klein",
"author_id": 17632,
"author_profile": "https://Stackoverflow.com/users/17632",
"pm_score": 1,
"selected": false,
"text": "<p>You can also use this to get the size of the indexes and keys: (edit:sorry for wall of text, cant get the format to work)</p>\n\n<p><pre><code>\nWITH table_space_usage\n( schema_name, table_name, index_name, used, reserved, ind_rows, tbl_rows )\nAS (\nSELECT s.Name\n , o.Name\n , coalesce(i.Name, 'HEAP')\n , p.used_page_count * 8\n , p.reserved_page_count * 8\n , p.row_count\n , case when i.index_id in ( 0, 1 ) then p.row_count else 0 end\nFROM sys.dm_db_partition_stats p\n INNER JOIN sys.objects as o\n ON o.object_id = p.object_id\n INNER JOIN sys.schemas as s\n ON s.schema_id = o.schema_id\n LEFT OUTER JOIN sys.indexes as i\n on i.object_id = p.object_id and i.index_id = p.index_id\n WHERE o.type_desc = 'USER_TABLE'\n and o.is_ms_shipped = 0\n)\n SELECT t.schema_name\n , t.table_name\n , t.index_name\n , sum(t.used) as used_in_kb\n , sum(t.reserved) as reserved_in_kb\n , case grouping(t.index_name) \n when 0 then sum(t.ind_rows) \n else sum(t.tbl_rows) end as rows\n FROM table_space_usage as t\n GROUP BY\n t.schema_name\n , t.table_name\n , t.index_name\n WITH ROLLUP\n ORDER BY\n grouping(t.schema_name)\n , t.schema_name\n , grouping(t.table_name)\n , t.table_name\n , grouping(t.index_name)\n , t.index_name\n</pre></code></p>\n"
},
{
"answer_id": 114978,
"author": "Tokabi",
"author_id": 315,
"author_profile": "https://Stackoverflow.com/users/315",
"pm_score": 4,
"selected": false,
"text": "<p>This will give you a list of rows by size, just set @table and @idcol accordingly (as written it'll run against the Northwind sample)</p>\n\n<pre><code>declare @table varchar(20)\ndeclare @idcol varchar(10)\ndeclare @sql varchar(1000)\n\nset @table = 'Employees'\nset @idcol = 'EmployeeId'\nset @sql = 'select ' + @idcol +' , (0'\n\nselect @sql = @sql + ' + isnull(datalength(' + name + '), 1)' \n from syscolumns where id = object_id(@table)\nset @sql = @sql + ') as rowsize from ' + @table + ' order by rowsize desc'\n\nexec (@sql)\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15425/"
]
| One of my DBs have grown closer to permitted size.
Inorder to find out the table containing the max data, i used the following query:
```
exec sp_MSforeachtable @command1="print '?' exec sp_spaceused '?'"
```
It returned the culprit table comprising the max data.
As a next step, i want to cleanup the rows based on the size. For this, i would like to order the rows based on size.
How to achieve this using a query? Are there any tools to do this? | This will give you a list of rows by size, just set @table and @idcol accordingly (as written it'll run against the Northwind sample)
```
declare @table varchar(20)
declare @idcol varchar(10)
declare @sql varchar(1000)
set @table = 'Employees'
set @idcol = 'EmployeeId'
set @sql = 'select ' + @idcol +' , (0'
select @sql = @sql + ' + isnull(datalength(' + name + '), 1)'
from syscolumns where id = object_id(@table)
set @sql = @sql + ') as rowsize from ' + @table + ' order by rowsize desc'
exec (@sql)
``` |
114,733 | <p>Do anyone have good ideas of how to modify the toolbar for the WinForms version of the ReportViewer Toolbar?
That is, I want to remove some buttons and varius, but it looks like the solution is to create a brand new toolbar instead of modifying the one that is there.</p>
<p>Like, I had to remove export to excel, and did it this way:</p>
<pre><code> // Disable excel export
foreach (RenderingExtension extension in lr.ListRenderingExtensions()) {
if (extension.Name == "Excel") {
//extension.Visible = false; // Property is readonly...
FieldInfo fi = extension.GetType().GetField("m_isVisible", BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(extension, false);
}
}
</code></pre>
<p>A bit trickysh if you ask me..
For removing toolbarbuttons, an possible way was to iterate through the Control array inside the ReportViewer and change the Visible property for the buttons to hide, but it gets reset all the time, so it is not an good way..</p>
<p>WHEN do MS come with an new version btw?</p>
| [
{
"answer_id": 114766,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 0,
"selected": false,
"text": "<p>Generally you are suppose to create your own toolbar if you want to modify it. Your solution for removing buttons will probably work if that is all you need to do, but if you want to add your own you should probably just bite the bullet and build a replacement.</p>\n"
},
{
"answer_id": 114795,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 3,
"selected": true,
"text": "<p>There are a lot of properties to set which buttons would you like to see.</p>\n\n<p>For example <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer.showbackbutton(VS.80).aspx\" rel=\"nofollow noreferrer\">ShowBackButton</a>, <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer.showexportbutton(VS.80).aspx\" rel=\"nofollow noreferrer\">ShowExportButton</a>, <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer.showfindcontrols(VS.80).aspx\" rel=\"nofollow noreferrer\">ShowFindControls</a>, and so on. Check them in the <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer_members(VS.80).aspx\" rel=\"nofollow noreferrer\">help</a>, all starts with \"Show\".</p>\n\n<p>But you are right, you cannot add new buttons. You have to create your own toolbar in order to do this.</p>\n\n<p>What do you mean about new version? There is already a <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=bb196d5d-76c2-4a0e-9458-267d22b6aac6&DisplayLang=en\" rel=\"nofollow noreferrer\">2008 SP1</a> version of it.</p>\n"
},
{
"answer_id": 355705,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Yeap. You can do that in a little tricky way.\nI had a task to add more scale factors to zoom report. I did it this way:</p>\n\n<pre><code> private readonly string[] ZOOM_VALUES = { \"25%\", \"50%\", \"75%\", \"100%\", \"110%\", \"120%\", \"125%\", \"130%\", \"140%\", \"150%\", \"175%\", \"200%\", \"300%\", \"400%\", \"500%\" };\n private readonly int DEFAULT_ZOOM = 3;\n //--\n\n public ucReportViewer()\n {\n InitializeComponent(); \n this.reportViewer1.ProcessingMode = ProcessingMode.Local;\n\n setScaleFactor(ZOOM_VALUES[DEFAULT_ZOOM]);\n\n Control[] tb = reportViewer1.Controls.Find(\"ReportToolBar\", true);\n\n ToolStrip ts;\n if (tb != null && tb.Length > 0 && tb[0].Controls.Count > 0 && (ts = tb[0].Controls[0] as ToolStrip) != null)\n {\n //here we go if our trick works (tested at .NET Framework 2.0.50727 SP1)\n ToolStripComboBox tscb = new ToolStripComboBox();\n tscb.DropDownStyle = ComboBoxStyle.DropDownList;\n\n tscb.Items.AddRange(ZOOM_VALUES); \n tscb.SelectedIndex = 3; //100%\n\n tscb.SelectedIndexChanged += new EventHandler(toolStripZoomPercent_Click);\n\n ts.Items.Add(tscb);\n }\n else\n { \n //if there is some problems - just use context menu\n ContextMenuStrip cmZoomMenu = new ContextMenuStrip();\n\n for (int i = 0; i < ZOOM_VALUES.Length; i++)\n {\n ToolStripMenuItem tsmi = new ToolStripMenuItem(ZOOM_VALUES[i]);\n\n tsmi.Checked = (i == DEFAULT_ZOOM);\n //tsmi.Tag = (IntPtr)cmZoomMenu;\n tsmi.Click += new EventHandler(toolStripZoomPercent_Click);\n\n cmZoomMenu.Items.Add(tsmi);\n }\n\n reportViewer1.ContextMenuStrip = cmZoomMenu;\n } \n }\n\n private bool setScaleFactor(string value)\n {\n try\n {\n int percent = Convert.ToInt32(value.TrimEnd('%'));\n\n reportViewer1.ZoomMode = ZoomMode.Percent;\n reportViewer1.ZoomPercent = percent;\n\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n\n private void toolStripZoomPercent_Click(object sender, EventArgs e)\n {\n ToolStripMenuItem tsmi = sender as ToolStripMenuItem;\n ToolStripComboBox tscb = sender as ToolStripComboBox;\n\n if (tscb != null && tscb.SelectedIndex > -1)\n {\n setScaleFactor(tscb.Items[tscb.SelectedIndex].ToString());\n }\n else if (tsmi != null)\n {\n if (setScaleFactor(tsmi.Text))\n {\n foreach (ToolStripItem tsi in tsmi.Owner.Items)\n {\n ToolStripMenuItem item = tsi as ToolStripMenuItem;\n\n if (item != null && item.Checked)\n {\n item.Checked = false;\n }\n }\n\n tsmi.Checked = true;\n }\n else\n {\n tsmi.Checked = false;\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 1683049,
"author": "Chris",
"author_id": 204038,
"author_profile": "https://Stackoverflow.com/users/204038",
"pm_score": 3,
"selected": false,
"text": "<p>Get the toolbar from ReportViewer control:</p>\n\n<pre><code>ToolStrip toolStrip = (ToolStrip)reportViewer.Controls.Find(\"toolStrip1\", true)[0]\n</code></pre>\n\n<p>Add new items:</p>\n\n<pre><code>toolStrip.Items.Add(...)\n</code></pre>\n"
},
{
"answer_id": 1689525,
"author": "Adrian Grigore",
"author_id": 59301,
"author_profile": "https://Stackoverflow.com/users/59301",
"pm_score": 2,
"selected": false,
"text": "<p>Another way would be to manipulate the generated HTML at runtime via javascript. It's not very elegant, but it does give you full control over the generated HTML. </p>\n"
},
{
"answer_id": 27667387,
"author": "alex_vkcr",
"author_id": 3578480,
"author_profile": "https://Stackoverflow.com/users/3578480",
"pm_score": 1,
"selected": false,
"text": "<p>I had this question for al ong time I I found the answer after a long tie and the main source of kowledge I used was this webpega: I'd like to thank you all guys adding the code that allowed me to do it and a picture with the result.</p>\n\n<p>Instead of using the ReportViewer Class, you need to create a new classs, in my case, I named it ReportViewerPlus and it goes like this:</p>\n\n<pre><code>using Microsoft.Reporting.WinForms;\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace X\n{\n class ReportViewerPlus : ReportViewer\n {\n private Button boton { get; set; }\n\n public ReportViewerPlus(Button but) {\n this.boton = but;\n testc(this.Controls[0]);\n }\n public ReportViewerPlus()\n {\n }\n private void testc(Control item){\n if(item is ToolStrip) \n { \n ToolStripItemCollection tsic = ((ToolStrip)item).Items;\n tsic.Insert(0, new ToolStripControlHost(boton)); \n return; \n } \n for (int i = 0; i < item.Controls.Count; i++) \n { \n testc(item.Controls[i]); \n } \n }\n }\n}\n</code></pre>\n\n<p>You have to add the button directly in the constructor of the class and you can configure the button in your designer.</p>\n\n<p>Here's a pic of the result, not perfect, but enough to go(safe link I swear, but I can't post my own pics, don't have enough reputation).</p>\n\n<p><a href=\"http://prntscr.com/5lfssj\" rel=\"nofollow\">http://prntscr.com/5lfssj</a></p>\n\n<p>If you look carefully in the code of the class, you'd see more or less how it works and you could make your changes and make it possible to establish it in other site of the toolbar. </p>\n\n<p>Thank you so much for helping me in the past, I hope this helps lots of people!</p>\n"
},
{
"answer_id": 29372802,
"author": "Joseph",
"author_id": 4734672,
"author_profile": "https://Stackoverflow.com/users/4734672",
"pm_score": 2,
"selected": false,
"text": "<p>For VS2013 web ReportViewer V11 (indicated as rv), the code below adds a button. </p>\n\n<pre><code>private void AddPrintBtn()\n { \n foreach (Control c in rv.Controls)\n {\n foreach (Control c1 in c.Controls)\n {\n foreach (Control c2 in c1.Controls)\n {\n foreach (Control c3 in c2.Controls)\n {\n if (c3.ToString() == \"Microsoft.Reporting.WebForms.ToolbarControl\")\n {\n foreach (Control c4 in c3.Controls)\n {\n if (c4.ToString() == \"Microsoft.Reporting.WebForms.PageNavigationGroup\")\n {\n var btn = new Button();\n btn.Text = \"Criteria\";\n btn.ID = \"btnFlip\";\n btn.OnClientClick = \"$('#pnl').toggle();\";\n c4.Controls.Add(btn);\n return;\n }\n }\n }\n }\n }\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 30645044,
"author": "lison",
"author_id": 1182712,
"author_profile": "https://Stackoverflow.com/users/1182712",
"pm_score": 0,
"selected": false,
"text": "<p>You may modify reportviewer controls by CustomizeReportToolStrip method.\nthis example remove Page Setup Button, Page Layout Button in WinForm </p>\n\n<pre><code>public CustOrderReportForm() {\n InitializeComponent();\n CustomizeReport(this.reportViewer1);\n}\n\n\nprivate void CustomizeReport(Control reportControl, int recurCount = 0) {\n Console.WriteLine(\"\".PadLeft(recurCount + 1, '.') + reportControl.GetType() + \":\" + reportControl.Name);\n if (reportControl is Button) {\n CustomizeReportButton((Button)reportControl, recurCount);\n }\n else if (reportControl is ToolStrip) {\n CustomizeReportToolStrip((ToolStrip)reportControl, recurCount);\n }\n foreach (Control childControl in reportControl.Controls) {\n CustomizeReport(childControl, recurCount + 1);\n }\n}\n\n//-------------------------------------------------------------\n\n\nvoid CustomizeReportToolStrip(ToolStrip c, int recurCount) {\n List<ToolStripItem> customized = new List<ToolStripItem>();\n foreach (ToolStripItem i in c.Items) {\n if (CustomizeReportToolStripItem(i, recurCount + 1)) {\n customized.Add(i);\n }\n }\n foreach (var i in customized) c.Items.Remove(i);\n}\n\n//-------------------------------------------------------------\n\nvoid CustomizeReportButton(Button button, int recurCount) {\n}\n\n//-------------------------------------------------------------\n\nbool CustomizeReportToolStripItem(ToolStripItem i, int recurCount) {\n Console.WriteLine(\"\".PadLeft(recurCount + 1, '.') + i.GetType() + \":\" + i.Name);\n if (i.Name == \"pageSetup\") {\n return true;\n }\n else if (i.Name == \"printPreview\") {\n return true;\n }\n return false; ;\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3308/"
]
| Do anyone have good ideas of how to modify the toolbar for the WinForms version of the ReportViewer Toolbar?
That is, I want to remove some buttons and varius, but it looks like the solution is to create a brand new toolbar instead of modifying the one that is there.
Like, I had to remove export to excel, and did it this way:
```
// Disable excel export
foreach (RenderingExtension extension in lr.ListRenderingExtensions()) {
if (extension.Name == "Excel") {
//extension.Visible = false; // Property is readonly...
FieldInfo fi = extension.GetType().GetField("m_isVisible", BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(extension, false);
}
}
```
A bit trickysh if you ask me..
For removing toolbarbuttons, an possible way was to iterate through the Control array inside the ReportViewer and change the Visible property for the buttons to hide, but it gets reset all the time, so it is not an good way..
WHEN do MS come with an new version btw? | There are a lot of properties to set which buttons would you like to see.
For example [ShowBackButton](http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer.showbackbutton(VS.80).aspx), [ShowExportButton](http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer.showexportbutton(VS.80).aspx), [ShowFindControls](http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer.showfindcontrols(VS.80).aspx), and so on. Check them in the [help](http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.reportviewer_members(VS.80).aspx), all starts with "Show".
But you are right, you cannot add new buttons. You have to create your own toolbar in order to do this.
What do you mean about new version? There is already a [2008 SP1](http://www.microsoft.com/downloads/details.aspx?FamilyID=bb196d5d-76c2-4a0e-9458-267d22b6aac6&DisplayLang=en) version of it. |
114,787 | <p>I'm trying to setup a stress/load test using the WCAT toolkit included in the IIS Resources.</p>
<p>Using LogParser, I've processed a UBR file with configuration. It looks something like this:</p>
<pre><code> [Configuration]
NumClientMachines: 1 # number of distinct client machines to use
NumClientThreads: 100 # number of threads per machine
AsynchronousWait: TRUE # asynchronous wait for think and delay
Duration: 5m # length of experiment (m = minutes, s = seconds)
MaxRecvBuffer: 8192K # suggested maximum received buffer
ThinkTime: 0s # maximum think-time before next request
WarmupTime: 5s # time to warm up before taking statistics
CooldownTime: 6s # time to cool down at the end of the experiment
[Performance]
[Script]
SET RequestHeader = "Accept: */*\r\n"
APP RequestHeader = "Accept-Language: en-us\r\n"
APP RequestHeader = "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705)\r\n"
APP RequestHeader = "Host: %HOST%\r\n"
NEW TRANSACTION
classId = 1
NEW REQUEST HTTP
ResponseStatusCode = 200
Weight = 45117
verb = "GET"
URL = "http://Url1.com"
NEW TRANSACTION
classId = 3
NEW REQUEST HTTP
ResponseStatusCode = 200
Weight = 13662
verb = "GET"
URL = "http://Url1.com/test.aspx"
</code></pre>
<p>Does it look OK?</p>
<p>I execute the controller with this command: <code>wcctl -z StressTest.ubr -a localhost</code></p>
<p>The Client(s) is executed like this: <code>wcclient localhost</code></p>
<p>When the client is executed, I get this error: <code>main client thread Connect Attempt 0 Failed. Error = 10061</code></p>
<p>Has anyone in this world ever used WCAT?</p>
| [
{
"answer_id": 114863,
"author": "Corey Goldberg",
"author_id": 16148,
"author_profile": "https://Stackoverflow.com/users/16148",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have an answer for you, but have you considered using other tools for your testing? The WCAT tools seems pretty limited and complicated to use.</p>\n\n<p>OpenSTA and JMeter are good open source tools for load/stress/performance testing.</p>\n"
},
{
"answer_id": 114890,
"author": "MartinHN",
"author_id": 2972,
"author_profile": "https://Stackoverflow.com/users/2972",
"pm_score": 0,
"selected": false,
"text": "<p>OpenSTA and JMeter looks very Apache like. I'm running IIS on Windows Server 2003.</p>\n"
},
{
"answer_id": 115080,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>Have you looked at the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=e2c0585a-062a-439e-a67d-75a89aa36495&DisplayLang=en\" rel=\"nofollow noreferrer\">Microsoft Web Application Stress Tool</a>?</p>\n"
},
{
"answer_id": 240944,
"author": "Christopher G. Lewis",
"author_id": 13532,
"author_profile": "https://Stackoverflow.com/users/13532",
"pm_score": 2,
"selected": false,
"text": "<p>I'd look at updating to WCat 6.3 - available <a href=\"http://www.iis.net/downloads/default.aspx?tabid=34&i=1466&g=6\" rel=\"nofollow noreferrer\">here for x86</a> and <a href=\"http://www.iis.net/downloads/default.aspx?tabid=34&i=1467&g=6\" rel=\"nofollow noreferrer\">here for x64</a></p>\n\n<p>They've changed the settings/scenario file strucutures, which is a little painful, but should suit your needs.</p>\n"
},
{
"answer_id": 320340,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I've just started evaluating wcat 6.3 and I'm afraid my experience has been a bit disapointing in terms of online support/community.</p>\n\n<p>There is also a major bug in the wcat.wsf script - see:</p>\n\n<p><a href=\"http://forums.iis.net/t/1153312.aspx\" rel=\"nofollow noreferrer\">http://forums.iis.net/t/1153312.aspx</a></p>\n\n<p>I'm now struggling with getting performance counter measurement working.</p>\n"
},
{
"answer_id": 530239,
"author": "codepoke",
"author_id": 14127,
"author_profile": "https://Stackoverflow.com/users/14127",
"pm_score": 2,
"selected": false,
"text": "<p>I've had good success with WCAT, though I'm struggling with simulating NTLM connections. </p>\n\n<p>I'm using 6.3, so my config files look very different from yours. Some gotchas I noted along the way:<br>\n+ Make sure you've got your firewall turned off, or holes punched through for WMI.<br>\n+ Each thing you set in the request header has a tremendous impact on throughput. Apples to apples must have the same request headers.<br>\n+ Remote calls with multiple clients work only after correcting the bug identified by sthorogood. </p>\n\n<p>Once I crossed those hurdles, I got great results from WCAT. It tests quickly, repeatably, and aggressively. </p>\n\n<p>Best of luck,</p>\n\n<p>Kevin</p>\n"
},
{
"answer_id": 2605166,
"author": "Gunjan Sarda",
"author_id": 312506,
"author_profile": "https://Stackoverflow.com/users/312506",
"pm_score": 0,
"selected": false,
"text": "<p>for performance counter you can define -p .prf in the same command run for controller as:\nwcctl -c config.txt -d distribution.txt -s script.txt -a localhost - p performance.prf</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2972/"
]
| I'm trying to setup a stress/load test using the WCAT toolkit included in the IIS Resources.
Using LogParser, I've processed a UBR file with configuration. It looks something like this:
```
[Configuration]
NumClientMachines: 1 # number of distinct client machines to use
NumClientThreads: 100 # number of threads per machine
AsynchronousWait: TRUE # asynchronous wait for think and delay
Duration: 5m # length of experiment (m = minutes, s = seconds)
MaxRecvBuffer: 8192K # suggested maximum received buffer
ThinkTime: 0s # maximum think-time before next request
WarmupTime: 5s # time to warm up before taking statistics
CooldownTime: 6s # time to cool down at the end of the experiment
[Performance]
[Script]
SET RequestHeader = "Accept: */*\r\n"
APP RequestHeader = "Accept-Language: en-us\r\n"
APP RequestHeader = "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705)\r\n"
APP RequestHeader = "Host: %HOST%\r\n"
NEW TRANSACTION
classId = 1
NEW REQUEST HTTP
ResponseStatusCode = 200
Weight = 45117
verb = "GET"
URL = "http://Url1.com"
NEW TRANSACTION
classId = 3
NEW REQUEST HTTP
ResponseStatusCode = 200
Weight = 13662
verb = "GET"
URL = "http://Url1.com/test.aspx"
```
Does it look OK?
I execute the controller with this command: `wcctl -z StressTest.ubr -a localhost`
The Client(s) is executed like this: `wcclient localhost`
When the client is executed, I get this error: `main client thread Connect Attempt 0 Failed. Error = 10061`
Has anyone in this world ever used WCAT? | I'd look at updating to WCat 6.3 - available [here for x86](http://www.iis.net/downloads/default.aspx?tabid=34&i=1466&g=6) and [here for x64](http://www.iis.net/downloads/default.aspx?tabid=34&i=1467&g=6)
They've changed the settings/scenario file strucutures, which is a little painful, but should suit your needs. |
114,804 | <p>I want to write a real-time analysis tool for wireless traffic.</p>
<p>Does anyone know how to read from a promiscuous (or sniffing) device in C? </p>
<p>I know that you need to have root access to do it. I was wondering if anyone knows what functions are necessary to do this. Normal sockets don't seem to make sense here.</p>
| [
{
"answer_id": 114820,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 0,
"selected": false,
"text": "<p>Why wouldn't you use something like <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">WireShark</a>?</p>\n\n<p>It is open source, so at least you could learn a few things from it if you don't want to just use it.</p>\n"
},
{
"answer_id": 114982,
"author": "oliver",
"author_id": 2148773,
"author_profile": "https://Stackoverflow.com/users/2148773",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the pcap library (see <a href=\"http://www.tcpdump.org/pcap.htm\" rel=\"nofollow noreferrer\">http://www.tcpdump.org/pcap.htm</a>) which is also used by tcpdump and Wireshark.</p>\n"
},
{
"answer_id": 115169,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 5,
"selected": true,
"text": "<p>On Linux you use a PF_PACKET socket to read data from a raw device, such as an ethernet interface running in promiscuous mode: </p>\n\n<pre><code>s = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))\n</code></pre>\n\n<p>This will send copies of every packet received up to your socket. It is quite likely that you don't really want every packet, though. The kernel can perform a first level of filtering using BPF, the <A HREF=\"http://en.wikipedia.org/wiki/Berkeley_Packet_Filter\" rel=\"noreferrer\">Berkeley Packet Filter</A>. BPF is essentially a stack-based virtual machine: it handles a small set of instructions such as: </p>\n\n<pre><code>ldh = load halfword (from packet) \njeq = jump if equal \nret = return with exit code \n</code></pre>\n\n<p>BPF's exit code tells the kernel whether to copy the packet to the socket or not. It is possible to write relatively small BPF programs directly, using setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER, ). (WARNING: The kernel takes a struct sock_fprog, not a struct bpf_program, do not mix those up or your program will not work on some platforms).</p>\n\n<p>For anything reasonably complex, you really want to use libpcap. BPF is limited in what it can do, in particular in the number of instructions it can execute per packet. <A HREF=\"http://www.tcpdump.org/pcap.htm\" rel=\"noreferrer\">libpcap</A> will take care of splitting a complex filter up into two pieces, with the kernel performing a first level of filtering and the more-capable user-space code dropping the packets it didn't actually want to see.</p>\n\n<p>libpcap also abstracts the kernel interface out of your application code. Linux and BSD use similar APIs, but Solaris requires DLPI and Windows uses something else.</p>\n"
},
{
"answer_id": 229296,
"author": "user30684",
"author_id": 30684,
"author_profile": "https://Stackoverflow.com/users/30684",
"pm_score": 3,
"selected": false,
"text": "<p>I once had to listen on raw ethernet frames and ended up creating a wrapper for this. By calling the function with the device name, ex <code>eth0</code> I got a socket in return that was in promiscuous mode. \nWhat you need to do is to create a raw socket and then put it into promiscuous mode. Here is how I did it.</p>\n\n<pre><code>int raw_init (const char *device)\n{\n struct ifreq ifr;\n int raw_socket;\n\n memset (&ifr, 0, sizeof (struct ifreq));\n\n /* Open A Raw Socket */\n if ((raw_socket = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL))) < 1)\n {\n printf (\"ERROR: Could not open socket, Got #?\\n\");\n exit (1);\n }\n\n /* Set the device to use */\n strcpy (ifr.ifr_name, device);\n\n /* Get the current flags that the device might have */\n if (ioctl (raw_socket, SIOCGIFFLAGS, &ifr) == -1)\n {\n perror (\"Error: Could not retrive the flags from the device.\\n\");\n exit (1);\n }\n\n /* Set the old flags plus the IFF_PROMISC flag */\n ifr.ifr_flags |= IFF_PROMISC;\n if (ioctl (raw_socket, SIOCSIFFLAGS, &ifr) == -1)\n {\n perror (\"Error: Could not set flag IFF_PROMISC\");\n exit (1);\n }\n printf (\"Entering promiscuous mode\\n\");\n\n /* Configure the device */\n\n if (ioctl (raw_socket, SIOCGIFINDEX, &ifr) < 0)\n {\n perror (\"Error: Error getting the device index.\\n\");\n exit (1);\n }\n\n return raw_socket;\n}\n</code></pre>\n\n<p>Then when you have your socket you can just use select to handle packets as they arrive.</p>\n"
},
{
"answer_id": 28097722,
"author": "user2533930",
"author_id": 2533930,
"author_profile": "https://Stackoverflow.com/users/2533930",
"pm_score": 0,
"selected": false,
"text": "<p>WireShark on linux has the capability to capture the PLCP (physical layer convergence protocol) header information.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/542226/"
]
| I want to write a real-time analysis tool for wireless traffic.
Does anyone know how to read from a promiscuous (or sniffing) device in C?
I know that you need to have root access to do it. I was wondering if anyone knows what functions are necessary to do this. Normal sockets don't seem to make sense here. | On Linux you use a PF\_PACKET socket to read data from a raw device, such as an ethernet interface running in promiscuous mode:
```
s = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))
```
This will send copies of every packet received up to your socket. It is quite likely that you don't really want every packet, though. The kernel can perform a first level of filtering using BPF, the [Berkeley Packet Filter](http://en.wikipedia.org/wiki/Berkeley_Packet_Filter). BPF is essentially a stack-based virtual machine: it handles a small set of instructions such as:
```
ldh = load halfword (from packet)
jeq = jump if equal
ret = return with exit code
```
BPF's exit code tells the kernel whether to copy the packet to the socket or not. It is possible to write relatively small BPF programs directly, using setsockopt(s, SOL\_SOCKET, SO\_ATTACH\_FILTER, ). (WARNING: The kernel takes a struct sock\_fprog, not a struct bpf\_program, do not mix those up or your program will not work on some platforms).
For anything reasonably complex, you really want to use libpcap. BPF is limited in what it can do, in particular in the number of instructions it can execute per packet. [libpcap](http://www.tcpdump.org/pcap.htm) will take care of splitting a complex filter up into two pieces, with the kernel performing a first level of filtering and the more-capable user-space code dropping the packets it didn't actually want to see.
libpcap also abstracts the kernel interface out of your application code. Linux and BSD use similar APIs, but Solaris requires DLPI and Windows uses something else. |
114,814 | <p>In Bash, how do I count the number of non-blank lines of code in a project?</p>
| [
{
"answer_id": 114835,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 2,
"selected": false,
"text": "<pre><code>awk '/^[[:space:]]*$/ {++x} END {print x}' \"$testfile\"\n</code></pre>\n"
},
{
"answer_id": 114836,
"author": "Michael Cramer",
"author_id": 1496728,
"author_profile": "https://Stackoverflow.com/users/1496728",
"pm_score": 9,
"selected": true,
"text": "<pre><code>cat foo.c | sed '/^\\s*$/d' | wc -l\n</code></pre>\n\n<p>And if you consider comments blank lines:</p>\n\n<pre><code>cat foo.pl | sed '/^\\s*#/d;/^\\s*$/d' | wc -l\n</code></pre>\n\n<p>Although, that's language dependent. </p>\n"
},
{
"answer_id": 114844,
"author": "Jonathan Hartley",
"author_id": 10176,
"author_profile": "https://Stackoverflow.com/users/10176",
"pm_score": 4,
"selected": false,
"text": "<p>'wc' counts lines, words, chars, so to count all lines (including blank ones) use:</p>\n\n<pre><code>wc *.py\n</code></pre>\n\n<p>To filter out the blank lines, you can use grep:</p>\n\n<pre><code>grep -v '^\\s*$' *.py | wc\n</code></pre>\n\n<p>'-v' tells grep to output all lines except those that match\n'^' is the start of a line\n'\\s*' is zero or more whitespace characters\n'$' is the end of a line\n*.py is my example for all the files you wish to count (all python files in current dir)\npipe output to wc. Off you go.</p>\n\n<p>I'm answering my own (genuine) question. Couldn't find an stackoverflow entry that covered this.</p>\n"
},
{
"answer_id": 114849,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 5,
"selected": false,
"text": "<p>If you want to use something other than a shell script, try <a href=\"http://cloc.sourceforge.net/\" rel=\"noreferrer\">CLOC</a>:</p>\n\n<blockquote>\n <p>cloc counts blank lines, comment\n lines, and physical lines of source\n code in many programming languages. It\n is written entirely in Perl with no\n dependencies outside the standard\n distribution of Perl v5.6 and higher\n (code from some external modules is\n embedded within cloc) and so is quite\n portable.</p>\n</blockquote>\n"
},
{
"answer_id": 114861,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 5,
"selected": false,
"text": "<p>There are many ways to do this, using common shell utilities.</p>\n\n<p>My solution is:</p>\n\n<pre><code>grep -cve '^\\s*$' <file>\n</code></pre>\n\n<p>This searches for lines in <file> the do not match (-v) lines that match the pattern (-e) '^\\s*$', which is the beginning of a line, followed by 0 or more whitespace characters, followed by the end of a line (ie. no content other then whitespace), and display a count of matching lines (-c) instead of the matching lines themselves.</p>\n\n<p>An advantage of this method over methods that involve piping into <code>wc</code>, is that you can specify multiple files and get a separate count for each file:</p>\n\n<pre><code>$ grep -cve '^\\s*$' *.hh\n\nconfig.hh:36\nexceptions.hh:48\nlayer.hh:52\nmain.hh:39\n</code></pre>\n"
},
{
"answer_id": 114865,
"author": "curtisk",
"author_id": 17651,
"author_profile": "https://Stackoverflow.com/users/17651",
"pm_score": 3,
"selected": false,
"text": "<pre><code>cat 'filename' | grep '[^ ]' | wc -l\n</code></pre>\n\n<p>should do the trick just fine</p>\n"
},
{
"answer_id": 114867,
"author": "Linor",
"author_id": 3197,
"author_profile": "https://Stackoverflow.com/users/3197",
"pm_score": 1,
"selected": false,
"text": "<p>It's kinda going to depend on the number of files you have in the project. In theory you could use</p>\n\n<pre><code>grep -c '.' <list of files>\n</code></pre>\n\n<p>Where you can fill the list of files by using the find utility.</p>\n\n<pre><code>grep -c '.' `find -type f`\n</code></pre>\n\n<p>Would give you a line count per file.</p>\n"
},
{
"answer_id": 114870,
"author": "Gilles",
"author_id": 10024,
"author_profile": "https://Stackoverflow.com/users/10024",
"pm_score": 6,
"selected": false,
"text": "<pre><code>#!/bin/bash\nfind . -path './pma' -prune -o -path './blog' -prune -o -path './punbb' -prune -o -path './js/3rdparty' -prune -o -print | egrep '\\.php|\\.as|\\.sql|\\.css|\\.js' | grep -v '\\.svn' | xargs cat | sed '/^\\s*$/d' | wc -l\n</code></pre>\n\n<p>The above will give you the total count of lines of code (blank lines removed) for a project (current folder and all subfolders recursively).</p>\n\n<p>In the above \"./blog\" \"./punbb\" \"./js/3rdparty\" and \"./pma\" are folders I blacklist as I didn't write the code in them. Also .php, .as, .sql, .css, .js are the extensions of the files being looked at. Any files with a different extension are ignored.</p>\n"
},
{
"answer_id": 4586338,
"author": "Dutch",
"author_id": 561486,
"author_profile": "https://Stackoverflow.com/users/561486",
"pm_score": 0,
"selected": false,
"text": "<pre><code>grep -v '^\\W*$' `find -type f` | grep -c '.' > /path/to/lineCountFile.txt\n</code></pre>\n\n<p>gives an aggregate count for all files in the current directory and its subdirectories.</p>\n\n<p>HTH!</p>\n"
},
{
"answer_id": 5090546,
"author": "mahesh",
"author_id": 630123,
"author_profile": "https://Stackoverflow.com/users/630123",
"pm_score": 0,
"selected": false,
"text": "<p>This gives the count of number of lines without counting the blank lines:</p>\n\n<pre><code>grep -v ^$ filename wc -l | sed -e 's/ //g' \n</code></pre>\n"
},
{
"answer_id": 7054319,
"author": "Keith Pinson",
"author_id": 834176,
"author_profile": "https://Stackoverflow.com/users/834176",
"pm_score": 1,
"selected": false,
"text": "<p>Script to recursively count all non-blank lines with a certain file extension in the current directory:</p>\n\n<pre><code>#!/usr/bin/env bash\n(\necho 0;\nfor ext in \"$@\"; do\n for i in $(find . -name \"*$ext\"); do\n sed '/^\\s*$/d' $i | wc -l ## skip blank lines\n #cat $i | wc -l; ## count all lines\n echo +;\n done\ndone\necho p q;\n) | dc;\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre><code>./countlines.sh .py .java .html\n</code></pre>\n"
},
{
"answer_id": 8352769,
"author": "Andy",
"author_id": 504992,
"author_profile": "https://Stackoverflow.com/users/504992",
"pm_score": 1,
"selected": false,
"text": "<p>If you want the sum of all non-blank lines for all files of a given file extension throughout a project:</p>\n\n<pre><code>while read line\ndo grep -cve '^\\s*$' \"$line\"\ndone < <(find $1 -name \"*.$2\" -print) | awk '{s+=$1} END {print s}'\n</code></pre>\n\n<p>First arg is the project's base directory, second is the file extension. Sample usage:</p>\n\n<pre><code>./scriptname ~/Dropbox/project/src java\n</code></pre>\n\n<p>It's little more than a collection of previous solutions.</p>\n"
},
{
"answer_id": 10458195,
"author": "G1i1ch",
"author_id": 1072619,
"author_profile": "https://Stackoverflow.com/users/1072619",
"pm_score": -1,
"selected": false,
"text": "<p>There's already a program for this on linux called 'wc'.</p>\n\n<p>Just</p>\n\n<pre><code>wc -l *.c \n</code></pre>\n\n<p>and it gives you the total lines and the lines for each file.</p>\n"
},
{
"answer_id": 21773910,
"author": "sami",
"author_id": 3309383,
"author_profile": "https://Stackoverflow.com/users/3309383",
"pm_score": 3,
"selected": false,
"text": "<pre><code>grep -cvE '(^\\s*[/*])|(^\\s*$)' foo\n\n-c = count\n-v = exclude\n-E = extended regex\n'(comment lines) OR (empty lines)'\nwhere\n^ = beginning of the line\n\\s = whitespace\n* = any number of previous characters or none\n[/*] = either / or *\n| = OR\n$ = end of the line\n</code></pre>\n\n<p>I post this becaus other options gave wrong answers for me. This worked with my java source, where comment lines start with / or * (i use * on every line in multi-line comment).</p>\n"
},
{
"answer_id": 22774449,
"author": "curran",
"author_id": 2188100,
"author_profile": "https://Stackoverflow.com/users/2188100",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a Bash script that counts the lines of code in a project. It traverses a source tree recursively, and it excludes blank lines and single line comments that use \"//\".</p>\n\n<pre><code># $excluded is a regex for paths to exclude from line counting\nexcluded=\"spec\\|node_modules\\|README\\|lib\\|docs\\|csv\\|XLS\\|json\\|png\"\n\ncountLines(){\n # $total is the total lines of code counted\n total=0\n # -mindepth exclues the current directory (\".\")\n for file in `find . -mindepth 1 -name \"*.*\" |grep -v \"$excluded\"`; do\n # First sed: only count lines of code that are not commented with //\n # Second sed: don't count blank lines\n # $numLines is the lines of code\n numLines=`cat $file | sed '/\\/\\//d' | sed '/^\\s*$/d' | wc -l`\n\n # To exclude only blank lines and count comment lines, uncomment this:\n #numLines=`cat $file | sed '/^\\s*$/d' | wc -l`\n\n total=$(($total + $numLines))\n echo \" \" $numLines $file\n done\n echo \" \" $total in total\n}\n\necho Source code files:\ncountLines\necho Unit tests:\ncd spec\ncountLines\n</code></pre>\n\n<p>Here's what the output looks like for <a href=\"https://github.com/curran/phd/tree/f1ab3319a27c2bd3283df3402e568ce69be670de/prototype\" rel=\"nofollow\">my project</a>:</p>\n\n<pre><code>Source code files:\n 2 ./buildDocs.sh\n 24 ./countLines.sh\n 15 ./css/dashboard.css\n 53 ./data/un_population/provenance/preprocess.js\n 19 ./index.html\n 5 ./server/server.js\n 2 ./server/startServer.sh\n 24 ./SpecRunner.html\n 34 ./src/computeLayout.js\n 60 ./src/configDiff.js\n 18 ./src/dashboardMirror.js\n 37 ./src/dashboardScaffold.js\n 14 ./src/data.js\n 68 ./src/dummyVis.js\n 27 ./src/layout.js\n 28 ./src/links.js\n 5 ./src/main.js\n 52 ./src/processActions.js\n 86 ./src/timeline.js\n 73 ./src/udc.js\n 18 ./src/wire.js\n 664 in total\nUnit tests:\n 230 ./ComputeLayoutSpec.js\n 134 ./ConfigDiffSpec.js\n 134 ./ProcessActionsSpec.js\n 84 ./UDCSpec.js\n 149 ./WireSpec.js\n 731 in total\n</code></pre>\n\n<p>Enjoy! --<a href=\"https://github.com/curran/portfolio\" rel=\"nofollow\">Curran</a></p>\n"
},
{
"answer_id": 24034216,
"author": "coastline",
"author_id": 679724,
"author_profile": "https://Stackoverflow.com/users/679724",
"pm_score": 4,
"selected": false,
"text": "<p>This command count number of non-blank lines. <br><code>cat fileName | grep -v ^$ | wc -l</code><br> grep -v ^$ regular expression function is ignore blank lines.</p>\n"
},
{
"answer_id": 41039836,
"author": "jean-emmanuel",
"author_id": 7267664,
"author_profile": "https://Stackoverflow.com/users/7267664",
"pm_score": 0,
"selected": false,
"text": "<pre><code>rgrep . | wc -l\n</code></pre>\n\n<p>gives the count of non blank lines in the current working directory.</p>\n"
},
{
"answer_id": 58593331,
"author": "Jaydillan",
"author_id": 12286498,
"author_profile": "https://Stackoverflow.com/users/12286498",
"pm_score": 4,
"selected": false,
"text": "<pre><code>cat file.txt | awk 'NF' | wc -l\n</code></pre>\n"
},
{
"answer_id": 64147711,
"author": "Son Nguyen",
"author_id": 1548073,
"author_profile": "https://Stackoverflow.com/users/1548073",
"pm_score": 2,
"selected": false,
"text": "<p>The neatest command is</p>\n<pre><code>grep -vc ^$ fileName\n</code></pre>\n<p>with <code>-c</code> option, you don't even need <code>wc -l</code></p>\n"
},
{
"answer_id": 70705385,
"author": "Hamza Awashra",
"author_id": 17929460,
"author_profile": "https://Stackoverflow.com/users/17929460",
"pm_score": 0,
"selected": false,
"text": "<p>Try this one:</p>\n<pre><code>> grep -cve ^$ -cve '^//' *.java\n</code></pre>\n<p>it's easy to memorize and it also excludes blank lines and commented lines.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10176/"
]
| In Bash, how do I count the number of non-blank lines of code in a project? | ```
cat foo.c | sed '/^\s*$/d' | wc -l
```
And if you consider comments blank lines:
```
cat foo.pl | sed '/^\s*#/d;/^\s*$/d' | wc -l
```
Although, that's language dependent. |
114,819 | <p>Consider these classes.</p>
<pre><code>class Base
{
...
};
class Derived : public Base
{
...
};
</code></pre>
<p>this function</p>
<pre><code>void BaseFoo( std::vector<Base*>vec )
{
...
}
</code></pre>
<p>And finally my vector</p>
<pre><code>std::vector<Derived*>derived;
</code></pre>
<p>I want to pass <code>derived</code> to function <code>BaseFoo</code>, but the compiler doesn't let me. How do I solve this, without copying the whole vector to a <code>std::vector<Base*></code>?</p>
| [
{
"answer_id": 114833,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 3,
"selected": false,
"text": "<p>one option is to use a template</p>\n\n<pre><code>template<typename T>\nvoid BaseFoo( const std::vector<T*>& vec)\n{\n ...\n}\n</code></pre>\n\n<p>The drawback is that the implementation has to be in the header and you will get a little code bloat. You will wind up with different functions being instantiated for each type, but the code stays the same. Depending on the use case it's a quick and dirty solution.</p>\n\n<p>Edit, I should note the reason we need a template here is because we are trying to write the same code for unrelated types as noted by several other posters. Templates allow you do solve these exact problems. I also updated it to use a const reference. You should also pass \"heavy\" objects like a vector by const reference when you don't need a copy, which is basically always.</p>\n"
},
{
"answer_id": 114834,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>They are unrelated types -- you can't. </p>\n"
},
{
"answer_id": 114858,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 2,
"selected": false,
"text": "<p>Generally you would start with a container of base pointers, not the other way.</p>\n"
},
{
"answer_id": 114883,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 6,
"selected": true,
"text": "<p><code>vector<Base*></code> and <code>vector<Derived*></code> are unrelated types, so you can't do this. This is explained in the C++ FAQ <a href=\"http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.3\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>You need to change your variable from a <code>vector<Derived*></code> to a <code>vector<Base*></code> and insert <code>Derived</code> objects into it.</p>\n\n<p>Also, to avoid copying the <code>vector</code> unnecessarily, you should pass it by const-reference, not by value:</p>\n\n<pre><code>void BaseFoo( const std::vector<Base*>& vec )\n{\n ...\n}\n</code></pre>\n\n<p>Finally, to avoid memory leaks, and make your code exception-safe, consider using a container designed to handle heap-allocated objects, e.g:</p>\n\n<pre><code>#include <boost/ptr_container/ptr_vector.hpp>\nboost::ptr_vector<Base> vec;\n</code></pre>\n\n<p>Alternatively, change the vector to hold a smart pointer instead of using raw pointers:</p>\n\n<pre><code>#include <memory>\nstd::vector< std::shared_ptr<Base*> > vec;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>#include <boost/shared_ptr.hpp>\nstd::vector< boost::shared_ptr<Base*> > vec;\n</code></pre>\n\n<p>In each case, you would need to modify your <code>BaseFoo</code> function accordingly.</p>\n"
},
{
"answer_id": 114911,
"author": "eduffy",
"author_id": 7536,
"author_profile": "https://Stackoverflow.com/users/7536",
"pm_score": 2,
"selected": false,
"text": "<p>If you dealing with a third-party library, and this is your only hope, then you can do this:</p>\n\n<pre><code>BaseFoo (*reinterpret_cast<std::vector<Base *> *>(&derived));\n</code></pre>\n\n<p>Otherwise fix your code with one of the other suggesstions.</p>\n"
},
{
"answer_id": 115052,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 5,
"selected": false,
"text": "<p>Instead of passing the container object (<code>vector<></code>), pass in <code>begin</code> and <code>end</code> iterators like the rest of the STL algorithms. The function that receives them will be templated, and it won't matter if you pass in Derived* or Base*.</p>\n"
},
{
"answer_id": 115323,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 1,
"selected": false,
"text": "<p>If <code>std::vector</code> supported what you're asking for, then it would be possible to defeat the C++ type system without using any casts (edit: ChrisN's link to the C++ FAQ Lite talks about the same issue):</p>\n\n<pre><code>class Base {};\nclass Derived1 : public Base {};\nclass Derived2 : public Base {};\n\nvoid pushStuff(std::vector<Base*>& vec) {\n vec.push_back(new Derived2);\n vec.push_back(new Base);\n}\n\n...\nstd::vector<Derived1*> vec;\npushStuff(vec); // Not legal\n// Now vec contains a Derived2 and a Base!\n</code></pre>\n\n<p>Since your <code>BaseFoo()</code> function takes the vector by value, it cannot modify the original vector that you passed in, so what I wrote would not be possible. But if it takes a non-const reference and you use <code>reinterpret_cast<std::vector<Base*>&>()</code> to pass your <code>std::vector<Derived*></code>, you might not get the result that you want, and your program might crash.</p>\n\n<p>Java arrays support <a href=\"http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)\" rel=\"nofollow noreferrer\">covariant subtyping</a>, and this requires Java to <a href=\"http://www.pmg.csail.mit.edu/papers/popl97/node19.html\" rel=\"nofollow noreferrer\">do a runtime type check every time you store a value in an array</a>. This too is undesirable.</p>\n"
},
{
"answer_id": 115364,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 2,
"selected": false,
"text": "<p>Taking <a href=\"https://stackoverflow.com/questions/114819/how-get-a-vectorderived-into-a-function-that-expects-a-vectorbase-as-argument#114833\">Matt Price's</a> answer from above, given that you know in advance what types you want to use with your function, you can declare the function template in the header file, and then add explicit instantiations for those types:</p>\n\n<pre><code>// BaseFoo.h\ntemplate<typename T>\nvoid BaseFoo( const std::vector<T*>& vec);\n\n// BaseFoo.cpp\ntemplate<typename T>\nvoid BaseFoo( const std::vector<T*>& vec);\n{\n ...\n}\n\n// Explicit instantiation means no need for definition in the header file.\ntemplate void BaseFoo<Base> ( const std::vector<Base*>& vec );\ntemplate void BaseFoo<Derived> ( const std::vector<Derived*>& vec );\n</code></pre>\n"
},
{
"answer_id": 116128,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>This problem occurs in programming languages that have mutable containers. You cannot pass around a mutable bag of apples as a bag of fruit because you cannot be sure that someone else does not put a lemon into that bag of fruit, after which it no longer qualifies as a bag of apples. If the bag of apples were not mutable, passing it around as a bag of fruit would be fine. Search for covariance/contravariance.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
]
| Consider these classes.
```
class Base
{
...
};
class Derived : public Base
{
...
};
```
this function
```
void BaseFoo( std::vector<Base*>vec )
{
...
}
```
And finally my vector
```
std::vector<Derived*>derived;
```
I want to pass `derived` to function `BaseFoo`, but the compiler doesn't let me. How do I solve this, without copying the whole vector to a `std::vector<Base*>`? | `vector<Base*>` and `vector<Derived*>` are unrelated types, so you can't do this. This is explained in the C++ FAQ [here](http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.3).
You need to change your variable from a `vector<Derived*>` to a `vector<Base*>` and insert `Derived` objects into it.
Also, to avoid copying the `vector` unnecessarily, you should pass it by const-reference, not by value:
```
void BaseFoo( const std::vector<Base*>& vec )
{
...
}
```
Finally, to avoid memory leaks, and make your code exception-safe, consider using a container designed to handle heap-allocated objects, e.g:
```
#include <boost/ptr_container/ptr_vector.hpp>
boost::ptr_vector<Base> vec;
```
Alternatively, change the vector to hold a smart pointer instead of using raw pointers:
```
#include <memory>
std::vector< std::shared_ptr<Base*> > vec;
```
or
```
#include <boost/shared_ptr.hpp>
std::vector< boost::shared_ptr<Base*> > vec;
```
In each case, you would need to modify your `BaseFoo` function accordingly. |
114,830 | <p>One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?</p>
| [
{
"answer_id": 114831,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 9,
"selected": true,
"text": "<p>Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, <a href=\"http://mail.python.org/pipermail/python-list/2000-March/048085.html\" rel=\"noreferrer\" title=\"Tim Peters\">here</a>.</p>\n\n<p>That's why you can't use something 'not hashable' as a dict key, like a list:</p>\n\n<pre><code>>>> a = {}\n>>> b = ['some', 'list']\n>>> hash(b)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: list objects are unhashable\n>>> a[b] = 'some'\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: list objects are unhashable\n</code></pre>\n\n<p>You can <a href=\"http://en.wikipedia.org/wiki/Hash_table\" rel=\"noreferrer\" title=\"Hash table on wikipedia\">read more about hash tables</a> or <a href=\"https://hg.python.org/cpython/file/10eea15880db/Objects/dictobject.c\" rel=\"noreferrer\" title=\"Dict Object in Python source code\">check how it has been implemented in python</a> and <a href=\"https://hg.python.org/cpython/file/10eea15880db/Objects/dictnotes.txt\" rel=\"noreferrer\" title=\"Notes on optimizing dictionaries in the CPython distribution\">why it is implemented that way</a>.</p>\n"
},
{
"answer_id": 114848,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 5,
"selected": false,
"text": "<p>Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (<a href=\"https://mail.python.org/pipermail/python-list/2000-February/036421.html\" rel=\"noreferrer\">source</a>).</p>\n"
},
{
"answer_id": 115379,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 3,
"selected": false,
"text": "<p>To expand upon nosklo's explanation:</p>\n\n<pre><code>a = {}\nb = ['some', 'list']\na[b] = 'some' # this won't work\na[tuple(b)] = 'some' # this will, same as a['some', 'list']\n</code></pre>\n"
},
{
"answer_id": 33459086,
"author": "Bob Stein",
"author_id": 673991,
"author_profile": "https://Stackoverflow.com/users/673991",
"pm_score": 6,
"selected": false,
"text": "<p>There must be more to a Python dictionary than a table lookup on hash(). By brute experimentation I found this <strong>hash collision</strong>:</p>\n<pre><code>>>> hash(1.1)\n2040142438\n>>> hash(4504.1)\n2040142438\n</code></pre>\n<p>Yet it doesn't break the dictionary:</p>\n<pre><code>>>> d = { 1.1: 'a', 4504.1: 'b' }\n>>> d[1.1]\n'a'\n>>> d[4504.1]\n'b'\n</code></pre>\n<p>Sanity check:</p>\n<pre><code>>>> for k,v in d.items(): print(hash(k))\n2040142438\n2040142438\n</code></pre>\n<p>Possibly there's another lookup level beyond hash() that avoids collisions between dictionary keys. Or maybe dict() uses a different hash.</p>\n<p>(By the way, this in Python 2.7.10. Same story in Python 3.4.3 and 3.5.0 with a collision at <code>hash(1.1) == hash(214748749.8)</code>.)</p>\n<p>(I haven't found any collisions in Python 3.9.6. Since the hashes are bigger -- <code>hash(1.1) == 230584300921369601</code> -- I estimate it would take my desktop a thousand years to find one. So I'll get back to you on this.)</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11575/"
]
| One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it? | Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, [here](http://mail.python.org/pipermail/python-list/2000-March/048085.html "Tim Peters").
That's why you can't use something 'not hashable' as a dict key, like a list:
```
>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
```
You can [read more about hash tables](http://en.wikipedia.org/wiki/Hash_table "Hash table on wikipedia") or [check how it has been implemented in python](https://hg.python.org/cpython/file/10eea15880db/Objects/dictobject.c "Dict Object in Python source code") and [why it is implemented that way](https://hg.python.org/cpython/file/10eea15880db/Objects/dictnotes.txt "Notes on optimizing dictionaries in the CPython distribution"). |
114,851 | <p>I have the following code:</p>
<pre><code>ListBox.DataSource = DataSet.Tables("table_name").Select("some_criteria = match")
ListBox.DisplayMember = "name"
</code></pre>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.select(VS.80).aspx" rel="noreferrer"><code>DataTable.Select()</code> method</a> returns an array of <a href="http://msdn.microsoft.com/en-us/library/system.data.datarow(VS.80).aspx" rel="noreferrer"><code>System.Data.DataRow</code></a> objects.</p>
<p>No matter what I specify in the <code>ListBox.DisplayMember</code> property, all I see is the ListBox with the correct number of items all showing as <code>System.Data.DataRow</code> instead of the value I want which is in the <code>"name"</code> column!</p>
<p>Is it possible to bind to the resulting array from <code>DataTable.Select()</code>, instead of looping through it and adding each one to the <code>ListBox</code>?</p>
<p>(I've no problem with looping, but doesn't seem an elegant ending!)</p>
| [
{
"answer_id": 114887,
"author": "Josh",
"author_id": 11702,
"author_profile": "https://Stackoverflow.com/users/11702",
"pm_score": 6,
"selected": true,
"text": "<p>Use a <a href=\"http://msdn.microsoft.com/en-us/library/hy5b8exc(VS.71).aspx\" rel=\"noreferrer\">DataView</a> instead.</p>\n\n<pre><code>ListBox.DataSource = new DataView(DataSet.Tables(\"table_name\"), \"some_criteria = match\", \"name\", DataViewRowState.CurrentRows);\nListBox.DisplayMember = \"name\"\n</code></pre>\n"
},
{
"answer_id": 115029,
"author": "t3rse",
"author_id": 64,
"author_profile": "https://Stackoverflow.com/users/64",
"pm_score": 1,
"selected": false,
"text": "<p>Josh has it right with the DataView. If you need a very large hammer, you can take the array of rows from any DataTable.Select(\"...\") and do a merge into a different DataSet.</p>\n\n<pre>\n<code>\n DataSet copy = new DataSet();\n copy.Merge(myDataTable.Select(\"Foo='Bar'\"));\n // copy.Tables[0] has a clone\n</code>\n</pre>\n\n<p>That approach for what you're trying to do is most probably overkill but there are instances when you may need to get a datatable out of an array of rows where it's helpful.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5662/"
]
| I have the following code:
```
ListBox.DataSource = DataSet.Tables("table_name").Select("some_criteria = match")
ListBox.DisplayMember = "name"
```
The [`DataTable.Select()` method](http://msdn.microsoft.com/en-us/library/system.data.datatable.select(VS.80).aspx) returns an array of [`System.Data.DataRow`](http://msdn.microsoft.com/en-us/library/system.data.datarow(VS.80).aspx) objects.
No matter what I specify in the `ListBox.DisplayMember` property, all I see is the ListBox with the correct number of items all showing as `System.Data.DataRow` instead of the value I want which is in the `"name"` column!
Is it possible to bind to the resulting array from `DataTable.Select()`, instead of looping through it and adding each one to the `ListBox`?
(I've no problem with looping, but doesn't seem an elegant ending!) | Use a [DataView](http://msdn.microsoft.com/en-us/library/hy5b8exc(VS.71).aspx) instead.
```
ListBox.DataSource = new DataView(DataSet.Tables("table_name"), "some_criteria = match", "name", DataViewRowState.CurrentRows);
ListBox.DisplayMember = "name"
``` |
114,859 | <p>I use a custom Matrix class in my application, and I frequently add multiple matrices:</p>
<pre><code>Matrix result = a + b + c + d; // a, b, c and d are also Matrices
</code></pre>
<p>However, this creates an intermediate matrix for each addition operation. Since this is simple addition, it is possible to avoid the intermediate objects and create the result by adding the elements of all 4 matrices at once. How can I accomplish this?</p>
<p>NOTE: I know I can define multiple functions like <code>Add3Matrices(a, b, c)</code>, <code>Add4Matrices(a, b, c, d)</code>, etc. but I want to keep the elegancy of <code>result = a + b + c + d</code>.</p>
| [
{
"answer_id": 114881,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 0,
"selected": false,
"text": "<p>It is not possible, using operators.</p>\n"
},
{
"answer_id": 114894,
"author": "David Dibben",
"author_id": 5022,
"author_profile": "https://Stackoverflow.com/users/5022",
"pm_score": 2,
"selected": false,
"text": "<p>In C++ it is possible to use <a href=\"http://en.wikipedia.org/wiki/Template_metaprogramming\" rel=\"nofollow noreferrer\">Template Metaprograms</a> and also <a href=\"http://ubiety.uwaterloo.ca/~tveldhui/papers/Template-Metaprograms/meta-art.html\" rel=\"nofollow noreferrer\">here</a>, using templates to do exactly this. However, the template programing is non-trivial. I don't know if a similar technique is available in C#, quite possibly not. </p>\n\n<p>This technique, in c++ does exactly what you want. The disadvantage is that if something is not quite right then the compiler error messages tend to run to several pages and are almost impossible to decipher. </p>\n\n<p>Without such techniques I suspect you are limited to functions such as Add3Matrices.</p>\n\n<p>But for C# this link might be exactly what you need: <a href=\"http://www.codeproject.com/KB/recipes/dynmatrixmath.aspx\" rel=\"nofollow noreferrer\">Efficient Matrix Programming in C#</a> although it seems to work slightly differently to C++ template expressions.</p>\n"
},
{
"answer_id": 114905,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>Something that would at least avoid the pain of </p>\n\n<pre><code>Matrix Add3Matrices(a,b,c) //and so on \n</code></pre>\n\n<p>would be </p>\n\n<pre><code>Matrix AddMatrices(Matrix[] matrices)\n</code></pre>\n"
},
{
"answer_id": 114915,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "<p>You can't avoid creating intermediate objects.</p>\n\n<p>However, you can use expression templates as described <a href=\"http://ubiety.uwaterloo.ca/~tveldhui/papers/Expression-Templates/exprtmpl.html\" rel=\"nofollow noreferrer\">here</a> to minimise them and do fancy lazy evaluation of the templates.</p>\n\n<p>At the simplest level, the expression template could be an object that stores references to several matrices and calls an appropriate function like Add3Matrices() upon assignment. At the most advanced level, the expression templates will do things like calculate the minimum amount of information in a lazy fashion upon request.</p>\n"
},
{
"answer_id": 114952,
"author": "Ian G",
"author_id": 5764,
"author_profile": "https://Stackoverflow.com/users/5764",
"pm_score": 4,
"selected": true,
"text": "<p>You could limit yourself to a single small intermediate by using lazy evaluation. Something like</p>\n\n<pre><code>public class LazyMatrix\n{\n public static implicit operator Matrix(LazyMatrix l)\n {\n Matrix m = new Matrix();\n foreach (Matrix x in l.Pending)\n {\n for (int i = 0; i < 2; ++i)\n for (int j = 0; j < 2; ++j)\n m.Contents[i, j] += x.Contents[i, j];\n }\n\n return m;\n }\n\n public List<Matrix> Pending = new List<Matrix>();\n}\n\npublic class Matrix\n{\n public int[,] Contents = { { 0, 0 }, { 0, 0 } };\n\n public static LazyMatrix operator+(Matrix a, Matrix b)\n {\n LazyMatrix l = new LazyMatrix();\n l.Pending.Add(a);\n l.Pending.Add(b);\n return l;\n }\n\n public static LazyMatrix operator+(Matrix a, LazyMatrix b)\n {\n b.Pending.Add(a);\n return b;\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Matrix a = new Matrix();\n Matrix b = new Matrix();\n Matrix c = new Matrix();\n Matrix d = new Matrix();\n\n a.Contents[0, 0] = 1;\n b.Contents[1, 0] = 4;\n c.Contents[0, 1] = 9;\n d.Contents[1, 1] = 16;\n\n Matrix m = a + b + c + d;\n\n for (int i = 0; i < 2; ++i)\n {\n for (int j = 0; j < 2; ++j)\n {\n System.Console.Write(m.Contents[i, j]);\n System.Console.Write(\" \");\n }\n System.Console.WriteLine();\n }\n\n System.Console.ReadLine();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 114964,
"author": "Tetha",
"author_id": 17663,
"author_profile": "https://Stackoverflow.com/users/17663",
"pm_score": 2,
"selected": false,
"text": "<p>This is not the cleanest solution, but if you know the evaluation order, you could do something like this:</p>\n\n<pre><code>result = MatrixAdditionCollector() << a + b + c + d\n</code></pre>\n\n<p>(or the same thing with different names). The MatrixCollector then implements + as +=, that is, starts with a 0-matrix of undefined size, takes a size once the first + is evaluated and adds everything together (or, copies the first matrix). This reduces the amount of intermediate objects to 1 (or even 0, if you implement assignment in a good way, because the MatrixCollector might be/contain the result immediately.)<br>\nI am not entirely sure if this is ugly as hell or one of the nicer hacks one might do. A certain advantage is that it is kind of obvious what's happening.</p>\n"
},
{
"answer_id": 115005,
"author": "Kokuma",
"author_id": 12088,
"author_profile": "https://Stackoverflow.com/users/12088",
"pm_score": 0,
"selected": false,
"text": "<p>My first solution would be something along this lines (to add in the Matrix class if possible) :</p>\n\n<pre><code>static Matrix AddMatrices(Matrix[] lMatrices) // or List<Matrix> lMatrices\n{\n // Check consistency of matrices\n\n Matrix m = new Matrix(n, p);\n\n for (int i = 0; i < n; i++)\n for (int j = 0; j < n; j++)\n foreach (Maxtrix mat in lMatrices)\n m[i, j] += mat[i, j];\n\n return m;\n}\n</code></pre>\n\n<p>I'd had it in the Matrix class because you can rely on the private methods and properties that could be usefull for your function in case the implementation of the matrix change (linked list of non empty nodes instead of a big double array, for example).</p>\n\n<p>Of course, you would loose the elegance of <code>result = a + b + c + d</code>. But you would have something along the lines of <code>result = Matrix.AddMatrices(new Matrix[] { a, b, c, d });</code>.</p>\n"
},
{
"answer_id": 115007,
"author": "Frank Szczerba",
"author_id": 8964,
"author_profile": "https://Stackoverflow.com/users/8964",
"pm_score": 2,
"selected": false,
"text": "<p>I thought that you could just make the desired add-in-place behavior explicit:</p>\n\n<pre><code>Matrix result = a;\nresult += b;\nresult += c;\nresult += d;\n</code></pre>\n\n<p>But as pointed out by Doug in the Comments on this post, this code is treated by the compiler as if I had written:</p>\n\n<pre><code>Matrix result = a;\nresult = result + b;\nresult = result + c;\nresult = result + d;\n</code></pre>\n\n<p>so temporaries are still created.</p>\n\n<p>I'd just delete this answer, but it seems others might have the same misconception, so consider this a counter example.</p>\n"
},
{
"answer_id": 115044,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 2,
"selected": false,
"text": "<p>Might I suggest a MatrixAdder that behaves much like a StringBuilder. You add matrixes to the MatrixAdder and then call a ToMatrix() method that would do the additions for you in a lazy implementation. This would get you the result you want, could be expandable to any sort of LazyEvaluation, but also wouldn't introduce any clever implementations that could confuse other maintainers of the code.</p>\n"
},
{
"answer_id": 115155,
"author": "gnobal",
"author_id": 7748,
"author_profile": "https://Stackoverflow.com/users/7748",
"pm_score": 1,
"selected": false,
"text": "<p>Bjarne Stroustrup has a short paper called <a href=\"http://www.research.att.com/~bs/abstraction.pdf\" rel=\"nofollow noreferrer\">Abstraction, libraries, and efficiency in C++</a> where he mentions techniques used to achieve what you're looking for. Specifically, he mentions the library <a href=\"http://www.oonumerics.org/blitz/\" rel=\"nofollow noreferrer\">Blitz++</a>, a library for scientific calculations that also has efficient operations for matrices, along with some other interesting libraries. Also, I recommend reading <a href=\"http://www.artima.com/intv/abstreffi.html\" rel=\"nofollow noreferrer\">a conversation with Bjarne Stroustrup on artima.com</a> on that subject.</p>\n"
},
{
"answer_id": 152821,
"author": "OldMan",
"author_id": 23415,
"author_profile": "https://Stackoverflow.com/users/23415",
"pm_score": 0,
"selected": false,
"text": "<p>There are several ways to implement lazy evaluation to achieve that. But its important to remember that not always your compiler will be able to get the best code of all of them.</p>\n\n<p>I already made implementations that worked great in GCC and even superceeded the performance of the traditional several For unreadable code because they lead the compiler to observe that there were no aliases between the data segments (somethign hard to grasp with arrays coming of nowhere). But some of those were a complete fail at MSVC and vice versa on other implementations. Unfortunately those are too long to post here (don't think several thousands lines of code fit here). </p>\n\n<p>A very complex library with great embedded knowledge int he area is Blitz++ library for scientific computation. </p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/976/"
]
| I use a custom Matrix class in my application, and I frequently add multiple matrices:
```
Matrix result = a + b + c + d; // a, b, c and d are also Matrices
```
However, this creates an intermediate matrix for each addition operation. Since this is simple addition, it is possible to avoid the intermediate objects and create the result by adding the elements of all 4 matrices at once. How can I accomplish this?
NOTE: I know I can define multiple functions like `Add3Matrices(a, b, c)`, `Add4Matrices(a, b, c, d)`, etc. but I want to keep the elegancy of `result = a + b + c + d`. | You could limit yourself to a single small intermediate by using lazy evaluation. Something like
```
public class LazyMatrix
{
public static implicit operator Matrix(LazyMatrix l)
{
Matrix m = new Matrix();
foreach (Matrix x in l.Pending)
{
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
m.Contents[i, j] += x.Contents[i, j];
}
return m;
}
public List<Matrix> Pending = new List<Matrix>();
}
public class Matrix
{
public int[,] Contents = { { 0, 0 }, { 0, 0 } };
public static LazyMatrix operator+(Matrix a, Matrix b)
{
LazyMatrix l = new LazyMatrix();
l.Pending.Add(a);
l.Pending.Add(b);
return l;
}
public static LazyMatrix operator+(Matrix a, LazyMatrix b)
{
b.Pending.Add(a);
return b;
}
}
class Program
{
static void Main(string[] args)
{
Matrix a = new Matrix();
Matrix b = new Matrix();
Matrix c = new Matrix();
Matrix d = new Matrix();
a.Contents[0, 0] = 1;
b.Contents[1, 0] = 4;
c.Contents[0, 1] = 9;
d.Contents[1, 1] = 16;
Matrix m = a + b + c + d;
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
System.Console.Write(m.Contents[i, j]);
System.Console.Write(" ");
}
System.Console.WriteLine();
}
System.Console.ReadLine();
}
}
``` |
114,872 | <p>Given some JS code like that one here:</p>
<pre><code> for (var i = 0; i < document.getElementsByName('scale_select').length; i++) {
document.getElementsByName('scale_select')[i].onclick = vSetScale;
}
</code></pre>
<p>Would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the variable after that?</p>
<p>I am not sure how large the effect is in real life, with the result from <code>getElementsByName</code> typically having < 10 items. I'd like to understand the underlying mechanics anyway.</p>
<p>Also, if there's anything else noteworthy about the two options, please tell me.</p>
| [
{
"answer_id": 114891,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>In principle, would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the variable after that?</p>\n</blockquote>\n\n<p>yes.</p>\n"
},
{
"answer_id": 114895,
"author": "Ikke",
"author_id": 20261,
"author_profile": "https://Stackoverflow.com/users/20261",
"pm_score": 0,
"selected": false,
"text": "<p>I think so. Everytime it loops, the engine needs to re-evaluate the document.getElementsByName statement. </p>\n\n<p>On the other hand, if the the value is saved in a variable, than it allready has the value.</p>\n"
},
{
"answer_id": 114904,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 5,
"selected": true,
"text": "<p>Definitely. The memory required to store that would only be a pointer to a DOM object and that's <strong><em>significantly</em></strong> less painful than doing a DOM search each time you need to use something!</p>\n\n<p>Idealish code:</p>\n\n<pre><code>var scale_select = document.getElementsByName('scale_select');\nfor (var i = 0; i < scale_select.length; i++)\n scale_select[i].onclick = vSetScale;\n</code></pre>\n"
},
{
"answer_id": 114906,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Use variables. They're not very expensive in JavaScript and function calls are definitely slower. If you loop at least 5 times over document.getElementById() use a variable. The idea here is not only the function call is slow but this specific function is very slow as it tries to locate the element with the given id in the DOM.</p>\n"
},
{
"answer_id": 114999,
"author": "pcorcoran",
"author_id": 15992,
"author_profile": "https://Stackoverflow.com/users/15992",
"pm_score": 2,
"selected": false,
"text": "<p>A smart implementation of DOM would do its own caching, invalidating the cache when something changes. But not all DOMs today can be counted on to be this smart (<em>cough</em> IE <em>cough</em>) so it's best if you do this yourself.</p>\n"
},
{
"answer_id": 117253,
"author": "ScottKoon",
"author_id": 1538,
"author_profile": "https://Stackoverflow.com/users/1538",
"pm_score": 2,
"selected": false,
"text": "<p>Caching the property lookup might help some, but c<a href=\"http://www.robertnyman.com/2008/04/11/javascript-loop-performance/\" rel=\"nofollow noreferrer\">aching the length of the array before starting the loop has proven to be faster.</a></p>\n\n<p>So declaring a variable in the loop that holds the value of the scale_select.length would speed up the entire loop some.</p>\n\n<pre><code>var scale_select = document.getElementsByName('scale_select');\nfor (var i = 0, al=scale_select.length; i < al; i++)\n scale_select[i].onclick = vSetScale;\n</code></pre>\n"
},
{
"answer_id": 120576,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 0,
"selected": false,
"text": "<p><strong>@ Oli</strong></p>\n\n<p>Caching the length property of the elements fetched in a variable is also a good idea:</p>\n\n<pre><code>var scaleSelect = document.getElementsByName('scale_select');\nvar scaleSelectLength = scaleSelect.length;\n\nfor (var i = 0; i < scaleSelectLength; i += 1)\n{\n // scaleSelect[i]\n}\n</code></pre>\n"
},
{
"answer_id": 686089,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>There's no point storing the scaleSelect.length in a separate variable; it's actually already in one - scaleSelect.length is just an attribute of the scaleSelect array, and as such it's as quick to access as any other static variable.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
]
| Given some JS code like that one here:
```
for (var i = 0; i < document.getElementsByName('scale_select').length; i++) {
document.getElementsByName('scale_select')[i].onclick = vSetScale;
}
```
Would the code be faster if we put the result of getElementsByName into a variable before the loop and then use the variable after that?
I am not sure how large the effect is in real life, with the result from `getElementsByName` typically having < 10 items. I'd like to understand the underlying mechanics anyway.
Also, if there's anything else noteworthy about the two options, please tell me. | Definitely. The memory required to store that would only be a pointer to a DOM object and that's ***significantly*** less painful than doing a DOM search each time you need to use something!
Idealish code:
```
var scale_select = document.getElementsByName('scale_select');
for (var i = 0; i < scale_select.length; i++)
scale_select[i].onclick = vSetScale;
``` |
114,914 | <p>We use <a href="http://hudson-ci.org/" rel="noreferrer">Hudson</a> as a continuous integration system to execute automated builds (nightly and based on CVS polling) of a lot of our projects.</p>
<p>Some projects poll CVS every 15 minutes, some others poll every 5 minutes and some poll every hour.</p>
<p>Every few weeks we'll get a build that fails with the following output:</p>
<pre><code>FATAL: java.io.IOException: Too many open files
java.io.IOException: java.io.IOException: Too many open files
at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
</code></pre>
<p>The next build always worked (with 0 changes) so we always chalked it up to 2 build jobs being run at the same time and happening to have too many files open during the process.</p>
<p>This weekend we had a build fail Friday night (automatic nightly build) with the message and every other nightly build also failed. Somehow this triggered Hudson to continuously build every project which failed until the issue was resolved. This resulted in a build every 30 minutes or so of every project until sometime Saturday night when the issue magically disappeared. </p>
| [
{
"answer_id": 114932,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 0,
"selected": false,
"text": "<p>Change system limits for per-process maximum open file descriptors? As in <code>ulimit -n</code> for the Java process?</p>\n"
},
{
"answer_id": 1139139,
"author": "Michael Donohue",
"author_id": 75204,
"author_profile": "https://Stackoverflow.com/users/75204",
"pm_score": 3,
"selected": true,
"text": "<p>This is Hudson issue 715 (<s><a href=\"http://issues.hudson-ci.org/browse/HUDSON-715\" rel=\"nofollow noreferrer\">http://issues.hudson-ci.org/browse/HUDSON-715</a></s>). The current recommendation is to set the 'maximum number of simultaneous polling threads' to keep the polling activity down.</p>\n"
},
{
"answer_id": 1139238,
"author": "Christofer Lundstedt",
"author_id": 136293,
"author_profile": "https://Stackoverflow.com/users/136293",
"pm_score": 0,
"selected": false,
"text": "<p>I have experienced this problem with another Java application running on Debian, it went away when we downgraded to Java version 1.6.0.0. Java never closed unused connections, causing it to throw the exception.</p>\n"
},
{
"answer_id": 2118821,
"author": "Kohsuke Kawaguchi",
"author_id": 437507,
"author_profile": "https://Stackoverflow.com/users/437507",
"pm_score": 2,
"selected": false,
"text": "<p>See <a href=\"https://wiki.jenkins-ci.org/display/JENKINS/I%27m+getting+too+many+open+files+error\" rel=\"nofollow noreferrer\">https://wiki.jenkins-ci.org/display/JENKINS/I%27m+getting+too+many+open+files+error</a> for what we need from you to fix this kind of problem.</p>\n"
},
{
"answer_id": 25280934,
"author": "Szymon P",
"author_id": 3936432,
"author_profile": "https://Stackoverflow.com/users/3936432",
"pm_score": 0,
"selected": false,
"text": "<p>One of the most common problem causing \"Too many open files\" is to have Active Directory plugin enabled and configured in Jenkins. There are known issues with this plugin which cause enormous number of threads to show up and \"Too many open files\" error in logs as well. After disabling it and switching to LDAP authentication I did not experience Jenkins to hang anymore.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9518/"
]
| We use [Hudson](http://hudson-ci.org/) as a continuous integration system to execute automated builds (nightly and based on CVS polling) of a lot of our projects.
Some projects poll CVS every 15 minutes, some others poll every 5 minutes and some poll every hour.
Every few weeks we'll get a build that fails with the following output:
```
FATAL: java.io.IOException: Too many open files
java.io.IOException: java.io.IOException: Too many open files
at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
```
The next build always worked (with 0 changes) so we always chalked it up to 2 build jobs being run at the same time and happening to have too many files open during the process.
This weekend we had a build fail Friday night (automatic nightly build) with the message and every other nightly build also failed. Somehow this triggered Hudson to continuously build every project which failed until the issue was resolved. This resulted in a build every 30 minutes or so of every project until sometime Saturday night when the issue magically disappeared. | This is Hudson issue 715 (~~<http://issues.hudson-ci.org/browse/HUDSON-715>~~). The current recommendation is to set the 'maximum number of simultaneous polling threads' to keep the polling activity down. |
114,928 | <p>I'm firing off a Java application from inside of a C# <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> console application. It works fine for the case where the Java application doesn't care what the "default" directory is, but fails for a Java application that only searches the current directory for support files.</p>
<p>Is there a process parameter that can be set to specify the default directory that a process is started in?</p>
| [
{
"answer_id": 114937,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 9,
"selected": true,
"text": "<p>Yes!\nProcessStartInfo Has a property called <em>WorkingDirectory</em>, just use:</p>\n\n<pre><code>...\nusing System.Diagnostics;\n...\n\nvar startInfo = new ProcessStartInfo();\n\n startInfo.WorkingDirectory = // working directory\n // set additional properties \n\nProcess proc = Process.Start(startInfo);\n</code></pre>\n"
},
{
"answer_id": 114938,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 3,
"selected": false,
"text": "<p>Use the ProcessStartInfo.WorkingDirectory property.</p>\n\n<p>Docs <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.workingdirectory.aspx\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 114945,
"author": "Simon Johnson",
"author_id": 854,
"author_profile": "https://Stackoverflow.com/users/854",
"pm_score": 3,
"selected": false,
"text": "<p>The Process.Start method has an overload that takes an instance of ProcessStartInfo. This class has a property called \"WorkingDirectory\".</p>\n\n<p>Set that property to the folder you want to use and that should make it start up in the correct folder.</p>\n"
},
{
"answer_id": 114947,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 2,
"selected": false,
"text": "<p>Use the <code>ProcessStartInfo</code> class and assign a value to the <code>WorkingDirectory</code> property.</p>\n"
},
{
"answer_id": 115287,
"author": "Larry Smithmier",
"author_id": 4911,
"author_profile": "https://Stackoverflow.com/users/4911",
"pm_score": 6,
"selected": false,
"text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.workingdirectory.aspx\" rel=\"noreferrer\" title=\"Link to MSDN documentation on ProcessStartInfo.WorkingDirectory\"><em>ProcessStartInfo.WorkingDirectory</em></a> property to set it prior to starting the process. If the property is not set, the default working directory is %SYSTEMROOT%\\system32. </p>\n\n<p>You can determine the value of %SYSTEMROOT% by using:</p>\n\n<pre><code>string _systemRoot = Environment.GetEnvironmentVariable(\"SYSTEMROOT\"); \n</code></pre>\n\n<p>Here is some sample code that opens Notepad.exe with a working directory of %ProgramFiles%:</p>\n\n<pre><code>...\nusing System.Diagnostics;\n...\n\nProcessStartInfo _processStartInfo = new ProcessStartInfo();\n _processStartInfo.WorkingDirectory = @\"%ProgramFiles%\";\n _processStartInfo.FileName = @\"Notepad.exe\";\n _processStartInfo.Arguments = \"test.txt\";\n _processStartInfo.CreateNoWindow = true;\nProcess myProcess = Process.Start(_processStartInfo);\n</code></pre>\n\n<p>There is also an Environment variable that controls the current working directory for your process that you can access directly through the <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.currentdirectory.aspx\" rel=\"noreferrer\" title=\"MSDN documentation on Environment.CurrentDirectory\"><em>Environment.CurrentDirectory</em></a> property .</p>\n"
},
{
"answer_id": 22871238,
"author": "CBBSpike",
"author_id": 3017963,
"author_profile": "https://Stackoverflow.com/users/3017963",
"pm_score": 5,
"selected": false,
"text": "<p>Just a note after hitting my head trying to implement this.\nSetting the WorkingDirectory value does not work if you have \"UseShellExecute\" set to false.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15689/"
]
| I'm firing off a Java application from inside of a C# [.NET](http://en.wikipedia.org/wiki/.NET_Framework) console application. It works fine for the case where the Java application doesn't care what the "default" directory is, but fails for a Java application that only searches the current directory for support files.
Is there a process parameter that can be set to specify the default directory that a process is started in? | Yes!
ProcessStartInfo Has a property called *WorkingDirectory*, just use:
```
...
using System.Diagnostics;
...
var startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = // working directory
// set additional properties
Process proc = Process.Start(startInfo);
``` |
114,983 | <p>Given:</p>
<pre><code>DateTime.UtcNow
</code></pre>
<p>How do I get a string which represents the same value in an <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a>-compliant format?</p>
<p>Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:</p>
<pre><code>yyyy-MM-ddTHH:mm:ssZ
</code></pre>
| [
{
"answer_id": 114997,
"author": "Iain",
"author_id": 20457,
"author_profile": "https://Stackoverflow.com/users/20457",
"pm_score": 7,
"selected": false,
"text": "<pre><code>DateTime.UtcNow.ToString(\"s\")\n</code></pre>\n\n<p>Returns something like 2008-04-10T06:30:00</p>\n\n<p><code>UtcNow</code> obviously returns a <a href=\"https://en.wikipedia.org/wiki/Coordinated_Universal_Time\" rel=\"noreferrer\">UTC</a> time so there is no harm in:</p>\n\n<pre><code>string.Concat(DateTime.UtcNow.ToString(\"s\"), \"Z\")\n</code></pre>\n"
},
{
"answer_id": 115002,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 10,
"selected": false,
"text": "<blockquote>\n<p><strong>Note to readers:</strong> Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.</p>\n</blockquote>\n<pre><code>DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\\\:mm\\\\:ss.fffffffzzz", CultureInfo.InvariantCulture);\n</code></pre>\n<p>Using <a href=\"https://learn.microsoft.com/dotnet/standard/base-types/custom-date-and-time-format-strings\" rel=\"noreferrer\">custom date-time formatting</a>, this gives you a date similar to<br />\n<strong>2008-09-22T13:57:31.2311892-04:00</strong>.</p>\n<p>Another way is:</p>\n<pre><code>DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);\n</code></pre>\n<p>which uses the standard <a href=\"https://learn.microsoft.com/dotnet/standard/base-types/standard-date-and-time-format-strings#Roundtrip\" rel=\"noreferrer\">"round-trip" style</a> (ISO 8601) to give you<br />\n<strong>2008-09-22T14:01:54.9571247Z</strong>.</p>\n<p>To get the specified format, you can use:</p>\n<pre><code>DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)\n</code></pre>\n"
},
{
"answer_id": 115034,
"author": "Simon Wilson",
"author_id": 12875,
"author_profile": "https://Stackoverflow.com/users/12875",
"pm_score": 9,
"selected": false,
"text": "<p><code>DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture)</code> should give you what you are looking for as the "s" format specifier is described as a sortable date/time pattern; conforms to ISO 8601.</p>\n<p><strong>EDIT:</strong> To get the additional <code>Z</code> at the end as the OP requires, use <code>"o"</code> instead of <code>"s"</code>.</p>\n"
},
{
"answer_id": 322305,
"author": "Oppositional",
"author_id": 2029,
"author_profile": "https://Stackoverflow.com/users/2029",
"pm_score": 3,
"selected": false,
"text": "<p>To convert DateTime.UtcNow to a string representation of <em>yyyy-MM-ddTHH:mm:ssZ</em>, you can use the ToString() method of the DateTime structure with a custom formatting string. When using custom format strings with a DateTime, it is important to remember that you need to escape your seperators using single quotes.</p>\n\n<p>The following will return the string represention you wanted:</p>\n\n<pre><code>DateTime.UtcNow.ToString(\"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'\", DateTimeFormatInfo.InvariantInfo)\n</code></pre>\n"
},
{
"answer_id": 6216560,
"author": "Sumrak",
"author_id": 19124,
"author_profile": "https://Stackoverflow.com/users/19124",
"pm_score": 4,
"selected": false,
"text": "<p>I would just use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlconvert\" rel=\"nofollow noreferrer\"><code>XmlConvert</code></a>:</p>\n\n<pre><code>XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.RoundtripKind);\n</code></pre>\n\n<p>It will automatically preserve the time zone.</p>\n"
},
{
"answer_id": 12385861,
"author": "Amal",
"author_id": 314373,
"author_profile": "https://Stackoverflow.com/users/314373",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>The <code>\"s\"</code> standard format specifier represents a custom date and time format string that is defined by the <a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.sortabledatetimepattern.aspx\">DateTimeFormatInfo.SortableDateTimePattern</a> property. The pattern reflects a defined standard (<strong>ISO 8601</strong>), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is <code>\"yyyy'-'MM'-'dd'T'HH':'mm':'ss\"</code>.</p>\n \n <p>When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.</p>\n</blockquote>\n\n<p>– from <a href=\"http://msdn.microsoft.com/en-us/library/az4se3k1.aspx#Sortable\">MSDN</a></p>\n"
},
{
"answer_id": 12467789,
"author": "Don",
"author_id": 1669344,
"author_profile": "https://Stackoverflow.com/users/1669344",
"pm_score": 6,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code>private void TimeFormats()\n{\n DateTime localTime = DateTime.Now;\n DateTime utcTime = DateTime.UtcNow;\n DateTimeOffset localTimeAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime));\n\n //UTC\n string strUtcTime_o = utcTime.ToString(\"o\");\n string strUtcTime_s = utcTime.ToString(\"s\");\n string strUtcTime_custom = utcTime.ToString(\"yyyy-MM-ddTHH:mm:ssK\");\n\n //Local\n string strLocalTimeAndOffset_o = localTimeAndOffset.ToString(\"o\");\n string strLocalTimeAndOffset_s = localTimeAndOffset.ToString(\"s\");\n string strLocalTimeAndOffset_custom = utcTime.ToString(\"yyyy-MM-ddTHH:mm:ssK\");\n\n //Output\n Response.Write(\"<br/>UTC<br/>\");\n Response.Write(\"strUtcTime_o: \" + strUtcTime_o + \"<br/>\");\n Response.Write(\"strUtcTime_s: \" + strUtcTime_s + \"<br/>\");\n Response.Write(\"strUtcTime_custom: \" + strUtcTime_custom + \"<br/>\");\n\n Response.Write(\"<br/>Local Time<br/>\");\n Response.Write(\"strLocalTimeAndOffset_o: \" + strLocalTimeAndOffset_o + \"<br/>\");\n Response.Write(\"strLocalTimeAndOffset_s: \" + strLocalTimeAndOffset_s + \"<br/>\");\n Response.Write(\"strLocalTimeAndOffset_custom: \" + strLocalTimeAndOffset_custom + \"<br/>\");\n\n}\n</code></pre>\n\n<h3>OUTPUT</h3>\n\n<pre><code>UTC\n strUtcTime_o: 2012-09-17T22:02:51.4021600Z\n strUtcTime_s: 2012-09-17T22:02:51\n strUtcTime_custom: 2012-09-17T22:02:51Z\n\nLocal Time\n strLocalTimeAndOffset_o: 2012-09-17T15:02:51.4021600-07:00\n strLocalTimeAndOffset_s: 2012-09-17T15:02:51\n strLocalTimeAndOffset_custom: 2012-09-17T22:02:51Z\n</code></pre>\n\n<h3>Sources:</h3>\n\n<ul>\n<li><p><em><a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings\" rel=\"noreferrer\">Standard Date and Time Format Strings</a></em> (MSDN)</p></li>\n<li><p><em><a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings\" rel=\"noreferrer\">Custom Date and Time Format Strings</a></em> (MSDN)</p></li>\n</ul>\n"
},
{
"answer_id": 15656407,
"author": "Simon Logic",
"author_id": 682256,
"author_profile": "https://Stackoverflow.com/users/682256",
"pm_score": 2,
"selected": false,
"text": "<p>If you're developing under <a href=\"https://en.wikipedia.org/wiki/SharePoint#Notable_changes_in_SharePoint_2010\" rel=\"nofollow\">SharePoint 2010</a> or higher you can use</p>\n\n<pre><code>using Microsoft.SharePoint;\nusing Microsoft.SharePoint.Utilities;\n...\nstring strISODate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now)\n</code></pre>\n"
},
{
"answer_id": 19345594,
"author": "Henrik",
"author_id": 63621,
"author_profile": "https://Stackoverflow.com/users/63621",
"pm_score": 6,
"selected": false,
"text": "<pre><code>System.DateTime.UtcNow.ToString(\"o\")\n</code></pre>\n\n<p>=></p>\n\n<pre><code>val it : string = \"2013-10-13T13:03:50.2950037Z\"\n</code></pre>\n"
},
{
"answer_id": 25893406,
"author": "Oaxas",
"author_id": 1448133,
"author_profile": "https://Stackoverflow.com/users/1448133",
"pm_score": 5,
"selected": false,
"text": "<p>You can get the \"Z\" (<a href=\"http://en.wikipedia.org/wiki/ISO_8601\" rel=\"noreferrer\">ISO 8601</a> <strong>UTC</strong>) with the next code:</p>\n\n<pre><code>Dim tmpDate As DateTime = New DateTime(Now.Ticks, DateTimeKind.Utc)\nDim res as String = tmpDate.toString(\"o\") '2009-06-15T13:45:30.0000000Z\n</code></pre>\n\n<p><br/></p>\n\n<p>Here is why:</p>\n\n<p>The ISO 8601 have some different formats:</p>\n\n<p><strong>DateTimeKind.Local</strong></p>\n\n<pre><code>2009-06-15T13:45:30.0000000-07:00\n</code></pre>\n\n<p><strong>DateTimeKind.Utc</strong></p>\n\n<pre><code>2009-06-15T13:45:30.0000000Z\n</code></pre>\n\n<p><strong>DateTimeKind.Unspecified</strong></p>\n\n<pre><code>2009-06-15T13:45:30.0000000\n</code></pre>\n\n<p><br/></p>\n\n<p>.NET provides us with an enum with those options:</p>\n\n<pre><code>'2009-06-15T13:45:30.0000000-07:00\nDim strTmp1 As String = New DateTime(Now.Ticks, DateTimeKind.Local).ToString(\"o\")\n\n'2009-06-15T13:45:30.0000000Z\nDim strTmp2 As String = New DateTime(Now.Ticks, DateTimeKind.Utc).ToString(\"o\")\n\n'2009-06-15T13:45:30.0000000\nDim strTmp3 As String = New DateTime(Now.Ticks, DateTimeKind.Unspecified).ToString(\"o\")\n</code></pre>\n\n<p><strong>Note</strong>: If you apply the Visual Studio 2008 \"watch utility\" to the <em>toString(\"o\")</em> part you may get different results, I don't know if it's a bug, but in this case you have better results using a String variable if you're debugging.</p>\n\n<p>Source: <em><a href=\"http://msdn.microsoft.com/en-us/library/az4se3k1%28v=vs.110%29.aspx\" rel=\"noreferrer\">Standard Date and Time Format Strings</a></em> (MSDN)</p>\n"
},
{
"answer_id": 27321188,
"author": "Justin Turner",
"author_id": 604624,
"author_profile": "https://Stackoverflow.com/users/604624",
"pm_score": 4,
"selected": false,
"text": "<p>Most of these answers have milliseconds / microseconds which clearly isn't supported by ISO 8601. The correct answer would be:</p>\n\n<pre><code>System.DateTime.Now.ToString(\"yyyy-MM-ddTHH:mm:ssK\");\n// or\nSystem.DateTime.Now.ToUniversalTime().ToString(\"yyyy-MM-ddTHH:mm:ssK\");\n</code></pre>\n\n<p>References:</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/ISO_8601\" rel=\"noreferrer\">ISO 8601 specification</a></li>\n<li><a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#KSpecifier\" rel=\"noreferrer\">\"K\" Specifier</a> </li>\n</ul>\n"
},
{
"answer_id": 31250678,
"author": "Alex Nolasco",
"author_id": 65694,
"author_profile": "https://Stackoverflow.com/users/65694",
"pm_score": 5,
"selected": false,
"text": "<p>You have a few options including the "Round-trip ("O") format specifier".</p>\n<pre><code>var date1 = new DateTime(2008, 3, 1, 7, 0, 0);\nConsole.WriteLine(date1.ToString("O"));\nConsole.WriteLine(date1.ToString("s", System.Globalization.CultureInfo.InvariantCulture));\n</code></pre>\n<p>Output</p>\n<pre><code>2008-03-01T07:00:00.0000000\n2008-03-01T07:00:00\n</code></pre>\n<p>However, DateTime + TimeZone may present other problems as described in the blog post <em><a href=\"https://engy.us/blog/2012/04/06/datetime-and-datetimeoffset-in-net-good-practices-and-common-pitfalls/\" rel=\"noreferrer\">DateTime and DateTimeOffset in .NET: Good practices and common pitfalls</a></em>:</p>\n<blockquote>\n<p>DateTime has countless traps in it that are designed to give your code bugs:</p>\n<p>1.- DateTime values with DateTimeKind.Unspecified are bad news.</p>\n<p>2.- DateTime doesn't care about UTC/Local when doing comparisons.</p>\n<p>3.- DateTime values are not aware of standard format strings.</p>\n<p>4.- Parsing a string that has a UTC marker with DateTime does not guarantee a UTC time.</p>\n</blockquote>\n"
},
{
"answer_id": 43793679,
"author": "Roman Pokrovskij",
"author_id": 506147,
"author_profile": "https://Stackoverflow.com/users/506147",
"pm_score": 3,
"selected": false,
"text": "<p>It is interesting that custom format \"yyyy-MM-ddTHH:mm:ssK\" (without ms) is the quickest format method.</p>\n\n<p>Also it is interesting that \"S\" format is slow on Classic and fast on Core...</p>\n\n<p>Of course numbers are very close, between some rows difference is insignificant (tests with suffix <code>_Verify</code> are the same as those that are without that suffix, demonstrates results repeatability)</p>\n\n<pre><code>BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393\nProcessor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4\nFrequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC\n [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0\n Clr : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0\n Core : .NET Core 4.6.25009.03, 64bit RyuJIT\n\n\n Method | Job | Runtime | Mean | Error | StdDev | Median | Min | Max | Rank | Gen 0 | Allocated |\n--------------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|\n CustomDev1 | Clr | Clr | 1,089.0 ns | 22.179 ns | 20.746 ns | 1,079.9 ns | 1,068.9 ns | 1,133.2 ns | 8 | 0.1086 | 424 B |\n CustomDev2 | Clr | Clr | 1,032.3 ns | 19.897 ns | 21.289 ns | 1,024.7 ns | 1,000.3 ns | 1,072.0 ns | 7 | 0.1165 | 424 B |\n CustomDev2WithMS | Clr | Clr | 1,168.2 ns | 16.543 ns | 15.474 ns | 1,168.5 ns | 1,149.3 ns | 1,189.2 ns | 10 | 0.1625 | 592 B |\n FormatO | Clr | Clr | 1,563.7 ns | 31.244 ns | 54.721 ns | 1,532.5 ns | 1,497.8 ns | 1,703.5 ns | 14 | 0.2897 | 976 B |\n FormatS | Clr | Clr | 1,243.5 ns | 24.615 ns | 31.130 ns | 1,229.3 ns | 1,200.6 ns | 1,324.2 ns | 13 | 0.2865 | 984 B |\n FormatS_Verify | Clr | Clr | 1,217.6 ns | 11.486 ns | 10.744 ns | 1,216.2 ns | 1,205.5 ns | 1,244.3 ns | 12 | 0.2885 | 984 B |\n CustomFormatK | Clr | Clr | 912.2 ns | 17.915 ns | 18.398 ns | 916.6 ns | 878.3 ns | 934.1 ns | 4 | 0.0629 | 240 B |\n CustomFormatK_Verify | Clr | Clr | 894.0 ns | 3.877 ns | 3.626 ns | 893.8 ns | 885.1 ns | 900.0 ns | 3 | 0.0636 | 240 B |\n CustomDev1 | Core | Core | 989.1 ns | 12.550 ns | 11.739 ns | 983.8 ns | 976.8 ns | 1,015.5 ns | 6 | 0.1101 | 423 B |\n CustomDev2 | Core | Core | 964.3 ns | 18.826 ns | 23.809 ns | 954.1 ns | 935.5 ns | 1,015.6 ns | 5 | 0.1267 | 423 B |\n CustomDev2WithMS | Core | Core | 1,136.0 ns | 21.914 ns | 27.714 ns | 1,138.1 ns | 1,099.9 ns | 1,200.2 ns | 9 | 0.1752 | 590 B |\n FormatO | Core | Core | 1,201.5 ns | 16.262 ns | 15.211 ns | 1,202.3 ns | 1,178.2 ns | 1,225.5 ns | 11 | 0.0656 | 271 B |\n FormatS | Core | Core | 993.5 ns | 19.272 ns | 24.372 ns | 999.4 ns | 954.2 ns | 1,029.5 ns | 6 | 0.0633 | 279 B |\n FormatS_Verify | Core | Core | 1,003.1 ns | 17.577 ns | 16.442 ns | 1,009.2 ns | 976.1 ns | 1,024.3 ns | 6 | 0.0674 | 279 B |\n CustomFormatK | Core | Core | 878.2 ns | 17.017 ns | 20.898 ns | 877.7 ns | 851.4 ns | 928.1 ns | 2 | 0.0555 | 215 B |\n CustomFormatK_Verify | Core | Core | 863.6 ns | 3.968 ns | 3.712 ns | 863.0 ns | 858.6 ns | 870.8 ns | 1 | 0.0550 | 215 B |\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code> public class BenchmarkDateTimeFormat\n {\n public static DateTime dateTime = DateTime.Now;\n\n [Benchmark]\n public string CustomDev1()\n {\n var d = dateTime.ToUniversalTime();\n var sb = new StringBuilder(20);\n\n sb.Append(d.Year).Append(\"-\");\n if (d.Month <= 9)\n sb.Append(\"0\");\n sb.Append(d.Month).Append(\"-\");\n if (d.Day <= 9)\n sb.Append(\"0\");\n sb.Append(d.Day).Append(\"T\");\n if (d.Hour <= 9)\n sb.Append(\"0\");\n sb.Append(d.Hour).Append(\":\");\n if (d.Minute <= 9)\n sb.Append(\"0\");\n sb.Append(d.Minute).Append(\":\");\n if (d.Second <= 9)\n sb.Append(\"0\");\n sb.Append(d.Second).Append(\"Z\");\n var text = sb.ToString();\n return text;\n }\n\n [Benchmark]\n public string CustomDev2()\n {\n var u = dateTime.ToUniversalTime();\n var sb = new StringBuilder(20);\n var y = u.Year;\n var d = u.Day;\n var M = u.Month;\n var h = u.Hour;\n var m = u.Minute;\n var s = u.Second;\n sb.Append(y).Append(\"-\");\n if (M <= 9)\n sb.Append(\"0\");\n sb.Append(M).Append(\"-\");\n if (d <= 9)\n sb.Append(\"0\");\n sb.Append(d).Append(\"T\");\n if (h <= 9)\n sb.Append(\"0\");\n sb.Append(h).Append(\":\");\n if (m <= 9)\n sb.Append(\"0\");\n sb.Append(m).Append(\":\");\n if (s <= 9)\n sb.Append(\"0\");\n sb.Append(s).Append(\"Z\");\n var text = sb.ToString();\n return text;\n }\n\n [Benchmark]\n public string CustomDev2WithMS()\n {\n var u = dateTime.ToUniversalTime();\n var sb = new StringBuilder(23);\n var y = u.Year;\n var d = u.Day;\n var M = u.Month;\n var h = u.Hour;\n var m = u.Minute;\n var s = u.Second;\n var ms = u.Millisecond;\n sb.Append(y).Append(\"-\");\n if (M <= 9)\n sb.Append(\"0\");\n sb.Append(M).Append(\"-\");\n if (d <= 9)\n sb.Append(\"0\");\n sb.Append(d).Append(\"T\");\n if (h <= 9)\n sb.Append(\"0\");\n sb.Append(h).Append(\":\");\n if (m <= 9)\n sb.Append(\"0\");\n sb.Append(m).Append(\":\");\n if (s <= 9)\n sb.Append(\"0\");\n sb.Append(s).Append(\".\");\n sb.Append(ms).Append(\"Z\");\n var text = sb.ToString();\n return text;\n }\n [Benchmark]\n public string FormatO()\n {\n var text = dateTime.ToUniversalTime().ToString(\"o\");\n return text;\n }\n [Benchmark]\n public string FormatS()\n {\n var text = string.Concat(dateTime.ToUniversalTime().ToString(\"s\"),\"Z\");\n return text;\n }\n\n [Benchmark]\n public string FormatS_Verify()\n {\n var text = string.Concat(dateTime.ToUniversalTime().ToString(\"s\"), \"Z\");\n return text;\n }\n\n [Benchmark]\n public string CustomFormatK()\n {\n var text = dateTime.ToUniversalTime().ToString(\"yyyy-MM-ddTHH:mm:ssK\");\n return text;\n }\n\n [Benchmark]\n public string CustomFormatK_Verify()\n {\n var text = dateTime.ToUniversalTime().ToString(\"yyyy-MM-ddTHH:mm:ssK\");\n return text;\n }\n }\n</code></pre>\n\n<p><a href=\"https://github.com/dotnet/BenchmarkDotNet\" rel=\"nofollow noreferrer\">https://github.com/dotnet/BenchmarkDotNet</a> was used</p>\n"
},
{
"answer_id": 50988941,
"author": "Nick Gallimore",
"author_id": 3097454,
"author_profile": "https://Stackoverflow.com/users/3097454",
"pm_score": 2,
"selected": false,
"text": "<p>To format like <strong>2018-06-22T13:04:16</strong> which can be passed in the URI of an API use:</p>\n\n<pre><code>public static string FormatDateTime(DateTime dateTime)\n{\n return dateTime.ToString(\"s\", System.Globalization.CultureInfo.InvariantCulture);\n}\n</code></pre>\n"
},
{
"answer_id": 52103826,
"author": "Pablo Salcedo",
"author_id": 7641848,
"author_profile": "https://Stackoverflow.com/users/7641848",
"pm_score": 4,
"selected": false,
"text": "<pre><code>DateTime.Now.ToString(\"yyyy-MM-dd'T'HH:mm:ss zzz\");\n\nDateTime.Now.ToString(\"O\");\n</code></pre>\n\n<p>NOTE: Depending on the conversion you are doing on your end, you will be using the first line (most like it) or the second one.</p>\n\n<p>Make sure to applied format only at local time, since \"zzz\" is the time zone information for UTC conversion.</p>\n\n<p><img src=\"https://i.stack.imgur.com/NFhkW.png\" alt=\"image\"></p>\n"
},
{
"answer_id": 56173223,
"author": "rburte",
"author_id": 653058,
"author_profile": "https://Stackoverflow.com/users/653058",
"pm_score": 5,
"selected": false,
"text": "<p>Surprised that no one suggested it:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>System.DateTime.UtcNow.ToString("u").Replace(' ','T')\n</code></pre>\n<pre><code># Using PowerShell Core to demo\n\n# Lowercase "u" format\n[System.DateTime]::UtcNow.ToString("u")\n> 2020-02-06 01:00:32Z\n\n# Lowercase "u" format with replacement\n[System.DateTime]::UtcNow.ToString("u").Replace(' ','T')\n> 2020-02-06T01:00:32Z\n\n</code></pre>\n<p>The <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.globalization.datetimeformatinfo.universalsortabledatetimepattern\" rel=\"nofollow noreferrer\">UniversalSortableDateTimePattern</a> gets you almost all the way to what you want (which is more an <a href=\"https://www.rfc-editor.org/rfc/rfc3339.html#section-5.8\" rel=\"nofollow noreferrer\">RFC 3339</a> representation).</p>\n<hr />\n<p>Added:\nI decided to use the benchmarks that were in answer <a href=\"https://stackoverflow.com/a/43793679/653058\">https://stackoverflow.com/a/43793679/653058</a> to compare how this performs.</p>\n<p>tl:dr; it's at the expensive end but still just a little over 650 <em>nanoseconds</em> on my crappy old laptop :-)</p>\n<p>Implementation:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>[Benchmark]\npublic string ReplaceU()\n{\n var text = dateTime.ToUniversalTime().ToString("u").Replace(' ', 'T');\n return text;\n}\n</code></pre>\n<p>Results:</p>\n<pre><code>// * Summary *\n\nBenchmarkDotNet=v0.11.5, OS=Windows 10.0.19002\nIntel Xeon CPU E3-1245 v3 3.40GHz, 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=3.0.100\n [Host] : .NET Core 3.0.0 (CoreCLR 4.700.19.46205, CoreFX 4.700.19.46214), 64bit RyuJIT\n DefaultJob : .NET Core 3.0.0 (CoreCLR 4.700.19.46205, CoreFX 4.700.19.46214), 64bit RyuJIT\n\n\n| Method | Mean | Error | StdDev |\n|--------------------- |---------:|----------:|----------:|\n| CustomDev1 | 562.4 ns | 11.135 ns | 10.936 ns |\n| CustomDev2 | 525.3 ns | 3.322 ns | 3.107 ns |\n| CustomDev2WithMS | 609.9 ns | 9.427 ns | 8.356 ns |\n| FormatO | 356.6 ns | 6.008 ns | 5.620 ns |\n| FormatS | 589.3 ns | 7.012 ns | 6.216 ns |\n| FormatS_Verify | 599.8 ns | 12.054 ns | 11.275 ns |\n| CustomFormatK | 549.3 ns | 4.911 ns | 4.594 ns |\n| CustomFormatK_Verify | 539.9 ns | 2.917 ns | 2.436 ns |\n| ReplaceU | 615.5 ns | 12.313 ns | 11.517 ns |\n\n// * Hints *\nOutliers\n BenchmarkDateTimeFormat.CustomDev2WithMS: Default -> 1 outlier was removed (668.16 ns)\n BenchmarkDateTimeFormat.FormatS: Default -> 1 outlier was removed (621.28 ns)\n BenchmarkDateTimeFormat.CustomFormatK: Default -> 1 outlier was detected (542.55 ns)\n BenchmarkDateTimeFormat.CustomFormatK_Verify: Default -> 2 outliers were removed (557.07 ns, 560.95 ns)\n\n// * Legends *\n Mean : Arithmetic mean of all measurements\n Error : Half of 99.9% confidence interval\n StdDev : Standard deviation of all measurements\n 1 ns : 1 Nanosecond (0.000000001 sec)\n\n// ***** BenchmarkRunner: End *****\n\n</code></pre>\n"
},
{
"answer_id": 56216091,
"author": "blackforest-tom",
"author_id": 5274931,
"author_profile": "https://Stackoverflow.com/users/5274931",
"pm_score": 2,
"selected": false,
"text": "<p>Using Newtonsoft.Json, you can do</p>\n\n<pre><code>JsonConvert.SerializeObject(DateTime.UtcNow)\n</code></pre>\n\n<p>Example: <a href=\"https://dotnetfiddle.net/O2xFSl\" rel=\"nofollow noreferrer\">https://dotnetfiddle.net/O2xFSl</a></p>\n"
},
{
"answer_id": 57825706,
"author": "Vlad DX",
"author_id": 3503521,
"author_profile": "https://Stackoverflow.com/users/3503521",
"pm_score": 1,
"selected": false,
"text": "<p>As mentioned in other answer, <code>DateTime</code> has issues by design.</p>\n\n<h2>NodaTime</h2>\n\n<p>I suggest to use <a href=\"https://nodatime.org/\" rel=\"nofollow noreferrer\">NodaTime</a> to manage date/time values:</p>\n\n<ul>\n<li>Local time, date, datetime</li>\n<li>Global time</li>\n<li>Time with timezone</li>\n<li>Period</li>\n<li>Duration</li>\n</ul>\n\n<h3>Formatting</h3>\n\n<p>So, to create and format <code>ZonedDateTime</code> you can use the following code snippet:</p>\n\n<pre><code>var instant1 = Instant.FromUtc(2020, 06, 29, 10, 15, 22);\n\nvar utcZonedDateTime = new ZonedDateTime(instant1, DateTimeZone.Utc);\nutcZonedDateTime.ToString(\"yyyy-MM-ddTHH:mm:ss'Z'\", CultureInfo.InvariantCulture);\n// 2020-06-29T10:15:22Z\n\n\nvar instant2 = Instant.FromDateTimeUtc(new DateTime(2020, 06, 29, 10, 15, 22, DateTimeKind.Utc));\n\nvar amsterdamZonedDateTime = new ZonedDateTime(instant2, DateTimeZoneProviders.Tzdb[\"Europe/Amsterdam\"]);\namsterdamZonedDateTime.ToString(\"yyyy-MM-ddTHH:mm:ss'Z'\", CultureInfo.InvariantCulture);\n// 2020-06-29T12:15:22Z\n\n</code></pre>\n\n<p>For me <code>NodaTime</code> code looks quite verbose. But types are really useful. They help to handle date/time values correctly.</p>\n\n<h3>Newtonsoft.Json</h3>\n\n<blockquote>\n <p>To use <code>NodaTime</code> with <code>Newtonsoft.Json</code> you need to add reference to <code>NodaTime.Serialization.JsonNet</code> NuGet package and configure JSON options.</p>\n</blockquote>\n\n<pre><code>services\n .AddMvc()\n .AddJsonOptions(options =>\n {\n var settings=options.SerializerSettings;\n settings.DateParseHandling = DateParseHandling.None;\n settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);\n });\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20457/"
]
| Given:
```
DateTime.UtcNow
```
How do I get a string which represents the same value in an [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601)-compliant format?
Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:
```
yyyy-MM-ddTHH:mm:ssZ
``` | >
> **Note to readers:** Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.
>
>
>
```
DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz", CultureInfo.InvariantCulture);
```
Using [custom date-time formatting](https://learn.microsoft.com/dotnet/standard/base-types/custom-date-and-time-format-strings), this gives you a date similar to
**2008-09-22T13:57:31.2311892-04:00**.
Another way is:
```
DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);
```
which uses the standard ["round-trip" style](https://learn.microsoft.com/dotnet/standard/base-types/standard-date-and-time-format-strings#Roundtrip) (ISO 8601) to give you
**2008-09-22T14:01:54.9571247Z**.
To get the specified format, you can use:
```
DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)
``` |
114,996 | <p>How can we connect a <code>PHP</code> script to <code>MS Access (.mdb)</code> file?</p>
<p>I tried by including following <code>PHP</code> code:</p>
<pre><code>$db_path = $_SERVER['DOCUMENT_ROOT'] . '\WebUpdate\\' . $file_name . '.mdb';
$cfg_dsn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" . $db_path;
$odbcconnect = odbc_connect($cfg_dsn, '', '');
</code></pre>
<p>But it failed and I received following error message:</p>
<pre><code> Warning: odbc_connect() [function.odbc-connect]: SQL error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect in C:\web\WebUpdate\index.php on line 41
</code></pre>
| [
{
"answer_id": 115009,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 4,
"selected": true,
"text": "<p>Here's a sample for a connect and a simple select...</p>\n\n<pre><code><?php\n$db_conn = new COM(\"ADODB.Connection\");\n$connstr = \"DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=\". realpath(\"./Northwind.mdb\").\";\";\n$db_conn->open($connstr);\n$rS = $db_conn->execute(\"SELECT * FROM Employees\");\n$f1 = $rS->Fields(0);\n$f2 = $rS->Fields(1);\nwhile (!$rS->EOF)\n{\n print $f1->value.\" \".$f2->value.\"<br />\\n\";\n $rS->MoveNext();\n}\n$rS->Close();\n$db_conn->Close();\n?> \n</code></pre>\n"
},
{
"answer_id": 115028,
"author": "Jesse Millikan",
"author_id": 7526,
"author_profile": "https://Stackoverflow.com/users/7526",
"pm_score": 0,
"selected": false,
"text": "<p>In the filename, I'm looking at '\\WebUpdate\\' - it looks like you have one backslash at the beginning at two at the end. Are you maybe missing a backslash at the beginning?</p>\n"
},
{
"answer_id": 115032,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$db_path = $_SERVER['DOCUMENT_ROOT'] . '\\WebUpdate\\\\' . $file_name . '.mdb';\n</code></pre>\n\n<p>replace the backslashes with slashes use . '/WebUpdate/' .</p>\n"
},
{
"answer_id": 115048,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 0,
"selected": false,
"text": "<p>it looks like a problem with the path seperators. ISTR that you have to pass backslashes not forward slashes</p>\n\n<p>The following works for me - with an MDB file in the webroot called db4</p>\n\n<pre>\n $defdir = str_replace(\"/\", \"\\\\\", $_SERVER[\"DOCUMENT_ROOT\"]);\n $dbq = $defdir . \"\\\\db4.mdb\";\nif (!file_exists($dbq)) { die(\"Database file $dbq does not exist\"); }\n\n $dsn = \"DRIVER=Microsoft Access Driver (*.mdb);UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL=MS Access;DriverId=25;DefaultDir=$defdir;DBQ=$dbq\";\n $odbc_conn = odbc_connect($dsn,\"\",\"\")\n or die(\"Could not connect to Access database $dsn\");\n</pre>\n"
},
{
"answer_id": 590768,
"author": "OldBuildingAndLoan",
"author_id": 70870,
"author_profile": "https://Stackoverflow.com/users/70870",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not certain if this is a violation of best practices or security, but I would like to throw out this suggestion:</p>\n\n<p>set up an ODBC connection and include the database's password in the odbc advance settings.\ngive the odbc conn a DSN name then save.</p>\n\n<p>in your code, just set up the connection like:</p>\n\n<pre><code>try {\n $conn = @odbc_connect(\"DSNName\", \"\", \"\", \"SQL_CUR_USE_ODBC\");\n // un and pw parameters are passed as empty strings since the DSN \n // has knowledge of the password already.\n // 4th parameter is optional\n\n $exec = @odbc_exec($conn, $insert) or die (\"exec error\");\n echo \"success!\";\n}\ncatch (Exception $e) {\n echo $e->getMessage();\n} // end try catch\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/114996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6561/"
]
| How can we connect a `PHP` script to `MS Access (.mdb)` file?
I tried by including following `PHP` code:
```
$db_path = $_SERVER['DOCUMENT_ROOT'] . '\WebUpdate\\' . $file_name . '.mdb';
$cfg_dsn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" . $db_path;
$odbcconnect = odbc_connect($cfg_dsn, '', '');
```
But it failed and I received following error message:
```
Warning: odbc_connect() [function.odbc-connect]: SQL error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect in C:\web\WebUpdate\index.php on line 41
``` | Here's a sample for a connect and a simple select...
```
<?php
$db_conn = new COM("ADODB.Connection");
$connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("./Northwind.mdb").";";
$db_conn->open($connstr);
$rS = $db_conn->execute("SELECT * FROM Employees");
$f1 = $rS->Fields(0);
$f2 = $rS->Fields(1);
while (!$rS->EOF)
{
print $f1->value." ".$f2->value."<br />\n";
$rS->MoveNext();
}
$rS->Close();
$db_conn->Close();
?>
``` |
115,008 | <p>How to print line numbers to the log. Say when outputting some information to the log, I also want to print the line number where that output is in the source code. As we can see in the stack trace, it displays the line number where the exception has occurred. Stack trace is available on the exception object.</p>
<p>Other alternative could be like manually including the line number when printing to the log. Is there any other way?</p>
| [
{
"answer_id": 115027,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 7,
"selected": false,
"text": "<p>From <a href=\"https://web.archive.org/web/20100818065334/http://blog.taragana.com:80/index.php/archive/core-java-how-to-get-java-source-code-line-number-file-name-in-code/\" rel=\"noreferrer\">Angsuman Chakraborty</a> (archived) :</p>\n<pre><code>/** Get the current line number.\n * @return int - Current line number.\n */\npublic static int getLineNumber() {\n return Thread.currentThread().getStackTrace()[2].getLineNumber();\n}\n</code></pre>\n"
},
{
"answer_id": 115038,
"author": "UberAlex",
"author_id": 170,
"author_profile": "https://Stackoverflow.com/users/170",
"pm_score": 1,
"selected": false,
"text": "<p>You can't guarantee line number consistency with code, especially if it is compiled for release. I would not recommend using line numbers for that purpose anyway, it would be better to give a payload of the place where the exception was raised (the trivial method being to set the message to include the details of the method call).</p>\n\n<p>You might like to look at exception enrichment as a technique to improve exception handling \n<a href=\"http://tutorials.jenkov.com/java-exception-handling/exception-enrichment.html\" rel=\"nofollow noreferrer\">http://tutorials.jenkov.com/java-exception-handling/exception-enrichment.html</a></p>\n"
},
{
"answer_id": 115057,
"author": "Ron Tuffin",
"author_id": 939,
"author_profile": "https://Stackoverflow.com/users/939",
"pm_score": 3,
"selected": false,
"text": "<p>The code posted by @simon.buchan will work...</p>\n\n<pre><code>Thread.currentThread().getStackTrace()[2].getLineNumber()\n</code></pre>\n\n<p>But if you call it in a method it will always return the line number of the line in the method so rather use the code snippet inline. </p>\n"
},
{
"answer_id": 115061,
"author": "GBa",
"author_id": 17614,
"author_profile": "https://Stackoverflow.com/users/17614",
"pm_score": 0,
"selected": false,
"text": "<p>If it's been compiled for release this isn't possible. You might want to look into something like Log4J which will automatically give you enough information to determine pretty closely where the logged code occurred.</p>\n"
},
{
"answer_id": 115062,
"author": "James A Wilson",
"author_id": 13892,
"author_profile": "https://Stackoverflow.com/users/13892",
"pm_score": 5,
"selected": false,
"text": "<p>I am compelled to answer by not answering your question. I'm assuming that you are looking for the line number solely to support debugging. There are better ways. There are hackish ways to get the current line. All I've seen are slow. You are better off using a logging framework like that in java.util.logging package or <a href=\"http://logging.apache.org/log4j/1.2/index.html\" rel=\"noreferrer\">log4j</a>. Using these packages you can configure your logging information to include context down to the class name. Then each log message would be unique enough to know where it came from. As a result, your code will have a 'logger' variable that you call via</p>\n\n<blockquote>\n <p><code>logger.debug(\"a really descriptive message\")</code></p>\n</blockquote>\n\n<p>instead of </p>\n\n<blockquote>\n <p><code>System.out.println(\"a really descriptive message\")</code></p>\n</blockquote>\n"
},
{
"answer_id": 115066,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I would recommend using a logging toolkit such as <a href=\"http://logging.apache.org/log4j/\" rel=\"noreferrer\">log4j</a>. Logging is configurable via properties files at runtime, and you can turn on / off features such as line number / filename logging.</p>\n\n<p>Looking at the javadoc for the <a href=\"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html\" rel=\"noreferrer\">PatternLayout</a> gives you the full list of options - what you're after is %L.</p>\n"
},
{
"answer_id": 115082,
"author": "Jim Kiley",
"author_id": 7178,
"author_profile": "https://Stackoverflow.com/users/7178",
"pm_score": 4,
"selected": false,
"text": "<p>Log4J allows you to include the line number as part of its output pattern. See <a href=\"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html\" rel=\"noreferrer\">http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html</a> for details on how to do this (the key element in the conversion pattern is \"L\"). However, the Javadoc does include the following:</p>\n\n<blockquote>\n <p>WARNING Generating caller location\n information is extremely slow. It's\n use should be avoided unless execution\n speed is not an issue.</p>\n</blockquote>\n"
},
{
"answer_id": 115144,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "<p>first the general method (in an utility class, in plain old java1.4 code though, you may have to rewrite it for java1.5 and more)</p>\n\n<pre><code>/**\n * Returns the first \"[class#method(line)]: \" of the first class not equal to \"StackTraceUtils\" and aclass. <br />\n * Allows to get past a certain class.\n * @param aclass class to get pass in the stack trace. If null, only try to get past StackTraceUtils. \n * @return \"[class#method(line)]: \" (never empty, because if aclass is not found, returns first class past StackTraceUtils)\n */\npublic static String getClassMethodLine(final Class aclass) {\n final StackTraceElement st = getCallingStackTraceElement(aclass);\n final String amsg = \"[\" + st.getClassName() + \"#\" + st.getMethodName() + \"(\" + st.getLineNumber()\n +\")] <\" + Thread.currentThread().getName() + \">: \";\n return amsg;\n}\n</code></pre>\n\n<p>Then the specific utility method to get the right stackElement:</p>\n\n<pre><code>/**\n * Returns the first stack trace element of the first class not equal to \"StackTraceUtils\" or \"LogUtils\" and aClass. <br />\n * Stored in array of the callstack. <br />\n * Allows to get past a certain class.\n * @param aclass class to get pass in the stack trace. If null, only try to get past StackTraceUtils. \n * @return stackTraceElement (never null, because if aClass is not found, returns first class past StackTraceUtils)\n * @throws AssertionFailedException if resulting statckTrace is null (RuntimeException)\n */\n public static StackTraceElement getCallingStackTraceElement(final Class aclass) {\n final Throwable t = new Throwable();\n final StackTraceElement[] ste = t.getStackTrace();\n int index = 1;\n final int limit = ste.length;\n StackTraceElement st = ste[index];\n String className = st.getClassName();\n boolean aclassfound = false;\n if(aclass == null) {\n aclassfound = true;\n }\n StackTraceElement resst = null;\n while(index < limit) {\n if(shouldExamine(className, aclass) == true) {\n if(resst == null) {\n resst = st;\n }\n if(aclassfound == true) {\n final StackTraceElement ast = onClassfound(aclass, className, st);\n if(ast != null) {\n resst = ast;\n break;\n }\n }\n else\n {\n if(aclass != null && aclass.getName().equals(className) == true) {\n aclassfound = true;\n }\n }\n }\n index = index + 1;\n st = ste[index];\n className = st.getClassName();\n }\n if(isNull(resst)) {\n throw new AssertionFailedException(StackTraceUtils.getClassMethodLine() + \" null argument:\" + \"stack trace should null\"); //$NON-NLS-1$\n }\n return resst;\n }\n\n static private boolean shouldExamine(String className, Class aclass) {\n final boolean res = StackTraceUtils.class.getName().equals(className) == false && (className.endsWith(LOG_UTILS\n ) == false || (aclass !=null && aclass.getName().endsWith(LOG_UTILS)));\n return res;\n }\n\n static private StackTraceElement onClassfound(Class aclass, String className, StackTraceElement st) {\n StackTraceElement resst = null;\n if(aclass != null && aclass.getName().equals(className) == false)\n {\n resst = st;\n }\n if(aclass == null)\n {\n resst = st;\n }\n return resst;\n }\n</code></pre>\n"
},
{
"answer_id": 4332163,
"author": "Michael Baltaks",
"author_id": 23312,
"author_profile": "https://Stackoverflow.com/users/23312",
"pm_score": 6,
"selected": false,
"text": "<p>We ended up using a custom class like this for our Android work:</p>\n\n<pre><code>import android.util.Log; \npublic class DebugLog {\n public final static boolean DEBUG = true; \n public static void log(String message) {\n if (DEBUG) {\n String fullClassName = Thread.currentThread().getStackTrace()[2].getClassName();\n String className = fullClassName.substring(fullClassName.lastIndexOf(\".\") + 1);\n String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();\n int lineNumber = Thread.currentThread().getStackTrace()[2].getLineNumber();\n\n Log.d(className + \".\" + methodName + \"():\" + lineNumber, message);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 5916374,
"author": "Juan",
"author_id": 261350,
"author_profile": "https://Stackoverflow.com/users/261350",
"pm_score": 5,
"selected": false,
"text": "<p>Quick and dirty way:</p>\n\n<pre><code>System.out.println(\"I'm in line #\" + \n new Exception().getStackTrace()[0].getLineNumber());\n</code></pre>\n\n<p>With some more details:</p>\n\n<pre><code>StackTraceElement l = new Exception().getStackTrace()[0];\nSystem.out.println(\n l.getClassName()+\"/\"+l.getMethodName()+\":\"+l.getLineNumber());\n</code></pre>\n\n<p>That will output something like this:</p>\n\n<pre><code>com.example.mytest.MyClass/myMethod:103\n</code></pre>\n"
},
{
"answer_id": 7100219,
"author": "jimmy.hautelook",
"author_id": 563038,
"author_profile": "https://Stackoverflow.com/users/563038",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the logger that we use. </p>\n\n<p>it wraps around Android Logger and display class name, method name and line number.</p>\n\n<p><a href=\"http://www.hautelooktech.com/2011/08/15/android-logging/\" rel=\"nofollow\">http://www.hautelooktech.com/2011/08/15/android-logging/</a></p>\n"
},
{
"answer_id": 10992416,
"author": "Bobs",
"author_id": 779408,
"author_profile": "https://Stackoverflow.com/users/779408",
"pm_score": 0,
"selected": false,
"text": "<p>Look at <a href=\"https://stackoverflow.com/a/10599298/779408\">this link</a>. In that method you can jump to your line code, when you double click on LogCat's row.</p>\n\n<p>Also you can use this code to get line number:</p>\n\n<pre><code>public static int getLineNumber()\n{\n int lineNumber = 0;\n StackTraceElement[] stackTraceElement = Thread.currentThread()\n .getStackTrace();\n int currentIndex = -1;\n for (int i = 0; i < stackTraceElement.length; i++) {\n if (stackTraceElement[i].getMethodName().compareTo(\"getLineNumber\") == 0)\n {\n currentIndex = i + 1;\n break;\n }\n }\n\n lineNumber = stackTraceElement[currentIndex].getLineNumber();\n\n return lineNumber;\n}\n</code></pre>\n"
},
{
"answer_id": 14317140,
"author": "Raymond",
"author_id": 1977074,
"author_profile": "https://Stackoverflow.com/users/1977074",
"pm_score": 0,
"selected": false,
"text": "<pre><code>private static final int CLIENT_CODE_STACK_INDEX;\n\nstatic {\n // Finds out the index of \"this code\" in the returned stack Trace - funny but it differs in JDK 1.5 and 1.6\n int i = 0;\n for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {\n i++;\n if (ste.getClassName().equals(Trace.class.getName())) {\n break;\n }\n }\n CLIENT_CODE_STACK_INDEX = i;\n}\n\nprivate String methodName() {\n StackTraceElement ste=Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX+1];\n return ste.getMethodName()+\":\"+ste.getLineNumber();\n}\n</code></pre>\n"
},
{
"answer_id": 16163512,
"author": "EmiDemi",
"author_id": 1286980,
"author_profile": "https://Stackoverflow.com/users/1286980",
"pm_score": -1,
"selected": false,
"text": "<p>My way it works for me</p>\n\n<pre><code>String str = \"select os.name from os where os.idos=\"+nameid; try {\n PreparedStatement stmt = conn.prepareStatement(str);\n ResultSet rs = stmt.executeQuery();\n if (rs.next()) {\n a = rs.getString(\"os.n1ame\");//<<<----Here is the ERROR \n }\n stmt.close();\n } catch (SQLException e) {\n System.out.println(\"error line : \" + e.getStackTrace()[2].getLineNumber()); \n return a;\n }\n</code></pre>\n"
},
{
"answer_id": 16839643,
"author": "Mark",
"author_id": 2344770,
"author_profile": "https://Stackoverflow.com/users/2344770",
"pm_score": 0,
"selected": false,
"text": "<p>These all get you the line numbers of your current thread and method which work great if you use a try catch where you are expecting an exception. But if you want to catch any unhandled exception then you are using the default uncaught exception handler and current thread will return the line number of the handler function, not the class method that threw the exception. Instead of using Thread.currentThread() simply use the Throwable passed in by the exception handler:</p>\n\n<pre><code>Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {\n public void uncaughtException(Thread t, Throwable e) { \n if(fShowUncaughtMessage(e,t)) \n System.exit(1);\n }\n });\n</code></pre>\n\n<p>In the above use e.getStackTrace()[0] in your handler function (fShowUncaughtMessage) to get the offender.</p>\n"
},
{
"answer_id": 23035405,
"author": "Sydwell",
"author_id": 344050,
"author_profile": "https://Stackoverflow.com/users/344050",
"pm_score": 3,
"selected": false,
"text": "<p>I use this little method that outputs the trace and line number of the method that called it. </p>\n\n<pre><code> Log.d(TAG, \"Where did i put this debug code again? \" + Utils.lineOut());\n</code></pre>\n\n<p>Double click the output to go to that source code line!</p>\n\n<p>You might need to adjust the level value depending on where you put your code.</p>\n\n<pre><code>public static String lineOut() {\n int level = 3;\n StackTraceElement[] traces;\n traces = Thread.currentThread().getStackTrace();\n return (\" at \" + traces[level] + \" \" );\n}\n</code></pre>\n"
},
{
"answer_id": 31399277,
"author": "rutvij gusani",
"author_id": 5065175,
"author_profile": "https://Stackoverflow.com/users/5065175",
"pm_score": -1,
"selected": false,
"text": "<p>you can use -> Reporter.log(\"\"); </p>\n"
},
{
"answer_id": 45583330,
"author": "Rahul",
"author_id": 3774035,
"author_profile": "https://Stackoverflow.com/users/3774035",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Below code is tested code for logging line no class name and method name from where logging method is called</strong></p>\n\n<pre><code>public class Utils {\n/*\n * debug variable enables/disables all log messages to logcat\n * Useful to disable prior to app store submission\n */\npublic static final boolean debug = true;\n\n/*\n * l method used to log passed string and returns the\n * calling file as the tag, method and line number prior\n * to the string's message\n */\npublic static void l(String s) {\n if (debug) {\n String[] msg = trace(Thread.currentThread().getStackTrace(), 3);\n Log.i(msg[0], msg[1] + s);\n } else {\n return;\n }\n}\n\n/*\n * l (tag, string)\n * used to pass logging messages as normal but can be disabled\n * when debug == false\n */\npublic static void l(String t, String s) {\n if (debug) {\n Log.i(t, s);\n } else {\n return;\n }\n}\n\n/*\n * trace\n * Gathers the calling file, method, and line from the stack\n * returns a string array with element 0 as file name and \n * element 1 as method[line]\n */\npublic static String[] trace(final StackTraceElement e[], final int level) {\n if (e != null && e.length >= level) {\n final StackTraceElement s = e[level];\n if (s != null) { return new String[] {\n e[level].getFileName(), e[level].getMethodName() + \"[\" + e[level].getLineNumber() + \"]\"\n };}\n }\n return null;\n}\n}\n</code></pre>\n"
},
{
"answer_id": 55423753,
"author": "Loyea",
"author_id": 4172311,
"author_profile": "https://Stackoverflow.com/users/4172311",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>stackLevel</code> depends on depth you call this method. You can try from 0 to a large number to see what difference. </p>\n\n<p>If <code>stackLevel</code> is legal, you will get string like <code>java.lang.Thread.getStackTrace(Thread.java:1536)</code></p>\n\n<pre><code>public static String getCodeLocationInfo(int stackLevel) {\n StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();\n if (stackLevel < 0 || stackLevel >= stackTraceElements.length) {\n return \"Stack Level Out Of StackTrace Bounds\";\n }\n StackTraceElement stackTraceElement = stackTraceElements[stackLevel];\n String fullClassName = stackTraceElement.getClassName();\n String methodName = stackTraceElement.getMethodName();\n String fileName = stackTraceElement.getFileName();\n int lineNumber = stackTraceElement.getLineNumber();\n\n return String.format(\"%s.%s(%s:%s)\", fullClassName, methodName, fileName, lineNumber);\n}\n</code></pre>\n"
},
{
"answer_id": 56856858,
"author": "Owen Chen",
"author_id": 2997128,
"author_profile": "https://Stackoverflow.com/users/2997128",
"pm_score": 0,
"selected": false,
"text": "<p>This is exactly the feature I implemented in this lib \n<a href=\"https://github.com/adherencegoo/XDDLib\" rel=\"nofollow noreferrer\">XDDLib</a>. (But, it's for android)</p>\n\n<pre><code>Lg.d(\"int array:\", intArrayOf(1, 2, 3), \"int list:\", listOf(4, 5, 6))\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/5iQFF.png\" alt=\"enter image description here\"></p>\n\n<p>One click on the <strong>underlined text</strong> to navigate to where the log command is</p>\n\n<p>That <code>StackTraceElement</code> is determined by the first element outside this library. Thus, anywhere outside this lib will be legal, including <code>lambda expression</code>, <code>static initialization block</code>, etc.</p>\n"
},
{
"answer_id": 64406183,
"author": "Delark",
"author_id": 11214643,
"author_profile": "https://Stackoverflow.com/users/11214643",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone wondering, the index in the <code>getStackTrace()[3]</code> method signals the amount of threads the triggering line travels until the actual .getStackTrace() method excluding the executing line.</p>\n<p>This means that if the <code>Thread.currentThread().getStackTrace()[X].getLineNumber();</code> line is executed from 3 nested methods <em>above</em>, the index number must be <strong>3</strong>.</p>\n<p>Example:</p>\n<p>First layer</p>\n<pre><code>private static String message(String TAG, String msg) {\n\n int lineNumber = Thread.currentThread().getStackTrace()[3].getLineNumber();\n\n return ".(" + TAG + ".java:"+ lineNumber +")" + " " + msg;\n}\n</code></pre>\n<p>Second Layer</p>\n<pre><code>private static void print(String s) {\n System.out.println(s);\n}\n</code></pre>\n<p>Third Layer</p>\n<pre><code>public static void normal(\n String TAG,\n String message\n) {\n print(\n message(\n TAG,\n message\n )\n );\n}\n</code></pre>\n<p>Executing Line:</p>\n<pre><code> Print.normal(TAG, "StatelessDispatcher");\n</code></pre>\n<p>As someone that has not received any formal education on IT, this has been mind opening on how compilers work.</p>\n"
},
{
"answer_id": 72992183,
"author": "sezad vakil",
"author_id": 7302401,
"author_profile": "https://Stackoverflow.com/users/7302401",
"pm_score": 0,
"selected": false,
"text": "<p>This is the code which prints the line number.</p>\n<pre><code>Thread.currentThread().getStackTrace()[2].getLineNumber()\n</code></pre>\n<p>Create a global public static method to make printing Logs easier.</p>\n<pre><code> public static void Loge(Context context, String strMessage, int strLineNumber) {\n \n Log.e(context.getClass().getSimpleName(), strLineNumber + " : " + strMessage);\n \n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15177/"
]
| How to print line numbers to the log. Say when outputting some information to the log, I also want to print the line number where that output is in the source code. As we can see in the stack trace, it displays the line number where the exception has occurred. Stack trace is available on the exception object.
Other alternative could be like manually including the line number when printing to the log. Is there any other way? | From [Angsuman Chakraborty](https://web.archive.org/web/20100818065334/http://blog.taragana.com:80/index.php/archive/core-java-how-to-get-java-source-code-line-number-file-name-in-code/) (archived) :
```
/** Get the current line number.
* @return int - Current line number.
*/
public static int getLineNumber() {
return Thread.currentThread().getStackTrace()[2].getLineNumber();
}
``` |
115,031 | <p>I have an assembly, written in C++\CLI, which uses some of enumerations, provided by .Net. It has such kind of properties: </p>
<pre><code>property System::ServiceProcess::ServiceControllerStatus ^ Status
{
ServiceControllerStatus ^ get()
{
return (ServiceControllerStatus)_status->dwCurrentState;
}
}
</code></pre>
<p>it works fine, but when i use this assembly from my C# code, type of this property is </p>
<pre><code>System.Enum
</code></pre>
<p>and i have to make type-cast</p>
<pre><code> if ((ServiceControllerStatus)currentService.Status == ServiceControllerStatus.Running)
//do smth
</code></pre>
<p>The question is simple: why is it so, and how to fix it ?</p>
| [
{
"answer_id": 115054,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>I think enums don't use the ^ -- try removing it from the property declaration and get().</p>\n"
},
{
"answer_id": 115106,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 4,
"selected": true,
"text": "<p>In C++/CLI <strong>^</strong> is like the analagous * in standard C++. Because enumerations are value types the <strong>^</strong> should not be included otherwise you will see them as <strong>System.Enum</strong>.</p>\n\n<p>Remove the ^ and you will see the correct enumeration on C# side.</p>\n\n<pre><code>property System::ServiceProcess::ServiceControllerStatus Status \n{ \n System::ServiceProcess::ServiceControllerStatus get() \n { \n return (System::ServiceProcess::ServiceControllerStatus)_status->dwCurrentState; \n } \n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6698/"
]
| I have an assembly, written in C++\CLI, which uses some of enumerations, provided by .Net. It has such kind of properties:
```
property System::ServiceProcess::ServiceControllerStatus ^ Status
{
ServiceControllerStatus ^ get()
{
return (ServiceControllerStatus)_status->dwCurrentState;
}
}
```
it works fine, but when i use this assembly from my C# code, type of this property is
```
System.Enum
```
and i have to make type-cast
```
if ((ServiceControllerStatus)currentService.Status == ServiceControllerStatus.Running)
//do smth
```
The question is simple: why is it so, and how to fix it ? | In C++/CLI **^** is like the analagous \* in standard C++. Because enumerations are value types the **^** should not be included otherwise you will see them as **System.Enum**.
Remove the ^ and you will see the correct enumeration on C# side.
```
property System::ServiceProcess::ServiceControllerStatus Status
{
System::ServiceProcess::ServiceControllerStatus get()
{
return (System::ServiceProcess::ServiceControllerStatus)_status->dwCurrentState;
}
}
``` |
115,039 | <p>Suppose that the <strong>ApplicationSettings</strong> class is a general repository of settings that apply to my application such as TimeoutPeriod, DefaultUnitOfMeasure, HistoryWindowSize, etc... And let's say MyClass makes use of one of those settings - DefaultUnitOfMeasure.</p>
<p>My reading of proper use of Inversion of Control Containers - and please correct me if I'm wrong on this - is that you define the dependencies of a class in its constructor:</p>
<pre><code>public class MyClass {
public MyClass(IDataSource ds, UnitOfMeasure default_uom) {...}
}
</code></pre>
<p>and then call instantiate your class with something like</p>
<pre><code>var mc = IoC.Container.Resolve<MyClass>();
</code></pre>
<p>Where <strong>IDataSource</strong> has been assigned a concrete implementation and default_uom has been wired up to instantiate from the <strong>ApplicationSettings.DefaultUnitOfMeasure</strong> property. I've got to wonder however, if all these hoops are really that necessary to jump through. What trouble am I setting myself up for should I do</p>
<pre><code>public class MyClass {
public MyClass(IDataSource ds) {
UnitOfMeasure duom = IoC.Container.Resolve<UnitOfMeasure>("default_uom");
}
}
</code></pre>
<p>Yes, many of my classes end up with a dependency on <strong>IoC.Container</strong> but that is a dependency that most of my classes will have anyways. It seems like I maybe should make full use of it as long as the classes are coupled. Please Agile gurus, tell me where I'm wrong.</p>
| [
{
"answer_id": 115183,
"author": "Mike Deck",
"author_id": 1247,
"author_profile": "https://Stackoverflow.com/users/1247",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Yes, many of my classes end up with a dependency on IoC.Container but that is a dependency that most of my classes will have anyways.</p>\n</blockquote>\n\n<p>I think this is the crux of the issue. If in fact most of your classes are coupled to the IoC container itself chances are you need to rethink your design.</p>\n\n<p>Generally speaking your app should only refer to the container class directly once during the bootstrapping. After you have that first hook into the container the rest of the object graph should be entirely managed by the container and all of those objects should be oblivious to the fact that they were created by an IoC container.</p>\n"
},
{
"answer_id": 115214,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 2,
"selected": false,
"text": "<p>I usually don't have many classes depending on my IoC container. I usually try to wrap the IoC stuff in a facade object that I inject into other classes, usually most of my IoC injection is done only in the higher layers of my application though.</p>\n\n<p>If you do things your way you can't test MyClass without creating a IoC configuration for your tests. This will make your tests harder to maintain.</p>\n\n<p>Another problem is that you're going to have powerusers of your software who want to change the configuration editing your IoC config files. This is something I'd want to avoid. You could split up your IoC config into a normal config file and the IoC specific stuff. But then you could just as well use the normal .Net config functionality to read the configuration.</p>\n"
},
{
"answer_id": 118939,
"author": "Bittercoder",
"author_id": 4843,
"author_profile": "https://Stackoverflow.com/users/4843",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>IoC.Container.Resolve(\"default_uom\");</p>\n</blockquote>\n\n<p>I see this as a classic anti-pattern, where you are using the IoC container as a service locater - the key issues that result are:</p>\n\n<ul>\n<li>Your application no longer fails-fast if your container is misconfigured (you'll only know about it the first time it tries to resolve that particular service in code, which might not occur except for a specific set of logic/circumstances).</li>\n<li>Harder to test - not impossible of course, but you either have to create a real (and semi-configured) instance of the windsor container for your tests or inject the singleton with a mock of IWindsorContainer - this adds a lot of friction to testing, compared to just being able to pass the mock/stub services directly into your class under test via constructors/properties.</li>\n<li>Harder to maintain this kind of application (configuration isn't centralized in one location)</li>\n<li>Violates a number of other software development principles (DRY, SOC etc.)</li>\n</ul>\n\n<p>The concerning part of your original statement is the implication that most of your classes will have a dependency on your IoC singleton - if they're getting all the services injected in via constructors/dependencies then having some tight coupling to IoC should be the exception to the rule - In general the only time I take a dependency on the container is when I'm doing something tricky i.e. trying to avoid a circular dependency problems, or wish to create components at run-time for some reason, and even then I can often avoid taking a dependency on anything more then a generic IServiceProvider interface, allowing me to swap in a home-bake IoC or service locater implementation if I need to reuse the components in an environment outside of the original project.</p>\n"
},
{
"answer_id": 119005,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 2,
"selected": false,
"text": "<p>To comment on your specific example:</p>\n\n<pre><code>public class MyClass {\n public MyClass(IDataSource ds) {\n UnitOfMeasure duom = IoC.Container.Resolve<UnitOfMeasure>(\"default_uom\");\n }\n}\n</code></pre>\n\n<p>This makes it harder to re-use your class. More specifically it makes it harder to instantiate your class outside of the narrow usage pattern you are confining it to. One of the most common places this will manifest itself is when trying to test your class. It's much easier to test that class if the UnitOfMeasure can be passed to the constructor directly.</p>\n\n<p>Also, your choice of name for the UOM instance (\"default_uom\") implies that the value could be overridden, depending on the usage of the class. In that case, you would not want to \"hard-code\" the value in the constructor like that.</p>\n\n<p>Using the constructor injection pattern <strong>does not</strong> make your class dependent on the IoC, just the opposite it gives clients the option to use the IoC or not.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
| Suppose that the **ApplicationSettings** class is a general repository of settings that apply to my application such as TimeoutPeriod, DefaultUnitOfMeasure, HistoryWindowSize, etc... And let's say MyClass makes use of one of those settings - DefaultUnitOfMeasure.
My reading of proper use of Inversion of Control Containers - and please correct me if I'm wrong on this - is that you define the dependencies of a class in its constructor:
```
public class MyClass {
public MyClass(IDataSource ds, UnitOfMeasure default_uom) {...}
}
```
and then call instantiate your class with something like
```
var mc = IoC.Container.Resolve<MyClass>();
```
Where **IDataSource** has been assigned a concrete implementation and default\_uom has been wired up to instantiate from the **ApplicationSettings.DefaultUnitOfMeasure** property. I've got to wonder however, if all these hoops are really that necessary to jump through. What trouble am I setting myself up for should I do
```
public class MyClass {
public MyClass(IDataSource ds) {
UnitOfMeasure duom = IoC.Container.Resolve<UnitOfMeasure>("default_uom");
}
}
```
Yes, many of my classes end up with a dependency on **IoC.Container** but that is a dependency that most of my classes will have anyways. It seems like I maybe should make full use of it as long as the classes are coupled. Please Agile gurus, tell me where I'm wrong. | >
> IoC.Container.Resolve("default\_uom");
>
>
>
I see this as a classic anti-pattern, where you are using the IoC container as a service locater - the key issues that result are:
* Your application no longer fails-fast if your container is misconfigured (you'll only know about it the first time it tries to resolve that particular service in code, which might not occur except for a specific set of logic/circumstances).
* Harder to test - not impossible of course, but you either have to create a real (and semi-configured) instance of the windsor container for your tests or inject the singleton with a mock of IWindsorContainer - this adds a lot of friction to testing, compared to just being able to pass the mock/stub services directly into your class under test via constructors/properties.
* Harder to maintain this kind of application (configuration isn't centralized in one location)
* Violates a number of other software development principles (DRY, SOC etc.)
The concerning part of your original statement is the implication that most of your classes will have a dependency on your IoC singleton - if they're getting all the services injected in via constructors/dependencies then having some tight coupling to IoC should be the exception to the rule - In general the only time I take a dependency on the container is when I'm doing something tricky i.e. trying to avoid a circular dependency problems, or wish to create components at run-time for some reason, and even then I can often avoid taking a dependency on anything more then a generic IServiceProvider interface, allowing me to swap in a home-bake IoC or service locater implementation if I need to reuse the components in an environment outside of the original project. |
115,103 | <p>I am trying to implement position-sensitive zooming inside a <code>JScrollPane</code>. The <code>JScrollPane</code> contains a component with a customized <code>paint</code> that will draw itself inside whatever space it is allocated - so zooming is as easy as using a <code>MouseWheelListener</code> that resizes the inner component as required.</p>
<p>But I also want zooming into (or out of) a point to keep that point as central as possible within the resulting zoomed-in (or -out) view (this is what I refer to as 'position-sensitive' zooming), similar to how zooming works in google maps. I am sure this has been done many times before - does anybody know the "right" way to do it under Java Swing?. Would it be better to play with <code>Graphic2D</code>'s transformations instead of using <code>JScrollPanes</code>?</p>
<p>Sample code follows:</p>
<pre><code>package test;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class FPanel extends javax.swing.JPanel {
private Dimension preferredSize = new Dimension(400, 400);
private Rectangle2D[] rects = new Rectangle2D[50];
public static void main(String[] args) {
JFrame jf = new JFrame("test");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400, 400);
jf.add(new JScrollPane(new FPanel()));
jf.setVisible(true);
}
public FPanel() {
// generate rectangles with pseudo-random coords
for (int i=0; i<rects.length; i++) {
rects[i] = new Rectangle2D.Double(
Math.random()*.8, Math.random()*.8,
Math.random()*.2, Math.random()*.2);
}
// mouse listener to detect scrollwheel events
addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
updatePreferredSize(e.getWheelRotation(), e.getPoint());
}
});
}
private void updatePreferredSize(int n, Point p) {
double d = (double) n * 1.08;
d = (n > 0) ? 1 / d : -d;
int w = (int) (getWidth() * d);
int h = (int) (getHeight() * d);
preferredSize.setSize(w, h);
getParent().doLayout();
// Question: how do I keep 'p' centered in the resulting view?
}
public Dimension getPreferredSize() {
return preferredSize;
}
private Rectangle2D r = new Rectangle2D.Float();
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.red);
int w = getWidth();
int h = getHeight();
for (Rectangle2D rect : rects) {
r.setRect(rect.getX() * w, rect.getY() * h,
rect.getWidth() * w, rect.getHeight() * h);
((Graphics2D)g).draw(r);
}
}
}
</code></pre>
| [
{
"answer_id": 115179,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 1,
"selected": false,
"text": "<p>Your MouseWheelListener also has to locate the cursor, move it to the center of the JScrollPane and adjust the xmin/ymin and xmax/ymax of the content to be viewed.</p>\n"
},
{
"answer_id": 2598320,
"author": "xycf7",
"author_id": 262537,
"author_profile": "https://Stackoverflow.com/users/262537",
"pm_score": 1,
"selected": false,
"text": "<p>I think smt like this should be working...</p>\n\n<pre><code>\nprivate void updatePreferredSize(int n, Point p) {\n double d = (double) n * 1.08;\n d = (n > 0) ? 1 / d : -d;\n int w = (int) (getWidth() * d);\n int h = (int) (getHeight() * d);\n preferredSize.setSize(w, h);\n\n // Question: how do I keep 'p' centered in the resulting view?\n\n int parentWdt = this.getParent( ).getWidth( ) ;\n int parentHgt = this.getParent( ).getHeight( ) ;\n\n int newLeft = p.getLocation( ).x - ( p.x - ( parentWdt / 2 ) ) ;\n int newTop = p.getLocation( ).y - ( p.y - ( parentHgt / 2 ) ) ;\n this.setLocation( newLeft, newTop ) ;\n\n getParent().doLayout();\n}\n\n</code></pre>\n\n<p>EDIT:\nChanged a couple things.</p>\n"
},
{
"answer_id": 2605254,
"author": "Kevin K",
"author_id": 292728,
"author_profile": "https://Stackoverflow.com/users/292728",
"pm_score": 4,
"selected": true,
"text": "<p>Tested this, seems to work...</p>\n\n<pre><code>private void updatePreferredSize(int n, Point p) {\n double d = (double) n * 1.08;\n d = (n > 0) ? 1 / d : -d;\n\n int w = (int) (getWidth() * d);\n int h = (int) (getHeight() * d);\n preferredSize.setSize(w, h);\n\n int offX = (int)(p.x * d) - p.x;\n int offY = (int)(p.y * d) - p.y;\n setLocation(getLocation().x-offX,getLocation().y-offY);\n\n getParent().doLayout();\n}\n</code></pre>\n\n<p><strong>Update</strong></p>\n\n<p>Here is an explanation: the point <code>p</code> is the location of the mouse relative to the <code>FPanel</code>. Since you are scaling the size of the panel, the location of <code>p</code> (relative to the size of the panel) will scale by the same factor. By subtracting the current location from the scaled location, you get how much the point 'shifts' when the panel is resized. Then it is simply a matter of shifting the panel location in the scroll pane by the same amount in the opposite direction to put <code>p</code> back under the mouse cursor.</p>\n"
},
{
"answer_id": 2609144,
"author": "Carl Manaster",
"author_id": 82118,
"author_profile": "https://Stackoverflow.com/users/82118",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a minor refactoring of @Kevin K's solution:</p>\n\n<pre><code>private void updatePreferredSize(int wheelRotation, Point stablePoint) {\n double scaleFactor = findScaleFactor(wheelRotation);\n scaleBy(scaleFactor);\n Point offset = findOffset(stablePoint, scaleFactor);\n offsetBy(offset);\n getParent().doLayout();\n}\n\nprivate double findScaleFactor(int wheelRotation) {\n double d = wheelRotation * 1.08;\n return (d > 0) ? 1 / d : -d;\n}\n\nprivate void scaleBy(double scaleFactor) {\n int w = (int) (getWidth() * scaleFactor);\n int h = (int) (getHeight() * scaleFactor);\n preferredSize.setSize(w, h);\n}\n\nprivate Point findOffset(Point stablePoint, double scaleFactor) {\n int x = (int) (stablePoint.x * scaleFactor) - stablePoint.x;\n int y = (int) (stablePoint.y * scaleFactor) - stablePoint.y;\n return new Point(x, y);\n}\n\nprivate void offsetBy(Point offset) {\n Point location = getLocation();\n setLocation(location.x - offset.x, location.y - offset.y);\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15472/"
]
| I am trying to implement position-sensitive zooming inside a `JScrollPane`. The `JScrollPane` contains a component with a customized `paint` that will draw itself inside whatever space it is allocated - so zooming is as easy as using a `MouseWheelListener` that resizes the inner component as required.
But I also want zooming into (or out of) a point to keep that point as central as possible within the resulting zoomed-in (or -out) view (this is what I refer to as 'position-sensitive' zooming), similar to how zooming works in google maps. I am sure this has been done many times before - does anybody know the "right" way to do it under Java Swing?. Would it be better to play with `Graphic2D`'s transformations instead of using `JScrollPanes`?
Sample code follows:
```
package test;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class FPanel extends javax.swing.JPanel {
private Dimension preferredSize = new Dimension(400, 400);
private Rectangle2D[] rects = new Rectangle2D[50];
public static void main(String[] args) {
JFrame jf = new JFrame("test");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400, 400);
jf.add(new JScrollPane(new FPanel()));
jf.setVisible(true);
}
public FPanel() {
// generate rectangles with pseudo-random coords
for (int i=0; i<rects.length; i++) {
rects[i] = new Rectangle2D.Double(
Math.random()*.8, Math.random()*.8,
Math.random()*.2, Math.random()*.2);
}
// mouse listener to detect scrollwheel events
addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
updatePreferredSize(e.getWheelRotation(), e.getPoint());
}
});
}
private void updatePreferredSize(int n, Point p) {
double d = (double) n * 1.08;
d = (n > 0) ? 1 / d : -d;
int w = (int) (getWidth() * d);
int h = (int) (getHeight() * d);
preferredSize.setSize(w, h);
getParent().doLayout();
// Question: how do I keep 'p' centered in the resulting view?
}
public Dimension getPreferredSize() {
return preferredSize;
}
private Rectangle2D r = new Rectangle2D.Float();
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.red);
int w = getWidth();
int h = getHeight();
for (Rectangle2D rect : rects) {
r.setRect(rect.getX() * w, rect.getY() * h,
rect.getWidth() * w, rect.getHeight() * h);
((Graphics2D)g).draw(r);
}
}
}
``` | Tested this, seems to work...
```
private void updatePreferredSize(int n, Point p) {
double d = (double) n * 1.08;
d = (n > 0) ? 1 / d : -d;
int w = (int) (getWidth() * d);
int h = (int) (getHeight() * d);
preferredSize.setSize(w, h);
int offX = (int)(p.x * d) - p.x;
int offY = (int)(p.y * d) - p.y;
setLocation(getLocation().x-offX,getLocation().y-offY);
getParent().doLayout();
}
```
**Update**
Here is an explanation: the point `p` is the location of the mouse relative to the `FPanel`. Since you are scaling the size of the panel, the location of `p` (relative to the size of the panel) will scale by the same factor. By subtracting the current location from the scaled location, you get how much the point 'shifts' when the panel is resized. Then it is simply a matter of shifting the panel location in the scroll pane by the same amount in the opposite direction to put `p` back under the mouse cursor. |
115,121 | <p>Does anyone know why there is no <code>respond_to</code> block for generated <code>edit</code> actions? Every other action in typical scaffold controllers has a <code>respond_to</code> block in order to output <code>html</code> and <code>xml</code> formats. Why is the <code>edit</code> action an exception?</p>
<p>I'm using the latest version of Ruby on Rails (2.1.1).</p>
| [
{
"answer_id": 115201,
"author": "Andrew",
"author_id": 17408,
"author_profile": "https://Stackoverflow.com/users/17408",
"pm_score": 1,
"selected": false,
"text": "<p>Because the edit action will only be called from HTML\nThere is no need for the edit form to be returned in an XML context.\nUsing REST, you simply make a put call directly to update with the relevant information.</p>\n"
},
{
"answer_id": 115211,
"author": "Pete",
"author_id": 13472,
"author_profile": "https://Stackoverflow.com/users/13472",
"pm_score": 5,
"selected": true,
"text": "<p>Rails handles the 99% case: It's fairly unlikely you'd ever need to do any XML or JSON translations in your Edit action, because non-visually, the Edit action is pretty much just like the Show action. Nonvisual clients that want to update a model in your application can call the controller this way</p>\n\n<pre><code>GET /my_models/[:id].xml (Show) \n</code></pre>\n\n<p>Then, the client app can make any transformations or edits and post (or put) the results to</p>\n\n<pre><code>PUT /my_models/[:id].xml (Update) \n</code></pre>\n\n<p>When you call this, you usually are doing it to get an editable form of the Show action: </p>\n\n<pre><code>GET /my_models/[:id]/edit \n</code></pre>\n\n<p>And it is intended for human use. 99% of the time, that is. Since it's unusual to transform the data in the Edit action, Rails assumes you aren't going to, and DRYs up your code by leaving respond_to out of the scaffold. </p>\n"
},
{
"answer_id": 116792,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 2,
"selected": false,
"text": "<p>Somewhat related. Some may wonder why the rails scaffolding for the new action still has a respond_to block; whereas the edit action does not. This is because a request to something like:</p>\n\n<pre><code>GET /my_models/new.xml\n</code></pre>\n\n<p>...gives back an XML template that can be used to create a new model.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467/"
]
| Does anyone know why there is no `respond_to` block for generated `edit` actions? Every other action in typical scaffold controllers has a `respond_to` block in order to output `html` and `xml` formats. Why is the `edit` action an exception?
I'm using the latest version of Ruby on Rails (2.1.1). | Rails handles the 99% case: It's fairly unlikely you'd ever need to do any XML or JSON translations in your Edit action, because non-visually, the Edit action is pretty much just like the Show action. Nonvisual clients that want to update a model in your application can call the controller this way
```
GET /my_models/[:id].xml (Show)
```
Then, the client app can make any transformations or edits and post (or put) the results to
```
PUT /my_models/[:id].xml (Update)
```
When you call this, you usually are doing it to get an editable form of the Show action:
```
GET /my_models/[:id]/edit
```
And it is intended for human use. 99% of the time, that is. Since it's unusual to transform the data in the Edit action, Rails assumes you aren't going to, and DRYs up your code by leaving respond\_to out of the scaffold. |
115,159 | <p>I have been using ASP.NET for years, but I can never remember when using the # and = are appropriate.</p>
<p>For example:</p>
<pre><code><%= Grid.ClientID %>
</code></pre>
<p>or</p>
<pre><code><%# Eval("FullName")%>
</code></pre>
<p>Can someone explain when each should be used so I can keep it straight in my mind? Is # only used in controls that support databinding?</p>
| [
{
"answer_id": 115199,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 6,
"selected": true,
"text": "<p><%= %> is the equivalent of doing Response.Write(\"\") wherever you place it.</p>\n\n<p><%# %> is for Databinding and can only be used where databinding is supported (you can use these on the page-level outside a control if you call Page.DataBind() in your codebehind)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms178366.aspx\" rel=\"noreferrer\">Databinding Expressions Overview</a></p>\n"
},
{
"answer_id": 115205,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a <a href=\"http://blogs.msdn.com/dancre/archive/2007/02/13/the-difference-between-lt-and-lt-in-asp-net.aspx\" rel=\"noreferrer\">great blog post by Dan Crevier</a> that walks through a test app he wrote to show the differences.</p>\n\n<p>In essence:</p>\n\n<ul>\n<li>The <%= expressions are evaluated at render time</li>\n<li>The <%# expressions are evaluated at DataBind() time and are not evaluated at all if DataBind() is not called.</li>\n<li><%# expressions can be used as properties in server-side controls. <%= expressions cannot.</li>\n</ul>\n"
},
{
"answer_id": 115212,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": false,
"text": "<p>There are a couple of different 'bee-stings':</p>\n\n<ul>\n<li><code><%@</code> - page directive</li>\n<li><code><%$</code> - resource access</li>\n<li><code><%=</code> - explicit output to page</li>\n<li><code><%#</code> - data binding</li>\n<li><code><%--</code> - server side comment block</li>\n</ul>\n\n<p>Also new in ASP.Net 4:</p>\n\n<ul>\n<li><code><%:</code> - writes out to the page, but with HTML encoded</li>\n</ul>\n\n<p>Also new in ASP.Net 4.5:</p>\n\n<ul>\n<li><code><%#:</code> - HTML encoded data binding</li>\n</ul>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417/"
]
| I have been using ASP.NET for years, but I can never remember when using the # and = are appropriate.
For example:
```
<%= Grid.ClientID %>
```
or
```
<%# Eval("FullName")%>
```
Can someone explain when each should be used so I can keep it straight in my mind? Is # only used in controls that support databinding? | <%= %> is the equivalent of doing Response.Write("") wherever you place it.
<%# %> is for Databinding and can only be used where databinding is supported (you can use these on the page-level outside a control if you call Page.DataBind() in your codebehind)
[Databinding Expressions Overview](http://msdn.microsoft.com/en-us/library/ms178366.aspx) |
115,167 | <p>I've been developing a site over the past few weeks using CodeIgniter as the framework. I've been thinking of the best way to accomplish something, which in a lot of other frameworks in other languages is relatively simple: sortable tables. CodeIgniter switches off query strings by default, because your URLs contain method parameters. So a URL might look like:</p>
<pre><code>/controller/method/param1/param2
</code></pre>
<p>You might think that you could just add in <code>sortBy</code> and <code>sortOrder</code> as two additional parameters to the controller method. I don't particularly want to do that, mainly because I want to have a re-usable controller. When you use query string parameters, PHP can easily tell you whether there is a parameter called <code>sortBy</code>. However, when you're using URL based parameters, it will vary with each controller.</p>
<p>I was wondering what my options were. As far as I can see they are something like:</p>
<ul>
<li>Pass in my <code>sortBy</code> and <code>sortOrder</code> parameters, just suck it up, and develop some less-than-reusable component for it.</li>
<li>Have an additional controller, which will store the <code>sortBy</code> and <code>sortOrder</code> in the session (although it would have to know where you came from, and send you back to the original page).</li>
<li>Have some kind of AJAX function, which would call the controller above; then reload the page.</li>
<li>Hack CodeIgniter to turn query strings back on. Actually, if this is the only option, any links to how to do this would be appreciated.</li>
</ul>
<p>I just can't quite believe such a simple task would present such a problem! Am I missing something? Does anyone have any recommendations?</p>
<p>While I love jQuery, and I'm already using it on the site, so TableSorter is a good option. However, I would like to do server-side sorting as there are some pages with potentially large numbers of results, including pagination.</p>
| [
{
"answer_id": 115259,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 0,
"selected": false,
"text": "<p>I recently added this <a href=\"http://tetlaw.id.au/view/blog/table-sorting-with-prototype/\" rel=\"nofollow noreferrer\">Table sorter</a> (which uses Prototype) to a bunch of my pages. It's fast and pretty easy to implement.</p>\n"
},
{
"answer_id": 115273,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 2,
"selected": false,
"text": "<p>If you're OK with sorting on the client side, <a href=\"http://tablesorter.com/docs\" rel=\"nofollow noreferrer\">the Tablesorter plugin for jQuery</a> is pretty nice.</p>\n"
},
{
"answer_id": 119265,
"author": "JayTee",
"author_id": 20153,
"author_profile": "https://Stackoverflow.com/users/20153",
"pm_score": 1,
"selected": false,
"text": "<p>I ran into this with a fairly complex table. The hard part was that the table could grow/shrink depending on certain variables!! Big pain :(</p>\n\n<p>Here's how I handled it..</p>\n\n<p>Adjusted system/application/config/config.php to allow the comma character in the URI:</p>\n\n<pre><code>$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\\-,';\n</code></pre>\n\n<p>Adjust my controller with a sorting function:</p>\n\n<pre><code>function sorter() {\n //get the sort params\n $sort = explode(\",\",$this->uri->segment(3)); //the 3rd segment is the column/order\n //pass the params to the model\n $data = $this->model_name->get_the_data($sort[0],$sort[1]);\n $this->_show($data);\n}\nfunction _show($data) {\n //all the code for displaying your table\n}\n</code></pre>\n\n<p>I've oversimplified, but you get the idea. The purpose is to have a url like this:</p>\n\n<p>/controller/sorter/columnname,sortorder</p>\n\n<p>The sorter function calls another internal function to deal with the display/template/view logic - it's job is to deal with the sorting call and get the appropriate data from the model.</p>\n\n<p>Of course, this could be reduced to just your current function:</p>\n\n<pre><code>function showGrid() {\n $sort = $this->uri->segment(3);\n if ($sort) {\n //get the data sorted\n } else {\n //get the data the default way\n }\n //rest of your view logic\n}\n</code></pre>\n\n<p>That way, you don't even need a separate function - and can use the third segment to define your sorting.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I've been developing a site over the past few weeks using CodeIgniter as the framework. I've been thinking of the best way to accomplish something, which in a lot of other frameworks in other languages is relatively simple: sortable tables. CodeIgniter switches off query strings by default, because your URLs contain method parameters. So a URL might look like:
```
/controller/method/param1/param2
```
You might think that you could just add in `sortBy` and `sortOrder` as two additional parameters to the controller method. I don't particularly want to do that, mainly because I want to have a re-usable controller. When you use query string parameters, PHP can easily tell you whether there is a parameter called `sortBy`. However, when you're using URL based parameters, it will vary with each controller.
I was wondering what my options were. As far as I can see they are something like:
* Pass in my `sortBy` and `sortOrder` parameters, just suck it up, and develop some less-than-reusable component for it.
* Have an additional controller, which will store the `sortBy` and `sortOrder` in the session (although it would have to know where you came from, and send you back to the original page).
* Have some kind of AJAX function, which would call the controller above; then reload the page.
* Hack CodeIgniter to turn query strings back on. Actually, if this is the only option, any links to how to do this would be appreciated.
I just can't quite believe such a simple task would present such a problem! Am I missing something? Does anyone have any recommendations?
While I love jQuery, and I'm already using it on the site, so TableSorter is a good option. However, I would like to do server-side sorting as there are some pages with potentially large numbers of results, including pagination. | If you're OK with sorting on the client side, [the Tablesorter plugin for jQuery](http://tablesorter.com/docs) is pretty nice. |
115,210 | <p>I'm processing some data files that are supposed to be valid UTF-8 but aren't, which causes the parser (not under my control) to fail. I'd like to add a stage of pre-validating the data for UTF-8 well-formedness, but I've not yet found a utility to help do this.</p>
<p>There's a <a href="http://www.w3.org/2005/01/yacker/uploads/utf8-validator" rel="noreferrer">web service</a> at W3C which appears to be dead, and I've found a Windows-only validation <a href="http://web.archive.org/web/20081101142036/http://bolek.techno.cz:80/UTF8-Validator/" rel="noreferrer">tool</a> that reports invalid UTF-8 files but doesn't report which lines/characters to fix.</p>
<p>I'd be happy with either a tool I can drop in and use (ideally cross-platform), or a ruby/perl script I can make part of my data loading process. </p>
| [
{
"answer_id": 115241,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "<p>Use python and str.encode|decode functions.</p>\n\n<pre><code>>>> a=\"γεια\"\n>>> a\n'\\xce\\xb3\\xce\\xb5\\xce\\xb9\\xce\\xb1'\n>>> b='\\xce\\xb3\\xce\\xb5\\xce\\xb9\\xff\\xb1' # note second-to-last char changed\n>>> print b.decode(\"utf_8\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/local/lib/python2.5/encodings/utf_8.py\", line 16, in decode\n return codecs.utf_8_decode(input, errors, True)\nUnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 6: unexpected code byte\n</code></pre>\n\n<p>The exception thrown has the info requested in its .args property.</p>\n\n<pre><code>>>> try: print b.decode(\"utf_8\")\n... except UnicodeDecodeError, exc: pass\n...\n>>> exc\nUnicodeDecodeError('utf8', '\\xce\\xb3\\xce\\xb5\\xce\\xb9\\xff\\xb1', 6, 7, 'unexpected code byte')\n>>> exc.args\n('utf8', '\\xce\\xb3\\xce\\xb5\\xce\\xb9\\xff\\xb1', 6, 7, 'unexpected code byte')\n</code></pre>\n"
},
{
"answer_id": 115250,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 3,
"selected": false,
"text": "<p>How about the gnu <a href=\"http://www.gnu.org/software/libiconv/documentation/libiconv/iconv.3.html\" rel=\"noreferrer\">iconv</a> library? Using the iconv() function: \"An invalid multibyte sequence is encountered in the input. In this case it sets errno to EILSEQ and returns (size_t)(-1). *inbuf is left pointing to the beginning of the invalid multibyte sequence.\"</p>\n\n<p>EDIT: oh - i missed the part where you want a scripting language. But for command line work, the <a href=\"http://www.gnu.org/software/libiconv/documentation/libiconv/iconv.1.html\" rel=\"noreferrer\">iconv</a> utility should validate for you too.</p>\n"
},
{
"answer_id": 115262,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 8,
"selected": true,
"text": "<p>You can use GNU iconv:</p>\n\n<pre><code>$ iconv -f UTF-8 your_file -o /dev/null; echo $?\n</code></pre>\n\n<p>Or with older versions of iconv, such as on macOS:</p>\n\n<pre><code>$ iconv -f UTF-8 your_file > /dev/null; echo $?\n</code></pre>\n\n<p>The command will return 0 if the file could be converted successfully, and 1 if not. Additionally, it will print out the byte offset where the invalid byte sequence occurred.</p>\n\n<p><strong>Edit</strong>: The output encoding doesn't have to be specified, it will be assumed to be UTF-8.</p>\n"
},
{
"answer_id": 37450729,
"author": "Roger Dahl",
"author_id": 442006,
"author_profile": "https://Stackoverflow.com/users/442006",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <a href=\"http://linux.die.net/man/1/isutf8\" rel=\"noreferrer\">isutf8</a> from the <a href=\"https://joeyh.name/code/moreutils/\" rel=\"noreferrer\">moreutils</a> collection.</p>\n\n<pre><code>$ apt-get install moreutils\n$ isutf8 your_file\n</code></pre>\n\n<p>In a shell script, use the <code>--quiet</code> switch and check the exit status, which is zero for files that are valid utf-8.</p>\n"
},
{
"answer_id": 60328220,
"author": "mivk",
"author_id": 111036,
"author_profile": "https://Stackoverflow.com/users/111036",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use <a href=\"https://linux.die.net/man/1/recode\" rel=\"nofollow noreferrer\"><code>recode</code></a>, which will exit with an error if it tries to decode UTF-8 and encounters invalid characters.</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>if recode utf8/..UCS < \"$FILE\" >/dev/null 2>&1; then\n echo \"Valid utf8 : $FILE\"\nelse\n echo \"NOT valid utf8: $FILE\"\nfi\n</code></pre>\n\n<p>This tries to recode to the <a href=\"https://en.wikipedia.org/wiki/Universal_Coded_Character_Set\" rel=\"nofollow noreferrer\">Universal Character Set (UCS)</a> which is always possible from valid UTF-8.</p>\n"
},
{
"answer_id": 61083154,
"author": "Sherzad",
"author_id": 2021982,
"author_profile": "https://Stackoverflow.com/users/2021982",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the bash script to check whether a file is valid UTF-8 or not:</p>\n\n<pre><code>#!/bin/bash\n\ninputFile=\"./testFile.txt\"\n\niconv -f UTF-8 \"$inputFile\" -o /dev/null\n\nif [[ $? -eq 0 ]]\nthen\n echo \"Valid UTF-8 file.\";\nelse\n echo \"Invalid UTF-8 file!\";\nfi\n</code></pre>\n\n<p><strong>Description:</strong></p>\n\n<ul>\n<li><code>--from-code</code>, <code>-f</code> encoding (Convert characters from encoding)</li>\n<li><code>--to-code</code>, <code>-t</code> encoding (Convert characters to encoding, it doesn't have to be specified, it will be assumed to be UTF-8.)</li>\n<li><code>--output</code>, <code>-o</code> file (Specify output file 'instead of stdout')</li>\n</ul>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6716/"
]
| I'm processing some data files that are supposed to be valid UTF-8 but aren't, which causes the parser (not under my control) to fail. I'd like to add a stage of pre-validating the data for UTF-8 well-formedness, but I've not yet found a utility to help do this.
There's a [web service](http://www.w3.org/2005/01/yacker/uploads/utf8-validator) at W3C which appears to be dead, and I've found a Windows-only validation [tool](http://web.archive.org/web/20081101142036/http://bolek.techno.cz:80/UTF8-Validator/) that reports invalid UTF-8 files but doesn't report which lines/characters to fix.
I'd be happy with either a tool I can drop in and use (ideally cross-platform), or a ruby/perl script I can make part of my data loading process. | You can use GNU iconv:
```
$ iconv -f UTF-8 your_file -o /dev/null; echo $?
```
Or with older versions of iconv, such as on macOS:
```
$ iconv -f UTF-8 your_file > /dev/null; echo $?
```
The command will return 0 if the file could be converted successfully, and 1 if not. Additionally, it will print out the byte offset where the invalid byte sequence occurred.
**Edit**: The output encoding doesn't have to be specified, it will be assumed to be UTF-8. |
115,249 | <p>I am trying to have a logout page where is displays a messages and then redirects to the login page. This is in ASP.net 2.0.</p>
<p>I have this in my <code>Page_Load</code>:</p>
<pre><code>ClientScript.RegisterStartupScript(typeof(Page), "pageredirect", JavascriptRedirect() );
</code></pre>
<p>This is my redirect function:</p>
<pre><code>private string JavascriptRedirect()
{
StringBuilder sb = new StringBuilder();
sb.Append("<script type=\"text/javascript\" language=\"javascript\">");
sb.Append("var x = 5;");
sb.Append("var y = 1;");
sb.Append("function startClock(){");
sb.Append("x = x-y;");
sb.Append("t=setTimeout(\"startClock()\", 1000);");
sb.Append("if(x==0){");
sb.Append("window.location='login.aspx';");
sb.Append("clearTimeout(t);");
sb.Append(" }");
sb.Append(" }");
sb.Append("startClock();");
sb.Append("</script>");
return sb.ToString();
}
</code></pre>
<p>When I test there is no javascript in my resulting logout page. Anyone have an idea on what is happening. Is <code>Page_Load</code> to late to register this?</p>
| [
{
"answer_id": 115279,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of typeof(Page), try typeof(YOURPAGECLASS) -- with YOURPAGECLASS set the name of your page's classname. Page_Load is definitely not too late.</p>\n"
},
{
"answer_id": 115286,
"author": "Johannes Hädrich",
"author_id": 18246,
"author_profile": "https://Stackoverflow.com/users/18246",
"pm_score": 2,
"selected": true,
"text": "<p>By the way: You don't need Javascript to redirect the browser to a page after a certain amount of time. Just use a plain HTML meta Tag in your <code><HEAD></code> section.</p>\n\n<pre><code><meta http-equiv=\"refresh\" content=\"5; URL=login.aspx\">\n</code></pre>\n\n<p>The number stands for the time in seconds, the URL for the target.</p>\n"
},
{
"answer_id": 115359,
"author": "kristian",
"author_id": 20377,
"author_profile": "https://Stackoverflow.com/users/20377",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps there is something unusual going on in your execution pipeline? </p>\n\n<p>When I create a new .aspx and paste in the code you're providing in your question, it works as you expect it to (i.e. Javascript is rendered to the client).</p>\n"
},
{
"answer_id": 115373,
"author": "brock.holum",
"author_id": 15860,
"author_profile": "https://Stackoverflow.com/users/15860",
"pm_score": 0,
"selected": false,
"text": "<p>I would register it like this:</p>\n\n<pre><code>Page.ClientScript.RegisterStartupScript(this.GetType(), \"Redirect\", \"script here\", true);\n</code></pre>\n\n<p>The last 'true' tells ASP.NET to render the script tags and CDATA so you don't have to write it all out.</p>\n\n<p>You may also want to place your javascript in a separate include file so that you don't have to recompile if/when you tweak it. If you do that, then in your page load you'd have:</p>\n\n<pre><code>Page.ClientScript.RegisterClientScriptInclude(\"RedirectInclude\", \"scripts/redirect.js\");\nPage.ClientScript.RegisterStartupScript(this.GetType(), \"Redirect\", \"JavascriptRedirect();\", true);\n</code></pre>\n"
},
{
"answer_id": 116117,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 0,
"selected": false,
"text": "<p>I don't undesrtand why it doesn't work, but i can give you a workaround: </p>\n\n<p>declare an asp:literal item in the page. in pageLoad,</p>\n\n<p>yourLiteral.Text = JavascriptRedirecct();</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
]
| I am trying to have a logout page where is displays a messages and then redirects to the login page. This is in ASP.net 2.0.
I have this in my `Page_Load`:
```
ClientScript.RegisterStartupScript(typeof(Page), "pageredirect", JavascriptRedirect() );
```
This is my redirect function:
```
private string JavascriptRedirect()
{
StringBuilder sb = new StringBuilder();
sb.Append("<script type=\"text/javascript\" language=\"javascript\">");
sb.Append("var x = 5;");
sb.Append("var y = 1;");
sb.Append("function startClock(){");
sb.Append("x = x-y;");
sb.Append("t=setTimeout(\"startClock()\", 1000);");
sb.Append("if(x==0){");
sb.Append("window.location='login.aspx';");
sb.Append("clearTimeout(t);");
sb.Append(" }");
sb.Append(" }");
sb.Append("startClock();");
sb.Append("</script>");
return sb.ToString();
}
```
When I test there is no javascript in my resulting logout page. Anyone have an idea on what is happening. Is `Page_Load` to late to register this? | By the way: You don't need Javascript to redirect the browser to a page after a certain amount of time. Just use a plain HTML meta Tag in your `<HEAD>` section.
```
<meta http-equiv="refresh" content="5; URL=login.aspx">
```
The number stands for the time in seconds, the URL for the target. |
115,269 | <p>There's something very unsatisfactory about this code:</p>
<pre><code>/*
Given a command string in which the first 8 characters are the command name
padded on the right with whitespace, construct the appropriate kind of
Command object.
*/
public class CommandFactory {
public Command getCommand(String cmd) {
cmdName = cmd.subString(0,8).trim();
if(cmdName.equals("START")) {
return new StartCommand(cmd);
}
if(cmdName.equals("END")) {
return new EndCommand(cmd);
}
// ... more commands in more if blocks here
// else it's a bad command.
return new InvalidCommand(cmd);
}
}
</code></pre>
<p>I'm unrepentant about the multiple exit points - the structure is clear. But I'm not happy about the series of near-identical if statements. I've considered making a Map of Strings to Commands:</p>
<pre><code>commandMap = new HashMap();
commandMap.put("START",StartCommand.class);
// ... etc.
</code></pre>
<p>... then using Reflection to make instances of the appropriate class looked up from the Map. However while conceptually elegant, this involves a fair amount of Reflection code that whoever inherits this code might not appreciate - although that cost might be offset by the benefits. All the lines hardcoding values into the commandMap smell almost as bad as the if block.</p>
<p>Even better would be if the factory's constructor could scan the classpath for subclasses of Command, query them for String representations, and automatically add them them to its repertoire.</p>
<p>So - how should I go about refactoring this?</p>
<p>I guess some of the frameworks out there give me this kind of thing for free. Let's assume I'm not in a position to migrate this stuff into such a framework.</p>
| [
{
"answer_id": 115289,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": -1,
"selected": false,
"text": "<p>At the very least, your command should have a getCommandString() -- where StartCommand overrides to return \"START\". Then you can just register or discover the classes.</p>\n"
},
{
"answer_id": 115292,
"author": "Gareth D",
"author_id": 3580,
"author_profile": "https://Stackoverflow.com/users/3580",
"pm_score": 1,
"selected": false,
"text": "<p>Taking a Convetion vs Configuration approach and using reflection to scan for available Command objects and loading them into your map would be the way to go. You then have the ability to expose new Commands without a recompile of the factory.</p>\n"
},
{
"answer_id": 115297,
"author": "Einar",
"author_id": 2964,
"author_profile": "https://Stackoverflow.com/users/2964",
"pm_score": 2,
"selected": false,
"text": "<p>Its not directly an answer to your question, but why don't you throw an InvalidCommandException (or something similar), rather then returning an object of type InvalidCommand?</p>\n"
},
{
"answer_id": 115313,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 5,
"selected": true,
"text": "<p>Your map of strings to commands I think is good. You could even factor out the string command name to the constructor (i.e. shouldn't StartCommand know that its command is \"START\"?) If you could do this, instantiation of your command objects is much simpler:</p>\n\n<pre><code>Class c = commandMap.get(cmdName);\nif (c != null)\n return c.newInstance();\nelse\n throw new IllegalArgumentException(cmdName + \" is not as valid command\");\n</code></pre>\n\n<p>Another option is to create an <code>enum</code> of all your commands with links to the classes (assume all your command objects implement <code>CommandInterface</code>):</p>\n\n<pre><code>public enum Command\n{\n START(StartCommand.class),\n END(EndCommand.class);\n\n private Class<? extends CommandInterface> mappedClass;\n private Command(Class<? extends CommandInterface> c) { mappedClass = c; }\n public CommandInterface getInstance()\n {\n return mappedClass.newInstance();\n }\n}\n</code></pre>\n\n<p>since the toString of an enum is its name, you can use <code>EnumSet</code> to locate the right object and get the class from within.</p>\n"
},
{
"answer_id": 115317,
"author": "John Flinchbaugh",
"author_id": 12591,
"author_profile": "https://Stackoverflow.com/users/12591",
"pm_score": 0,
"selected": false,
"text": "<p>Having this repetitive object creation code all hidden in the factory is not so bad. If it has to be done somewhere, at least it's all here, so I'd not worry about it too much.</p>\n\n<p>If you <em>really</em> want to do something about it, maybe go for the Map, but configure it from a properties file, and build the map from that props file.</p>\n\n<p>Without going the classpath discovery route (about which I don't know), you'll always be modifying 2 places: writing a class, and then adding a mapping somewhere (factory, map init, or properties file).</p>\n"
},
{
"answer_id": 115325,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 2,
"selected": false,
"text": "<p>With the exception of the </p>\n\n<pre><code>cmd.subString(0,8).trim();\n</code></pre>\n\n<p>part, this doesn't look too bad to me. You could go with the Map and use reflection, but, depending on how often you add/change commands, this might not buy you much.</p>\n\n<p>You should probably document why you only want the first 8 characters, or maybe change the protocol so it's easier to figure out which part of that string is the command (e.g. put a marker like ':' or ';' after the command key-word).</p>\n"
},
{
"answer_id": 115329,
"author": "Auron",
"author_id": 1679,
"author_profile": "https://Stackoverflow.com/users/1679",
"pm_score": 2,
"selected": false,
"text": "<p>I like your idea, but if you want to avoid reflection you could add instead instances to the HashMap:</p>\n\n<pre><code>commandMap = new HashMap();\ncommandMap.put(\"START\",new StartCommand());\n</code></pre>\n\n<p>Whenever you need a command, you just clone it:</p>\n\n<pre><code>command = ((Command) commandMap.get(cmdName)).clone();\n</code></pre>\n\n<p>And afterwards, you set the command string:</p>\n\n<pre><code>command.setCommandString(cmdName);\n</code></pre>\n\n<p>But using clone() doesn't sound as elegant as using reflection :(</p>\n"
},
{
"answer_id": 115331,
"author": "Tetha",
"author_id": 17663,
"author_profile": "https://Stackoverflow.com/users/17663",
"pm_score": 0,
"selected": false,
"text": "<p>Thinking about this, You could create little instantiation classes, like: </p>\n\n<pre><code>class CreateStartCommands implements CommandCreator {\n public bool is_fitting_commandstring(String identifier) {\n return identifier == \"START\"\n }\n public Startcommand create_instance(cmd) {\n return StartCommand(cmd);\n }\n}\n</code></pre>\n\n<p>Of course, this adds a whole bunch if tiny classes that can't do much more than say \"yes, thats start, give me that\" or \"nope, don't like that\", however, you can now rework the factory to contain a list of those CommandCreators and just ask each of it: \"you like this command?\" and return the result of create_instance of the first accepting CommandCreator. Of course it now looks kind of akward to extract the first 8 characters outside of the CommandCreator, so I would rework that so you pass the entire command string into the CommandCreator.</p>\n\n<p>I think I applied some \"Replace switch with polymorphism\"-Refactoring here, in case anyone wonders about that. </p>\n"
},
{
"answer_id": 115332,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 0,
"selected": false,
"text": "<p>I'd go for the map and creation via reflection. If scanning the class path is too slow, you can always add a custom annotation to the class, have an annotation processor running at compile time and store all class names in the jar metadata.</p>\n\n<p>Then, the only mistake you can do is forgetting the annotation.</p>\n\n<p>I did something like this a while ago, using maven and <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/apt/index.html\" rel=\"nofollow noreferrer\">APT</a>.</p>\n"
},
{
"answer_id": 115339,
"author": "Mike Deck",
"author_id": 1247,
"author_profile": "https://Stackoverflow.com/users/1247",
"pm_score": 2,
"selected": false,
"text": "<p>Unless there is a reason they can't be I always try to make my command implementations stateless. If that's the case you can add a method boolean identifier(String id) method to your command interface which would tell whether this instance could be used for the given string identifier. Then your factory could look something like this (note: I did not compile or test this):</p>\n\n<pre><code>public class CommandFactory {\n private static List<Command> commands = new ArrayList<Command>(); \n\n public static void registerCommand(Command cmd) {\n commands.add(cmd);\n }\n\n public Command getCommand(String cmd) {\n for(Command instance : commands) {\n if(instance.identifier(cmd)) {\n return cmd;\n }\n }\n throw new CommandNotRegisteredException(cmd);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 115347,
"author": "John Flinchbaugh",
"author_id": 12591,
"author_profile": "https://Stackoverflow.com/users/12591",
"pm_score": 1,
"selected": false,
"text": "<p>Another approach to dynamically finding the class to load, would be to omit the explicit map, and just try to build the class name from the command string. A title case and concatenate algorithm could turn \"START\" -> \"com.mypackage.commands.StartCommand\", and just use reflection to try to instantiate it. Fail somehow (InvalidCommand instance or an Exception of your own) if you can't find the class.</p>\n\n<p>Then you add commands just by adding one object and start using it.</p>\n"
},
{
"answer_id": 115628,
"author": "Roel Spilker",
"author_id": 12634,
"author_profile": "https://Stackoverflow.com/users/12634",
"pm_score": 4,
"selected": false,
"text": "<p>How about the following code:</p>\n\n<pre><code>public enum CommandFactory {\n START {\n @Override\n Command create(String cmd) {\n return new StartCommand(cmd);\n }\n },\n END {\n @Override\n Command create(String cmd) {\n return new EndCommand(cmd);\n }\n };\n\n abstract Command create(String cmd);\n\n public static Command getCommand(String cmd) {\n String cmdName = cmd.substring(0, 8).trim();\n\n CommandFactory factory;\n try {\n factory = valueOf(cmdName);\n }\n catch (IllegalArgumentException e) {\n return new InvalidCommand(cmd);\n }\n return factory.create(cmd);\n }\n}\n</code></pre>\n\n<p>The <code>valueOf(String)</code> of the enum is used to find the correct factory method. If the factory doesn't exist it will throw an <code>IllegalArgumentException</code>. We can use this as a signal to create the <code>InvalidCommand</code> object. </p>\n\n<p>An extra benefit is that if you can make the method <code>create(String cmd)</code> public if you would also make this way of constructing a Command object compile time checked available to the rest of your code. You could then use <code>CommandFactory.START.create(String cmd</code>) to create a Command object.</p>\n\n<p>The last benefit is that you can easily create a list of all available command in your Javadoc documentation.</p>\n"
},
{
"answer_id": 115635,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 1,
"selected": false,
"text": "<p>One option would be for each command type to have its own factory. This gives you two advantages:</p>\n\n<p>1) Your generic factory wouldn't call new. So each command type could in future return an object of a different class according to the arguments following the space padding in the string.</p>\n\n<p>2) In your HashMap scheme, you could avoid reflection by, for each command class, mapping to an object implementing a SpecialisedCommandFactory interface, instead of mapping to the class itself. This object in practice would probably be a singleton, but need not be specified as such. Your generic getCommand then calls the specialised getCommand.</p>\n\n<p>That said, factory proliferation can get out of hand, and the code you have is the simplest thing that does the job. Personally I'd probably leave it as it is: you can compare command lists in source and spec without non-local considerations like what might have previously called CommandFactory.registerCommand, or what classes have been discovered through reflection. It's not confusing. It's very unlikely to be slow for less than a thousand commands. The only problem is that you can't add new command types without modifying the factory. But the modification you'd make is simple and repetitive, and if you forget to make it you get an obvious error for command lines containing the new type, so it's not onerous.</p>\n"
},
{
"answer_id": 115688,
"author": "bpapa",
"author_id": 543,
"author_profile": "https://Stackoverflow.com/users/543",
"pm_score": 0,
"selected": false,
"text": "<p>The way I do it is to not have a generic Factory method. </p>\n\n<p>I like to use Domain Objects as my command objects. Since I use Spring MVC this is a great approach since the <a href=\"http://static.springframework.org/spring/docs/1.1.5/api/org/springframework/validation/DataBinder.html#setAllowedFields(java.lang.String[])\" rel=\"nofollow noreferrer\">DataBinder.setAllowedFields method</a> allows me a great deal of flexibility to use a single domain object for several different forms. </p>\n\n<p>To get a command object, I have a static factory method on the Domain object class. For example, in the member class I'd have methods like - </p>\n\n<pre><code>public static Member getCommandObjectForRegistration();\npublic static Member getCommandObjectForChangePassword();\n</code></pre>\n\n<p>And so on.</p>\n\n<p>I'm not sure that this is a great approach, I never saw it suggested anywhere and kind of just came up with it on my own b/c I like the idea of keeping things like this in one place. If anybody sees any reason to object please let me know in the comments...</p>\n"
},
{
"answer_id": 115708,
"author": "Ioannis",
"author_id": 20428,
"author_profile": "https://Stackoverflow.com/users/20428",
"pm_score": -1,
"selected": false,
"text": "<p>+1 on the reflection suggestion, it will give you a more sane structure in your class.</p>\n\n<p>Actually you could do the following (if you haven't thought about it already)\ncreate methods corresponding to the String you'd be expecting as an argument to your getCommand() factory method, then all you have to do is reflect and invoke() these methods and return the correct object.</p>\n"
},
{
"answer_id": 115737,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 0,
"selected": false,
"text": "<p>I would suggest avoiding reflection if at all possible. It is somewhat evil.</p>\n\n<p>You can make your code more concise by using the ternary operator:</p>\n\n<pre><code> return \n cmdName.equals(\"START\") ? new StartCommand (cmd) :\n cmdName.equals(\"END\" ) ? new EndCommand (cmd) :\n new InvalidCommand(cmd);\n</code></pre>\n\n<p>You could introduce an enum. Making each enum constant a factory is verbose and also has some runtime memory cost. But you can eaily lookup an enum and then use that with == or switch.</p>\n\n<pre><code> import xx.example.Command.*;\n\n Command command = Command.valueOf(commandStr);\n return \n command == START ? new StartCommand (commandLine) :\n command == END ? new EndCommand (commandLine) :\n new InvalidCommand(commandLine);\n</code></pre>\n"
},
{
"answer_id": 118300,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 0,
"selected": false,
"text": "<p>Go with your gut, and reflect. However, in this solution, your Command interface is now assumed to have the setCommandString(String s) method accessible, so that newInstance is easily useable. Also, commandMap is any map with String keys (cmd) to Command class instances that they correspond to.</p>\n\n<pre><code>public class CommandFactory {\n public Command getCommand(String cmd) {\n if(cmd == null) {\n return new InvalidCommand(cmd);\n }\n\n Class commandClass = (Class) commandMap.get(cmd);\n\n if(commandClass == null) {\n return new InvalidCommand(cmd);\n }\n\n try {\n Command newCommand = (Command) commandClass.newInstance();\n newCommand.setCommandString(cmd);\n return newCommand;\n }\n catch(Exception e) {\n return new InvalidCommand(cmd);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3037859,
"author": "StripLight",
"author_id": 177769,
"author_profile": "https://Stackoverflow.com/users/177769",
"pm_score": 0,
"selected": false,
"text": "<p>Hmm, browsing, and only just came across this. Can I still comment?</p>\n\n<p>IMHO there's <strong>nothing</strong> wrong with the original if/else block code. This is simple, and simplicity must always be our first call in design (<a href=\"http://c2.com/cgi/wiki?DoTheSimplestThingThatCouldPossiblyWork\" rel=\"nofollow noreferrer\">http://c2.com/cgi/wiki?DoTheSimplestThingThatCouldPossiblyWork</a>) </p>\n\n<p>This seems esp true as all the solutions offered are much less self documenting than the original code...I mean shouldn't we write our code for reading rather than translation...</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7512/"
]
| There's something very unsatisfactory about this code:
```
/*
Given a command string in which the first 8 characters are the command name
padded on the right with whitespace, construct the appropriate kind of
Command object.
*/
public class CommandFactory {
public Command getCommand(String cmd) {
cmdName = cmd.subString(0,8).trim();
if(cmdName.equals("START")) {
return new StartCommand(cmd);
}
if(cmdName.equals("END")) {
return new EndCommand(cmd);
}
// ... more commands in more if blocks here
// else it's a bad command.
return new InvalidCommand(cmd);
}
}
```
I'm unrepentant about the multiple exit points - the structure is clear. But I'm not happy about the series of near-identical if statements. I've considered making a Map of Strings to Commands:
```
commandMap = new HashMap();
commandMap.put("START",StartCommand.class);
// ... etc.
```
... then using Reflection to make instances of the appropriate class looked up from the Map. However while conceptually elegant, this involves a fair amount of Reflection code that whoever inherits this code might not appreciate - although that cost might be offset by the benefits. All the lines hardcoding values into the commandMap smell almost as bad as the if block.
Even better would be if the factory's constructor could scan the classpath for subclasses of Command, query them for String representations, and automatically add them them to its repertoire.
So - how should I go about refactoring this?
I guess some of the frameworks out there give me this kind of thing for free. Let's assume I'm not in a position to migrate this stuff into such a framework. | Your map of strings to commands I think is good. You could even factor out the string command name to the constructor (i.e. shouldn't StartCommand know that its command is "START"?) If you could do this, instantiation of your command objects is much simpler:
```
Class c = commandMap.get(cmdName);
if (c != null)
return c.newInstance();
else
throw new IllegalArgumentException(cmdName + " is not as valid command");
```
Another option is to create an `enum` of all your commands with links to the classes (assume all your command objects implement `CommandInterface`):
```
public enum Command
{
START(StartCommand.class),
END(EndCommand.class);
private Class<? extends CommandInterface> mappedClass;
private Command(Class<? extends CommandInterface> c) { mappedClass = c; }
public CommandInterface getInstance()
{
return mappedClass.newInstance();
}
}
```
since the toString of an enum is its name, you can use `EnumSet` to locate the right object and get the class from within. |
115,319 | <p>I'm using C# and connecting to a WebService via an auto-generated C# proxy object. The method I'm calling can be long running, and sometimes times out. I get different errors back, sometimes I get a <code>System.Net.WebException</code> or a <code>System.Web.Services.Protocols.SoapException</code>. These exceptions have properties I can interrogate to find the specific type of error from which I can display a human-friendly version of to the user.</p>
<p>But sometimes I just get an <code>InvalidOperationException</code>, and it has the following Message. Is there any way I can interpret what this is without digging through the string for things I recognize, that feels very dirty, and isn't internationalization agnostic, the error message might come back in a different language.</p>
<pre><code>Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.
The request failed with the error message:
--
<html>
<head>
<title>Request timed out.</title>
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Lucida Console";font-size: .9em}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/PerformanceManager' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Request timed out.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
<br><br>
<b> Exception Details: </b>System.Web.HttpException: Request timed out.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[HttpException (0x80004005): Request timed out.]
</pre></code>
</td>
</tr>
</table>
<br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.312; ASP.NET Version:2.0.50727.833
</font>
</body>
</html>
<!--
[HttpException]: Request timed out.
-->
--.
</code></pre>
<p>Edit:
I have a try-catch around the method on the web-server. I have debugged it, and the web-server method returns (after a minute or so) without any exception. I also added an unhandled exception handler in the web service and a breakpoint there wasn't hit. As soon as the web-service returns, I get this error in the client instead of the result I expected.</p>
| [
{
"answer_id": 115337,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "<p>That means that your consumer is expecting XML from the webservice but the webservice, as your error shows, returns HTML because it's failing due to a timeout. </p>\n\n<p>So you need to talk to the remote webservice provider to let them know it's failing and take corrective action. Unless you are the provider of the webservice in which case you should catch the exceptions and return XML telling the consumer which error occurred (the 'remote provider' should probably do that as well).</p>\n"
},
{
"answer_id": 116015,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 6,
"selected": false,
"text": "<p>This is happening because there is an unhandled exception in your Web service, and the .NET runtime is spitting out its HTML yellow screen of death server error/exception dump page, instead of XML.</p>\n\n<p>Since the consumer of your Web service was expecting a text/xml header and instead got text/html, it throws that error.</p>\n\n<p>You should address the cause of your timeouts (perhaps a lengthy SQL query?).</p>\n\n<p>Also, checkout <a href=\"http://blog.codinghorror.com/throwing-better-soap-exceptions/\" rel=\"noreferrer\">this blog post</a> on Jeff Atwood's blog that explains implementing a global unhandled exception handler and using SOAP exceptions.</p>\n"
},
{
"answer_id": 116066,
"author": "bastos.sergio",
"author_id": 12772,
"author_profile": "https://Stackoverflow.com/users/12772",
"pm_score": 3,
"selected": false,
"text": "<p>The webserver is returning an http 500 error code. These errors generally happen when an exception in thrown on the webserver and there's no logic to catch it so it spits out an http 500 error. You can usually resolve the problem by placing try-catch blocks in your code.</p>\n"
},
{
"answer_id": 1227974,
"author": "Erup",
"author_id": 148526,
"author_profile": "https://Stackoverflow.com/users/148526",
"pm_score": 2,
"selected": false,
"text": "<p>Is your webservice configured correctly in IIS? The pool its using, the version of ASP.NET (2.0) is set? Can you browse the .asmx?</p>\n\n<p>Talking about exceptions, try to put an try-catch block in the line that access your webservice. Put and catch(System.Web.Services.Protocolos.SoapException).</p>\n\n<p>Also, you can set a Timeout for your webservice object.</p>\n"
},
{
"answer_id": 6207632,
"author": "Mhoque",
"author_id": 557700,
"author_profile": "https://Stackoverflow.com/users/557700",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using .NET version 4.0. the validateRequestion is turned on by default for all the pages. in previous versions 1.1 and 2.0 it was only for aspx page. You can turn the default validation off. In that case you have to do the due diligence and make sure that the data is clean. Use HtmlEncode. Do the following to turn the validation off</p>\n\n<p>In the web.config \nadd the following lines for system.web</p>\n\n<pre><code> <httpRuntime requestValidationMode=\"2.0\" />\n</code></pre>\n\n<p>and </p>\n\n<pre><code> <pages validateRequest=\"false\" />\n</code></pre>\n\n<p>You can read more about this <a href=\"http://www.asp.net/learn/whitepapers/aspnet4/breaking-changes\" rel=\"noreferrer\">http://www.asp.net/learn/whitepapers/aspnet4/breaking-changes</a>\nalso <a href=\"http://msdn.microsoft.com/en-us/library/ff649310.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ff649310.aspx</a></p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 11118400,
"author": "oekstrem",
"author_id": 38737,
"author_profile": "https://Stackoverflow.com/users/38737",
"pm_score": 3,
"selected": false,
"text": "<p>I had this happen as a result of a configuration error in web.config. Checking the connection string etc might be the answer for the time out.</p>\n"
},
{
"answer_id": 30801216,
"author": "asimolmez",
"author_id": 3142513,
"author_profile": "https://Stackoverflow.com/users/3142513",
"pm_score": 2,
"selected": false,
"text": "<p>Delete web.config file and insert again. <a href=\"http://forums.asp.net/post/916808.aspx\" rel=\"nofollow\">http://forums.asp.net/post/916808.aspx</a></p>\n"
},
{
"answer_id": 33893246,
"author": "Zameer Ansari",
"author_id": 2404470,
"author_profile": "https://Stackoverflow.com/users/2404470",
"pm_score": 2,
"selected": false,
"text": "<p>I had got this error after changing the web service return type and <a href=\"https://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapdocumentmethodattribute.oneway(v=vs.110).aspx\" rel=\"nofollow noreferrer\">SoapDocumentMethod</a>.</p>\n\n<p>Initially it was:</p>\n\n<pre><code>[WebMethod]\npublic int Foo()\n{\n return 0;\n}\n</code></pre>\n\n<p>I decided to make it <a href=\"https://stackoverflow.com/questions/1541555/asp-net-fire-and-forget-one-way-web-service\">fire and forget type</a> like this:</p>\n\n<pre><code>[SoapDocumentMethod(OneWay = true)]\n[WebMethod]\npublic void Foo()\n{\n return;\n}\n</code></pre>\n\n<p>In such cases, updating the web reference helped.</p>\n\n<p>To update a web service reference:</p>\n\n<ul>\n<li>Expand solution explorer</li>\n<li>Locate <strong>Web References</strong> - this will be visible only if you have added a web service reference in your project</li>\n<li>Right click and click update web reference</li>\n</ul>\n"
},
{
"answer_id": 51866257,
"author": "Phi",
"author_id": 3200493,
"author_profile": "https://Stackoverflow.com/users/3200493",
"pm_score": 1,
"selected": false,
"text": "<p>The problem I had was related to SOAP version. The <code>asmx</code> service was configured to accept both versions, 1.1 and 1.2, so, I think that when you are consuming the service, the client or the server doesn't know what version resolve.</p>\n\n<p>To fix that, is necessary add:</p>\n\n<pre><code>using (wsWebService yourService = new wsWebService())\n{\n yourService.Url = \"https://myUrlService.com/wsWebService.asmx?op=someOption\";\n yourService.UseDefaultCredentials = true; // this line depends on your authentication type\n yourService.SoapVersion = SoapProtocolVersion.Soap11; // asign the version of SOAP\n var result = yourService.SomeMethod(\"Parameter\");\n}\n</code></pre>\n\n<p>Where <code>wsWebService</code> is the name of the class generated as a reference.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11898/"
]
| I'm using C# and connecting to a WebService via an auto-generated C# proxy object. The method I'm calling can be long running, and sometimes times out. I get different errors back, sometimes I get a `System.Net.WebException` or a `System.Web.Services.Protocols.SoapException`. These exceptions have properties I can interrogate to find the specific type of error from which I can display a human-friendly version of to the user.
But sometimes I just get an `InvalidOperationException`, and it has the following Message. Is there any way I can interpret what this is without digging through the string for things I recognize, that feels very dirty, and isn't internationalization agnostic, the error message might come back in a different language.
```
Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.
The request failed with the error message:
--
<html>
<head>
<title>Request timed out.</title>
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Lucida Console";font-size: .9em}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/PerformanceManager' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Request timed out.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
<br><br>
<b> Exception Details: </b>System.Web.HttpException: Request timed out.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[HttpException (0x80004005): Request timed out.]
</pre></code>
</td>
</tr>
</table>
<br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.312; ASP.NET Version:2.0.50727.833
</font>
</body>
</html>
<!--
[HttpException]: Request timed out.
-->
--.
```
Edit:
I have a try-catch around the method on the web-server. I have debugged it, and the web-server method returns (after a minute or so) without any exception. I also added an unhandled exception handler in the web service and a breakpoint there wasn't hit. As soon as the web-service returns, I get this error in the client instead of the result I expected. | This is happening because there is an unhandled exception in your Web service, and the .NET runtime is spitting out its HTML yellow screen of death server error/exception dump page, instead of XML.
Since the consumer of your Web service was expecting a text/xml header and instead got text/html, it throws that error.
You should address the cause of your timeouts (perhaps a lengthy SQL query?).
Also, checkout [this blog post](http://blog.codinghorror.com/throwing-better-soap-exceptions/) on Jeff Atwood's blog that explains implementing a global unhandled exception handler and using SOAP exceptions. |
115,328 | <p>I have the following class</p>
<pre>
public class Car
{
public Name {get; set;}
}
</pre>
<p>and I want to bind this programmatically to a text box.</p>
<p>How do I do that?</p>
<p>Shooting in the dark:</p>
<pre>
...
Car car = new Car();
TextEdit editBox = new TextEdit();
editBox.DataBinding.Add("Name", car, "Car - Name");
...
</pre>
<p>I get the following error</p>
<blockquote>
<p>"Cannot bind to the propery 'Name' on the target control.</p>
</blockquote>
<p>What am I doing wrong and how should I be doing this? I am finding the databinding concept a bit difficult to grasp coming from web-development.</p>
| [
{
"answer_id": 115346,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 4,
"selected": false,
"text": "<p>Without looking at the syntax, I'm pretty sure it's:</p>\n\n<pre><code>editBox.DataBinding.Add(\"Text\", car, \"Name\");\n</code></pre>\n"
},
{
"answer_id": 115348,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You're trying to bind to the \"Name\" of the TextEdit control. The name is used for accessing the control programmatically, and cannot be bound against. You should be binding against the Text of the control. </p>\n"
},
{
"answer_id": 115351,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 7,
"selected": true,
"text": "<p>You want</p>\n\n<pre><code>editBox.DataBindings.Add(\"Text\", car, \"Name\");\n</code></pre>\n\n<p>The first parameter is the name of the property on the control that you want to be databound, the second is the data source, the third parameter is the property on the data source that you want to bind to.</p>\n"
},
{
"answer_id": 115354,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>editBox.DataBinding.Add( \"Text\", car\", \"Name\" );\n</code></pre>\n"
},
{
"answer_id": 115360,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 2,
"selected": false,
"text": "<p>I believe that</p>\n<p><code>editBox.DataBindings.Add(new Binding("Text", car, "Name"));</code></p>\n<p>should do the trick. Didn't try it out, but I think that's the idea.</p>\n"
},
{
"answer_id": 115365,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 3,
"selected": false,
"text": "<pre><code>editBox.DataBinding.Add(\"Text\", car, \"Name\");\n</code></pre>\n\n<p>First arg is the name of the control property, the second is the object to bind, and the last, the name of the object property you want to use as the data source.</p>\n"
},
{
"answer_id": 115441,
"author": "John Hunter",
"author_id": 2253,
"author_profile": "https://Stackoverflow.com/users/2253",
"pm_score": 3,
"selected": false,
"text": "<p>You are quite close the data bindings line would be</p>\n\n<pre><code>editBox.DataBinding.Add(\"Text\", car, \"Name\");\n</code></pre>\n\n<p>This first parameter is the property of your editbox object that will be data bound. The second parameter is the data source you are binding to and the last parameter is the property on the data source that you want to bind to.</p>\n\n<p>Bear in mind that the data binding is one way so if you change the edit box then the car object gets updated but if you change the car name directly the edit box is not updated.</p>\n"
},
{
"answer_id": 39832923,
"author": "tofo",
"author_id": 2987439,
"author_profile": "https://Stackoverflow.com/users/2987439",
"pm_score": 0,
"selected": false,
"text": "<p>The following is generic class that can be used as a property and implements INotifyPropertyChanged used by bound controls to capture changes in the property value. </p>\n\n<pre><code>public class NotifyValue<datatype> : INotifyPropertyChanged \n{\n public event PropertyChangedEventHandler PropertyChanged = delegate { };\n\n datatype _value;\n public datatype Value\n {\n get\n {\n return _value;\n }\n set\n {\n _value = value;\n PropertyChanged.Invoke(this, new PropertyChangedEventArgs(\"Value\"));\n }\n }\n\n}\n</code></pre>\n\n<p>It can be declared like this:</p>\n\n<pre><code>public NotifyValue<int> myInteger = new NotifyValue<int>();\n</code></pre>\n\n<p>and assigned to a textbox like this</p>\n\n<pre><code>Textbox1.DataBindings.Add(\n \"Text\", \n this, \n \"myInteger.Value\", \n false, \n DataSourceUpdateMode.OnPropertyChanged\n);\n</code></pre>\n\n<p>..where \"Text\" is the property of the textbox, 'this' is current Form instance.</p>\n\n<p>A class does not have to inherit the INotifyPropertyChanged class. Once you declare an event of type System.ComponentModel.PropertyChangedEventHandler the class change event will be subscribed to by the controls databinder</p>\n"
},
{
"answer_id": 44983067,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 2,
"selected": false,
"text": "<p>Using C# 4.6 syntax:</p>\n\n<pre><code>editBox.DataBinding.Add(nameof(editBox.Text), car, nameof(car.Name));\n</code></pre>\n\n<p>if car is null, then the above code will fail in a more conspicuous way than using literal string to represent the <code>datamember</code> of <code>car</code></p>\n"
},
{
"answer_id": 46167248,
"author": "Ramgy Borja",
"author_id": 7978302,
"author_profile": "https://Stackoverflow.com/users/7978302",
"pm_score": 0,
"selected": false,
"text": "<p>it's </p>\n\n<pre><code> this.editBox.DataBindings.Add(new Binding(\"Text\", car, \"Name\"));\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
]
| I have the following class
```
public class Car
{
public Name {get; set;}
}
```
and I want to bind this programmatically to a text box.
How do I do that?
Shooting in the dark:
```
...
Car car = new Car();
TextEdit editBox = new TextEdit();
editBox.DataBinding.Add("Name", car, "Car - Name");
...
```
I get the following error
>
> "Cannot bind to the propery 'Name' on the target control.
>
>
>
What am I doing wrong and how should I be doing this? I am finding the databinding concept a bit difficult to grasp coming from web-development. | You want
```
editBox.DataBindings.Add("Text", car, "Name");
```
The first parameter is the name of the property on the control that you want to be databound, the second is the data source, the third parameter is the property on the data source that you want to bind to. |
115,399 | <p>My credit card processor requires I send a two-digit year from the credit card expiration date. Here is how I am currently processing:</p>
<ol>
<li>I put a <code>DropDownList</code> of the 4-digit year on the page.</li>
<li>I validate the expiration date in a <code>DateTime</code> field to be sure that the expiration date being passed to the CC processor isn't expired.</li>
<li>I send a two-digit year to the CC processor (as required). I do this via a substring of the value from the year DDL.</li>
</ol>
<p>Is there a method out there to convert a four-digit year to a two-digit year. I am not seeing anything on the <code>DateTime</code> object. Or should I just keep processing it as I am?</p>
| [
{
"answer_id": 115419,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 1,
"selected": false,
"text": "<p>At this point, the simplest way is to just truncate the last two digits of the year. For credit cards, having a date in the past is unnecessary so Y2K has no meaning. The same applies for if somehow your code is still running in 90+ years.</p>\n\n<p>I'd go further and say that instead of using a drop down list, let the user type in the year themselves. This is a common way of doing it and most users can handle it.</p>\n"
},
{
"answer_id": 115424,
"author": "Andrew Jahn",
"author_id": 5831,
"author_profile": "https://Stackoverflow.com/users/5831",
"pm_score": 0,
"selected": false,
"text": "<p>Why not have the original drop down on the page be a 2 digit value only? Credit cards only cover a small span when looking at the year especially if the CC vendor only takes in 2 digits already.</p>\n"
},
{
"answer_id": 115427,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": -1,
"selected": false,
"text": "<p>Even if a builtin way existed, it wouldn't validate it as greater than today and it would differ very little from a substring call. I wouldn't worry about it.</p>\n"
},
{
"answer_id": 115432,
"author": "ckramer",
"author_id": 20504,
"author_profile": "https://Stackoverflow.com/users/20504",
"pm_score": 2,
"selected": false,
"text": "<p>Use the DateTime object ToString with a custom format string like myDate.ToString(\"MM/dd/yy\") for example.</p>\n"
},
{
"answer_id": 115440,
"author": "brock.holum",
"author_id": 15860,
"author_profile": "https://Stackoverflow.com/users/15860",
"pm_score": 8,
"selected": true,
"text": "<p>If you're creating a DateTime object using the expiration dates (month/year), you can use ToString() on your DateTime variable like so:</p>\n\n<pre><code>DateTime expirationDate = new DateTime(2008, 1, 31); // random date\nstring lastTwoDigitsOfYear = expirationDate.ToString(\"yy\");\n</code></pre>\n\n<p>Edit: Be careful with your dates though if you use the DateTime object during validation. If somebody selects 05/2008 as their card's expiration date, it expires at the end of May, not on the first.</p>\n"
},
{
"answer_id": 115448,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 1,
"selected": false,
"text": "<p>I've seen some systems decide that the cutoff is 75; 75+ is 19xx and below is 20xx.</p>\n"
},
{
"answer_id": 115480,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 3,
"selected": false,
"text": "<p>This should work for you:</p>\n\n<pre><code>public int Get4LetterYear(int twoLetterYear)\n{\n int firstTwoDigits =\n Convert.ToInt32(DateTime.Now.Year.ToString().Substring(2, 2));\n return Get4LetterYear(twoLetterYear, firstTwoDigits);\n}\n\npublic int Get4LetterYear(int twoLetterYear, int firstTwoDigits)\n{\n return Convert.ToInt32(firstTwoDigits.ToString() + twoLetterYear.ToString());\n}\n\npublic int Get2LetterYear(int fourLetterYear)\n{\n return Convert.ToInt32(fourLetterYear.ToString().Substring(2, 2));\n}\n</code></pre>\n\n<p>I don't think there are any special built-in stuff in .NET.</p>\n\n<p><strong>Update</strong>: It's missing some validation that you maybe should do. Validate length of inputted variables, and so on.</p>\n"
},
{
"answer_id": 115494,
"author": "Harv",
"author_id": 10004,
"author_profile": "https://Stackoverflow.com/users/10004",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a link to a 4Guys article on how you can format Dates and Times using the ToString() method by passing in a custom format string.</p>\n\n<p><a href=\"http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=181\" rel=\"nofollow noreferrer\">http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=181</a></p>\n\n<p>Just in case it goes away here is one of the examples.</p>\n\n<pre><code>'Create a var. named rightNow and set it to the current date/time\nDim rightNow as DateTime = DateTime.Now\nDim s as String 'create a string\n\ns = rightNow.ToString(\"MMM dd, yyyy\")\n</code></pre>\n\n<p>Since his link is broken here is a link to the DateTimeFormatInfo class that makes those formatting options possible.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx</a></p>\n\n<p>It's probably a little more consistent to do something like that rather than use a substring, but who knows.</p>\n"
},
{
"answer_id": 5685703,
"author": "V.K.D Baghel",
"author_id": 711026,
"author_profile": "https://Stackoverflow.com/users/711026",
"pm_score": 2,
"selected": false,
"text": "<pre><code>//using java script\nvar curDate = new Date();\nvar curYear = curDate.getFullYear();\ncurYear = curYear.toString().slice(2);\ndocument.write(curYear)\n//using java script\n//using sqlserver\nselect Right(Year(getDate()),2)\n//using sql server\n//Using c#.net \nDateTime dt = DateTime.Now;\n string curYear = dt.Year.ToString().Substring(2,2).ToString() ;\n//using c#.net\n</code></pre>\n"
},
{
"answer_id": 6235347,
"author": "Phiplex",
"author_id": 783708,
"author_profile": "https://Stackoverflow.com/users/783708",
"pm_score": 1,
"selected": false,
"text": "<pre><code>DateTime.Now.Year - (DateTime.Now.Year / 100 * 100)\n</code></pre>\n\n<p>Works for current year. Change <code>DateTime.Now.Year</code> to make it work also for another year. </p>\n"
},
{
"answer_id": 23782904,
"author": "Chris W",
"author_id": 890258,
"author_profile": "https://Stackoverflow.com/users/890258",
"pm_score": 6,
"selected": false,
"text": "<p><strong>1st solution</strong> (fastest) :</p>\n\n<pre><code>yourDateTime.Year % 100\n</code></pre>\n\n<p><strong>2nd solution</strong> (more elegant in my opinion) :</p>\n\n<pre><code>yourDateTime.ToString(\"yy\")\n</code></pre>\n"
},
{
"answer_id": 30935175,
"author": "Christian Phillips",
"author_id": 1449181,
"author_profile": "https://Stackoverflow.com/users/1449181",
"pm_score": 0,
"selected": false,
"text": "<p>This is an old post, but I thought I'd give an example using an <code>ExtensionMethod</code> (since C# 3.0), since this will hide the implementation and allow for use everywhere in the project instead or recreating the code over and over or needing to be aware of some utility class.</p>\n\n<blockquote>\n <p>Extension methods enable you to \"add\" methods to existing types\n without creating a new derived type, recompiling, or otherwise\n modifying the original type. Extension methods are a special kind of\n static method, but they are called as if they were instance methods on\n the extended type. For client code written in C# and Visual Basic,\n there is no apparent difference between calling an extension method\n and the methods that are actually defined in a type.</p>\n</blockquote>\n\n<pre><code>public static class DateTimeExtensions\n {\n public static int ToYearLastTwoDigit(this DateTime date)\n {\n var temp = date.ToString(\"yy\");\n return int.Parse(temp);\n }\n }\n</code></pre>\n\n<p>You can then call this method anywhere you use a <code>DateTime</code> object, for example...</p>\n\n<pre><code>var dateTime = new DateTime(2015, 06, 19);\nvar year = cob.ToYearLastTwoDigit();\n</code></pre>\n"
},
{
"answer_id": 40234891,
"author": "Iliass Nassibane",
"author_id": 5847256,
"author_profile": "https://Stackoverflow.com/users/5847256",
"pm_score": 1,
"selected": false,
"text": "<p>The answer is quite simple:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime Today = DateTime.Today;\nstring zeroBased = Today.ToString(\"yy-MM-dd\");\n</code></pre>\n"
},
{
"answer_id": 44357335,
"author": "Sadid Khan",
"author_id": 1999720,
"author_profile": "https://Stackoverflow.com/users/1999720",
"pm_score": 4,
"selected": false,
"text": "<p>The answer is already given. But here I want to add something.\nSome person told that it did not work. </p>\n\n<p>May be you are using </p>\n\n<blockquote>\n <p><code>DateTime.Now.Year.ToString(\"yy\");</code></p>\n</blockquote>\n\n<p>that is why it is not working. I also made the same the mistake.</p>\n\n<p>Change it to </p>\n\n<blockquote>\n <p><code>DateTime.Now.ToString(\"yy\");</code></p>\n</blockquote>\n"
},
{
"answer_id": 53219298,
"author": "John",
"author_id": 7297374,
"author_profile": "https://Stackoverflow.com/users/7297374",
"pm_score": 0,
"selected": false,
"text": "<p>This seems to work okay for me.\n<code>yourDateTime.ToString().Substring(2);</code></p>\n"
},
{
"answer_id": 67874599,
"author": "JakeMc",
"author_id": 2859272,
"author_profile": "https://Stackoverflow.com/users/2859272",
"pm_score": 2,
"selected": false,
"text": "<p>Starting with c# 6.0 you can use the built-in composite formatting in <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\">string interpolation</a> on anything that processes c#, like an MVC Razor page.</p>\n<pre><code>DateTime date = DateTime.Now;\n\nstring myTwoDigitYear = $"{date:yy};\n</code></pre>\n<p>No extensions necessary. You can use most of the <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings\" rel=\"nofollow noreferrer\">standard date and time format strings</a> after the colon after any valid DateTime object inside the curly brackets to use the built-in <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting\" rel=\"nofollow noreferrer\">composite formatting</a>.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535/"
]
| My credit card processor requires I send a two-digit year from the credit card expiration date. Here is how I am currently processing:
1. I put a `DropDownList` of the 4-digit year on the page.
2. I validate the expiration date in a `DateTime` field to be sure that the expiration date being passed to the CC processor isn't expired.
3. I send a two-digit year to the CC processor (as required). I do this via a substring of the value from the year DDL.
Is there a method out there to convert a four-digit year to a two-digit year. I am not seeing anything on the `DateTime` object. Or should I just keep processing it as I am? | If you're creating a DateTime object using the expiration dates (month/year), you can use ToString() on your DateTime variable like so:
```
DateTime expirationDate = new DateTime(2008, 1, 31); // random date
string lastTwoDigitsOfYear = expirationDate.ToString("yy");
```
Edit: Be careful with your dates though if you use the DateTime object during validation. If somebody selects 05/2008 as their card's expiration date, it expires at the end of May, not on the first. |
115,425 | <p>Aside from trying</p>
<pre><code>perldoc <module name>
</code></pre>
<p>individually for any CPAN module that takes my fancy or going through the file system and looking at the directories I have no idea what modules we have installed. </p>
<p>What's the easiest way to just get a big list of every CPAN module installed? From the command line or otherwise.</p>
| [
{
"answer_id": 115439,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 5,
"selected": false,
"text": "<pre><code>perldoc perllocal\n</code></pre>\n\n<p>Edit: There's a (little) more info about it in the <a href=\"http://www.cpan.org/misc/cpan-faq.html#How_installed_modules\" rel=\"noreferrer\">CPAN FAQ</a></p>\n"
},
{
"answer_id": 115564,
"author": "amoore",
"author_id": 7573,
"author_profile": "https://Stackoverflow.com/users/7573",
"pm_score": 3,
"selected": false,
"text": "<p>I like to use the CPAN 'r' command for this. You can get into the CPAN shell with the old style:</p>\n\n<pre><code>sudo perl -MCPAN -e shell\n</code></pre>\n\n<p>or, on most newer systems, there is a 'cpan' command, so this command will get you to the shell:</p>\n\n<pre><code>sudo cpan\n</code></pre>\n\n<p>(You typically have to use 'sudo' to run it as root, or use 'su -' to become root before you run it, unless you have cpan set up to let you run it as a normal user, but install as root. If you don't have root on this machine, you can still use the CPAN shell to find out this information, but you won't be able to install modules, and you may have to go through a bit of setup the first time you run it.)</p>\n\n<p>Then, once you're in the cpan shell, you can use the 'r' command to report all installed modules and their versions. So, at the \"cpan>\" prompt, type 'r'. This will list all installed modules and their versions. Use '?' to get some more help.</p>\n"
},
{
"answer_id": 115793,
"author": "shelfoo",
"author_id": 3444,
"author_profile": "https://Stackoverflow.com/users/3444",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a really hacky way to do it in *nix, you'll get some stuff you don't really care about (ie: warnings::register etc), but it should give you a list of every .pm file that's accessible via perl.</p>\n\n<pre>\n<code>\nfor my $path (@INC) {\n my @list = `ls -R $path/**/*.pm`;\n for (@list) {\n s/$path\\///g;\n s/\\//::/g;\n s/\\.pm$//g;\n print;\n }\n}\n</code>\n</pre>\n"
},
{
"answer_id": 115897,
"author": "Ovid",
"author_id": 8003,
"author_profile": "https://Stackoverflow.com/users/8003",
"pm_score": 5,
"selected": false,
"text": "<p>It's worth noting that perldoc perllocal will only report on modules installed via CPAN. If someone installs modules manually, it won't find them. Also, if you have multiple people installing modules and the perllocal.pod is under source control, people might resolve conflicts incorrectly and corrupt the list (this has happened here at work, for example).</p>\n\n<p>Regrettably, the solution appears to be walking through @INC with File::Find or something similar. However, that doesn't just find the modules, it also finds related modules in a distribution. For example, it would report TAP::Harness and TAP::Parser in addition to the actual distribution name of Test::Harness (assuming you have version 3 or above). You could potentially match them up with distribution names and discard those names which don't match, but then you might be discarding locally built and installed modules.</p>\n\n<p>I believe brian d foy's backpan indexing work is supposed to have code to hand it at .pm file and it will attempt to infer the distribution, but even this fails at times because what's in a package is not necessarily installed (see Devel::Cover::Inc for an example).</p>\n"
},
{
"answer_id": 117386,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 4,
"selected": false,
"text": "<p>You can try <a href=\"http://search.cpan.org/dist/ExtUtils-Installed\" rel=\"noreferrer\">ExtUtils-Installed</a>, but that only looks in <code>.packlist</code>s, so it may miss modules that people moved things into <code>@INC</code> by hand.</p>\n\n<p>I wrote <a href=\"http://search.cpan.org/dist/App-Module-Lister\" rel=\"noreferrer\">App-Module-Lister</a> for a friend who wanted to do this as a CGI script on a non-shell web hosting account. You simple take the module file and upload it as a filename that your server will treat as a CGI script. It has no dependencies outside of the Standard Library. Use it as is or steal the code.</p>\n\n<p>It outputs a list of the modules and their versions:</p>\n\n<pre>\nTie::Cycle 1.15\nTie::IxHash 1.21\nTie::Toggle 1.07\nTie::ToObject 0.03\nTime::CTime 99.062201\nTime::DaysInMonth 99.1117\nTime::Epoch 0.02\nTime::Fuzzy 0.34\nTime::JulianDay 2003.1125\nTime::ParseDate 2006.0814\nTime::Timezone 2006.0814\n</pre>\n\n<p>I've been meaning to add this as a feature to the <code>cpan</code> tool, so I'll do that too. [Time passes] And, now I have a <code>-l</code> switch in <code>cpan</code>. I have a few other things to do with it before I make a release, but <A href=\"http://github.com/briandfoy/cpan-script/tree/master\" rel=\"noreferrer\">it's in github</a>. If you don't want to wait for that, you could just try the <code>-a</code> switch to create an autobundle, although that puts some Pod around the list.</p>\n\n<p>Good luck;</p>\n"
},
{
"answer_id": 117771,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 1,
"selected": false,
"text": "<p>To walk through the @INC directory trees without using an external program like ls(1), one could use the <code>File::Find::Rule</code> module, which has a nice declarative interface.</p>\n\n<p>Also, you want to filter out duplicates in case previous Perl versions contain the same modules. The code to do this looks like:</p>\n\n<pre><code>#! /usr/bin/perl -l\n\nuse strict;\nuse warnings;\nuse File::Find::Rule;\n\nmy %seen;\nfor my $path (@INC) {\n for my $file (File::Find::Rule->name('*.pm')->in($path)) {\n my $module = substr($file, length($path)+1);\n $module =~ s/.pm$//;\n $module =~ s{[\\\\/]}{::}g;\n print $module unless $seen{$module}++;\n }\n}\n</code></pre>\n\n<p>At the end of the run, you also have all your module names as keys in the %seen hash. The code could be adapted to save the canonical filename (given in $file) as the value of the key instead of a count of times seen.</p>\n"
},
{
"answer_id": 118855,
"author": "pjf",
"author_id": 19422,
"author_profile": "https://Stackoverflow.com/users/19422",
"pm_score": 7,
"selected": true,
"text": "<p>This is answered in the Perl FAQ, the answer which can be quickly found with <code>perldoc -q installed</code>. In short, it comes down to using <code>ExtUtils::Installed</code> or using <code>File::Find</code>, variants of both of which have been covered previously in this thread.</p>\n\n<p>You can also find the FAQ entry <a href=\"http://perldoc.perl.org/perlfaq3.html#How-do-I-find-which-modules-are-installed-on-my-system%3f\" rel=\"noreferrer\">\"How do I find which modules are installed on my system?\"</a> in perlfaq3. You can see a list of all FAQ answers by looking in <a href=\"http://perldoc.perl.org/perlfaq.html\" rel=\"noreferrer\">perlfaq</a></p>\n"
},
{
"answer_id": 931074,
"author": "Sinan Ünür",
"author_id": 100754,
"author_profile": "https://Stackoverflow.com/users/100754",
"pm_score": 2,
"selected": false,
"text": "<p>The answer can be found in the <a href=\"http://perldoc.perl.org/perlfaq3.html#How-do-I-find-which-modules-are-installed-on-my-system%3f\" rel=\"nofollow noreferrer\">Perl FAQ list</a>.</p>\n\n<p>You should skim the excellent documentation that comes with Perl</p>\n\n<pre><code>perldoc perltoc\n</code></pre>\n"
},
{
"answer_id": 931213,
"author": "aks",
"author_id": 2533756,
"author_profile": "https://Stackoverflow.com/users/2533756",
"pm_score": 1,
"selected": false,
"text": "<p>I wrote a perl script just yesterday to do exactly this. The script returns the list of perl modules installed in @INC using the '::' as the separator. Call the script using - </p>\n\n<pre><code>perl perlmod.pl\n</code></pre>\n\n<p>OR </p>\n\n<pre><code>perl perlmod.pl <module name> #Case-insensitive(eg. perl perlmod.pl ftp)\n</code></pre>\n\n<p>As of now the script skips the current directory('.') since I was having problems with recursing soft-links but you can include it by changing the grep function in line 17 from </p>\n\n<pre><code> grep { $_ !~ '^\\.$' } @INC\n</code></pre>\n\n<p>to just,</p>\n\n<pre><code>@INC\n</code></pre>\n\n<p>The script can be found <a href=\"http://pastebin.com/f79372961\" rel=\"nofollow noreferrer\">here.</a></p>\n"
},
{
"answer_id": 934268,
"author": "Walter H",
"author_id": 115384,
"author_profile": "https://Stackoverflow.com/users/115384",
"pm_score": 2,
"selected": false,
"text": "<p>Try <code>man perllocal</code> or <code>perldoc perllocal</code>.</p>\n"
},
{
"answer_id": 1733090,
"author": "toolic",
"author_id": 197758,
"author_profile": "https://Stackoverflow.com/users/197758",
"pm_score": 1,
"selected": false,
"text": "<p>Here is yet another command-line tool to list all installed .pm files:</p>\n\n<p><a href=\"http://www.perlmonks.org/?node_id=795418\" rel=\"nofollow noreferrer\">Find installed Perl modules matching a regular expression</a></p>\n\n<ul>\n<li>Portable (only uses core modules)</li>\n<li>Cache option for faster look-up's</li>\n<li>Configurable display options</li>\n</ul>\n"
},
{
"answer_id": 5577447,
"author": "Joakim",
"author_id": 305996,
"author_profile": "https://Stackoverflow.com/users/305996",
"pm_score": 4,
"selected": false,
"text": "<p>Here a script which would do the trick:</p>\n\n<pre><code>use ExtUtils::Installed;\n\nmy $inst = ExtUtils::Installed->new();\nmy @modules = $inst->modules();\nforeach $module (@modules){\n print $module .\" - \". $inst->version($module). \"\\n\";\n}\n\n=head1 ABOUT\n\nThis scripts lists installed cpan modules using the ExtUtils modules\n\n=head1 FORMAT\n\nPrints each module in the following format\n<name> - <version>\n\n=cut\n</code></pre>\n"
},
{
"answer_id": 6145944,
"author": "knb",
"author_id": 202553,
"author_profile": "https://Stackoverflow.com/users/202553",
"pm_score": 0,
"selected": false,
"text": "<p>the Perl cookbook contains several iterations of a script \"pmdesc\" that does what you want. \nGoogle-search for \"Perl Cookbook pmdesc\" and you'll find <a href=\"http://kb.ucla.edu/articles/how-do-i-find-what-perl-modules-are-installed-on-my-system\" rel=\"nofollow\">articles on other Q&A Sites</a>, several code listings on the net, a discussion of the solution, and even <a href=\"http://www.perlmonks.org/index.pl?node_id=275693\" rel=\"nofollow\">some refinements</a>. </p>\n"
},
{
"answer_id": 7112891,
"author": "thealexbaron",
"author_id": 407164,
"author_profile": "https://Stackoverflow.com/users/407164",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a Perl one-liner that will print out a list of installed modules:</p>\n\n<pre><code>perl -MExtUtils::Installed -MData::Dumper -e 'my ($inst) = ExtUtils::Installed->new(); print Dumper($inst->modules());'\n</code></pre>\n\n<p>Just make sure you have Data::Dumper installed.</p>\n"
},
{
"answer_id": 14598354,
"author": "user2024286",
"author_id": 2024286,
"author_profile": "https://Stackoverflow.com/users/2024286",
"pm_score": 3,
"selected": false,
"text": "<p>Try the following command</p>\n<pre><code>instmodsh\n</code></pre>\n<p>With <code>l</code> you will <em>List all installed modules</em>.</p>\n<p>From <a href=\"https://linux.die.net/man/1/instmodsh\" rel=\"nofollow noreferrer\">man page</a>:</p>\n<blockquote>\n<p>A shell to examine installed modules.<br />\nA little interface to ExtUtils::Installed to examine installed modules, validate your packlists and even create a tarball from an installed module.</p>\n</blockquote>\n"
},
{
"answer_id": 14599339,
"author": "slayedbylucifer",
"author_id": 1251660,
"author_profile": "https://Stackoverflow.com/users/1251660",
"pm_score": 3,
"selected": false,
"text": "<pre><code>perl -MFile::Find=find -MFile::Spec::Functions -Tlwe 'find { wanted => sub { print canonpath $_ if /\\.pm\\z/ }, no_chdir => 1 }, @INC'\n</code></pre>\n"
},
{
"answer_id": 15166368,
"author": "Paul Rubel",
"author_id": 351984,
"author_profile": "https://Stackoverflow.com/users/351984",
"pm_score": 5,
"selected": false,
"text": "<p><code>perldoc -q installed</code></p>\n\n<p>claims that <code>cpan -l</code> will do the trick, however it's not working for me. The other option:</p>\n\n<p><code>cpan -a</code></p>\n\n<p>does spit out a nice list of installed packages and has the nice side effect of writing them to a file.</p>\n"
},
{
"answer_id": 19976944,
"author": "Thiyagu ATR",
"author_id": 1859477,
"author_profile": "https://Stackoverflow.com/users/1859477",
"pm_score": 3,
"selected": false,
"text": "<p>You can get list of perl modules installed in you system by using <code>instmodsh</code> command in your terminal.It will ask you three option in order to enhance the output they are: </p>\n\n<pre><code> l - List all installed modules\n m <module> - Select a module\n q - Quit the program\n</code></pre>\n"
},
{
"answer_id": 21918638,
"author": "mpersico",
"author_id": 1830614,
"author_profile": "https://Stackoverflow.com/users/1830614",
"pm_score": 0,
"selected": false,
"text": "<pre><code>cd /the/lib/dir/of/your/perl/installation\nperldoc $(find . -name perllocal.pod)\n</code></pre>\n\n<p>Windows users just do a Windows Explorer search to find it.</p>\n"
},
{
"answer_id": 30671631,
"author": "Dan",
"author_id": 3884826,
"author_profile": "https://Stackoverflow.com/users/3884826",
"pm_score": 5,
"selected": false,
"text": "<pre><code>$ for M in `perldoc -t perllocal|grep Module |sed -e 's/^.*\" //'`; do V=`perldoc -t perllocal|awk \"/$M/{y=1;next}y\" |grep VERSION |head -n 1`; printf \"%30s %s\\n\" \"$M\" \"$V\"; done |sort\n Class::Inspector * \"VERSION: 1.28\"\n Crypt::CBC * \"VERSION: 2.33\"\n Crypt::Rijndael * \"VERSION: 1.11\"\n Data::Dump * \"VERSION: 1.22\"\n DBD::Oracle * \"VERSION: 1.68\"\n DBI * \"VERSION: 1.630\"\n Digest::SHA * \"VERSION: 5.92\"\n ExtUtils::MakeMaker * \"VERSION: 6.84\"\n install * \"VERSION: 6.84\"\n IO::SessionData * \"VERSION: 1.03\"\n IO::Socket::SSL * \"VERSION: 2.016\"\n JSON * \"VERSION: 2.90\"\n MIME::Base64 * \"VERSION: 3.14\"\n MIME::Base64 * \"VERSION: 3.14\"\n Mozilla::CA * \"VERSION: 20141217\"\n Net::SSLeay * \"VERSION: 1.68\"\n parent * \"VERSION: 0.228\"\n REST::Client * \"VERSION: 271\"\n SOAP::Lite * \"VERSION: 1.08\"\n Task::Weaken * \"VERSION: 1.04\"\n Term::ReadKey * \"VERSION: 2.31\"\n Test::Manifest * \"VERSION: 1.23\"\n Test::Simple * \"VERSION: 1.001002\"\n Text::CSV_XS * \"VERSION: 1.16\"\n Try::Tiny * \"VERSION: 0.22\"\n XML::LibXML * \"VERSION: 2.0108\"\n XML::NamespaceSupport * \"VERSION: 1.11\"\n XML::SAX::Base * \"VERSION: 1.08\"\n</code></pre>\n"
},
{
"answer_id": 44709219,
"author": "caot",
"author_id": 3882744,
"author_profile": "https://Stackoverflow.com/users/3882744",
"pm_score": 1,
"selected": false,
"text": "<p>The following worked for me.</p>\n\n<pre><code>$ perldoc perllocal | grep Module\n$ perldoc perllocal | grep -E 'VERSION|Module'\n</code></pre>\n"
},
{
"answer_id": 45776727,
"author": "Henrik",
"author_id": 5725091,
"author_profile": "https://Stackoverflow.com/users/5725091",
"pm_score": -1,
"selected": false,
"text": "<p>As you enter your Perl script you have all the installed modules as .pm files below the folders in @INC so a small bash script will do the job for you:</p>\n\n<pre><code>#!/bin/bash\n\necho -e -n \"Content-type: text/plain\\n\\n\"\n\ninc=`perl -e '$, = \"\\n\"; print @INC;'`\n\nfor d in $inc\ndo\n find $d -name '*.pm'\ndone\n</code></pre>\n"
},
{
"answer_id": 47173830,
"author": "Yasiru G",
"author_id": 1383889,
"author_profile": "https://Stackoverflow.com/users/1383889",
"pm_score": -1,
"selected": false,
"text": "<p>For Linux the easiest way to get is,</p>\n\n<pre><code>dpkg -l | grep \"perl\"\n</code></pre>\n"
},
{
"answer_id": 52566268,
"author": "Wernfried Domscheit",
"author_id": 3027266,
"author_profile": "https://Stackoverflow.com/users/3027266",
"pm_score": 3,
"selected": false,
"text": "<p>On Linux/Unix I use this simple command:</p>\n\n<pre><code>perl -e 'print qx/find $_ -name \"*.pm\"/ foreach ( @INC );' \n</code></pre>\n\n<p>It scans all folder in <code>@INC</code> and looks for any *.pm file.</p>\n"
},
{
"answer_id": 57885230,
"author": "Haili Sun",
"author_id": 6242896,
"author_profile": "https://Stackoverflow.com/users/6242896",
"pm_score": 0,
"selected": false,
"text": "<p>Try \"perldoc -l\":</p>\n\n<p>$ perldoc -l Log::Dispatch\n/usr/local/share/perl/5.26.1/Log/Dispatch.pm</p>\n"
},
{
"answer_id": 58114369,
"author": "user2967328",
"author_id": 2967328,
"author_profile": "https://Stackoverflow.com/users/2967328",
"pm_score": 2,
"selected": false,
"text": "<p>All those who can't install perldoc, or other modules, and want to know what modules are available (CPAN or otherwise), the following works for linux and Mingw32/64:</p>\n\n<pre><code>grep -RhIP '^package [A-Z][\\w:]+;' `perl -e 'print join \" \",@INC'` | sed 's/package //' | sort | uniq\n</code></pre>\n\n<p>Yes, it's messy. Yes, it probably reports more than you want. But if you pipe it into a file, you can easily check for, say, which dbm interfaces are present:</p>\n\n<pre><code> grep -RhIP '^package [A-Z][\\w:]+;' `perl -e 'print join \" \",@INC'` | sed 's/package //' | sort | uniq > modules-installed\n cat modules-installed | grep -i dbm \n\nAnyDBM_File;\nMemoize::AnyDBM_File;\nMemoize::NDBM_File;\nMemoize::SDBM_File;\nWWW::RobotRules::AnyDBM_File;\n</code></pre>\n\n<p>Which is why I ended up on this page (disappointed)</p>\n\n<p>(I realise this doesn't answer the OP's question exactly, but I'm posting it for anybody who ended up here for the same reason I did. That's the problem with stack*** it's almost imposisble to find the question you're asking, even when it exists, yet stack*** is nearly always google's top hit!)</p>\n"
},
{
"answer_id": 64310781,
"author": "Nicholas Sushkin",
"author_id": 789544,
"author_profile": "https://Stackoverflow.com/users/789544",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a script by @JamesThomasMoon1979 rewritten as a one-liner</p>\n<pre><code>perl -MExtUtils::Installed -e '$i=ExtUtils::Installed->new(); \n print "$_ ".$i->version($_)."\\n" for $i->modules();'\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3404/"
]
| Aside from trying
```
perldoc <module name>
```
individually for any CPAN module that takes my fancy or going through the file system and looking at the directories I have no idea what modules we have installed.
What's the easiest way to just get a big list of every CPAN module installed? From the command line or otherwise. | This is answered in the Perl FAQ, the answer which can be quickly found with `perldoc -q installed`. In short, it comes down to using `ExtUtils::Installed` or using `File::Find`, variants of both of which have been covered previously in this thread.
You can also find the FAQ entry ["How do I find which modules are installed on my system?"](http://perldoc.perl.org/perlfaq3.html#How-do-I-find-which-modules-are-installed-on-my-system%3f) in perlfaq3. You can see a list of all FAQ answers by looking in [perlfaq](http://perldoc.perl.org/perlfaq.html) |
115,426 | <p>I'm looking for an algorithm to detect if two rectangles intersect (one at an arbitrary angle, the other with only vertical/horizontal lines).</p>
<p>Testing if a corner of one is in the other ALMOST works. It fails if the rectangles form a cross-like shape.</p>
<p>It seems like a good idea to avoid using slopes of the lines, which would require special cases for vertical lines.</p>
| [
{
"answer_id": 115476,
"author": "Brendan Cashman",
"author_id": 5814,
"author_profile": "https://Stackoverflow.com/users/5814",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using Java, all implementations of the Shape interface have an <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/Shape.html#intersects(double,%20double,%20double,%20double)\" rel=\"nofollow noreferrer\">intersects</a> method that take a rectangle. </p>\n"
},
{
"answer_id": 115484,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 0,
"selected": false,
"text": "<p>Well, the brute force method is to walk the edges of the horizontal rectangle and check each point along the edge to see if it falls on or in the other rectangle.</p>\n\n<p>The mathematical answer is to form equations describing each edge of both rectangles. Now you can simply find if any of the four lines from rectangle A intersect any of the lines of rectangle B, which should be a simple (fast) linear equation solver.</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 115485,
"author": "Louis Brandy",
"author_id": 2089740,
"author_profile": "https://Stackoverflow.com/users/2089740",
"pm_score": 2,
"selected": false,
"text": "<p>Check to see if any of the lines from one rectangle intersect any of the lines from the other. Naive line segment intersection is easy to code up.</p>\n\n<p>If you need more speed, there are advanced algorithms for line segment intersection (sweep-line). See <a href=\"http://en.wikipedia.org/wiki/Line_segment_intersection\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Line_segment_intersection</a></p>\n"
},
{
"answer_id": 115497,
"author": "HenryR",
"author_id": 2827,
"author_profile": "https://Stackoverflow.com/users/2827",
"pm_score": 0,
"selected": false,
"text": "<p>You could find the intersection of each side of the angled rectangle with each side of the axis-aligned one. Do this by finding the equation of the infinite line on which each side lies (i.e. v1 + t(v2-v1) and v'1 + t'(v'2-v'1) basically), finding the point at which the lines meet by solving for t when those two equations are equal (if they're parallel, you can test for that) and then testing whether that point lies on the line segment between the two vertices, i.e. is it true that 0 <= t <= 1 and 0 <= t' <= 1.</p>\n\n<p>However, this doesn't cover the case when one rectangle completely covers the other. That you can cover by testing whether all four points of either rectangle lie inside the other rectangle. </p>\n"
},
{
"answer_id": 115499,
"author": "m_pGladiator",
"author_id": 446104,
"author_profile": "https://Stackoverflow.com/users/446104",
"pm_score": 4,
"selected": false,
"text": "<p>Basically look at the following picture: </p>\n\n<p><br><a href=\"https://i.stack.imgur.com/q9fHm.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/q9fHm.gif\" alt=\"\"></a></p>\n\n<p>If the two boxes collide, the lines A and B will overlap.</p>\n\n<p>Note that this will have to be done on both the X and the Y axis, and both need to overlap for the rectangles to collide.</p>\n\n<p>There is a good article in <a href=\"http://www.gamasutra.com/features/20000330/bobic_01.htm\" rel=\"nofollow noreferrer\">gamasutra.com</a> which answers the question (the picture is from the article).\nI did similar algorithm 5 years ago and I have to find my code snippet to post it here later</p>\n\n<p><strong>Amendment</strong>: The Separating Axis Theorem states that two convex shapes <strong>do not</strong> overlap if a separating axis exists (i.e. one where the projections as shown <strong>do not</strong> overlap). So \"A separating axis exists\" => \"No overlap\". This is not a bi-implication so you cannot conclude the converse. </p>\n"
},
{
"answer_id": 115505,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I would do, for the <em>3D</em> version of this problem:</p>\n\n<p>Model the 2 rectangles as planes described by equation P1 and P2, then write P1=P2 and derive from that the line of intersection equation, which won't exist if the planes are parallel (no intersection), or are in the same plane, in which case you get 0=0. In that case you will need to employ a 2D rectangle intersection algorithm.</p>\n\n<p>Then I would see if that line, which is in the plane of both rectangles, passes through both rectangles. If it does, then you have an intersection of 2 rectangles, otherwise you don't (or shouldn't, I might have missed a corner case in my head).</p>\n\n<p>To find if a line passes through a rectangle in the same plane, I would find the 2 points of intersection of the line and the sides of the rectangle (modelling them using line equations), and then make sure the points of intersections are with in range.</p>\n\n<p>That is the mathematical descriptions, unfortunately I have no code to do the above.</p>\n"
},
{
"answer_id": 115520,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 8,
"selected": true,
"text": "<p>The standard method would be to do the <strong>separating axis test</strong> (do a google search on that).</p>\n\n<p>In short:</p>\n\n<ul>\n<li>Two objects don't intersect if you can find a line that separates the two objects. e.g. the objects / all points of an object are on different sides of the line.</li>\n</ul>\n\n<p>The fun thing is, that it's sufficient to just check all edges of the two rectangles. If the rectangles don't overlap one of the edges will be the separating axis.</p>\n\n<p>In 2D you can do this without using slopes. An edge is simply defined as the difference between two vertices, e.g.</p>\n\n<pre><code> edge = v(n) - v(n-1)\n</code></pre>\n\n<p>You can get a perpendicular to this by rotating it by 90°. In 2D this is easy as:</p>\n\n<pre><code> rotated.x = -unrotated.y\n rotated.y = unrotated.x\n</code></pre>\n\n<p>So no trigonometry or slopes involved. Normalizing the vector to unit-length is not required either.</p>\n\n<p>If you want to test if a point is on one or another side of the line you can just use the dot-product. the sign will tell you which side you're on:</p>\n\n<pre><code> // rotated: your rotated edge\n // v(n-1) any point from the edge.\n // testpoint: the point you want to find out which side it's on.\n\n side = sign (rotated.x * (testpoint.x - v(n-1).x) + \n rotated.y * (testpoint.y - v(n-1).y);\n</code></pre>\n\n<p>Now test all points of rectangle A against the edges of rectangle B and vice versa. If you find a separating edge the objects don't intersect (providing all other points in B are on the other side of the edge being tested for - see drawing below). If you find no separating edge either the rectangles are intersecting or one rectangle is contained in the other.</p>\n\n<p>The test works with any convex polygons btw.. </p>\n\n<p><strong>Amendment:</strong> To identify a separating edge, it is not enough to test all points of one rectangle against each edge of the other. The candidate-edge E (below) would as such be identified as a separating edge, as all points in A are in the same half-plane of E. However, it isn't a separating edge because the vertices Vb1 and Vb2 of B are also in that half-plane. It would only have been a separating edge if that had not been the case\n<a href=\"http://www.iassess.com/collision.png\">http://www.iassess.com/collision.png</a></p>\n"
},
{
"answer_id": 204447,
"author": "Howard May",
"author_id": 23435,
"author_profile": "https://Stackoverflow.com/users/23435",
"pm_score": 2,
"selected": false,
"text": "<p>One solution is to use something called a No Fit Polygon. This polygon is calculated from the two polygons (conceptually by sliding one around the other) and it defines the area for which the polygons overlap given their relative offset. Once you have this NFP then you simply have to do an inclusion test with a point given by the relative offset of the two polygons. This inclusion test is quick and easy but you do have to create the NFP first.</p>\n\n<p>Have a search for No Fit Polygon on the web and see if you can find an algorithm for convex polygons (it gets MUCH more complex if you have concave polygons). If you can't find anything then email me at howard dot J dot may gmail dot com</p>\n"
},
{
"answer_id": 5443722,
"author": "Mads",
"author_id": 678198,
"author_profile": "https://Stackoverflow.com/users/678198",
"pm_score": 0,
"selected": false,
"text": "<p>Another way to do the test which is slightly faster than using the separating axis test, is to use the winding numbers algorithm (on quadrants only - <em>not</em> angle-summation which is horrifically slow) on each vertex of either rectangle (arbitrarily chosen). If any of the vertices have a non-zero winding number, the two rectangles overlap.</p>\n\n<p>This algorithm is somewhat more long-winded than the separating axis test, but is faster because it only require a half-plane test if edges are crossing two quadrants (as opposed to up to 32 tests using the separating axis method)</p>\n\n<p>The algorithm has the further advantage that it can be used to test overlap of <em>any</em> polygon (convex or concave). As far as I know, the algorithm only works in 2D space.</p>\n"
},
{
"answer_id": 13550752,
"author": "tristan",
"author_id": 1109630,
"author_profile": "https://Stackoverflow.com/users/1109630",
"pm_score": 2,
"selected": false,
"text": "<p>m_pGladiator's answer is right and I prefer to it.\n<strong>Separating axis test</strong> is simplest and standard method to detect rectangle overlap. A line for which the projection intervals do not overlap we call a <strong>separating axis</strong>. Nils Pipenbrinck's solution is too general. It use <strong>dot product</strong> to check whether one shape is totally on the one side of the edge of the other. This solution is actually could induce to n-edge convex polygons. However, it is not optmized for two rectangles.</p>\n\n<p>the critical point of m_pGladiator's answer is that we should check two rectangles' projection on both axises (x and y). If two projections are overlapped, then we could say these two rectangles are overlapped. So the comments above to m_pGladiator's answer are wrong.</p>\n\n<p>for the simple situation, if two rectangles are not rotated,\nwe present a rectangle with structure:</p>\n\n<pre><code>struct Rect {\n x, // the center in x axis\n y, // the center in y axis\n width,\n height\n}\n</code></pre>\n\n<p>we name rectangle A, B with rectA, rectB.</p>\n\n<pre><code> if Math.abs(rectA.x - rectB.x) < (Math.abs(rectA.width + rectB.width) / 2) \n&& (Math.abs(rectA.y - rectB.y) < (Math.abs(rectA.height + rectB.height) / 2))\n then\n // A and B collide\n end if\n</code></pre>\n\n<p>if any one of the two rectangles are rotated, \nIt may needs some efforts to determine the projection of them on x and y axises. Define struct RotatedRect as following:</p>\n\n<pre><code>struct RotatedRect : Rect {\n double angle; // the rotating angle oriented to its center\n}\n</code></pre>\n\n<p>the difference is how the width' is now a little different:\nwidthA' for rectA: <code>Math.sqrt(rectA.width*rectA.width + rectA.height*rectA.height) * Math.cos(rectA.angle)</code>\nwidthB' for rectB: <code>Math.sqrt(rectB.width*rectB.width + rectB.height*rectB.height) * Math.cos(rectB.angle)</code></p>\n\n<pre><code> if Math.abs(rectA.x - rectB.x) < (Math.abs(widthA' + widthB') / 2) \n&& (Math.abs(rectA.y - rectB.y) < (Math.abs(heightA' + heightB') / 2))\n then\n // A and B collide\n end if\n</code></pre>\n\n<p>Could refer to a GDC(Game Development Conference 2007) PPT <a href=\"http://www.realtimecollisiondetection.net/pubs/GDC07_Ericson_Physics_Tutorial_SAT.ppt\" rel=\"nofollow\">www.realtimecollisiondetection.net/pubs/GDC07_Ericson_Physics_Tutorial_SAT.ppt</a></p>\n"
},
{
"answer_id": 13878566,
"author": "Leonardo",
"author_id": 1903977,
"author_profile": "https://Stackoverflow.com/users/1903977",
"pm_score": 2,
"selected": false,
"text": "<p>In Cocoa you could easily detect whether the selectedArea rect intersects your rotated NSView's frame rect.\nYou don't even need to calculate polygons, normals an such. Just add these methods to your NSView subclass.\nFor instance, the user selects an area on the NSView's superview, then you call the method DoesThisRectSelectMe passing the selectedArea rect. The API convertRect: will do that job. The same trick works when you click on the NSView to select it. In that case simply override the hitTest method as below. The API convertPoint: will do that job ;-)</p>\n\n<pre><code>- (BOOL)DoesThisRectSelectMe:(NSRect)selectedArea\n{\n NSRect localArea = [self convertRect:selectedArea fromView:self.superview];\n\n return NSIntersectsRect(localArea, self.bounds);\n}\n\n\n- (NSView *)hitTest:(NSPoint)aPoint\n{\n NSPoint localPoint = [self convertPoint:aPoint fromView:self.superview];\n return NSPointInRect(localPoint, self.bounds) ? self : nil;\n}\n</code></pre>\n"
},
{
"answer_id": 14145813,
"author": "user1517108",
"author_id": 1517108,
"author_profile": "https://Stackoverflow.com/users/1517108",
"pm_score": 0,
"selected": false,
"text": "<p>Either I am missing something else why make this so complicated?</p>\n\n<p>if (x1,y1) and (X1,Y1) are corners of the rectangles, then to find intersection do:</p>\n\n<pre><code> xIntersect = false;\n yIntersect = false;\n if (!(Math.min(x1, x2, x3, x4) > Math.max(X1, X2, X3, X4) || Math.max(x1, x2, x3, x4) < Math.min(X1, X2, X3, X4))) xIntersect = true;\n if (!(Math.min(y1, y2, y3, y4) > Math.max(Y1, Y2, Y3, Y4) || Math.max(y1, y2, y3, y4) < Math.min(Y1, Y2, Y3, Y4))) yIntersect = true;\n if (xIntersect && yIntersect) {alert(\"Intersect\");}\n</code></pre>\n"
},
{
"answer_id": 15444203,
"author": "Robotbugs",
"author_id": 986059,
"author_profile": "https://Stackoverflow.com/users/986059",
"pm_score": 0,
"selected": false,
"text": "<p>I implemented it like this:</p>\n\n<pre><code>bool rectCollision(const CGRect &boundsA, const Matrix3x3 &mB, const CGRect &boundsB)\n{\n float Axmin = boundsA.origin.x;\n float Axmax = Axmin + boundsA.size.width;\n float Aymin = boundsA.origin.y;\n float Aymax = Aymin + boundsA.size.height;\n\n float Bxmin = boundsB.origin.x;\n float Bxmax = Bxmin + boundsB.size.width;\n float Bymin = boundsB.origin.y;\n float Bymax = Bymin + boundsB.size.height;\n\n // find location of B corners in A space\n float B0x = mB(0,0) * Bxmin + mB(0,1) * Bymin + mB(0,2);\n float B0y = mB(1,0) * Bxmin + mB(1,1) * Bymin + mB(1,2);\n\n float B1x = mB(0,0) * Bxmax + mB(0,1) * Bymin + mB(0,2);\n float B1y = mB(1,0) * Bxmax + mB(1,1) * Bymin + mB(1,2);\n\n float B2x = mB(0,0) * Bxmin + mB(0,1) * Bymax + mB(0,2);\n float B2y = mB(1,0) * Bxmin + mB(1,1) * Bymax + mB(1,2);\n\n float B3x = mB(0,0) * Bxmax + mB(0,1) * Bymax + mB(0,2);\n float B3y = mB(1,0) * Bxmax + mB(1,1) * Bymax + mB(1,2);\n\n if(B0x<Axmin && B1x<Axmin && B2x<Axmin && B3x<Axmin)\n return false;\n if(B0x>Axmax && B1x>Axmax && B2x>Axmax && B3x>Axmax)\n return false;\n if(B0y<Aymin && B1y<Aymin && B2y<Aymin && B3y<Aymin)\n return false;\n if(B0y>Aymax && B1y>Aymax && B2y>Aymax && B3y>Aymax)\n return false;\n\n float det = mB(0,0)*mB(1,1) - mB(0,1)*mB(1,0);\n float dx = mB(1,2)*mB(0,1) - mB(0,2)*mB(1,1);\n float dy = mB(0,2)*mB(1,0) - mB(1,2)*mB(0,0);\n\n // find location of A corners in B space\n float A0x = (mB(1,1) * Axmin - mB(0,1) * Aymin + dx)/det;\n float A0y = (-mB(1,0) * Axmin + mB(0,0) * Aymin + dy)/det;\n\n float A1x = (mB(1,1) * Axmax - mB(0,1) * Aymin + dx)/det;\n float A1y = (-mB(1,0) * Axmax + mB(0,0) * Aymin + dy)/det;\n\n float A2x = (mB(1,1) * Axmin - mB(0,1) * Aymax + dx)/det;\n float A2y = (-mB(1,0) * Axmin + mB(0,0) * Aymax + dy)/det;\n\n float A3x = (mB(1,1) * Axmax - mB(0,1) * Aymax + dx)/det;\n float A3y = (-mB(1,0) * Axmax + mB(0,0) * Aymax + dy)/det;\n\n if(A0x<Bxmin && A1x<Bxmin && A2x<Bxmin && A3x<Bxmin)\n return false;\n if(A0x>Bxmax && A1x>Bxmax && A2x>Bxmax && A3x>Bxmax)\n return false;\n if(A0y<Bymin && A1y<Bymin && A2y<Bymin && A3y<Bymin)\n return false;\n if(A0y>Bymax && A1y>Bymax && A2y>Bymax && A3y>Bymax)\n return false;\n\n return true;\n}\n</code></pre>\n\n<p>The matrix mB is any affine transform matrix that converts points in the B space to points in the A space. This includes simple rotation and translation, rotation plus scaling, and full affine warps, but not perspective warps.</p>\n\n<p>It may not be as optimal as possible. Speed was not a huge concern. However it seems to work ok for me.</p>\n"
},
{
"answer_id": 17287663,
"author": "John Smith",
"author_id": 2489753,
"author_profile": "https://Stackoverflow.com/users/2489753",
"pm_score": 1,
"selected": false,
"text": "<p>Here is what I think will take care of all possible cases.\nDo the following tests. </p>\n\n<ol>\n<li>Check any of the vertices of rectangle 1 reside inside rectangle 2 and vice versa. Anytime you find a vertex that resides inside the other rectangle you can conclude that they intersect and stop the search. THis will take care of one rectangle residing completely inside the other.</li>\n<li>If the above test is inconclusive find the intersecting points of each line of 1 rectangle with each line of the other rectangle. Once a point of intersection is found check if it resides between inside the imaginary rectangle created by the corresponding 4 points. When ever such a point is found conclude that they intersect and stop the search.</li>\n</ol>\n\n<p>If the above 2 tests return false then these 2 rectangles do not overlap.</p>\n"
},
{
"answer_id": 44210241,
"author": "Jed",
"author_id": 5535270,
"author_profile": "https://Stackoverflow.com/users/5535270",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a matlab implementation of the accepted answer:</p>\n\n<pre><code>function olap_flag = ol(A,B,sub)\n\n%A and B should be 4 x 2 matrices containing the xy coordinates of the corners in clockwise order\n\nif nargin == 2\n olap_flag = ol(A,B,1) && ol(B,A,1);\n return;\nend\n\nurdl = diff(A([1:4 1],:));\ns = sum(urdl .* A, 2);\nsdiff = B * urdl' - repmat(s,[1 4]);\n\nolap_flag = ~any(max(sdiff)<0);\n</code></pre>\n"
},
{
"answer_id": 44216173,
"author": "Siva Srinivas Kolukula",
"author_id": 2118434,
"author_profile": "https://Stackoverflow.com/users/2118434",
"pm_score": 0,
"selected": false,
"text": "<p>This is the conventional method, go line by line and check whether the lines are intersecting. This is the code in MATLAB. </p>\n\n<pre><code>C1 = [0, 0]; % Centre of rectangle 1 (x,y)\nC2 = [1, 1]; % Centre of rectangle 2 (x,y)\nW1 = 5; W2 = 3; % Widths of rectangles 1 and 2\nH1 = 2; H2 = 3; % Heights of rectangles 1 and 2\n% Define the corner points of the rectangles using the above\nR1 = [C1(1) + [W1; W1; -W1; -W1]/2, C1(2) + [H1; -H1; -H1; H1]/2];\nR2 = [C2(1) + [W2; W2; -W2; -W2]/2, C2(2) + [H2; -H2; -H2; H2]/2];\n\nR1 = [R1 ; R1(1,:)] ;\nR2 = [R2 ; R2(1,:)] ;\n\nplot(R1(:,1),R1(:,2),'r')\nhold on\nplot(R2(:,1),R2(:,2),'b')\n\n\n%% lines of Rectangles \nL1 = [R1(1:end-1,:) R1(2:end,:)] ;\nL2 = [R2(1:end-1,:) R2(2:end,:)] ;\n%% GEt intersection points\nP = zeros(2,[]) ;\ncount = 0 ;\nfor i = 1:4\n line1 = reshape(L1(i,:),2,2) ;\n for j = 1:4\n line2 = reshape(L2(j,:),2,2) ;\n point = InterX(line1,line2) ;\n if ~isempty(point)\n count = count+1 ;\n P(:,count) = point ;\n end\n end\nend\n%%\nif ~isempty(P)\n fprintf('Given rectangles intersect at %d points:\\n',size(P,2))\n plot(P(1,:),P(2,:),'*k')\nend\n</code></pre>\n\n<p>the function InterX can be downloaded from: <a href=\"https://in.mathworks.com/matlabcentral/fileexchange/22441-curve-intersections?focused=5165138&tab=function\" rel=\"nofollow noreferrer\">https://in.mathworks.com/matlabcentral/fileexchange/22441-curve-intersections?focused=5165138&tab=function</a></p>\n"
},
{
"answer_id": 44577435,
"author": "BitFarmer",
"author_id": 3432871,
"author_profile": "https://Stackoverflow.com/users/3432871",
"pm_score": 0,
"selected": false,
"text": "<p>I have a simplier method of my own, if we have 2 rectangles:</p>\n\n<p>R1 = (min_x1, max_x1, min_y1, max_y1)</p>\n\n<p>R2 = (min_x2, max_x2, min_y2, max_y2)</p>\n\n<p>They overlap if and only if:</p>\n\n<p>Overlap = (max_x1 > min_x2) and (max_x2 > min_x1) and (max_y1 > min_y2) and (max_y2 > min_y1)</p>\n\n<p>You can do it for 3D boxes too, actually it works for any number of dimensions.</p>\n"
},
{
"answer_id": 50918572,
"author": "Przemek",
"author_id": 959552,
"author_profile": "https://Stackoverflow.com/users/959552",
"pm_score": 0,
"selected": false,
"text": "<p>Enough has been said in other answers, so I'll just add pseudocode one-liner:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>!(a.left > b.right || b.left > a.right || a.top > b.bottom || b.top > a.bottom);\n</code></pre>\n"
},
{
"answer_id": 64162017,
"author": "Puco4",
"author_id": 12131616,
"author_profile": "https://Stackoverflow.com/users/12131616",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"https://stackoverflow.com/a/115520/12131616\">accepted answer</a> about the <strong>separating axis test</strong> was very illuminating but I still felt it was not trivial to apply. I will share the pseudo-code I thought, "optimizing" first with the <strong>bounding circle test</strong> (see <a href=\"https://stackoverflow.com/a/6016515/12131616\">this other answer</a>), in case it might help other people. I considered two rectangles A and B of the same size (but it is straightforward to consider the general situation).</p>\n<h2>1 Bounding circle test:</h2>\n<p><img src=\"https://i.stack.imgur.com/uDmiTm.png\" alt=\"enter image description here\" /></p>\n<pre class=\"lang-py prettyprint-override\"><code> function isRectangleACollidingWithRectangleB:\n if d > 2 * R:\n return False\n ...\n</code></pre>\n<p>Computationally is much faster than the separating axis test. You only need to consider the separating axis test in the situation that both circles collide.</p>\n<h2>2 Separating axis test</h2>\n<p><img src=\"https://i.stack.imgur.com/jkovqm.png\" alt=\"enter image description here\" /></p>\n<p>The main idea is:</p>\n<ul>\n<li><p>Consider one rectangle. Cycle along its vertices V(i).</p>\n</li>\n<li><p>Calculate the vector Si+1: V(i+1) - V(i).</p>\n</li>\n<li><p>Calculate the vector Ni using Si+1: Ni = (-Si+1.y, Si+1.x). This vector is the blue from the image. The sign of the dot product between the vectors from V(i) to the other vertices and Ni will define the separating axis (magenta dashed line).</p>\n</li>\n<li><p>Calculate the vector Si-1: V(i-1) - V(i). The sign of the dot product between Si-1 and Ni will define the location of the first rectangle with respect to the separating axis. In the example of the picture, they go in different directions, so the sign will be negative.</p>\n</li>\n<li><p>Cycle for all vertices j of the second square and calculate the vector Sij = V(j) - V(i).</p>\n</li>\n<li><p>If for any vertex V(j), the sign of the dot product of the vector Sij with Ni is the same as with the dot product of the vector Si-1 with Ni, this means both vertices V(i) and V(j) are on the same side of the magenta dashed line and, thus, vertex V(i) does not have a separating axis. So we can just skip vertex V(i) and repeat for the next vertex V(i+1). But first we update Si-1 = - Si+1. When we reach the last vertex (i = 4), if we have not found a separating axis, we repeat for the other rectangle. And if we still do not find a separating axis, this implies there is no separating axis and both rectangles collide.</p>\n</li>\n<li><p>If for a given vertex V(i) and all vertices V(j), the sign of the dot product of the vector Sij with Ni is different than with the vector Si-1 with Ni (as occurs in the image), this means we have found the separating axis and the rectangles do not collide.</p>\n</li>\n</ul>\n<p>In pseudo-code:</p>\n<pre class=\"lang-py prettyprint-override\"><code> function isRectangleACollidingWithRectangleB:\n ...\n #Consider first rectangle A:\n Si-1 = Vertex_A[4] - Vertex_A[1]\n for i in Vertex_A:\n Si+1 = Vertex_A[i+1] - Vertex_A[i]\n Ni = [- Si+1.y, Si+1.x ]\n sgn_i = sign( dot_product(Si-1, Ni) ) #sgn_i is the sign of rectangle A with respect the separating axis\n\n for j in Vertex_B:\n sij = Vertex_B[j] - Vertex_A[i]\n sgn_j = sign( dot_product(sij, Ni) ) #sgnj is the sign of vertex j of square B with respect the separating axis\n if sgn_i * sgn_j > 0: #i.e., we have the same sign\n break #Vertex i does not define separating axis\n else:\n if j == 4: #we have reached the last vertex so vertex i defines the separating axis\n return False\n \n Si-1 = - Si+1\n\n #Repeat for rectangle B\n ...\n\n #If we do not find any separating axis\n return True \n</code></pre>\n<p>You can find the code in Python <a href=\"https://github.com/Puco4/separating_axis_test/blob/main/separating_axis_test.py\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p><strong>Note:</strong>\nIn <a href=\"https://stackoverflow.com/a/6016515/12131616\">this other answer</a> they also suggest for optimization to try before the separating axis test whether the vertices of one rectangle are inside the other as a sufficient condition for colliding. However, in my trials I found this intermediate step to actually be less efficient.</p>\n"
},
{
"answer_id": 65060456,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Check if the center of mass of all the vertices of both rectangles lies within one of the rectangles.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20493/"
]
| I'm looking for an algorithm to detect if two rectangles intersect (one at an arbitrary angle, the other with only vertical/horizontal lines).
Testing if a corner of one is in the other ALMOST works. It fails if the rectangles form a cross-like shape.
It seems like a good idea to avoid using slopes of the lines, which would require special cases for vertical lines. | The standard method would be to do the **separating axis test** (do a google search on that).
In short:
* Two objects don't intersect if you can find a line that separates the two objects. e.g. the objects / all points of an object are on different sides of the line.
The fun thing is, that it's sufficient to just check all edges of the two rectangles. If the rectangles don't overlap one of the edges will be the separating axis.
In 2D you can do this without using slopes. An edge is simply defined as the difference between two vertices, e.g.
```
edge = v(n) - v(n-1)
```
You can get a perpendicular to this by rotating it by 90°. In 2D this is easy as:
```
rotated.x = -unrotated.y
rotated.y = unrotated.x
```
So no trigonometry or slopes involved. Normalizing the vector to unit-length is not required either.
If you want to test if a point is on one or another side of the line you can just use the dot-product. the sign will tell you which side you're on:
```
// rotated: your rotated edge
// v(n-1) any point from the edge.
// testpoint: the point you want to find out which side it's on.
side = sign (rotated.x * (testpoint.x - v(n-1).x) +
rotated.y * (testpoint.y - v(n-1).y);
```
Now test all points of rectangle A against the edges of rectangle B and vice versa. If you find a separating edge the objects don't intersect (providing all other points in B are on the other side of the edge being tested for - see drawing below). If you find no separating edge either the rectangles are intersecting or one rectangle is contained in the other.
The test works with any convex polygons btw..
**Amendment:** To identify a separating edge, it is not enough to test all points of one rectangle against each edge of the other. The candidate-edge E (below) would as such be identified as a separating edge, as all points in A are in the same half-plane of E. However, it isn't a separating edge because the vertices Vb1 and Vb2 of B are also in that half-plane. It would only have been a separating edge if that had not been the case
<http://www.iassess.com/collision.png> |
115,428 | <p>I am looking to convert a <code>MySQL timestamp</code> to a epoch time in seconds using <code>PHP</code>, and vice versa. </p>
<p>What's the cleanest way to do this?</p>
| [
{
"answer_id": 115506,
"author": "Harrison Fisk",
"author_id": 16111,
"author_profile": "https://Stackoverflow.com/users/16111",
"pm_score": 3,
"selected": false,
"text": "<p>There are two functions in MySQL which are useful for converting back and forth from the unix epoch time that PHP likes:</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_from-unixtime\" rel=\"nofollow noreferrer\">from_unixtime()</a></p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_unix-timestamp\" rel=\"nofollow noreferrer\">unix_timestamp()</a></p>\n\n<p>For example, to get it back in PHP unix time, you could do:</p>\n\n<pre>SELECT unix_timestamp(timestamp_col) FROM tbl WHERE ...</pre>\n"
},
{
"answer_id": 115510,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 3,
"selected": false,
"text": "<p>See <a href=\"http://www.php.net/strtotime\" rel=\"nofollow noreferrer\">strtotime</a> and <a href=\"http://www.php.net/date\" rel=\"nofollow noreferrer\">date</a> functions in PHP manual.</p>\n\n<pre><code>$unixTimestamp = strtotime($mysqlDate);\n$mysqlDate = date('Y-m-d h:i:s', $unixTimestamp);\n</code></pre>\n"
},
{
"answer_id": 115514,
"author": "Magsol",
"author_id": 13604,
"author_profile": "https://Stackoverflow.com/users/13604",
"pm_score": 0,
"selected": false,
"text": "<p>From MySQL timestamp to epoch seconds:</p>\n\n<pre><code>strtotime($mysql_timestamp);\n</code></pre>\n\n<p>From epoch seconds to MySQL timestamp:</p>\n\n<pre><code>$mysql_timestamp = date('Y-m-d H:i:s', time());\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am looking to convert a `MySQL timestamp` to a epoch time in seconds using `PHP`, and vice versa.
What's the cleanest way to do this? | There are two functions in MySQL which are useful for converting back and forth from the unix epoch time that PHP likes:
[from\_unixtime()](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_from-unixtime)
[unix\_timestamp()](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_unix-timestamp)
For example, to get it back in PHP unix time, you could do:
```
SELECT unix_timestamp(timestamp_col) FROM tbl WHERE ...
``` |
115,431 | <p>Suppose I have some XAML like this:</p>
<pre><code><Window.Resources>
<v:MyClass x:Key="whatever" Text="foo\nbar" />
</Window.Resources>
</code></pre>
<p>Obviously I want a newline character in the MyClass.Text property, but the XAML parser constructs the object with the literal string "foo\nbar".</p>
<p>Is there (a) a way to convince the parser to translate escape sequences, or (b) a .NET method to interpret a string in the way that the C# compiler would?</p>
<p>I realize that I can go in there looking for <code>\n</code> sequences, but it would be nicer to have a generic way to do this.</p>
| [
{
"answer_id": 115543,
"author": "deepcode.co.uk",
"author_id": 20524,
"author_profile": "https://Stackoverflow.com/users/20524",
"pm_score": 1,
"selected": false,
"text": "<p>Off the top of my head, try;</p>\n\n<ol>\n<li>A custom binding expression perhaps?</li>\n</ol>\n\n<blockquote>\n <p><code><v:MyClass x:Key=\"whatever\" Text=\"{MyBinder foo\\nbar}\"/></code></p>\n</blockquote>\n\n<ol start=\"2\">\n<li><p>Use a string static resource?</p></li>\n<li><p>Make Text the default property of your control and;</p></li>\n</ol>\n\n<blockquote>\n<pre><code><v:MyClass x:Key=\"whatever\">\nfoo\nbar\n</v:MyClass>\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 115718,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I realize that I can go in there looking for \\n sequences, [...]</p>\n</blockquote>\n\n<p>If all you care about is \\n's, then you could try something like:</p>\n\n<pre><code>string s = \"foo\\\\nbar\";\ns = s.Replace(\"\\\\n\", \"\\n\");\n</code></pre>\n\n<p>Or, for b) since I don't know of and can't find a builtin function to do this, something like:</p>\n\n<pre><code>using System.Text.RegularExpressions;\n\n// snip\nstring s = \"foo\\\\nbar\";\nRegex r = new Regex(\"\\\\\\\\[rnt\\\\\\\\]\");\ns = r.Replace(s, ReplaceControlChars); ;\n// /snip\n\nstring ReplaceControlChars(Match m)\n{\n switch (m.ToString()[1])\n {\n case 'r': return \"\\r\";\n case 'n': return \"\\n\";\n case '\\\\': return \"\\\\\";\n case 't': return \"\\t\";\n // some control character we don't know how to handle\n default: return m.ToString();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 115738,
"author": "SmartyP",
"author_id": 18005,
"author_profile": "https://Stackoverflow.com/users/18005",
"pm_score": 0,
"selected": false,
"text": "<p>I would use the default TextBlock control as a reference here. In that control you do line breaks like so:</p>\n\n<pre><code> <TextBlock>\n Line 1\n <LineBreak />\n Line 2\n </TextBlock>\n</code></pre>\n\n<p>You should be able to do something similar with your control by making the content value of your control be the text property.</p>\n"
},
{
"answer_id": 116706,
"author": "Vriff Polo",
"author_id": 20653,
"author_profile": "https://Stackoverflow.com/users/20653",
"pm_score": 5,
"selected": true,
"text": "<p>You can use XML character escaping</p>\n\n<pre><code><TextBlock Text=\"Hello&#13;World!\"/>\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9591/"
]
| Suppose I have some XAML like this:
```
<Window.Resources>
<v:MyClass x:Key="whatever" Text="foo\nbar" />
</Window.Resources>
```
Obviously I want a newline character in the MyClass.Text property, but the XAML parser constructs the object with the literal string "foo\nbar".
Is there (a) a way to convince the parser to translate escape sequences, or (b) a .NET method to interpret a string in the way that the C# compiler would?
I realize that I can go in there looking for `\n` sequences, but it would be nicer to have a generic way to do this. | You can use XML character escaping
```
<TextBlock Text="Hello World!"/>
``` |
115,462 | <p>I'm having a little bit of a problem scaling my images to a properly predefined size. I was wondering - since it is purely mathematics, if there's some sort of common logical algorithm that works in every language (PHP, ActionScript, Javascript etc.) to scale images proportionally.</p>
<p>I'm using this at the moment: </p>
<pre><code>var maxHeight = 300;
var maxWidth = 300;
var ratio:Number = height / width;
if (height > maxHeight) {
height = maxHeight;
width = Math.round(height / ratio);
}
else if(width > maxWidth) {
width = maxWidth;
height = Math.round(width * ratio);
}
</code></pre>
<p>But it doesn't work properly. The images scales proportionately, sure enough, but the size isn't set at 300 (either in width or in height). It kind of makes sense, but I was wondering if there's a fool-proof, easy way to scale images proportionally.</p>
| [
{
"answer_id": 115487,
"author": "Alex Weinstein",
"author_id": 16668,
"author_profile": "https://Stackoverflow.com/users/16668",
"pm_score": 2,
"selected": false,
"text": "<p>I'd recommend not writing this code yourself; there are myriads of pixel-level details that take a serious while to get right. Use ImageMagick, it's the best graphics library out there. </p>\n"
},
{
"answer_id": 115492,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 7,
"selected": true,
"text": "<pre><code>ratio = MIN( maxWidth / width, maxHeight/ height );\nwidth = ratio * width;\nheight = ratio * height;\n</code></pre>\n\n<p>Make sure all divides are floating-point.</p>\n"
},
{
"answer_id": 116100,
"author": "Josh Millard",
"author_id": 13600,
"author_profile": "https://Stackoverflow.com/users/13600",
"pm_score": 2,
"selected": false,
"text": "<p>Dark Shikari has it. Your solution as stated in the question fails because you aren't <i>first</i> establishing which dimenson's size-to-maxsize ratio is greater and <i>then</i> reducing both dimensions by that greater ratio.</p>\n\n<p>Your current solution's use of a serial, conditional analysis of one potential dimensional violation and then the other won't work.</p>\n\n<p>Note also that if you want to <i>upscale</i> images, your current solution won't fly, and Dark Shikari's again will.</p>\n"
},
{
"answer_id": 7746280,
"author": "Bogdan Ciocoiu",
"author_id": 914832,
"author_profile": "https://Stackoverflow.com/users/914832",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a function I've developed for my site, you might want to use. It's based on your answer above.</p>\n\n<p>It does other things not only the image processing - <strong>please remove everything which is unnecessary</strong>.</p>\n\n<pre><code><?php\n\n$thumb_width = 500;\n$thumb_height = 500;\n\nif ($handle = opendir('to-do')) {\n echo \"Directory handle: $handle<br />\";\n echo \"Files:<br /><br />\";\n\n /* This is the correct way to loop over the directory. */\n while (false !== ($file = readdir($handle))) {\n\n if ( ($file != \".\") && ($file != \"..\") ){\n echo \"$file\";\n\n $original_path = \"to-do/\" . $file;\n\n $source_image = ImageCreateFromJPEG( $original_path );\n $thumb_width = $thumb_width;\n $thumb_height = $thumb_height;\n\n // Create the image, of the required size\n $thumbnail = imagecreatetruecolor($thumb_width, $thumb_height);\n if($thumbnail === false) {\n //creation failed -- probably not enough memory\n return null;\n }\n\n // Fill the image with a white color (this will be visible in the padding around the image,\n // if the aspect ratios of the image and the thumbnail do not match)\n // Replace this with any color you want, or comment it out for black.\n // I used grey for testing =)\n $fill = imagecolorallocate($thumbnail, 255, 255, 255);\n imagefill($thumbnail, 0, 0, $fill);\n\n // Compute resize ratio\n $hratio = $thumb_height / imagesy($source_image);\n $wratio = $thumb_width / imagesx($source_image);\n $ratio = min($hratio, $wratio);\n\n // If the source is smaller than the thumbnail size, \n // Don't resize -- add a margin instead\n // (that is, dont magnify images)\n if ($ratio > 1.0)\n $ratio = 1.0;\n\n // Compute sizes\n $sy = floor(imagesy($source_image) * $ratio);\n $sx = floor(imagesx($source_image) * $ratio);\n\n // Compute margins\n // Using these margins centers the image in the thumbnail.\n // If you always want the image to the top left, set both of these to 0\n $m_y = floor(($thumb_height - $sy) / 2);\n $m_x = floor(($thumb_width - $sx) / 2);\n\n // Copy the image data, and resample\n // If you want a fast and ugly thumbnail, replace imagecopyresampled with imagecopyresized\n if (!imagecopyresampled($thumbnail, $source_image,\n $m_x, $m_y, //dest x, y (margins)\n 0, 0, //src x, y (0,0 means top left)\n $sx, $sy,//dest w, h (resample to this size (computed above)\n imagesx($source_image), imagesy($source_image)) //src w, h (the full size of the original)\n ) {\n //copy failed\n imagedestroy($thumbnail);\n return null;\n }\n\n /* Set the new file name */\n $thumbnail_file_name = $file;\n\n /* Apply changes on the original image and write the result on the disk */\n ImageJPEG( $thumbnail, $complete_path . \"done/\" . $thumbnail_file_name );\n unset($source_image);\n unset($thumbnail);\n unset($original_path);\n unset($targeted_image_size);\n\n echo \" done<br />\";\n\n }\n\n }\n\n closedir($handle);\n}\n\n?>\n</code></pre>\n"
},
{
"answer_id": 8961028,
"author": "Nicholas",
"author_id": 1163414,
"author_profile": "https://Stackoverflow.com/users/1163414",
"pm_score": 0,
"selected": false,
"text": "<p>well I made this function to scale proportional, it uses a given width, height, and optionally the max width/height u want (depends on the given width and height)</p>\n\n<pre><code> function scaleProportional($img_w,$img_h,$max=50)\n {\n $w = 0;\n $h = 0;\n\n $img_w > $img_h ? $w = $img_w / $img_h : $w = 1;\n $img_h > $img_w ? $h = $img_h / $img_w : $h = 1;\n\n $ws = $w > $h ? $ws = ($w / $w) * $max : $ws = (1 / $h) * $max;\n $hs = $h > $w ? $hs = ($h / $h) * $max : $hs = (1 / $w) * $max;\n\n return array(\n 'width'=>$ws,\n 'height'=>$hs\n );\n }\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code> $getScale = scaleProportional(600,200,500);\n $targ_w = $getScale['width']; //returns 500\n $targ_h = $getScale['height']; //returns 16,6666667\n</code></pre>\n"
},
{
"answer_id": 9505587,
"author": "Arvin",
"author_id": 628864,
"author_profile": "https://Stackoverflow.com/users/628864",
"pm_score": 2,
"selected": false,
"text": "<p>Here is how I do it:</p>\n\n<pre><code>+ (NSSize) scaleHeight:(NSSize)origSize \n newHeight:(CGFloat)height {\n\n NSSize newSize = NSZeroSize;\n if ( origSize.height == 0 ) return newSize;\n\n newSize.height = height;\n CGFloat factor = ( height / origSize.height );\n newSize.width = (origSize.width * factor );\n\n return newSize;\n}\n\n+ (NSSize) scaleWidth:(NSSize)origSize \n newWidth:(CGFloat)width {\n\n NSSize newSize = NSZeroSize;\n if ( origSize.width == 0 ) return newSize;\n\n newSize.width = width;\n CGFloat factor = ( width / origSize.width );\n newSize.height = (origSize.height * factor );\n\n return newSize;\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17362/"
]
| I'm having a little bit of a problem scaling my images to a properly predefined size. I was wondering - since it is purely mathematics, if there's some sort of common logical algorithm that works in every language (PHP, ActionScript, Javascript etc.) to scale images proportionally.
I'm using this at the moment:
```
var maxHeight = 300;
var maxWidth = 300;
var ratio:Number = height / width;
if (height > maxHeight) {
height = maxHeight;
width = Math.round(height / ratio);
}
else if(width > maxWidth) {
width = maxWidth;
height = Math.round(width * ratio);
}
```
But it doesn't work properly. The images scales proportionately, sure enough, but the size isn't set at 300 (either in width or in height). It kind of makes sense, but I was wondering if there's a fool-proof, easy way to scale images proportionally. | ```
ratio = MIN( maxWidth / width, maxHeight/ height );
width = ratio * width;
height = ratio * height;
```
Make sure all divides are floating-point. |
115,478 | <p>The following code is in the <code>/Courses/Detail</code> action:</p>
<pre><code> [AcceptVerbs("GET")]
public ActionResult Detail(int id)
{
ViewData["Title"] = "A View Title";
return View(tmdc.GetCourseById(id));
}
</code></pre>
<p>The <code>tmdc.GetCourseById(id)</code> method returns an instance of type <code>Course</code> for the View. In the View I am using </p>
<pre><code><%= HTML.TextBox("Title")%>
</code></pre>
<p>to display the value of the <code>Title</code> property for the <code>Course</code> object. Instead the text box is displaying the string <code>A View Title</code>. Is this normal/expected behavior? What would be the best way to handle this?</p>
<p><b>Update</b><br />
As a workaround, I've changed <code>ViewData["Title"]</code> to <code>ViewData["VIEW_TITLE"]</code> but would like a cleaner way to handle this collision or to know if this is an expected result.</p>
| [
{
"answer_id": 115704,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 1,
"selected": false,
"text": "<p>You have to wait for the IDE to parse the JavaScript code. Just wait a while and you should see the JavaScript code change color. You will then be able to add breakpoints.</p>\n"
},
{
"answer_id": 120879,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest using <a href=\"http://www.getfirebug.com/\" rel=\"nofollow noreferrer\">FireBug</a> for JavaScript debugging. Give it a spin :)</p>\n"
},
{
"answer_id": 158064,
"author": "Raithlin",
"author_id": 6528,
"author_profile": "https://Stackoverflow.com/users/6528",
"pm_score": 0,
"selected": false,
"text": "<p>I sometimes have this problem with external JavaScript files - it is caused by the browser cache holding onto an old copy of the file. Forcing a refresh of the page linking to the JavaScript code solves the issue in this case.</p>\n\n<p>Of course, make sure your debugger is attached to the correct browser process. ;)</p>\n"
},
{
"answer_id": 174627,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Make sure you turn on <a href=\"http://msdn.microsoft.com/en-us/library/z959x58c.aspx\" rel=\"noreferrer\">script debugging</a> in your internet options. And if you think it's on, double check it.</p>\n"
},
{
"answer_id": 466131,
"author": "Ian Robinson",
"author_id": 326,
"author_profile": "https://Stackoverflow.com/users/326",
"pm_score": 5,
"selected": true,
"text": "<p>I was experiencing the same behavior in Visual Studio 2008, and after spending several minutes trying to get the symbols to load I ended up using a workaround - adding a line with the \"debugger;\" command in my JavaScript file.</p>\n\n<p>After adding <code>debugger;</code> when you then reload the script in Internet Explorer it'll let you bring up a new instance of the script debugger, and it'll stop on your debugger command let you debug from there.</p>\n\n<p>In this scenario I was already debugging the JavaScript in <a href=\"http://en.wikipedia.org/wiki/Firebug_%28software%29\" rel=\"nofollow noreferrer\">Firebug</a>, but I wanted to debug against Internet Explorer as well.</p>\n"
},
{
"answer_id": 734464,
"author": "CubanX",
"author_id": 27555,
"author_profile": "https://Stackoverflow.com/users/27555",
"pm_score": 2,
"selected": false,
"text": "<p>I finally found the answer to this I think.</p>\n\n<p>When you attach your debugger to the iexplore.exe process, you need to make sure you select \"Script\" as one of the debugging choices.</p>\n\n<p>It's the button in a red box here: <a href=\"http://screencast.com/t/5uAUb3g9H8\" rel=\"nofollow noreferrer\">Screenshot of Select Button in Attach to Process Window</a></p>\n\n<p>Then on the next screen, choose Script: <a href=\"http://screencast.com/t/AeWH27rc\" rel=\"nofollow noreferrer\">Screenshot of Select Code Type window</a></p>\n\n<p>This will warn you that you cannot debug Managed and Script at the same time, but that should be fine because your managed code is your server code and you attach to the web process (aspnet or w3wp) instead.</p>\n\n<p>You'll know you did it right because VS 2008 will load ALL the script documents pertaining to that page (inline stuff, eval stuff, etc.) in Solution Explorer.</p>\n\n<p>You'll have full access to the DOM, the immediate window will work, etc. It's pretty slick.</p>\n"
},
{
"answer_id": 1278156,
"author": "ExceptionRaiser",
"author_id": 156528,
"author_profile": "https://Stackoverflow.com/users/156528",
"pm_score": 3,
"selected": false,
"text": "<p>I had the same issue, but I solved it by changing my browser settings in Internet Explorer. Go to menu <em>Tools</em> -> <em>Internet Options</em>, select the <em>Advanced</em> tab, then make sure that both \"Disable Script Debugging (Internet Explorer)\" and \"Disable Script Debugging (Other)\" are unchecked.</p>\n\n<p>Also, I needed to set Internet Explorer as my default browser, which is normally set as Firefox. To do that, in Visual Studio just right click on any browseable file in <a href=\"http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Other_tools\" rel=\"nofollow noreferrer\">Solution Explorer</a> and select \"Browse With...\" Select Internet Explorer and click \"Set as Default\".</p>\n\n<p>I'm not sure if there's a way to get debugging running with other browsers, but it wouldn't surprise me if Visual Studio only plays nice with Internet Explorer.</p>\n\n<p>Also, you may need to do \"Attach to process\" and add <code>IExplorer.exe</code> to get the debugger to start.</p>\n"
},
{
"answer_id": 8217166,
"author": "ccalvert",
"author_id": 253576,
"author_profile": "https://Stackoverflow.com/users/253576",
"pm_score": 0,
"selected": false,
"text": "<p>This is perhaps glaringly obvious, but I stumbled over this for a second, so perhaps others will too. I didn't have Internet Explorer set up to handle HTML/HTTP, and hence it was not launched when I pressed the run button in Visual Studio.</p>\n\n<p>Instead, I was starting Firefox. I went to <strong>Start Button | Default Programs</strong>, set all the defaults for Internet Explorer, and then debugging started working in Visual Studio for me without any other fuss.</p>\n"
},
{
"answer_id": 9540968,
"author": "Jeff Hopper",
"author_id": 352299,
"author_profile": "https://Stackoverflow.com/users/352299",
"pm_score": 0,
"selected": false,
"text": "<p>This can also happen when your solution has multiple web projects, even if they're being served from a different ASP.NET Development Server (WebDev.WebServer40.exe) instance on different ports.</p>\n"
},
{
"answer_id": 9831734,
"author": "Zarepheth",
"author_id": 1075980,
"author_profile": "https://Stackoverflow.com/users/1075980",
"pm_score": 0,
"selected": false,
"text": "<p>If running two or more web projects within your solution and you have multiple script files with the same name at the same place in different webs, the development web-servers may serve up the wrong file, causing this problem.</p>\n\n<p>In my case, deleting the extra copies resolved the problem.</p>\n"
},
{
"answer_id": 12590691,
"author": "Kakoroat",
"author_id": 1698488,
"author_profile": "https://Stackoverflow.com/users/1698488",
"pm_score": 2,
"selected": false,
"text": "<p>One other thing you might look for is a syntax error in your JavaScript code. That is what happened to me today. No symbols would load because I had one too many parentheses in my code. The IntelliSense barely registered the error. Once I fixed the syntax error, everything worked normally.</p>\n"
},
{
"answer_id": 17354061,
"author": "MtnManChris",
"author_id": 2133578,
"author_profile": "https://Stackoverflow.com/users/2133578",
"pm_score": 2,
"selected": false,
"text": "<p>All of these answers are correct, but there is one more thing to check. Until yesterday I was always able to debug my JavaScript code from inside of Visual Studio (<a href=\"http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2012\" rel=\"nofollow\">2012</a>). I had added a <a href=\"http://en.wikipedia.org/wiki/Microsoft_Silverlight\" rel=\"nofollow\">Silverlight</a> project to the solution, which turned on the Silverlight Debugger. This was my problem.</p>\n\n<p>On the property page for the web application -> Start Options -> at the bottom of the page be sure that \"Silverlight\" is unchecked. Actually, I have only ASP.NET checked and now the debugger goes through Visual Studio.</p>\n\n<p>Unchecking it and now the debugger stops on the \"initialize\" function as I wanted.</p>\n"
},
{
"answer_id": 26127377,
"author": "carlosmdelc",
"author_id": 4096186,
"author_profile": "https://Stackoverflow.com/users/4096186",
"pm_score": 1,
"selected": false,
"text": "<p>The solution for me was to update the IE from version 9 to 11. Hope it helps to someone. Peace!</p>\n"
},
{
"answer_id": 34822358,
"author": "Fed X",
"author_id": 5797183,
"author_profile": "https://Stackoverflow.com/users/5797183",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same annoying issues on <a href=\"http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2013\" rel=\"nofollow\">Visual Studio 2013</a>, and JavaScript development without a debugger is just suicide.</p>\n\n<p>All I did to fix it was to right click the break point red dot -> <em>Disable Breakpoint</em> and then right click again -> Enable Breakpoint.</p>\n\n<p>This made the debugger work on JavaScript like a charm again.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19251/"
]
| The following code is in the `/Courses/Detail` action:
```
[AcceptVerbs("GET")]
public ActionResult Detail(int id)
{
ViewData["Title"] = "A View Title";
return View(tmdc.GetCourseById(id));
}
```
The `tmdc.GetCourseById(id)` method returns an instance of type `Course` for the View. In the View I am using
```
<%= HTML.TextBox("Title")%>
```
to display the value of the `Title` property for the `Course` object. Instead the text box is displaying the string `A View Title`. Is this normal/expected behavior? What would be the best way to handle this?
**Update**
As a workaround, I've changed `ViewData["Title"]` to `ViewData["VIEW_TITLE"]` but would like a cleaner way to handle this collision or to know if this is an expected result. | I was experiencing the same behavior in Visual Studio 2008, and after spending several minutes trying to get the symbols to load I ended up using a workaround - adding a line with the "debugger;" command in my JavaScript file.
After adding `debugger;` when you then reload the script in Internet Explorer it'll let you bring up a new instance of the script debugger, and it'll stop on your debugger command let you debug from there.
In this scenario I was already debugging the JavaScript in [Firebug](http://en.wikipedia.org/wiki/Firebug_%28software%29), but I wanted to debug against Internet Explorer as well. |
115,488 | <p>I am having difficulty reliably creating / removing event sources during the installation of my .Net Windows Service.</p>
<p>Here is the code from my ProjectInstaller class:</p>
<pre><code>// Create Process Installer
ServiceProcessInstaller spi = new ServiceProcessInstaller();
spi.Account = ServiceAccount.LocalSystem;
// Create Service
ServiceInstaller si = new ServiceInstaller();
si.ServiceName = Facade.GetServiceName();
si.Description = "Processes ...";
si.DisplayName = "Auto Checkout";
si.StartType = ServiceStartMode.Automatic;
// Remove Event Source if already there
if (EventLog.SourceExists("AutoCheckout"))
EventLog.DeleteEventSource("AutoCheckout");
// Create Event Source and Event Log
EventLogInstaller log = new EventLogInstaller();
log.Source = "AutoCheckout";
log.Log = "AutoCheckoutLog";
Installers.AddRange(new Installer[] { spi, si, log });
</code></pre>
<p>The facade methods referenced just return the strings for the name of the log, service, etc.</p>
<p>This code works most of the time, but recently after installing I started getting my log entries showing up in the Application Log instead of the custom log. And the following errors are in the log as well:</p>
<blockquote>
<p>The description for Event ID ( 0 ) in Source ( AutoCheckout ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. </p>
</blockquote>
<p>For some reason it either isn't properly removing the source during the uninstall or it isn't creating it during the install.</p>
<p>Any help with best practices here is appreciated.</p>
<p>Thanks!</p>
<p>In addition, here is a sample of how I am writing exceptions to the log:</p>
<pre><code>// Write to Log
EventLog.WriteEntry(Facade.GetEventLogSource(), errorDetails, EventLogEntryType.Error, 99);
</code></pre>
<p><strong>Regarding stephbu's answer:</strong> The recommended path is an installer script and installutil, or a Windows Setup routine.</p>
<p>I am using a Setup Project, which performs the installation of the service and sets up the log. Whether I use the installutil.exe or the windows setup project I believe they both call the same ProjectInstaller class I show above.</p>
<p>I see how the state of my test machine could be causing the error if the log isn't truly removed until rebooting. I will experiment more to see if that solves the issue.</p>
<p><strong>Edit:</strong>
I'm interested in a sure fire way to register the source and the log name during the installation of the service. So if the service had previously been installed, it would remove the source, or reuse the source during subsequent installations.</p>
<p>I haven't yet had an opportunity to learn WiX to try that route.</p>
| [
{
"answer_id": 116222,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 3,
"selected": false,
"text": "<p>Couple of things here</p>\n\n<p>Creating Event Logs and Sources on the fly is pretty frowned upon. primarily because of the rights required to perform the action - you don't really want to bless your applications with that power.</p>\n\n<p>Moreover if you delete an event log or source the entry is only <em>truely</em> deleted when the server reboots, so you can get into wierd states if you delete and recreate entries without bouncing the box. There are also a bunch of unwritten rules about naming conflicts due to the way the metadata is stored in the registry.</p>\n\n<p>The recommended path is an installer script and installutil, or a Windows Setup routine.</p>\n"
},
{
"answer_id": 157061,
"author": "Albert",
"author_id": 24065,
"author_profile": "https://Stackoverflow.com/users/24065",
"pm_score": 4,
"selected": true,
"text": "<p>The best recommendation would be to not use the Setup Project in Visual Studio. It has very severe limitations.\nI had very good results with <a href=\"http://wix.sourceforge.net/\" rel=\"nofollow noreferrer\">WiX</a></p>\n"
},
{
"answer_id": 158041,
"author": "Zachary Yates",
"author_id": 8360,
"author_profile": "https://Stackoverflow.com/users/8360",
"pm_score": 2,
"selected": false,
"text": "<p>I have to agree with stephbu about the \"weird states\" that the event log gets into, I've run into that before. If I were to guess, some of your difficulties lie there.</p>\n\n<p>However, the best way that I know of to do event logging in the application is actually with a TraceListener. You can configure them via the service's app.config:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogtracelistener.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogtracelistener.aspx</a></p>\n\n<p>There is a section near the middle of that page that describes how to use the EventLog property to specify the EventLog you wish to write to.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 183749,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 0,
"selected": false,
"text": "<p>I experienced some similar weird behaviour because I tried to register an event source with the same name as the service I was starting. </p>\n\n<p>I notice that you also have the DisplayName set to the same name as your event Source.</p>\n\n<p>On starting the service up, we found that Windows logged a \"Service started successfully\" entry in the Application log, with source as the DisplayName. This seemed to have the effect of registering <em>Application Name</em> with the application log. </p>\n\n<p>In my event logger class I later tried to register <em>Application Name</em> as the source with a different event log, but when it came to adding new event log entries they always got added to the Application log.</p>\n\n<p>I also got the \"The description for Event ID ( 0 ) in Source\" message several times.</p>\n\n<p>As a work around I simply registered the message source with a slightly different name to the DisplayName, and it's worked ever since. It would be worth trying this if you haven't already.</p>\n"
},
{
"answer_id": 828845,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I am having the same problems. In my case it seems that Windows installer is adding the event source which is of the same name as my service automatically and this seems to cause problems. Are you using the same name for the windows service and for the log source? Try changing it so that your event log source is called differently then the name of the service.</p>\n"
},
{
"answer_id": 1258614,
"author": "nojetlag",
"author_id": 154154,
"author_profile": "https://Stackoverflow.com/users/154154",
"pm_score": 0,
"selected": false,
"text": "<p>The problem comes from installutil which by default registers an event source with your services name in the \"Application\" EventLog. I'm still looking for a way to stop it doing this crap. It would be really nice if one could influence the behaviour of installutil :(</p>\n"
},
{
"answer_id": 1287334,
"author": "helb",
"author_id": 157690,
"author_profile": "https://Stackoverflow.com/users/157690",
"pm_score": 5,
"selected": false,
"text": "<p>The <code>ServiceInstaller</code> class automatically creates an <code>EventLogInstaller</code> and puts it inside its own Installers collection.</p>\n\n<p>Try this code:</p>\n\n<pre><code>ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();\nserviceProcessInstaller.Password = null;\nserviceProcessInstaller.Username = null;\nserviceProcessInstaller.Account = ServiceAccount.LocalSystem;\n\n// serviceInstaller\nServiceInstaller serviceInstaller = new ServiceInstaller();\nserviceInstaller.ServiceName = \"MyService\";\nserviceInstaller.DisplayName = \"My Service\";\nserviceInstaller.StartType = ServiceStartMode.Automatic;\nserviceInstaller.Description = \"My Service Description\";\n// kill the default event log installer\nserviceInstaller.Installers.Clear(); \n\n// Create Event Source and Event Log \nEventLogInstaller logInstaller = new EventLogInstaller();\nlogInstaller.Source = \"MyService\"; // use same as ServiceName\nlogInstaller.Log = \"MyLog\";\n\n// Add all installers\nthis.Installers.AddRange(new Installer[] {\n serviceProcessInstaller, serviceInstaller, logInstaller\n});\n</code></pre>\n"
},
{
"answer_id": 1407669,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Following <strong>helb's</strong> suggestion resolved the problem for me. Killing the default event log installer, at the point indicated in his example, prevented the installer from automatically registering my Windows Service under the Application Event log.</p>\n\n<p>Far too much time was lost attempting to resolve this frustrating quirk. Thanks a million!</p>\n\n<p>FWIW, I could not modify the code within my designer-generated ProjectInstaller class without causing VS to carp about the mods. I scrapped the designer-generated code and manually entered the class.</p>\n"
},
{
"answer_id": 3674774,
"author": "Tod Flak",
"author_id": 380605,
"author_profile": "https://Stackoverflow.com/users/380605",
"pm_score": 2,
"selected": false,
"text": "<p>I also followed <strong>helb's</strong> suggestion, except that I basically used the standard designer generated classes (the default objects \"ServiceProcessInstaller1\" and \"ServiceInstaller1\"). I decided to post this since it is a slightly simpler version; and also because I am working in VB and people sometimes like to see the VB-way.</p>\n\n<p>As <strong>tartheode</strong> said, you should not modify the designer-generated ProjectInstaller class in the <em>ProjectInstaller.Designer.vb</em> file, but you <em>can</em> modify the code in the <strong>ProjectInstaller.vb</strong> file. After creating a normal ProjectInstaller (using the standard 'Add Installer' mechanism), the only change I made was in the New() of the ProjectInstaller class. After the normal \"InitializeComponent()\" call, I inserted this code:</p>\n\n<pre><code> ' remove the default event log installer \n Me.ServiceInstaller1.Installers.Clear()\n\n ' Create an EventLogInstaller, and set the Event Source and Event Log \n Dim logInstaller As New EventLogInstaller\n logInstaller.Source = \"MyServiceName\"\n logInstaller.Log = \"MyCustomEventLogName\"\n\n ' Add the event log installer\n Me.ServiceInstaller1.Installers.Add(logInstaller)\n</code></pre>\n\n<p>This worked as expected, in that the installer did <strong>not</strong> create the Event Source in the Application log, but rather created in the new custom log file.</p>\n\n<p>However, I had screwed around enough that I had a bit of a mess on one server. The problem with the custom logs is that if the event source name exists associated to the <strong>wrong</strong> log file (e.g. the 'Application' log instead of your new custom log), then the source name must first be deleted; then the machine rebooted; then the source can be created with association to the correct log. The Microsoft Help clearly states (in the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.eventloginstaller.aspx\" rel=\"nofollow noreferrer\">EventLogInstaller class description</a>):</p>\n\n<blockquote>\n <p>The Install method throws an exception\n if the Source property matches a\n source name that is registered for a\n different event log on the computer.</p>\n</blockquote>\n\n<p>Therefore, I also have this function in my service, which is called when the service starts:</p>\n\n<pre><code> Private Function EventLogSourceNameExists() As Boolean\n 'ensures that the EventSource name exists, and that it is associated to the correct Log \n\n Dim EventLog_SourceName As String = Utility.RetrieveAppSetting(\"EventLog_SourceName\")\n Dim EventLog_LogName As String = Utility.RetrieveAppSetting(\"EventLog_LogName\")\n\n Dim SourceExists As Boolean = EventLog.SourceExists(EventLog_SourceName)\n If Not SourceExists Then\n ' Create the source, if it does not already exist.\n ' An event log source should not be created and immediately used.\n ' There is a latency time to enable the source, it should be created\n ' prior to executing the application that uses the source.\n 'So pass back a False to cause the service to terminate. User will have \n 'to re-start the application to make it work. This ought to happen only once on the \n 'machine on which the service is newly installed\n\n EventLog.CreateEventSource(EventLog_SourceName, EventLog_LogName) 'create as a source for the SMRT event log\n Else\n 'make sure the source is associated with the log file that we want\n Dim el As New EventLog\n el.Source = EventLog_SourceName\n If el.Log <> EventLog_LogName Then\n el.WriteEntry(String.Format(\"About to delete this source '{0}' from this log '{1}'. You may have to kill the service using Task Manageer. Then please reboot the computer; then restart the service two times more to ensure that this event source is created in the log {2}.\", _\n EventLog_SourceName, el.Log, EventLog_LogName))\n\n EventLog.DeleteEventSource(EventLog_SourceName)\n SourceExists = False 'force a close of service\n End If\n End If\n Return SourceExists\n End Function\n</code></pre>\n\n<p>If the function returns False, the service startup code simply stops the service. This function pretty much ensures that you will eventually get the correct Event Source name associated to the correct Event Log file. You may have to reboot the machine once; and you may have to try starting the service more than once.</p>\n"
},
{
"answer_id": 5608532,
"author": "netniV",
"author_id": 697159,
"author_profile": "https://Stackoverflow.com/users/697159",
"pm_score": 1,
"selected": false,
"text": "<p>I just posted a solution to this over on MSDN forums which was to that I managed to get around this using a standard setup MSI project. What I did was to add code to the PreInstall and Committed events which meant I could keep everything else exactly as it was:</p>\n\n<pre><code>SortedList<string, string> eventSources = new SortedList<string, string>();\nprivate void serviceProcessInstaller_BeforeInstall(object sender, InstallEventArgs e)\n{\n RemoveServiceEventLogs();\n}\n\nprivate void RemoveServiceEventLogs()\n{\n foreach (Installer installer in this.Installers)\n if (installer is ServiceInstaller)\n {\n ServiceInstaller serviceInstaller = installer as ServiceInstaller;\n if (EventLog.SourceExists(serviceInstaller.ServiceName))\n {\n eventSources.Add(serviceInstaller.ServiceName, EventLog.LogNameFromSourceName(serviceInstaller.ServiceName, Environment.MachineName));\n EventLog.DeleteEventSource(serviceInstaller.ServiceName);\n }\n }\n}\n\nprivate void serviceProcessInstaller_Committed(object sender, InstallEventArgs e)\n{\n RemoveServiceEventLogs();\n foreach (KeyValuePair<string, string> eventSource in eventSources)\n {\n if (EventLog.SourceExists(eventSource.Key))\n EventLog.DeleteEventSource(eventSource.Key);\n\n EventLog.CreateEventSource(eventSource.Key, eventSource.Value);\n }\n}\n</code></pre>\n\n<p>The code could be modified a bit further to only remove the event sources that didn't already exist or create them (though the logname would need to be stored somewhere against the installer) but since my application code actually creates the event sources as it runs then there's no point for me. If there are already events then there should already be an event source. To ensure that they are created, you can just automatically start the service.</p>\n"
},
{
"answer_id": 15100160,
"author": "Ray Hulha",
"author_id": 756233,
"author_profile": "https://Stackoverflow.com/users/756233",
"pm_score": 0,
"selected": false,
"text": "<p>Adding an empty registry key to HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\eventlog\\Application\\MY_CUSTOM_SOURCE_NAME_HERE seems to work fine.</p>\n"
},
{
"answer_id": 28111365,
"author": "Simon Mattes",
"author_id": 3687883,
"author_profile": "https://Stackoverflow.com/users/3687883",
"pm_score": 0,
"selected": false,
"text": "<p>An easy way to change the default behavior (that is, that the project installer creates an event log source with the name of your service in the application log) is to easily modify the constructor of the project installer as following:</p>\n\n<pre><code>[RunInstaller( true )]\npublic partial class ProjectInstaller : System.Configuration.Install.Installer\n{\n public ProjectInstaller()\n {\n InitializeComponent();\n\n //Skip through all ServiceInstallers.\n foreach( ServiceInstaller ThisInstaller in Installers.OfType<ServiceInstaller>() )\n {\n //Find the first default EventLogInstaller.\n EventLogInstaller ThisLogInstaller = ThisInstaller.Installers.OfType<EventLogInstaller>().FirstOrDefault();\n if( ThisLogInstaller == null )\n continue;\n\n //Modify the used log from \"Application\" to the same name as the source name. This creates a source in the \"Applications and Services log\" which separates your service logs from the default application log.\n ThisLogInstaller.Log = ThisLogInstaller.Source;\n }\n }\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13368/"
]
| I am having difficulty reliably creating / removing event sources during the installation of my .Net Windows Service.
Here is the code from my ProjectInstaller class:
```
// Create Process Installer
ServiceProcessInstaller spi = new ServiceProcessInstaller();
spi.Account = ServiceAccount.LocalSystem;
// Create Service
ServiceInstaller si = new ServiceInstaller();
si.ServiceName = Facade.GetServiceName();
si.Description = "Processes ...";
si.DisplayName = "Auto Checkout";
si.StartType = ServiceStartMode.Automatic;
// Remove Event Source if already there
if (EventLog.SourceExists("AutoCheckout"))
EventLog.DeleteEventSource("AutoCheckout");
// Create Event Source and Event Log
EventLogInstaller log = new EventLogInstaller();
log.Source = "AutoCheckout";
log.Log = "AutoCheckoutLog";
Installers.AddRange(new Installer[] { spi, si, log });
```
The facade methods referenced just return the strings for the name of the log, service, etc.
This code works most of the time, but recently after installing I started getting my log entries showing up in the Application Log instead of the custom log. And the following errors are in the log as well:
>
> The description for Event ID ( 0 ) in Source ( AutoCheckout ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details.
>
>
>
For some reason it either isn't properly removing the source during the uninstall or it isn't creating it during the install.
Any help with best practices here is appreciated.
Thanks!
In addition, here is a sample of how I am writing exceptions to the log:
```
// Write to Log
EventLog.WriteEntry(Facade.GetEventLogSource(), errorDetails, EventLogEntryType.Error, 99);
```
**Regarding stephbu's answer:** The recommended path is an installer script and installutil, or a Windows Setup routine.
I am using a Setup Project, which performs the installation of the service and sets up the log. Whether I use the installutil.exe or the windows setup project I believe they both call the same ProjectInstaller class I show above.
I see how the state of my test machine could be causing the error if the log isn't truly removed until rebooting. I will experiment more to see if that solves the issue.
**Edit:**
I'm interested in a sure fire way to register the source and the log name during the installation of the service. So if the service had previously been installed, it would remove the source, or reuse the source during subsequent installations.
I haven't yet had an opportunity to learn WiX to try that route. | The best recommendation would be to not use the Setup Project in Visual Studio. It has very severe limitations.
I had very good results with [WiX](http://wix.sourceforge.net/) |
115,503 | <p>I recently asked a question about Oracle Encryption. Along the way to finding a solution for myself I decided to move the encryption (well, obfuscation) to the application side for certain tasks. </p>
<p>My problem is that the database is already encrypting data a certain way and I need Java code to duplicate that functionality, so that text encrypted by one system can be decrypted by the other and vice versa.</p>
<p>I want the encryption to be compatible with what the DB was already doing but couldn't find the documentation that describes exactly what Oracle is doing. How do I replicate this in Java?</p>
<pre><code>dbms_obfuscation_toolkit.DESEncrypt(
input_string => v_string,
key_string => key_string,
encrypted_string => encrypted_string );
RETURN UTL_RAW.CAST_TO_RAW(encrypted_string);
</code></pre>
<p>No matter what I try, it seems as if the Java DES encryption is different than Oracle's.</p>
| [
{
"answer_id": 115540,
"author": "Mr. Shiny and New 安宇",
"author_id": 7867,
"author_profile": "https://Stackoverflow.com/users/7867",
"pm_score": 3,
"selected": true,
"text": "<p>I found this works:</p>\n\n<pre><code>KeySpec ks = new DESKeySpec(new byte[] {'s','e','c','r','e','t','!','!'});\nSecretKeyFactory skf = SecretKeyFactory.getInstance(\"DES\");\nSecretKey sk = skf.generateSecret(ks);\nCipher c = Cipher.getInstance(\"DES/CBC/NoPadding\");\nIvParameterSpec ips = new IvParameterSpec(new byte[] {0,0,0,0,0,0,0,0});\nc.init(Cipher.ENCRYPT, sk, ips);\n// or\nc.init(Cipher.DECRYPT, sk, ips);\n</code></pre>\n\n<p>The missing piece was the Initialization Vector (ips) which must be 8 zeros. When you use null in Java you get something different.</p>\n"
},
{
"answer_id": 116247,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "<p>Using Java in the database would have been another approach that would (should!) have guarenteed that the code (and hence results) would be identical.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7867/"
]
| I recently asked a question about Oracle Encryption. Along the way to finding a solution for myself I decided to move the encryption (well, obfuscation) to the application side for certain tasks.
My problem is that the database is already encrypting data a certain way and I need Java code to duplicate that functionality, so that text encrypted by one system can be decrypted by the other and vice versa.
I want the encryption to be compatible with what the DB was already doing but couldn't find the documentation that describes exactly what Oracle is doing. How do I replicate this in Java?
```
dbms_obfuscation_toolkit.DESEncrypt(
input_string => v_string,
key_string => key_string,
encrypted_string => encrypted_string );
RETURN UTL_RAW.CAST_TO_RAW(encrypted_string);
```
No matter what I try, it seems as if the Java DES encryption is different than Oracle's. | I found this works:
```
KeySpec ks = new DESKeySpec(new byte[] {'s','e','c','r','e','t','!','!'});
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = skf.generateSecret(ks);
Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
IvParameterSpec ips = new IvParameterSpec(new byte[] {0,0,0,0,0,0,0,0});
c.init(Cipher.ENCRYPT, sk, ips);
// or
c.init(Cipher.DECRYPT, sk, ips);
```
The missing piece was the Initialization Vector (ips) which must be 8 zeros. When you use null in Java you get something different. |
115,526 | <p>I'm running an c# .net app in an iframe of an asp page on an older site. Accessing the Asp page's session information is somewhat difficult, so I'd like to make my .net app simply verify that it's being called from an approved page, or else immediately halt.</p>
<p>Is there a way for a page to find out the url of it's parent document?</p>
| [
{
"answer_id": 115533,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 5,
"selected": true,
"text": "<pre><code>top.location.href\n</code></pre>\n\n<p>But that will only work if both pages (the iframe and the main page) are being served from the same domain.</p>\n"
},
{
"answer_id": 116157,
"author": "Raleigh Buckner",
"author_id": 1153,
"author_profile": "https://Stackoverflow.com/users/1153",
"pm_score": 1,
"selected": false,
"text": "<pre><code>parent.location.href\n</code></pre>\n"
},
{
"answer_id": 2835018,
"author": "jumpdart",
"author_id": 341335,
"author_profile": "https://Stackoverflow.com/users/341335",
"pm_score": 2,
"selected": false,
"text": "<p>To get the URL:</p>\n\n<pre><code>Request.UrlReferrer....\n</code></pre>\n\n<p>To digest the query string:</p>\n\n<pre><code>NameValueCollection qs = HttpUtility.ParseQueryString(Request.UrlReferrer.Query);\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12382/"
]
| I'm running an c# .net app in an iframe of an asp page on an older site. Accessing the Asp page's session information is somewhat difficult, so I'd like to make my .net app simply verify that it's being called from an approved page, or else immediately halt.
Is there a way for a page to find out the url of it's parent document? | ```
top.location.href
```
But that will only work if both pages (the iframe and the main page) are being served from the same domain. |
115,548 | <p>This code in JS gives me a popup saying "i think null is a number", which I find slightly disturbing. What am I missing?</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-js lang-js prettyprint-override"><code>if (isNaN(null)) {
alert("null is not a number");
} else {
alert("i think null is a number");
}</code></pre>
</div>
</div>
</p>
<p>I'm using Firefox 3. Is that a browser bug?</p>
<p>Other tests:</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-js lang-js prettyprint-override"><code>console.log(null == NaN); // false
console.log(isNaN("text")); // true
console.log(NaN == "text"); // false</code></pre>
</div>
</div>
</p>
<p>So, the problem seems not to be an exact comparison with NaN?</p>
<p><i><b>Edit:</b> Now the question has been answered, I have cleaned up my post to have a better version for the archive. However, this renders some comments and even some answers a little incomprehensible. Don't blame their authors. Among the things I changed was:</p>
<ul>
<li>Removed a note saying that I had screwed up the headline in the first place by reverting its meaning</li>
<li>Earlier answers showed that I didn't state clearly enough why I thought the behaviour was weird, so I added the examples that check a string and do a manual comparison.
</i></li>
</ul>
| [
{
"answer_id": 115559,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 2,
"selected": false,
"text": "<p>Null is not NaN, as well as a string is not NaN. isNaN() just test if you really have the NaN object.</p>\n"
},
{
"answer_id": 115610,
"author": "Jason Tennier",
"author_id": 500,
"author_profile": "https://Stackoverflow.com/users/500",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not exactly sure when it comes to JS but I've seen similar things in other languages and it's usually because the function is only checking whether null is exactly equal to NaN (i.e. null === NaN would be false). In other words it's not that it thinks that null is in fact a number, but it's rather that null is not NaN. This is probably because both are represented differently in JS so that they won't be exactly equal, in the same way that 9 !== '9'.</p>\n"
},
{
"answer_id": 115696,
"author": "Glenn Moss",
"author_id": 5726,
"author_profile": "https://Stackoverflow.com/users/5726",
"pm_score": 8,
"selected": true,
"text": "<p>I believe the code is trying to ask, \"is <code>x</code> numeric?\" with the specific case here of <code>x = null</code>. The function <code>isNaN()</code> can be used to answer this question, but semantically it's referring specifically to the value <code>NaN</code>. From Wikipedia for <a href=\"http://en.wikipedia.org/wiki/NaN\" rel=\"noreferrer\"><code>NaN</code></a>: </p>\n\n<blockquote>\n <p>NaN (<b>N</b>ot <b>a</b> <b>N</b>umber) is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations.</p>\n</blockquote>\n\n<p>In most cases we think the answer to \"is null numeric?\" should be no. However, <code>isNaN(null) == false</code> is semantically correct, because <code>null</code> is not <code>NaN</code>.</p>\n\n<p>Here's the algorithmic explanation:</p>\n\n<p>The function <code>isNaN(x)</code> attempts to convert the passed parameter to a number<sup><a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN\" rel=\"noreferrer\">1</a></sup> (equivalent to <code>Number(x)</code>) and then tests if the value is <code>NaN</code>. If the parameter can't be converted to a number, <code>Number(x)</code> will return <code>NaN</code><sup><a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number\" rel=\"noreferrer\">2</a></sup>. Therefore, if the conversion of parameter <code>x</code> to a number results in <code>NaN</code>, it returns true; otherwise, it returns false. </p>\n\n<p>So in the specific case <code>x = null</code>, <code>null</code> is converted to the number 0, (try evaluating <code>Number(null)</code> and see that it returns 0,) and <code>isNaN(0)</code> returns false. A string that is only digits can be converted to a number and isNaN also returns false. A string (e.g. <code>'abcd'</code>) that cannot be converted to a number will cause <code>isNaN('abcd')</code> to return true, specifically because <code>Number('abcd')</code> returns <code>NaN</code>.</p>\n\n<p>In addition to these apparent edge cases are the standard numerical reasons for returning NaN like 0/0.</p>\n\n<p>As for the seemingly inconsistent tests for equality shown in the question, the behavior of <code>NaN</code> is specified such that any comparison <code>x == NaN</code> is false, regardless of the other operand, including <code>NaN</code> itself<sup><a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN\" rel=\"noreferrer\">1</a></sup>.</p>\n"
},
{
"answer_id": 118084,
"author": "treat your mods well",
"author_id": 20772,
"author_profile": "https://Stackoverflow.com/users/20772",
"pm_score": 3,
"selected": false,
"text": "<p>This is indeed disturbing. Here is an array of values that I tested:</p>\n\n<pre><code>var x = [undefined, NaN, 'blah', 0/0, null, 0, '0', 1, 1/0, -1/0, Number(5)]\n</code></pre>\n\n<p>It evaluates (in the Firebug console) to:</p>\n\n<pre><code>,NaN,blah,NaN,,0,0,1,Infinity,-Infinity,5\n</code></pre>\n\n<p>When I call <code>x.map(isNaN)</code> (to call isNaN on each value), I get:</p>\n\n<pre><code>true,true,true,true,false,false,false,false,false,false,false\n</code></pre>\n\n<p>In conclusion, <code>isNaN</code> looks pretty useless! (<strong>Edit</strong>: Except it turns out isNaN is only <em>defined</em> over Number, in which case it works just fine -- just with a misleading name.)</p>\n\n<p>Incidentally, here are the types of those values:</p>\n\n<pre><code>x.map(function(n){return typeof n})\n-> undefined,number,string,number,object,number,string,number,number,number,number\n</code></pre>\n"
},
{
"answer_id": 118154,
"author": "treat your mods well",
"author_id": 20772,
"author_profile": "https://Stackoverflow.com/users/20772",
"pm_score": 4,
"selected": false,
"text": "<p>(My other comment takes a practical approach. Here's the theoretical side.)</p>\n\n<p>I looked up the <a href=\"http://www.ecma-international.org/publications/standards/Ecma-262.htm\" rel=\"noreferrer\">ECMA 262 standard</a>, which is what Javascript implements. Their specification for isNan:</p>\n\n<blockquote>\n <p>Applies ToNumber to its argument, then returns true if the result is NaN, and otherwise returns false.</p>\n</blockquote>\n\n<p>Section 9.3 specifies the behavior of <code>ToNumber</code> (which is not a callable function, but rather a component of the type conversion system). To summarize the table, certain input types can produce a NaN. These are type <code>undefined</code>, type <code>number</code> (but only the value <code>NaN</code>), any object whose primitive representation is <code>NaN</code>, and any <code>string</code> that cannot be parsed. This leaves <code>undefined</code>, <code>NaN</code>, <code>new Number(NaN)</code>, and most strings.</p>\n\n<p>Any such input that produces <code>NaN</code> as an output when passed to <code>ToNumber</code> will produce a <code>true</code> when fed to <code>isNaN</code>. Since <code>null</code> can successfully be converted to a number, it does not produce <code>true</code>.</p>\n\n<p>And that is why.</p>\n"
},
{
"answer_id": 120499,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": -1,
"selected": false,
"text": "<p>Note:</p>\n\n<pre><code>\"1\" == 1 // true\n\"1\" === 1 // false\n</code></pre>\n\n<p>The == operator does type-conversion, while === does not.</p>\n\n<p><a href=\"http://crockford.com/\" rel=\"nofollow noreferrer\">Douglas Crockford's website</a>, a Yahoo! JavaScript evangelist, is a great resource for stuff like this.</p>\n"
},
{
"answer_id": 20629324,
"author": "guy mograbi",
"author_id": 1068746,
"author_profile": "https://Stackoverflow.com/users/1068746",
"pm_score": 5,
"selected": false,
"text": "<p>I just ran into this issue myself. </p>\n\n<p>For me, the best way to use isNaN is like so </p>\n\n<p><code>isNaN(parseInt(myInt))</code></p>\n\n<p>taking phyzome's example from above, </p>\n\n<pre><code>var x = [undefined, NaN, 'blah', 0/0, null, 0, '0', 1, 1/0, -1/0, Number(5)]\nx.map( function(n){ return isNaN(parseInt(n))})\n [true, true, true, true, true, false, false, false, true, true, false]\n</code></pre>\n\n<p>( I aligned the result according to the input, hope it makes it easier to read. )</p>\n\n<p>This seems better to me. </p>\n"
},
{
"answer_id": 29821670,
"author": "rab",
"author_id": 1722625,
"author_profile": "https://Stackoverflow.com/users/1722625",
"pm_score": 2,
"selected": false,
"text": "<p>In ES5, it defined as <code>isNaN (number)</code> returns true if the argument coerces to NaN, and otherwise returns false.</p>\n\n<ul>\n<li>If <a href=\"https://es5.github.io/#x9.3\" rel=\"nofollow\">ToNumber(number)</a> is NaN, return true.</li>\n<li>Otherwise, return false.</li>\n</ul>\n\n<p>And see the <a href=\"https://es5.github.io/#x9.3\" rel=\"nofollow\">The abstract operation ToNumber convertion table</a>. So it internally js engine evaluate <code>ToNumber(Null)</code> is <code>+0</code>, then eventually <code>isNaN(null)</code> is <code>false</code></p>\n"
},
{
"answer_id": 67980304,
"author": "5ervant - techintel.github.io",
"author_id": 2007055,
"author_profile": "https://Stackoverflow.com/users/2007055",
"pm_score": -1,
"selected": false,
"text": "<pre><code>(NaN == null) // false\n(NaN != null) // true\n</code></pre>\n<p>Funny though:</p>\n<pre><code>(NaN == true) // false\n(NaN == false) // false\n(NaN) // false\n(!NaN) // true\n</code></pre>\n<p>Aren't <code>(NaN == false)</code> and <code>(!NaN)</code> identical?</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
]
| This code in JS gives me a popup saying "i think null is a number", which I find slightly disturbing. What am I missing?
```js
if (isNaN(null)) {
alert("null is not a number");
} else {
alert("i think null is a number");
}
```
I'm using Firefox 3. Is that a browser bug?
Other tests:
```js
console.log(null == NaN); // false
console.log(isNaN("text")); // true
console.log(NaN == "text"); // false
```
So, the problem seems not to be an exact comparison with NaN?
***Edit:** Now the question has been answered, I have cleaned up my post to have a better version for the archive. However, this renders some comments and even some answers a little incomprehensible. Don't blame their authors. Among the things I changed was:*
* Removed a note saying that I had screwed up the headline in the first place by reverting its meaning
* Earlier answers showed that I didn't state clearly enough why I thought the behaviour was weird, so I added the examples that check a string and do a manual comparison. | I believe the code is trying to ask, "is `x` numeric?" with the specific case here of `x = null`. The function `isNaN()` can be used to answer this question, but semantically it's referring specifically to the value `NaN`. From Wikipedia for [`NaN`](http://en.wikipedia.org/wiki/NaN):
>
> NaN (**N**ot **a** **N**umber) is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations.
>
>
>
In most cases we think the answer to "is null numeric?" should be no. However, `isNaN(null) == false` is semantically correct, because `null` is not `NaN`.
Here's the algorithmic explanation:
The function `isNaN(x)` attempts to convert the passed parameter to a number[1](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN) (equivalent to `Number(x)`) and then tests if the value is `NaN`. If the parameter can't be converted to a number, `Number(x)` will return `NaN`[2](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number). Therefore, if the conversion of parameter `x` to a number results in `NaN`, it returns true; otherwise, it returns false.
So in the specific case `x = null`, `null` is converted to the number 0, (try evaluating `Number(null)` and see that it returns 0,) and `isNaN(0)` returns false. A string that is only digits can be converted to a number and isNaN also returns false. A string (e.g. `'abcd'`) that cannot be converted to a number will cause `isNaN('abcd')` to return true, specifically because `Number('abcd')` returns `NaN`.
In addition to these apparent edge cases are the standard numerical reasons for returning NaN like 0/0.
As for the seemingly inconsistent tests for equality shown in the question, the behavior of `NaN` is specified such that any comparison `x == NaN` is false, regardless of the other operand, including `NaN` itself[1](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/isNaN). |
115,557 | <p>We are struggling to configure our web app to be able to connect with web services via Spring WS. We have tried to use the example from the documentation of client-side Spring-WS, but we end up with a WebServiceTransportException. The XML config looks like this:</p>
<pre><code><bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.http.CommonsHttpMessageSender">
<property name="credentials">
<bean class="org.apache.commons.httpclient.UsernamePasswordCredentials">
<constructor-arg value="john"/>
<constructor-arg value="secret"/>
</bean>
</property>
</bean>
</property>
</bean>
</code></pre>
<p>We have been able to configure the application programmatically, but this configuration was not possible to "transfer" to a Spring XML config because some setters did not use the format Spring expects. (HttpState.setCredentials(...) takes two parameters). The config was lifted from some other Spring-WS client code in the company.</p>
<p>This is the configuration that works:</p>
<pre><code> public List<String> getAll() {
List<String> carTypes = new ArrayList<String>();
try {
Source source = new ResourceSource(request);
JDOMResult result = new JDOMResult();
SaajSoapMessageFactory soapMessageFactory = new SaajSoapMessageFactory(MessageFactory.newInstance());
WebServiceTemplate template = new WebServiceTemplate(soapMessageFactory);
HttpClientParams clientParams = new HttpClientParams();
clientParams.setSoTimeout(60000);
clientParams.setConnectionManagerTimeout(60000);
clientParams.setAuthenticationPreemptive(true);
HttpClient client = new HttpClient(clientParams);
client.getState().setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("username", "password"));
CommonsHttpMessageSender messageSender = new CommonsHttpMessageSender(client);
template.setMessageSender(messageSender);
template.sendSourceAndReceiveToResult(SERVICE_URI,
source, result);
// Handle the XML
} catch (IOException e) {
throw new RuntimeException(e);
} catch (SOAPException e) {
throw new RuntimeException(e);
}
return carTypes;
}
</code></pre>
<p>Does anyone know how to solve my problem? Every tutorial I have see out there lists the first configuration. It seems that when I set the credentials on the messageSender object, they are just ignored...</p>
| [
{
"answer_id": 150178,
"author": "Symbioxys",
"author_id": 1841427,
"author_profile": "https://Stackoverflow.com/users/1841427",
"pm_score": 1,
"selected": false,
"text": "<p>How do you distinguish these:</p>\n\n<pre><code><constructor-arg value=\"john\"/>\n<constructor-arg value=\"secret\"/>\n</code></pre>\n\n<p>try and replace it with this:</p>\n\n<pre><code><property name=\"userName\" value=\"john\" />\n<property name=\"password\" value=\"secret\" />\n</code></pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 1915645,
"author": "DonHaji",
"author_id": 233092,
"author_profile": "https://Stackoverflow.com/users/233092",
"pm_score": 2,
"selected": false,
"text": "<p>Override HttpClient with a constructor that takes the parameters and wire through Spring using constructor-args</p>\n\n<pre><code>public MyHttpClient(HttpClientParams params, UsernamePasswordCredentials usernamePasswordCredentials) {\n super(params); \n getState().setCredentials(AuthScope.ANY, usernamePasswordCredentials);\n }\n</code></pre>\n"
},
{
"answer_id": 16325196,
"author": "abandonedVeran",
"author_id": 2340659,
"author_profile": "https://Stackoverflow.com/users/2340659",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using a defaultHttpClient like you are in your example, Use the afterPropertiesSet method on your HTTPMessageSender and that should fix your problem by applying the credentials correctly </p>\n"
},
{
"answer_id": 25661201,
"author": "Jemo",
"author_id": 1010056,
"author_profile": "https://Stackoverflow.com/users/1010056",
"pm_score": 0,
"selected": false,
"text": "<p>At first we were setting credentials in our project like this:</p>\n\n<pre><code><bean id=\"authenticationEnabledCommonsHttpMessageSender\" parent=\"commonsHttpMessageSender\"\n p:credentials-ref=\"clientCredentials\" lazy-init=\"true\" />\n<bean id=\"clientCredentials\"\n class=\"org.apache.commons.httpclient.UsernamePasswordCredentials\"\n c:userName=\"${clientCredentials.userName}\"\n c:password=\"${clientCredentials.password}\"\n lazy-init=\"true\" />\n</code></pre>\n\n<p>This is our cridentials enabled option. A problem occured while we are setting credentials like that. \nIf the server we send message (has Axis impl) has not got username password credentials we get \"Unauthorized\" exception. Because ,when we trace vie TCPMon, we realized \"username:password:\" string was sent, as you can see username and password have no value.</p>\n\n<p>After that we set the credentials like that:</p>\n\n<pre><code>public Message sendRequest(OutgoingRequest message, MessageHeaders headers,\n EndpointInfoProvider endpointInfoProvider,\n WebServiceMessageCallback requestCallback){\n Assert.notNull(endpointInfoProvider, \"Destination provider is required!\");\n final Credentials credentials = endpointInfoProvider.getCredentials();\n URI destinationUri = endpointInfoProvider.getDestination();\n for (WebServiceMessageSender messageSender : webServiceTemplate.getMessageSenders()) {\n if (messageSender instanceof CommonsHttpMessageSender) {\n HttpClient httpClient = ((CommonsHttpMessageSender) messageSender).getHttpClient();\n httpClient.getState().setCredentials(\n new AuthScope(destinationUri.getHost(),\n destinationUri.getPort(), AuthScope.ANY_REALM,\n AuthScope.ANY_SCHEME), credentials\n );\n httpClient.getParams().setAuthenticationPreemptive(true);\n ((CommonsHttpMessageSender) messageSender)\n .setConnectionTimeout(endpointInfoProvider\n .getTimeOutDuration());\n }\n }\n</code></pre>\n\n<p>And the getCredentials methos is:</p>\n\n<pre><code>@Override\npublic Credentials getCredentials(){\n if (credentials != null) {\n return credentials;\n }\n String username = parameterService.usernameFor(getServiceName());\n String password = parameterService.passwordFor(getServiceName());\n if (username == null && password == null) {\n return null;\n }\n credentials = new UsernamePasswordCredentials(username, password);\n return credentials;\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20529/"
]
| We are struggling to configure our web app to be able to connect with web services via Spring WS. We have tried to use the example from the documentation of client-side Spring-WS, but we end up with a WebServiceTransportException. The XML config looks like this:
```
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="messageSender">
<bean class="org.springframework.ws.transport.http.CommonsHttpMessageSender">
<property name="credentials">
<bean class="org.apache.commons.httpclient.UsernamePasswordCredentials">
<constructor-arg value="john"/>
<constructor-arg value="secret"/>
</bean>
</property>
</bean>
</property>
</bean>
```
We have been able to configure the application programmatically, but this configuration was not possible to "transfer" to a Spring XML config because some setters did not use the format Spring expects. (HttpState.setCredentials(...) takes two parameters). The config was lifted from some other Spring-WS client code in the company.
This is the configuration that works:
```
public List<String> getAll() {
List<String> carTypes = new ArrayList<String>();
try {
Source source = new ResourceSource(request);
JDOMResult result = new JDOMResult();
SaajSoapMessageFactory soapMessageFactory = new SaajSoapMessageFactory(MessageFactory.newInstance());
WebServiceTemplate template = new WebServiceTemplate(soapMessageFactory);
HttpClientParams clientParams = new HttpClientParams();
clientParams.setSoTimeout(60000);
clientParams.setConnectionManagerTimeout(60000);
clientParams.setAuthenticationPreemptive(true);
HttpClient client = new HttpClient(clientParams);
client.getState().setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("username", "password"));
CommonsHttpMessageSender messageSender = new CommonsHttpMessageSender(client);
template.setMessageSender(messageSender);
template.sendSourceAndReceiveToResult(SERVICE_URI,
source, result);
// Handle the XML
} catch (IOException e) {
throw new RuntimeException(e);
} catch (SOAPException e) {
throw new RuntimeException(e);
}
return carTypes;
}
```
Does anyone know how to solve my problem? Every tutorial I have see out there lists the first configuration. It seems that when I set the credentials on the messageSender object, they are just ignored... | Override HttpClient with a constructor that takes the parameters and wire through Spring using constructor-args
```
public MyHttpClient(HttpClientParams params, UsernamePasswordCredentials usernamePasswordCredentials) {
super(params);
getState().setCredentials(AuthScope.ANY, usernamePasswordCredentials);
}
``` |
115,573 | <p>I'm sure we all have received the wonderfully vague "Object reference not set to instance of an Object" exception at some time or another. Identifying the object that is the problem is often a tedious task of setting breakpoints and inspecting all members in each statement. </p>
<p>Does anyone have any tricks to easily and efficiently identify the object that causes the exception, either via programmatical means or otherwise?</p>
<p>--edit</p>
<p>It seems I was vague like the exception =). The point is to _not have to debug the app to find the errant object. The compiler/runtime does know that the object has been allocated/declared, and that the object has not yet been instantiated. Is there a way to extract / identify those details in a caught exception</p>
<p>@ W. Craig Trader</p>
<p>Your explanation that it is a result of a design problem is probably the best answer I could get. I am fairly compulsive with defensive coding and have managed to get rid of most of these errors after fixing my habits over time. The remaining ones just <strong><em>tweak</em></strong> me to no end, and lead me to posting this question to the community. </p>
<p>Thanks for everyone's suggestions.</p>
| [
{
"answer_id": 115599,
"author": "Oliver Mellet",
"author_id": 12001,
"author_profile": "https://Stackoverflow.com/users/12001",
"pm_score": 1,
"selected": false,
"text": "<p>There's really not much you can do besides look at the stack trace; if you're dereferencing multiple object references in the same line of code, there's no way to determine which one is null without setting a breakpoint. You could avoid this by only dereferencing one object per line, but that would result in some pretty terrible-looking code.</p>\n"
},
{
"answer_id": 115602,
"author": "Kuvo",
"author_id": 12623,
"author_profile": "https://Stackoverflow.com/users/12623",
"pm_score": 0,
"selected": false,
"text": "<p>you can check the Message and InnerException properties</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.exception.innerexception.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.exception.innerexception.aspx</a></p>\n"
},
{
"answer_id": 115609,
"author": "Pawel Pabich",
"author_id": 3323,
"author_profile": "https://Stackoverflow.com/users/3323",
"pm_score": 1,
"selected": false,
"text": "<p>Well, you can not really identify the object as it does not exist and thus the exception you are getting.</p>\n"
},
{
"answer_id": 115619,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 1,
"selected": false,
"text": "<p>The line # and file are usually all you need to find the culprit. If you are the one throwing the exception, consider using an <code>ArgumentNullException</code>, if appropriate, or checking for nulls and throwing <code>NullReferenceException</code>s that have more details about the null field.</p>\n\n<p>Edit @ your edit :)</p>\n\n<p>AFAIK, you would have to examine the stack trace string to get that line # and file. Your best bet would be to get the innermost exception, and then look at the first line of its stack trace. If you want to be able to programatically parse that information to find out which field caused the null, and do something with that field's name, I fear you will be out of luck.</p>\n\n<p>@W. Craig Trader</p>\n\n<p>Good point. For a null value that is passed into the method, an <code><a href=\"http://msdn.microsoft.com/en-us/library/system.argumentnullexception.aspx\" rel=\"nofollow noreferrer\">ArgumentNullException</a></code> should be thrown. For a member variable that has not yet been initialized, something like an <code>InvalidStateException</code> would probably be good to throw. Unfortunately, I can't find any such exception in MSDN. Roll your own?</p>\n"
},
{
"answer_id": 115642,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 0,
"selected": false,
"text": "<p>If you're catching your exceptions for friendly user messages or logging you'd probably want the debugger to stop at an exception while debugging. Go to Debug/Exceptions and check the exception types you want the debugger to stop running at, System.NullReferenceException in your case.</p>\n"
},
{
"answer_id": 115664,
"author": "MarcE",
"author_id": 7262,
"author_profile": "https://Stackoverflow.com/users/7262",
"pm_score": 0,
"selected": false,
"text": "<p>Set VS to break on exceptions, then when you get your error it's usually pretty obvious what line it's on. The stack trace window will tell you how you got there. Not much else you can do apart from that.</p>\n"
},
{
"answer_id": 115732,
"author": "Craig Trader",
"author_id": 12895,
"author_profile": "https://Stackoverflow.com/users/12895",
"pm_score": 5,
"selected": true,
"text": "<p>At the point where the NRE is thrown, there is no target object -- that's the point of the exception. The most you can hope for is to trap the file and line number where the exception occurred. If you're having problems identifying which object reference is causing the problem, then you might want to rethink your coding standards, because it sounds like you're doing too much on one line of code.</p>\n\n<p>A better solution to this sort of problem is <a href=\"http://en.wikipedia.org/wiki/Design_By_Contract\" rel=\"nofollow noreferrer\">Design by Contract</a>, either through builtin language constructs, or via a library. DbC would suggest pre-checking any incoming arguments for a method for out-of-range data (ie: Null) and throwing exceptions because the method won't work with bad data.</p>\n\n<p><strong>[Edit to match question edit:]</strong></p>\n\n<p>I think the NRE description is misleading you. The problem that the CLR is having is that it was asked to dereference an object reference, when the object reference is Null. Take this example program:</p>\n\n<pre><code>public class NullPointerExample {\n public static void Main()\n {\n Object foo;\n System.Console.WriteLine( foo.ToString() );\n }\n}\n</code></pre>\n\n<p>When you run this, it's going to throw an NRE on line 5, when it tried to evaluate the ToString() method on foo. There are no objects to debug, only an uninitialized object reference (foo). There's a class and a method, but no object.</p>\n\n<hr>\n\n<p>Re: Chris Marasti-Georg's <a href=\"https://stackoverflow.com/questions/115573/detecting-what-the-target-object-is-when-nullreferenceexception-is-thrown#115619\">answer</a>:</p>\n\n<p>You should never throw NRE yourself -- that's a system exception with a specific meaning: the CLR (or JVM) has attempted to evaluate an object reference that wasn't initialized. If you pre-check an object reference, then either throw some sort of invalid argument exception or an application-specific exception, but not NRE, because you'll only confuse the next programmer who has to maintain your app.</p>\n"
},
{
"answer_id": 116233,
"author": "Pat",
"author_id": 14206,
"author_profile": "https://Stackoverflow.com/users/14206",
"pm_score": 0,
"selected": false,
"text": "<p>For reference, a similar thread:<a href=\"https://stackoverflow.com/questions/95547/should-i-catch-exceptions-only-to-log-them#95773\">Should I catch exceptions only to log them?</a></p>\n\n<p>Salient points is that you want to effectively capture the exception. In my experience, the goal is to make sure that the programmer checks for null references in code - however we know that in reality, we miss some. UI code should have some level of exception handling. I liked my answer to that question: <a href=\"https://stackoverflow.com/questions/95547/should-i-catch-exceptions-only-to-log-them#95773\">My Answer</a>. More importantly, the comment by <a href=\"https://stackoverflow.com/users/3146/1800-information\">1800 information</a>, who pointed out that you simply throw, and not throw ex in order to capture the entire stack trace which is how you ultimately debug these issues.</p>\n"
},
{
"answer_id": 116424,
"author": "Matt Ryan",
"author_id": 19548,
"author_profile": "https://Stackoverflow.com/users/19548",
"pm_score": 4,
"selected": false,
"text": "<p>As a few answers have pointed out, tell Visual Studio to break on Throw for NullReferenceException.</p>\n\n<p><em>How to tell VS to break when unhandled exceptions are thrown</em></p>\n\n<ul>\n<li>Debug menu | Exceptions (or <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>E</kbd>)</li>\n<li>Drill into Common Language Runtime Exceptions</li>\n<li>Drill into System</li>\n<li>Find System.NullRefernceException, and check the box to Break whenever this exception is thrown, rather than allowing it to proceed to whatever Catch blocks are in place</li>\n</ul>\n\n<p>So now when it occurs, VS will break immediately, and the Current Statement line will be sitting on the expression that evaluated to null.</p>\n\n<p>This facility is useful for all kinds of exceptions, including custom ones (can add the fully qualified type name, and VS will match it at Debug time)</p>\n\n<p>The one drawback to this approach is if there is code loaded in the debugger that follows the bad practice of throwing and catching lots of the exceptions you're looking for, in which case it turns back into a haystack / needle issue (unless you can fix that code of course - then you've solved two problems :)</p>\n\n<hr>\n\n<p>One other trick that may come in handy (but only in some languages) is the use of the When (or equivalent) keyword... In VB, this looks like</p>\n\n<pre><code>Try\n ' // Do some work '\nCatch ex As Exception When CallMethodToInspectException(ex)\n\nEnd Try\n</code></pre>\n\n<p>The trick here is that the When expression is evaluated <em>before the callstack is unwound to the Catch block</em>. So if you're using the debugger, you can set a breakpoint that expression, and if you look at the callstack window (Debug | Windows | Callstack), you can see and navigate to line that triggered the exception. </p>\n\n<p>(You can choose to return false from the CallMethodToInspectException, so the Catch block will be ignored and the runtime will continue the search through the stack for an appropriate Catch block - which can allow for logging that doesn't affect behavior, and with less overhead than a catch and re-throw)</p>\n\n<hr>\n\n<p>If you were just interested in non-interactive logging, then assuming you've got a Debug build (or to some extent as you have do deal with optimisation issues, Release build with PDBs) you could get most of the info needed to track down the bug from the Exception ToString, with the included stack-trace-with-line-number.</p>\n\n<p>If however line number wasn't enough, you can get the column number too (so pretty much, the particular local or expression that is null) by extracting the StackTrace for the exception (using either the above technique, or just in the catch block itself):</p>\n\n<pre><code>int colNumber = new System.Diagnostics.StackTrace(ex, true).GetFrame(0).GetFileColumnNumber();\n</code></pre>\n\n<hr>\n\n<p>While I've not seen what it does for NullReference or other runtime generated exceptions, may also be interested in looking at <a href=\"http://www.red-gate.com/products/Exception_Hunter/index.htm\" rel=\"noreferrer\">Exception Hunter</a> as a static analysis tool.</p>\n"
},
{
"answer_id": 316983,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 0,
"selected": false,
"text": "<p>With regards to setting Visual Studio to catch the exception (as suggested <a href=\"https://stackoverflow.com/questions/115573/detecting-what-the-target-object-is-when-nullreferenceexception-is-thrown#116424\">here</a>), DON'T FORGET to remove this option once you've fixed the problem. I've just wasted half an hour trying to work out why my application was hanging deep in some part of System.Windows.Forms....</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16391/"
]
| I'm sure we all have received the wonderfully vague "Object reference not set to instance of an Object" exception at some time or another. Identifying the object that is the problem is often a tedious task of setting breakpoints and inspecting all members in each statement.
Does anyone have any tricks to easily and efficiently identify the object that causes the exception, either via programmatical means or otherwise?
--edit
It seems I was vague like the exception =). The point is to \_not have to debug the app to find the errant object. The compiler/runtime does know that the object has been allocated/declared, and that the object has not yet been instantiated. Is there a way to extract / identify those details in a caught exception
@ W. Craig Trader
Your explanation that it is a result of a design problem is probably the best answer I could get. I am fairly compulsive with defensive coding and have managed to get rid of most of these errors after fixing my habits over time. The remaining ones just ***tweak*** me to no end, and lead me to posting this question to the community.
Thanks for everyone's suggestions. | At the point where the NRE is thrown, there is no target object -- that's the point of the exception. The most you can hope for is to trap the file and line number where the exception occurred. If you're having problems identifying which object reference is causing the problem, then you might want to rethink your coding standards, because it sounds like you're doing too much on one line of code.
A better solution to this sort of problem is [Design by Contract](http://en.wikipedia.org/wiki/Design_By_Contract), either through builtin language constructs, or via a library. DbC would suggest pre-checking any incoming arguments for a method for out-of-range data (ie: Null) and throwing exceptions because the method won't work with bad data.
**[Edit to match question edit:]**
I think the NRE description is misleading you. The problem that the CLR is having is that it was asked to dereference an object reference, when the object reference is Null. Take this example program:
```
public class NullPointerExample {
public static void Main()
{
Object foo;
System.Console.WriteLine( foo.ToString() );
}
}
```
When you run this, it's going to throw an NRE on line 5, when it tried to evaluate the ToString() method on foo. There are no objects to debug, only an uninitialized object reference (foo). There's a class and a method, but no object.
---
Re: Chris Marasti-Georg's [answer](https://stackoverflow.com/questions/115573/detecting-what-the-target-object-is-when-nullreferenceexception-is-thrown#115619):
You should never throw NRE yourself -- that's a system exception with a specific meaning: the CLR (or JVM) has attempted to evaluate an object reference that wasn't initialized. If you pre-check an object reference, then either throw some sort of invalid argument exception or an application-specific exception, but not NRE, because you'll only confuse the next programmer who has to maintain your app. |
115,643 | <p>PowerShell is definitely in the category of dynamic languages, but would it be considered strongly typed? </p>
| [
{
"answer_id": 115676,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 3,
"selected": false,
"text": "<p>It can be if you need it to be.</p>\n\n<p>Like so:</p>\n\n<pre><code>[1] » [int]$x = 5\n[2] » $x\n5\n[3] » $x = 'haha'\nCannot convert value \"haha\" to type \"System.Int32\". Error: \"Input string was not in a correct format.\"\nAt line:1 char:3\n+ $x <<<< = 'haha'\n[4] »\n</code></pre>\n\n<p>Use the [type] notation to indicate if you care about variables being strongly typed.</p>\n\n<p><strong>EDIT</strong>:</p>\n\n<p>As <a href=\"https://stackoverflow.com/questions/115643/is-powershell-a-strongly-typed-language#115715\">edg</a> pointed out, this doesn't prevent PowerShell from interpreting \"5\" as an integer, when executing (5 + \"5\"). I dug a little more, and according to Bruce Payette in <a href=\"https://rads.stackoverflow.com/amzn/click/com/1932394907\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Windows PowerShell in Action</a>, PowerShell is actually a \"type-promiscuous language.\" So, I guess, my answer is \"sort of.\"</p>\n"
},
{
"answer_id": 115677,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 1,
"selected": false,
"text": "<p>Technically it is a strongly typed language.</p>\n\n<p>You can decline to declare types in the shell, allowing it to behave like a dynamic typed scripting language, but it will wrap weakly-typed objects in a wrapper of type \"PsObject\". By declaring objects using the \"New-Object\" syntax, objects are strongly typed and not wrappered.</p>\n\n<pre><code>$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters\n</code></pre>\n"
},
{
"answer_id": 115762,
"author": "Timothy Lee Russell",
"author_id": 12919,
"author_profile": "https://Stackoverflow.com/users/12919",
"pm_score": -1,
"selected": false,
"text": "<p>I retract my previous answer -- quoted below. I should have said something more nuanced like:</p>\n\n<p><strong>PowerShell has a strong type system with robust type inference and is dynamically typed.</strong></p>\n\n<p>It seems to me that there are several issues at work here, so the answers asking for a better definition of what was meant by a \"strongly-typed language\" were probably more wise in their approach to the question.</p>\n\n<p>Since PowerShell crosses many boundaries, the answer to where PowerShell lies probably exists in a Venn diagram consisting of the following areas:</p>\n\n<ul>\n<li>Static vs. dynamic type checking</li>\n<li>Strong vs. weak typing</li>\n<li>Safe vs. unsafe typing</li>\n<li>Explicit vs. implicit declaration and inference</li>\n<li>Structural vs. nominative type systems</li>\n</ul>\n\n<blockquote>\n <blockquote>\n <p>\"PowerShell is a strongly typed language.</p>\n \n <p>However, it only requires you to declare the type where there is ambiguity.</p>\n \n <p>If it is able to infer a type, it does not require you to specify it.\"</p>\n </blockquote>\n</blockquote>\n"
},
{
"answer_id": 115787,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 1,
"selected": false,
"text": "<p>I think you will need to define what you mean by \"Strongly Typed\":</p>\n\n<blockquote>\n <p>In computer science and computer programming, the term strong typing is used to describe those situations where programming languages specify one or more restrictions on how operations involving values having different datatypes can be intermixed. The antonym is weak typing. However, these terms have been given such a wide variety of meanings over the short history of computing that it is often difficult to know, out of context, what an individual writer means when using them.</p>\n</blockquote>\n\n<p>--<a href=\"http://en.wikipedia.org/wiki/Strongly_typed\" rel=\"nofollow noreferrer\">Wikipedia</a></p>\n"
},
{
"answer_id": 115815,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 5,
"selected": false,
"text": "<p>There is a certain amount of confusion around the terminlogy. <a href=\"http://eli.thegreenplace.net/2006/11/25/a-taxonomy-of-typing-systems/\" rel=\"noreferrer\">This article</a> explains a useful taxonomy of type systems.</p>\n\n<p>PowerShell is dynamically, implicit typed:</p>\n\n<pre><code>> $x=100\n> $x=dir\n</code></pre>\n\n<p>No type errors - a variable can change its type at runtime. This is like <a href=\"http://en.wikipedia.org/wiki/Python_%28programming_language%29\" rel=\"noreferrer\">Python</a>, <a href=\"http://en.wikipedia.org/wiki/Perl\" rel=\"noreferrer\">Perl</a>, <a href=\"http://en.wikipedia.org/wiki/JavaScript\" rel=\"noreferrer\">JavaScript</a> but different from <a href=\"http://en.wikipedia.org/wiki/C%2B%2B\" rel=\"noreferrer\">C++</a>, <a href=\"http://en.wikipedia.org/wiki/Java_%28programming_language%29\" rel=\"noreferrer\">Java</a>, <a href=\"http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29\" rel=\"noreferrer\">C#</a>, etc.</p>\n\n<p>However:</p>\n\n<pre><code>> [int]$x = 100\n> $x = dir\nCannot convert \"scripts-2.5\" to \"System.Int32\".\n</code></pre>\n\n<p>So it also supports <em>explicit</em> typing of variables if you want. However, the type checking is done at runtime rather than compile time, so it's not <em>statically</em> typed.</p>\n\n<p>I have seen some say that PowerShell uses <em>type inference</em> (because you don't have to declare the type of a variable), but I think that is the wrong words. Type inference is a feature of systems that does type-checking at compile time (like \"<code>var</code>\" in C#). PowerShell only checks types at runtime, so it can check the actual value rather than do inference.</p>\n\n<p>However, there is some amount of automatic type-conversion going on:</p>\n\n<pre><code>> [int]$a = 1\n> [string]$b = $a\n> $b\n1\n> $b.GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n</code></pre>\n\n<p>So <em>some</em> types are converted on the fly. This will by most definitions make PowerShell a <em>weakly typed</em> language. It is certainly more weak than e.g. Python which (almost?) never convert types on the fly. But probably not at weak as Perl which will convert almost anything as needed.</p>\n"
},
{
"answer_id": 115914,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 1,
"selected": false,
"text": "<p>I think looking at the adding a String to an Int example further would provide more grist for the discussion mill. What is considered to be dynamic type casting? Someone in one of the comments said that in this case:</p>\n\n<pre><code>4 + \"4\"\n</code></pre>\n\n<p>The <code>\"4\"</code> <strong>becomes an Int32</strong>. I don't believe that is the case at all. I believe instead that an intermediate step happens where the command is changed to:</p>\n\n<pre><code>4 + [System.Convert]::ToInt32(\"4\")\n</code></pre>\n\n<p>Note that this means that <code>\"4\"</code> stays a String through the entire process. To demonstrate this, consider this example:</p>\n\n<pre><code>19# $foo = \"4\"\n20# $foo.GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n\n\n21# 4 + $foo\n8\n22# $foo.GetType()\n\nIsPublic IsSerial Name BaseType\n-------- -------- ---- --------\nTrue True String System.Object\n</code></pre>\n"
},
{
"answer_id": 2636714,
"author": "The Old Hag",
"author_id": 316401,
"author_profile": "https://Stackoverflow.com/users/316401",
"pm_score": 1,
"selected": false,
"text": "<p>PowerShell is dynamically typed, plain and simple. It is described as such by its creator, Bruce Payette.</p>\n\n<p>Additionally, if anyone has taken a basic programming language theory class they would know this. Just because there is a type annotation system doesn't mean it is strongly typed. Even the type annotated variables behave dynamically during a cast. Any language that allows you to assign a string to a variable and print it out and then assign a number to the same variable and do calculations with it is dynamically typed.</p>\n\n<p>Additionally, PowerShell is dynamically scoped (if anyone here knows what that means).</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3289/"
]
| PowerShell is definitely in the category of dynamic languages, but would it be considered strongly typed? | There is a certain amount of confusion around the terminlogy. [This article](http://eli.thegreenplace.net/2006/11/25/a-taxonomy-of-typing-systems/) explains a useful taxonomy of type systems.
PowerShell is dynamically, implicit typed:
```
> $x=100
> $x=dir
```
No type errors - a variable can change its type at runtime. This is like [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), [Perl](http://en.wikipedia.org/wiki/Perl), [JavaScript](http://en.wikipedia.org/wiki/JavaScript) but different from [C++](http://en.wikipedia.org/wiki/C%2B%2B), [Java](http://en.wikipedia.org/wiki/Java_%28programming_language%29), [C#](http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29), etc.
However:
```
> [int]$x = 100
> $x = dir
Cannot convert "scripts-2.5" to "System.Int32".
```
So it also supports *explicit* typing of variables if you want. However, the type checking is done at runtime rather than compile time, so it's not *statically* typed.
I have seen some say that PowerShell uses *type inference* (because you don't have to declare the type of a variable), but I think that is the wrong words. Type inference is a feature of systems that does type-checking at compile time (like "`var`" in C#). PowerShell only checks types at runtime, so it can check the actual value rather than do inference.
However, there is some amount of automatic type-conversion going on:
```
> [int]$a = 1
> [string]$b = $a
> $b
1
> $b.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
```
So *some* types are converted on the fly. This will by most definitions make PowerShell a *weakly typed* language. It is certainly more weak than e.g. Python which (almost?) never convert types on the fly. But probably not at weak as Perl which will convert almost anything as needed. |
115,649 | <p>We have various servers that have many directories shared. It's easy enough to look at the share browser to see what the "top level" shares are, but underneath is a jumbled mess of custom permissions, none of which is documented.</p>
<p>I'd like to enumerate all the shares on the domain (definitely all the 'servers', local PCs would be nice) and then recurse down each one and report any deviation from the parent. If the child has the same permissions, no need to report that back.</p>
<p>I'd prefer a simple script-y solution to writing a big C# app, but any method that works will do (even existing software).</p>
<p>For example, I'd like to get:</p>
<pre><code>SERVER1\
\-- C: (EVERYONE: Total control, ADMINs, etc. etc.)
\-- (skip anything that is not the same as above)
\-- SuperSecretStuff (Everyone: NO access; Bob: Read access)
SERVER2\
\-- Stuff (some people)
</code></pre>
<p>etc.</p>
| [
{
"answer_id": 115689,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 2,
"selected": true,
"text": "<p>According to the JEdit <a href=\"http://jedit.org/index.php?page=features\" rel=\"nofollow noreferrer\">features page</a> it already supports Objective C.</p>\n"
},
{
"answer_id": 365420,
"author": "Ross Rogers",
"author_id": 20712,
"author_profile": "https://Stackoverflow.com/users/20712",
"pm_score": 0,
"selected": false,
"text": "<p>One of my favorite things about JEdit is how easy it is to define a new syntax highlighting mode. I work in a land in which every fool wants to create his own custom configuration file language and I've gotten to where I can create a new approximate syntax highlighting mode in about 5 minutes. I start by copying a mode that is similar to the new language I wanted to create and then iteratively refining the edit mode as I learn more parts of the language. I did this with Specman ( a hardware verification language ) as I was going through the intro course.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2590/"
]
| We have various servers that have many directories shared. It's easy enough to look at the share browser to see what the "top level" shares are, but underneath is a jumbled mess of custom permissions, none of which is documented.
I'd like to enumerate all the shares on the domain (definitely all the 'servers', local PCs would be nice) and then recurse down each one and report any deviation from the parent. If the child has the same permissions, no need to report that back.
I'd prefer a simple script-y solution to writing a big C# app, but any method that works will do (even existing software).
For example, I'd like to get:
```
SERVER1\
\-- C: (EVERYONE: Total control, ADMINs, etc. etc.)
\-- (skip anything that is not the same as above)
\-- SuperSecretStuff (Everyone: NO access; Bob: Read access)
SERVER2\
\-- Stuff (some people)
```
etc. | According to the JEdit [features page](http://jedit.org/index.php?page=features) it already supports Objective C. |
115,658 | <p>In my C# application I am using the Microsoft Jet OLEDB data provider to read a CSV file. The connection string looks like this:</p>
<pre><code>Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\Data;Extended Properties="text;HDR=Yes;FMT=Delimited
</code></pre>
<p>I open an ADO.NET OleDbConnection using that connection string and select all the rows from the CSV file with the command:</p>
<pre><code>select * from Data.csv
</code></pre>
<p>When I open an OleDbDataReader and examine the data types of the columns it returns, I find that something in the stack has tried to guess at the data types based on the first row of data in the file. For example, suppose the CSV file contains:</p>
<pre><code>House,Street,Town
123,Fake Street,Springfield
12a,Evergreen Terrace,Springfield
</code></pre>
<p>Calling the OleDbDataReader.GetDataTypeName method for the House column will reveal that the column has been given the data type "DBTYPE_I4", so all values read from it are interpreted as integers. My problem is that House should be a string - when I try to read the House value from the second row, the OleDbDataReader returns null.</p>
<p>How can I tell either the Jet database provider or the OleDbDataReader to interpret a column as strings instead of numbers?</p>
| [
{
"answer_id": 115684,
"author": "MarcE",
"author_id": 7262,
"author_profile": "https://Stackoverflow.com/users/7262",
"pm_score": 4,
"selected": true,
"text": "<p>There's a schema file you can create that would tell ADO.NET how to interpret the CSV - in effect giving it a structure.</p>\n\n<p>Try this: <a href=\"https://web.archive.org/web/20081009034412/http://www.aspdotnetcodes.com/Importing_CSV_Database_Schema.ini.aspx\" rel=\"nofollow noreferrer\">http://www.aspdotnetcodes.com/Importing_CSV_Database_Schema.ini.aspx</a></p>\n\n<p>Or the most recent <a href=\"https://learn.microsoft.com/en-us/sql/odbc/microsoft/schema-ini-file-text-file-driver?view=sql-server-2017\" rel=\"nofollow noreferrer\">MS Documentation</a></p>\n"
},
{
"answer_id": 116111,
"author": "Rory MacLeod",
"author_id": 1016,
"author_profile": "https://Stackoverflow.com/users/1016",
"pm_score": 4,
"selected": false,
"text": "<p>To expand on Marc's answer, I need to create a text file called Schema.ini and put it in the same directory as the CSV file. As well as column types, this file can specify the file format, date time format, regional settings, and the column names if they're not included in the file. </p>\n\n<p>To make the example I gave in the question work, the Schema file should look like this:</p>\n\n<pre><code>[Data.csv]\nColNameHeader=True\nCol1=House Text\nCol2=Street Text\nCol3=Town Text\n</code></pre>\n\n<p>I could also try this to make the data provider examine all the rows in the file before it tries to guess the data types:</p>\n\n<pre><code>[Data.csv]\nColNameHeader=true\nMaxScanRows=0\n</code></pre>\n\n<p>In real life, my application imports data from files with dynamic names, so I have to create a Schema.ini file on the fly and write it to the same directory as the CSV file before I open my connection.</p>\n\n<p>Further details can be found here - <a href=\"http://msdn.microsoft.com/en-us/library/ms709353(VS.85).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms709353(VS.85).aspx</a> - or by searching the MSDN Library for \"Schema.ini file\".</p>\n"
},
{
"answer_id": 7658003,
"author": "Akhil",
"author_id": 574328,
"author_profile": "https://Stackoverflow.com/users/574328",
"pm_score": 3,
"selected": false,
"text": "<p>Please check</p>\n\n<p><a href=\"http://kbcsv.codeplex.com/\" rel=\"nofollow\">http://kbcsv.codeplex.com/</a></p>\n\n<pre><code>using (var reader = new CsvReader(\"data.csv\"))\n{\n reader.ReadHeaderRecord();\n foreach (var record in reader.DataRecords)\n {\n var name = record[\"Name\"];\n var age = record[\"Age\"];\n }\n}\n</code></pre>\n"
},
{
"answer_id": 47577138,
"author": "Jon",
"author_id": 2350083,
"author_profile": "https://Stackoverflow.com/users/2350083",
"pm_score": 0,
"selected": false,
"text": "<p>You need to tell the driver to scan all rows to determine the schema. Otherwise if the first few rows are numeric and the rest are alphanumeric, the alphanumeric cells will be blank.</p>\n\n<p>Like <a href=\"https://stackoverflow.com/a/116111/2350083\">Rory</a>, I found that I needed to create a schema.ini file dynamically because there is no way to programatically tell the driver to scan all rows. (this is not the case for excel files)</p>\n\n<p>You must have <code>MaxScanRows=0</code> in your schema.ini</p>\n\n<p>Here's a code example:</p>\n\n<pre><code> public static DataTable GetDataFromCsvFile(string filePath, bool isFirstRowHeader = true)\n {\n if (!File.Exists(filePath))\n {\n throw new FileNotFoundException(\"The path: \" + filePath + \" doesn't exist!\");\n }\n\n if (!(Path.GetExtension(filePath) ?? string.Empty).ToUpper().Equals(\".CSV\"))\n {\n throw new ArgumentException(\"Only CSV files are supported\");\n }\n var pathOnly = Path.GetDirectoryName(filePath);\n var filename = Path.GetFileName(filePath);\n var schemaIni =\n $\"[{filename}]{Environment.NewLine}\" +\n $\"Format=CSVDelimited{Environment.NewLine}\" +\n $\"ColNameHeader={(isFirstRowHeader ? \"True\" : \"False\")}{Environment.NewLine}\" +\n $\"MaxScanRows=0{Environment.NewLine}\" +\n $\" ; scan all rows for data type{Environment.NewLine}\" +\n $\" ; This file was automatically generated\";\n var schemaFile = pathOnly != null ? Path.Combine(pathOnly, \"schema.ini\") : \"schema.ini\";\n File.WriteAllText(schemaFile, schemaIni);\n\n try\n {\n var sqlCommand = $@\"SELECT * FROM [{filename}]\";\n\n var oleDbConnString =\n $\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={pathOnly};Extended Properties=\\\"Text;HDR={(isFirstRowHeader ? \"Yes\" : \"No\")}\\\"\";\n\n using (var oleDbConnection = new OleDbConnection(oleDbConnString))\n using (var adapter = new OleDbDataAdapter(sqlCommand, oleDbConnection))\n using (var dataTable = new DataTable())\n {\n adapter.FillSchema(dataTable, SchemaType.Source);\n adapter.Fill(dataTable);\n return dataTable;\n }\n }\n finally\n {\n if (File.Exists(schemaFile))\n {\n File.Delete(schemaFile);\n }\n }\n }\n</code></pre>\n\n<p>You'll need to do some modification if you are running this on the same directory in multiple threads at the same time.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1016/"
]
| In my C# application I am using the Microsoft Jet OLEDB data provider to read a CSV file. The connection string looks like this:
```
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\Data;Extended Properties="text;HDR=Yes;FMT=Delimited
```
I open an ADO.NET OleDbConnection using that connection string and select all the rows from the CSV file with the command:
```
select * from Data.csv
```
When I open an OleDbDataReader and examine the data types of the columns it returns, I find that something in the stack has tried to guess at the data types based on the first row of data in the file. For example, suppose the CSV file contains:
```
House,Street,Town
123,Fake Street,Springfield
12a,Evergreen Terrace,Springfield
```
Calling the OleDbDataReader.GetDataTypeName method for the House column will reveal that the column has been given the data type "DBTYPE\_I4", so all values read from it are interpreted as integers. My problem is that House should be a string - when I try to read the House value from the second row, the OleDbDataReader returns null.
How can I tell either the Jet database provider or the OleDbDataReader to interpret a column as strings instead of numbers? | There's a schema file you can create that would tell ADO.NET how to interpret the CSV - in effect giving it a structure.
Try this: [http://www.aspdotnetcodes.com/Importing\_CSV\_Database\_Schema.ini.aspx](https://web.archive.org/web/20081009034412/http://www.aspdotnetcodes.com/Importing_CSV_Database_Schema.ini.aspx)
Or the most recent [MS Documentation](https://learn.microsoft.com/en-us/sql/odbc/microsoft/schema-ini-file-text-file-driver?view=sql-server-2017) |
115,665 | <p>I'm using the <code>cacheCounter</code> in <code>CakePHP</code>, which increments a counter for related fields.</p>
<p>Example, I have a Person table a Source table. Person.source_id maps to a row in the Source table. Each person has one Source, and each Source has none or many Person rows.</p>
<p><code>cacheCounter</code> is working great when I change the value of a source on a person. It increments <code>Source.Person_Count</code>. Cool.</p>
<p>But when it increments, it adds it to the destination source for a person, but doesn't remove it from the old value. I tried <code>updateCacheControl()</code> in <code>afterSave</code>, but that didn't do anything.</p>
<p>So then I wrote some code in my model for <code>afterSave</code> that would subtract the source source_id, but it always did this even when I wasn't even changing the <code>source_id</code>. (So the count went negative).</p>
<p>My question: Is there a way to tell if a field was changed in the model in <code>CakePHP</code>?</p>
| [
{
"answer_id": 120009,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": -1,
"selected": false,
"text": "<p>See if the \"save\" uses some sort of DBAL call that returns \"affected rows\", usually this is how you can judge if the last query changed data, or if it didn't. Because if it didn't, the affected rows after an UPDATE-statement are 0.</p>\n"
},
{
"answer_id": 123403,
"author": "neilcrookes",
"author_id": 9968,
"author_profile": "https://Stackoverflow.com/users/9968",
"pm_score": 0,
"selected": false,
"text": "<p>Edits happen infrequently, so another select before you do the update is no big deal, so, fetch the record before you save, save it, compare the data submitted in the edit form with the data you fetched from the db before you saved it, if its different, do something.</p>\n"
},
{
"answer_id": 123485,
"author": "neilcrookes",
"author_id": 9968,
"author_profile": "https://Stackoverflow.com/users/9968",
"pm_score": 0,
"selected": false,
"text": "<p>In the edit view, include another hidden field for the field you want to monitor but suffix the field name with something like \"_prev\" and set the value to the current value of the field you want to monitor. Then in your controller's edit action, do something if the two fields are not equal. e.g.</p>\n\n<pre><code>echo $form->input('field_to_monitor');\necho $form->hidden('field_to_monitor_prev', array('value'=>$form->value('field_to_monitor')));\n</code></pre>\n"
},
{
"answer_id": 138574,
"author": "Alexander Morland",
"author_id": 4013,
"author_profile": "https://Stackoverflow.com/users/4013",
"pm_score": 5,
"selected": true,
"text": "<p>To monitor changes in a field, you can use this logic in your model with no changes elsewhere required:</p>\n\n<pre><code>function beforeSave() {\n $this->recursive = -1;\n $this->old = $this->find(array($this->primaryKey => $this->id));\n if ($this->old){\n $changed_fields = array();\n foreach ($this->data[$this->alias] as $key =>$value) {\n if ($this->old[$this->alias][$key] != $value) {\n $changed_fields[] = $key;\n }\n }\n }\n // $changed_fields is an array of fields that changed\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 7408274,
"author": "Sajib Hassan",
"author_id": 943382,
"author_profile": "https://Stackoverflow.com/users/943382",
"pm_score": -1,
"selected": false,
"text": "<p>You can call getAffectedRows() on any model class.</p>\n\n<p>From class Model :</p>\n\n<pre><code>/**\n * Returns the number of rows affected by the last query\n *\n * @return int Number of rows\n * @access public\n */\n function getAffectedRows() {\n $db =& ConnectionManager::getDataSource($this->useDbConfig);\n return $db->lastAffected();\n }\n</code></pre>\n"
},
{
"answer_id": 12103681,
"author": "Vins",
"author_id": 733087,
"author_profile": "https://Stackoverflow.com/users/733087",
"pm_score": 3,
"selected": false,
"text": "<p>With reference to <strong><em>Alexander Morland</em></strong> Answer.</p>\n\n<p>How about this instead of looping through it in before filter.</p>\n\n<pre><code>$result = array_diff_assoc($this->old[$this->alias],$this->data[$this->alias]);\n</code></pre>\n\n<p>You will get key as well as value also.</p>\n"
},
{
"answer_id": 63474054,
"author": "Sebastian Sperandio",
"author_id": 1934672,
"author_profile": "https://Stackoverflow.com/users/1934672",
"pm_score": 0,
"selected": false,
"text": "<p>You could use ->isDirty() in the entity to see if a field has been modified.</p>\n<pre><code>// Prior to 3.5 use dirty()\n$article->isDirty('title');\n</code></pre>\n<p>check the doc: <a href=\"https://book.cakephp.org/3/en/orm/entities.html#checking-if-an-entity-has-been-modified\" rel=\"nofollow noreferrer\">https://book.cakephp.org/3/en/orm/entities.html#checking-if-an-entity-has-been-modified</a></p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43/"
]
| I'm using the `cacheCounter` in `CakePHP`, which increments a counter for related fields.
Example, I have a Person table a Source table. Person.source\_id maps to a row in the Source table. Each person has one Source, and each Source has none or many Person rows.
`cacheCounter` is working great when I change the value of a source on a person. It increments `Source.Person_Count`. Cool.
But when it increments, it adds it to the destination source for a person, but doesn't remove it from the old value. I tried `updateCacheControl()` in `afterSave`, but that didn't do anything.
So then I wrote some code in my model for `afterSave` that would subtract the source source\_id, but it always did this even when I wasn't even changing the `source_id`. (So the count went negative).
My question: Is there a way to tell if a field was changed in the model in `CakePHP`? | To monitor changes in a field, you can use this logic in your model with no changes elsewhere required:
```
function beforeSave() {
$this->recursive = -1;
$this->old = $this->find(array($this->primaryKey => $this->id));
if ($this->old){
$changed_fields = array();
foreach ($this->data[$this->alias] as $key =>$value) {
if ($this->old[$this->alias][$key] != $value) {
$changed_fields[] = $key;
}
}
}
// $changed_fields is an array of fields that changed
return true;
}
``` |
115,685 | <p>I once wrote this line in a Java class. This compiled fine in Eclipse but not on the command line. </p>
<p>This is on</p>
<ul>
<li>Eclipse 3.3</li>
<li>JDK 1.5</li>
<li>Windows XP Professional</li>
</ul>
<p>Any clues?</p>
<p>Error given on the command line is:</p>
<pre><code>Icons.java:16: code too large
public static final byte[] compileIcon = { 71, 73, 70, 56, 57, 97, 50,
^
</code></pre>
<p>The code line in question is:</p>
<pre><code>public static final byte[] compileIcon = { 71, 73, 70, 56, 57, 97, 50,
0, 50, 0, -9, 0, 0, -1, -1, -1, -24, -72, -72, -24, -64, -64,
-8, -16, -24, -8, -24, -24, -16, -24, -32, -1, -8, -8, 48, 72,
-72, -24, -80, -80, 72, 96, -40, -24, -24, -8, 56, 88, -56,
-24, -40, -48, -24, -48, -64, 56, 80, -64, 64, 88, -48, -56,
-64, -64, -16, -24, -24, -32, -40, -40, -32, -88, -96, -72,
-72, -72, -48, -56, -56, -24, -32, -32, -8, -8, -1, -24, -40,
-56, -64, -72, -72, -16, -32, -40, 48, 80, -72, -40, -96, -104,
-40, -96, -96, -56, -104, -104, 120, 88, -104, -40, -64, -80,
-32, -88, -88, -32, -56, -72, -72, -80, -80, -32, -80, -88,
104, -96, -1, -40, -40, -40, -64, -104, -104, -32, -56, -64,
-112, 104, 112, -48, -104, -112, -128, -112, -24, -72, -80,
-88, -8, -8, -8, -64, -112, -120, 72, 104, -40, 120, 96, -96,
-112, -96, -24, -112, -120, -72, -40, -88, -88, -48, -64, -72,
-32, -72, -80, -48, -72, -88, -88, -72, -24, 64, 88, -56, -120,
96, 104, 88, -128, -72, 48, 56, 56, 104, 104, 120, 112, -120,
-16, -128, 104, -88, -40, -48, -48, 88, -120, -24, 104, 88,
-104, -40, -56, -72, -128, 112, -88, -128, 96, -88, -104, -88,
-24, -96, -120, 120, -88, -128, -80, -56, -56, -64, 96, 120,
-8, -96, -128, -88, -80, -96, -104, -32, -72, -72, 96, 104,
112, 96, -104, -8, -72, -112, -112, -64, -72, -80, 64, 64, 72,
-128, -120, -96, -128, 88, 88, -56, -72, -80, 88, 96, 120, -72,
-128, 112, 72, 112, -40, 96, 120, -56, 88, -112, -16, 64, 104,
-48, -64, -80, -88, -88, -120, -80, 88, 88, 96, -56, -96, -120,
-40, -56, -64, 96, 104, 120, -120, -80, -24, -104, -88, -40,
-48, -72, -80, -64, -56, -16, -88, -112, -128, -32, -48, -56,
-24, -16, -8, -64, -120, 120, -96, -96, -88, 80, -128, -24,
-56, -72, -88, -96, 120, 88, -72, -112, 120, -64, -104, 120,
-48, -56, -64, -120, -104, -32, -104, 120, -80, -96, -112,
-120, 56, 88, -64, -128, 96, 64, 88, 120, -40, -80, -104, -120,
-104, -128, 104, 96, -104, -24, -72, -120, -128, 56, 96, -56,
-128, 112, 104, -48, -88, -112, 96, 96, 104, -104, -88, -72,
-40, -88, -96, -72, -88, -96, -120, 120, 104, -80, -88, -96,
72, 72, 80, -120, 88, 96, 120, -120, -24, 96, -104, -16, 104,
80, 48, -56, -80, -96, -56, -88, -104, -104, 120, -88, -88,
120, 104, -72, -120, -120, -24, -32, -40, 112, 88, -104, 120,
96, -104, -32, -32, -32, -96, 96, 96, 80, 80, 88, 64, 88, 120,
72, 120, -40, 72, 88, 112, -88, -96, -104, -56, -80, -88, -72,
-88, -104, -56, -64, -72, -80, -120, 104, -80, -120, -80, -112,
112, -88, 120, 112, 112, 112, -96, -24, -120, -120, -64, -120,
120, -80, 64, 96, -128, 96, 64, 64, 96, -128, -32, 80, 112,
-24, 112, -120, -24, 104, -96, -8, 96, 120, -16, -88, 120, 120,
-72, -56, -16, -128, -128, -128, -104, -120, -72, -64, -96,
-120, -32, -64, -64, -40, -48, -56, -64, -88, -96, -64, -104,
-72, -96, -88, -24, -104, -96, -40, -96, -128, 96, -128, -128,
-96, 104, 88, 80, 112, -88, -8, -64, -104, -80, -96, -120, 112,
96, 120, -32, 56, 80, -72, -104, -88, -32, 104, -128, -24, -56,
-88, -120, -80, -72, -8, -96, -128, -128, -64, -128, 96, -72,
-96, -120, 72, 104, -32, -96, 96, 64, -72, -96, -112, -32, -40,
-48, -64, -88, -112, -88, -128, 96, -88, -128, -88, -64, -64,
-32, -128, -96, -32, -88, -104, -112, 32, 32, 64, -120, 104,
-88, 120, -120, -16, -104, 120, -72, -24, -48, -56, -96, -96,
-96, -64, 96, 96, 96, 64, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 0, 0, 0, 0,
50, 0, 50, 0, 0, 8, -1, 0, 1, 8, 28, 72, -80, -96, -63, -125,
8, 19, 42, 92, -120, 112, 0, 3, 6, 12, 23, 6, -104, 72, -79,
-94, -59, -117, 19, 39, -124, 64, -128, -128, 3, -121, 9, 19,
48, -118, -92, 24, 81, 33, -118, 8, 40, 7, -88, 84, -55, -64,
12, 6, 6, 45, 74, -54, 52, 8, 73, -60, 24, 22, 25, 92, 73, 40,
64, -96, -64, 74, -121, 24, 94, -58, -100, 25, -79, -59, 47,
17, 3, 52, -120, 88, -125, 105, 73, 6, 42, -102, -68, 96, -16,
-71, 18, 3, -118, 6, 13, 14, -114, -36, 26, -64, 69, 7, 18, 28,
-61, -110, -32, -32, -62, -54, -94, 72, -61, -48, -88, -40, 72,
34, -60, 4, 21, 23, -119, 14, -92, 80, -58, 6, -108, 10, 18,
44, 68, -8, 57, -96, -128, 16, 98, 70, -24, -48, 97, -45, 6, 4,
6, 16, 67, -27, 18, 52, -79, -52, -89, -46, 49, -105, -74, -32,
109, -45, -85, -63, -49, 2, 13, 88, -51, -62, 5, 40, 80, 31,
91, 103, 20, 11, -116, 32, -124, -81, -54, 2, 40, -58, -40,
-103, -59, -122, 13, 43, 51, 12, 122, 106, 96, -48, 0, -105,
40, 29, 106, 32, 17, 20, -64, -69, -73, -17, -33, -68, 25, 113,
13, 80, -125, 44, -102, 72, 108, -84, -88, 80, 49, -127, -61,
-94, 28, -97, -108, -4, -98, -103, 102, 9, -127, -21, -40, -81,
23, -32, 35, -126, 39, -10, 2, 32, -116, 29, -1, 27, -74, 37,
-40, 29, 60, 90, -60, -120, -90, 0, -122, -118, -23, -107, 54,
-36, -72, -15, 2, 66, -61, -23, -39, 24, -8, -36, -7, -108,
-27, -128, 44, -59, -112, -16, -64, 67, 3, -39, 21, 72, 0, 6,
34, 120, -31, -123, 124, 124, 52, 16, 84, 3, -119, -88, 82,
-62, 28, -2, 21, 4, -36, -123, -83, -92, -96, 97, 13, 20, 117,
112, 2, -121, 24, 77, -128, 6, 48, -64, 72, -93, -62, 31, 104,
-56, 48, 68, 16, 65, 112, 49, 29, 67, 82, 8, 24, 72, 118, 18,
84, 48, 66, 6, 63, 72, 96, 96, 1, 26, -128, 64, -97, 8, 50, 24,
114, -64, -112, -22, -51, -28, 7, 24, 77, 116, -15, 75, 1, 123,
53, 2, -63, 15, 22, 88, 0, 1, 5, 44, 72, 32, -127, 74, -78,
-47, -122, -62, 27, -90, -24, 49, -28, 1, 69, -106, -108, 76,
21, -99, 8, -127, -119, 29, -81, 60, 41, -63, 15, 16, -116, 80,
65, -114, 22, -44, 40, 72, 6, 111, 60, 4, 77, 3, 34, -124, 1,
-60, -105, 7, 40, 96, -31, -123, -68, 49, -111, 66, 30, 32,
102, -92, 66, 30, 86, 60, -47, -63, 12, 30, 42, 58, 67, 13, 51,
120, -32, 1, 35, 30, 112, 112, -62, 39, -114, -80, 24, -124,
116, 47, 30, 116, 6, 15, -120, 24, -104, 93, 3, -105, 44, -79,
12, 11, -103, -116, 112, 35, 20, 52, -96, 64, 3, 32, 91, -40,
-1, 114, 5, -97, 126, -106, 36, 5, 24, -106, -67, 103, 26, 3,
32, -68, -14, 10, 20, 44, 88, -78, -124, 37, 91, -124, -47,
-33, -105, 112, -56, -28, 7, -103, -70, -86, 116, -57, 29, 52,
80, 37, -101, 8, 54, 24, 99, -121, 17, 82, -108, -80, 0, -83,
7, 93, 56, 70, 14, 41, -96, -78, -107, 11, -117, -48, 97, -42,
12, 127, 32, 64, 66, 91, 19, -96, -88, -94, 35, -16, 110, 10,
-88, 65, 103, 76, -62, 67, 19, 114, -120, -102, 93, 49, 107,
-108, 65, -121, 29, -121, -36, 65, -116, 16, 24, -32, 121,
-125, 33, -70, 108, -96, 112, -97, 37, 5, -127, 100, 23, -128,
-4, 68, 65, 5, 123, -103, 102, -63, 24, 101, -20, 49, -51, 33,
-121, -40, 80, 65, 9, 122, 40, -84, 112, -78, 17, 73, 81, 69,
-110, -110, -28, -38, -105, 9, 84, -30, 69, 21, -106, 60, 106,
32, 68, 25, -127, -96, -96, -25, 6, 14, 56, -96, 112, -83, 90,
81, 116, 2, -72, 57, 16, 66, 8, 88, 28, 49, 26, 66, 8, 51, 60,
-15, -60, 9, 51, -128, -75, -82, 91, 19, 116, 96, -87, 12, 31,
84, 93, -75, 18, 91, 13, 100, -126, -67, 125, 72, 50, 72, 45,
63, 89, -112, 1, 5, 20, -104, 96, 65, 1, 38, -4, 48, 49, 4,
-82, 60, 84, 48, 13, -90, 92, -111, -13, -36, 60, 39, -44, 66,
40, 96, -12, -47, -59, 32, 81, -20, -1, -15, 19, 4, 18, 68, 80,
64, 5, 72, -80, 0, -127, 9, 17, 72, -112, 9, 20, -106, -48,
-48, -86, -79, 56, -49, 77, -14, 66, -76, -100, -68, 119, 20,
59, 44, -15, 19, -53, 20, 0, 30, 103, -101, 110, -66, 97, -122,
25, 52, 44, 33, -125, -74, 11, -92, -98, 115, -35, 90, -55, 1,
52, 33, 83, 76, 33, -118, 10, 97, 73, -70, 81, 7, 29, 44, -35,
1, -46, 29, 76, -22, 2, 7, 30, -84, 50, -60, 7, 48, 60, 114,
-11, 112, 0, -124, -95, 67, 21, -110, 96, -66, -61, 14, 12,
-84, 36, -27, 8, -99, -101, 80, -128, 5, 72, -36, -104, -55,
23, -92, 83, -95, -116, 19, 14, -92, 46, 62, -21, 8, 21, 1, 68,
9, -93, -124, -78, 3, 51, 59, -68, -84, 82, -30, 72, 84, 64, 1,
18, 121, 85, 0, -123, 32, -126, -80, -112, 6, -56, 11, -32, 32,
-2, -28, 10, -71, -64, 5, -80, 48, 7, 74, 56, -63, 16, 58, -40,
65, 45, -28, -16, 5, -108, 56, 16, 37, -112, -80, 17, 5, 70,
-16, 6, 87, 124, -127, 5, -98, 0, -126, 3, 30, -128, -125, 14,
-30, 64, 1, 2, 12, -95, 8, 67, 8, 0, -118, 108, -126, 8, 31,
-16, 1, 40, 100, -96, -120, 20, 76, 33, 18, 121, -104, 64, 88,
102, 24, 2, -78, 48, 66, 5, -101, -96, 26, 12, 118, -72, 67,
100, 12, 103, 34, 4, 89, 65, 18, -1, 72, -127, -125, 2, 30, 80,
7, -107, -24, -37, 22, 26, -15, -66, 2, 20, -96, 17, 12, 64,
65, 52, -30, -74, -128, 7, 88, -47, -118, -28, 99, -120, 2,
122, -112, -124, 36, -100, 34, 1, 14, -48, -126, 26, 74, -128,
-121, 80, 68, 33, 10, -127, -80, -127, 6, 98, -122, 1, 42, 120,
34, 11, 27, -72, -94, 21, 1, 56, 19, 50, 116, -47, -117, -89,
32, -59, 3, 28, 112, 5, 39, -108, 0, -119, 81, 16, -123, 17,
108, 96, 6, 42, -8, 65, 91, 15, 72, -128, 28, -77, -120, 16,
-116, -64, -30, 25, 113, -120, 100, 36, -101, -15, 8, 24, -84,
80, 6, 46, -116, 93, 36, -124, -9, 1, 34, 120, -46, -109, 71,
-8, 33, 73, 16, 66, -122, 21, -12, -32, -108, 61, 40, 5, 47,
18, 48, -121, 62, -2, 113, 18, 58, 112, -62, 6, 18, 64, -53,
90, 50, 82, 49, 10, 40, -62, 41, 11, -63, 75, 94, -68, 32, 117,
106, -16, -93, 30, 18, 89, -53, 4, -60, 64, 52, 10, 81, -128,
47, 86, -64, 76, 102, -106, 34, 23, 47, -48, -126, 22, 28, 80,
76, 90, -34, 82, 32, 6, -56, -90, 54, 69, 25, 0, 38, -64, -126,
11, 71, 8, -89, 56, -107, -96, 8, 31, -104, -45, 7, 68, -32, 2,
55, -127, 72, -108, 11, -112, -95, 8, 49, -120, -89, 60, 71,
-15, -126, 122, 38, -32, -102, -56, 60, -120, 2, 110, 80, 51,
-124, 126, -58, -94, 8, -62, -88, -25, 49, -13, 41, 23, 5,
-112, -31, 6, 8, 93, 65, 64, -15, -39, -56, 117, 98, -124, 9,
51, -72, -59, 45, 56, -95, 78, -121, 6, -128, -96, 5, -39, 39,
67, 49, -54, -47, -114, 122, -44, 32, 1, 1, 0, 59 };
</code></pre>
| [
{
"answer_id": 115693,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 0,
"selected": false,
"text": "<p>Hard to say from what's provided, but guesses are</p>\n\n<ol>\n<li>Different JVM in Eclipse than command line.</li>\n<li>Bad classpath settings in command line.</li>\n</ol>\n\n<p>What are the compile errors?</p>\n\n<p>Can you isolate the problem in a dummy class for demonstration?</p>\n"
},
{
"answer_id": 115722,
"author": "Alan",
"author_id": 17205,
"author_profile": "https://Stackoverflow.com/users/17205",
"pm_score": 2,
"selected": false,
"text": "<p>Hard to tell why you have command line compilation errors, but ...</p>\n\n<p>Since you have an awful lot of \"magic numbers\", there may be a better approach than hardcoding an array literal.</p>\n\n<p>Consider</p>\n\n<ul>\n<li>Using a static initializer block to initialize an List</li>\n<li>Reading an XML file that will have your numbers, and using your class that reads the XML to return the datatype you want (be it a List or byte[]</li>\n</ul>\n"
},
{
"answer_id": 115776,
"author": "Steve g",
"author_id": 12092,
"author_profile": "https://Stackoverflow.com/users/12092",
"pm_score": 2,
"selected": false,
"text": "<p>What you have seems to compile.</p>\n\n<p>If possible, I would suggest trying to embed the resource in the Jar and using \n ClassLoader.getResourceAsStream().</p>\n"
},
{
"answer_id": 115783,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>Providing the exact error message would help us to help you too...<br>\nAnd I wonder why you hard-code an image (icon) in the source, instead of using some form of resource.</p>\n"
},
{
"answer_id": 115812,
"author": "Andreas Bakurov",
"author_id": 7400,
"author_profile": "https://Stackoverflow.com/users/7400",
"pm_score": 0,
"selected": false,
"text": "<p>if you are on windows\nwrite</p>\n\n<blockquote>\n <p>set JAVA_HOME=C:\\Program Files.... path to JDK\n the path should be the jdk path not jre\n on my PC is C:\\Program Files\\Java\\jdk1.6.0_07</p>\n</blockquote>\n\n<p><strong>WARNING</strong> : THE PATH SHOULD NOT BE NOT SURROUNDED BY QUOTES (\") cmd's autocompletions puts them !</p>\n\n<p>on unix like systems use</p>\n\n<blockquote>\n <p>export JAVA_HOME=<em>PATH TO JDK</em> (quotes are tolerated)</p>\n</blockquote>\n"
},
{
"answer_id": 116184,
"author": "Kip",
"author_id": 18511,
"author_profile": "https://Stackoverflow.com/users/18511",
"pm_score": 3,
"selected": true,
"text": "<p>Taking from <a href=\"http://forums.sun.com/thread.jspa?threadID=747860&messageID=4278559\" rel=\"nofollow noreferrer\">this forum on Sun's support site</a>, no method can be more than 64 KB long:</p>\n\n<p>When you have code (pseudo) like the following...</p>\n\n<pre><code>class MyClass\n{\n private String[] s = { \"a\", \"b\", \"c\"}\n\n public MyClass()\n {\n }\n</code></pre>\n\n<p>The compiler ends up producing code that basically looks like the following.</p>\n\n<pre><code>class MyClass\n{\n private String[] s;\n\n private void FunnyName$Method()\n {\n s[0] = \"a\";\n s[1] = \"b\";\n s[2] = \"c\";\n }\n public MyClass()\n {\n FunnyName$Method();\n }\n</code></pre>\n\n<p>And as noted java limits all methods to 64k, even the ones the compiler creates.</p>\n\n<p>It may be that Eclipse is doing something sneaky to get around this, but I assure you this is still possible in Eclipse because I have seen the same error message. A better solution is to just read from a static file, like this:</p>\n\n<pre><code>public class Icons\n{\n public static final byte[] compileIcon;\n static\n {\n compileIcon = readFileToBytes(\"compileIcon.gif\");\n }\n //... (I assume there are several other icons)\n private static byte[] readFileToBytes(String filename)\n {\n try {\n File file = new File(filename);\n byte[] bytes = new byte[(int)file.length()];\n FileInputStream fin = new FileInputStream(file);\n fin.read(bytes);\n fin.close();\n }\n catch (Exception e) {\n e.printStackTrace();\n System.exit(1);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 155855,
"author": "Alvin",
"author_id": 23637,
"author_profile": "https://Stackoverflow.com/users/23637",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure your commandline and eclipse are using same version of Java compiler and same compile setting? To find you what version of Java you are using in command line type: Java -version</p>\n"
},
{
"answer_id": 172032,
"author": "ILikeCoffee",
"author_id": 25270,
"author_profile": "https://Stackoverflow.com/users/25270",
"pm_score": 2,
"selected": false,
"text": "<p>Eclipse has it's own compiler. The Eclipse JDT compiler seems to handle your array differently than javac.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9425/"
]
| I once wrote this line in a Java class. This compiled fine in Eclipse but not on the command line.
This is on
* Eclipse 3.3
* JDK 1.5
* Windows XP Professional
Any clues?
Error given on the command line is:
```
Icons.java:16: code too large
public static final byte[] compileIcon = { 71, 73, 70, 56, 57, 97, 50,
^
```
The code line in question is:
```
public static final byte[] compileIcon = { 71, 73, 70, 56, 57, 97, 50,
0, 50, 0, -9, 0, 0, -1, -1, -1, -24, -72, -72, -24, -64, -64,
-8, -16, -24, -8, -24, -24, -16, -24, -32, -1, -8, -8, 48, 72,
-72, -24, -80, -80, 72, 96, -40, -24, -24, -8, 56, 88, -56,
-24, -40, -48, -24, -48, -64, 56, 80, -64, 64, 88, -48, -56,
-64, -64, -16, -24, -24, -32, -40, -40, -32, -88, -96, -72,
-72, -72, -48, -56, -56, -24, -32, -32, -8, -8, -1, -24, -40,
-56, -64, -72, -72, -16, -32, -40, 48, 80, -72, -40, -96, -104,
-40, -96, -96, -56, -104, -104, 120, 88, -104, -40, -64, -80,
-32, -88, -88, -32, -56, -72, -72, -80, -80, -32, -80, -88,
104, -96, -1, -40, -40, -40, -64, -104, -104, -32, -56, -64,
-112, 104, 112, -48, -104, -112, -128, -112, -24, -72, -80,
-88, -8, -8, -8, -64, -112, -120, 72, 104, -40, 120, 96, -96,
-112, -96, -24, -112, -120, -72, -40, -88, -88, -48, -64, -72,
-32, -72, -80, -48, -72, -88, -88, -72, -24, 64, 88, -56, -120,
96, 104, 88, -128, -72, 48, 56, 56, 104, 104, 120, 112, -120,
-16, -128, 104, -88, -40, -48, -48, 88, -120, -24, 104, 88,
-104, -40, -56, -72, -128, 112, -88, -128, 96, -88, -104, -88,
-24, -96, -120, 120, -88, -128, -80, -56, -56, -64, 96, 120,
-8, -96, -128, -88, -80, -96, -104, -32, -72, -72, 96, 104,
112, 96, -104, -8, -72, -112, -112, -64, -72, -80, 64, 64, 72,
-128, -120, -96, -128, 88, 88, -56, -72, -80, 88, 96, 120, -72,
-128, 112, 72, 112, -40, 96, 120, -56, 88, -112, -16, 64, 104,
-48, -64, -80, -88, -88, -120, -80, 88, 88, 96, -56, -96, -120,
-40, -56, -64, 96, 104, 120, -120, -80, -24, -104, -88, -40,
-48, -72, -80, -64, -56, -16, -88, -112, -128, -32, -48, -56,
-24, -16, -8, -64, -120, 120, -96, -96, -88, 80, -128, -24,
-56, -72, -88, -96, 120, 88, -72, -112, 120, -64, -104, 120,
-48, -56, -64, -120, -104, -32, -104, 120, -80, -96, -112,
-120, 56, 88, -64, -128, 96, 64, 88, 120, -40, -80, -104, -120,
-104, -128, 104, 96, -104, -24, -72, -120, -128, 56, 96, -56,
-128, 112, 104, -48, -88, -112, 96, 96, 104, -104, -88, -72,
-40, -88, -96, -72, -88, -96, -120, 120, 104, -80, -88, -96,
72, 72, 80, -120, 88, 96, 120, -120, -24, 96, -104, -16, 104,
80, 48, -56, -80, -96, -56, -88, -104, -104, 120, -88, -88,
120, 104, -72, -120, -120, -24, -32, -40, 112, 88, -104, 120,
96, -104, -32, -32, -32, -96, 96, 96, 80, 80, 88, 64, 88, 120,
72, 120, -40, 72, 88, 112, -88, -96, -104, -56, -80, -88, -72,
-88, -104, -56, -64, -72, -80, -120, 104, -80, -120, -80, -112,
112, -88, 120, 112, 112, 112, -96, -24, -120, -120, -64, -120,
120, -80, 64, 96, -128, 96, 64, 64, 96, -128, -32, 80, 112,
-24, 112, -120, -24, 104, -96, -8, 96, 120, -16, -88, 120, 120,
-72, -56, -16, -128, -128, -128, -104, -120, -72, -64, -96,
-120, -32, -64, -64, -40, -48, -56, -64, -88, -96, -64, -104,
-72, -96, -88, -24, -104, -96, -40, -96, -128, 96, -128, -128,
-96, 104, 88, 80, 112, -88, -8, -64, -104, -80, -96, -120, 112,
96, 120, -32, 56, 80, -72, -104, -88, -32, 104, -128, -24, -56,
-88, -120, -80, -72, -8, -96, -128, -128, -64, -128, 96, -72,
-96, -120, 72, 104, -32, -96, 96, 64, -72, -96, -112, -32, -40,
-48, -64, -88, -112, -88, -128, 96, -88, -128, -88, -64, -64,
-32, -128, -96, -32, -88, -104, -112, 32, 32, 64, -120, 104,
-88, 120, -120, -16, -104, 120, -72, -24, -48, -56, -96, -96,
-96, -64, 96, 96, 96, 64, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 44, 0, 0, 0, 0,
50, 0, 50, 0, 0, 8, -1, 0, 1, 8, 28, 72, -80, -96, -63, -125,
8, 19, 42, 92, -120, 112, 0, 3, 6, 12, 23, 6, -104, 72, -79,
-94, -59, -117, 19, 39, -124, 64, -128, -128, 3, -121, 9, 19,
48, -118, -92, 24, 81, 33, -118, 8, 40, 7, -88, 84, -55, -64,
12, 6, 6, 45, 74, -54, 52, 8, 73, -60, 24, 22, 25, 92, 73, 40,
64, -96, -64, 74, -121, 24, 94, -58, -100, 25, -79, -59, 47,
17, 3, 52, -120, 88, -125, 105, 73, 6, 42, -102, -68, 96, -16,
-71, 18, 3, -118, 6, 13, 14, -114, -36, 26, -64, 69, 7, 18, 28,
-61, -110, -32, -32, -62, -54, -94, 72, -61, -48, -88, -40, 72,
34, -60, 4, 21, 23, -119, 14, -92, 80, -58, 6, -108, 10, 18,
44, 68, -8, 57, -96, -128, 16, 98, 70, -24, -48, 97, -45, 6, 4,
6, 16, 67, -27, 18, 52, -79, -52, -89, -46, 49, -105, -74, -32,
109, -45, -85, -63, -49, 2, 13, 88, -51, -62, 5, 40, 80, 31,
91, 103, 20, 11, -116, 32, -124, -81, -54, 2, 40, -58, -40,
-103, -59, -122, 13, 43, 51, 12, 122, 106, 96, -48, 0, -105,
40, 29, 106, 32, 17, 20, -64, -69, -73, -17, -33, -68, 25, 113,
13, 80, -125, 44, -102, 72, 108, -84, -88, 80, 49, -127, -61,
-94, 28, -97, -108, -4, -98, -103, 102, 9, -127, -21, -40, -81,
23, -32, 35, -126, 39, -10, 2, 32, -116, 29, -1, 27, -74, 37,
-40, 29, 60, 90, -60, -120, -90, 0, -122, -118, -23, -107, 54,
-36, -72, -15, 2, 66, -61, -23, -39, 24, -8, -36, -7, -108,
-27, -128, 44, -59, -112, -16, -64, 67, 3, -39, 21, 72, 0, 6,
34, 120, -31, -123, 124, 124, 52, 16, 84, 3, -119, -88, 82,
-62, 28, -2, 21, 4, -36, -123, -83, -92, -96, 97, 13, 20, 117,
112, 2, -121, 24, 77, -128, 6, 48, -64, 72, -93, -62, 31, 104,
-56, 48, 68, 16, 65, 112, 49, 29, 67, 82, 8, 24, 72, 118, 18,
84, 48, 66, 6, 63, 72, 96, 96, 1, 26, -128, 64, -97, 8, 50, 24,
114, -64, -112, -22, -51, -28, 7, 24, 77, 116, -15, 75, 1, 123,
53, 2, -63, 15, 22, 88, 0, 1, 5, 44, 72, 32, -127, 74, -78,
-47, -122, -62, 27, -90, -24, 49, -28, 1, 69, -106, -108, 76,
21, -99, 8, -127, -119, 29, -81, 60, 41, -63, 15, 16, -116, 80,
65, -114, 22, -44, 40, 72, 6, 111, 60, 4, 77, 3, 34, -124, 1,
-60, -105, 7, 40, 96, -31, -123, -68, 49, -111, 66, 30, 32,
102, -92, 66, 30, 86, 60, -47, -63, 12, 30, 42, 58, 67, 13, 51,
120, -32, 1, 35, 30, 112, 112, -62, 39, -114, -80, 24, -124,
116, 47, 30, 116, 6, 15, -120, 24, -104, 93, 3, -105, 44, -79,
12, 11, -103, -116, 112, 35, 20, 52, -96, 64, 3, 32, 91, -40,
-1, 114, 5, -97, 126, -106, 36, 5, 24, -106, -67, 103, 26, 3,
32, -68, -14, 10, 20, 44, 88, -78, -124, 37, 91, -124, -47,
-33, -105, 112, -56, -28, 7, -103, -70, -86, 116, -57, 29, 52,
80, 37, -101, 8, 54, 24, 99, -121, 17, 82, -108, -80, 0, -83,
7, 93, 56, 70, 14, 41, -96, -78, -107, 11, -117, -48, 97, -42,
12, 127, 32, 64, 66, 91, 19, -96, -88, -94, 35, -16, 110, 10,
-88, 65, 103, 76, -62, 67, 19, 114, -120, -102, 93, 49, 107,
-108, 65, -121, 29, -121, -36, 65, -116, 16, 24, -32, 121,
-125, 33, -70, 108, -96, 112, -97, 37, 5, -127, 100, 23, -128,
-4, 68, 65, 5, 123, -103, 102, -63, 24, 101, -20, 49, -51, 33,
-121, -40, 80, 65, 9, 122, 40, -84, 112, -78, 17, 73, 81, 69,
-110, -110, -28, -38, -105, 9, 84, -30, 69, 21, -106, 60, 106,
32, 68, 25, -127, -96, -96, -25, 6, 14, 56, -96, 112, -83, 90,
81, 116, 2, -72, 57, 16, 66, 8, 88, 28, 49, 26, 66, 8, 51, 60,
-15, -60, 9, 51, -128, -75, -82, 91, 19, 116, 96, -87, 12, 31,
84, 93, -75, 18, 91, 13, 100, -126, -67, 125, 72, 50, 72, 45,
63, 89, -112, 1, 5, 20, -104, 96, 65, 1, 38, -4, 48, 49, 4,
-82, 60, 84, 48, 13, -90, 92, -111, -13, -36, 60, 39, -44, 66,
40, 96, -12, -47, -59, 32, 81, -20, -1, -15, 19, 4, 18, 68, 80,
64, 5, 72, -80, 0, -127, 9, 17, 72, -112, 9, 20, -106, -48,
-48, -86, -79, 56, -49, 77, -14, 66, -76, -100, -68, 119, 20,
59, 44, -15, 19, -53, 20, 0, 30, 103, -101, 110, -66, 97, -122,
25, 52, 44, 33, -125, -74, 11, -92, -98, 115, -35, 90, -55, 1,
52, 33, 83, 76, 33, -118, 10, 97, 73, -70, 81, 7, 29, 44, -35,
1, -46, 29, 76, -22, 2, 7, 30, -84, 50, -60, 7, 48, 60, 114,
-11, 112, 0, -124, -95, 67, 21, -110, 96, -66, -61, 14, 12,
-84, 36, -27, 8, -99, -101, 80, -128, 5, 72, -36, -104, -55,
23, -92, 83, -95, -116, 19, 14, -92, 46, 62, -21, 8, 21, 1, 68,
9, -93, -124, -78, 3, 51, 59, -68, -84, 82, -30, 72, 84, 64, 1,
18, 121, 85, 0, -123, 32, -126, -80, -112, 6, -56, 11, -32, 32,
-2, -28, 10, -71, -64, 5, -80, 48, 7, 74, 56, -63, 16, 58, -40,
65, 45, -28, -16, 5, -108, 56, 16, 37, -112, -80, 17, 5, 70,
-16, 6, 87, 124, -127, 5, -98, 0, -126, 3, 30, -128, -125, 14,
-30, 64, 1, 2, 12, -95, 8, 67, 8, 0, -118, 108, -126, 8, 31,
-16, 1, 40, 100, -96, -120, 20, 76, 33, 18, 121, -104, 64, 88,
102, 24, 2, -78, 48, 66, 5, -101, -96, 26, 12, 118, -72, 67,
100, 12, 103, 34, 4, 89, 65, 18, -1, 72, -127, -125, 2, 30, 80,
7, -107, -24, -37, 22, 26, -15, -66, 2, 20, -96, 17, 12, 64,
65, 52, -30, -74, -128, 7, 88, -47, -118, -28, 99, -120, 2,
122, -112, -124, 36, -100, 34, 1, 14, -48, -126, 26, 74, -128,
-121, 80, 68, 33, 10, -127, -80, -127, 6, 98, -122, 1, 42, 120,
34, 11, 27, -72, -94, 21, 1, 56, 19, 50, 116, -47, -117, -89,
32, -59, 3, 28, 112, 5, 39, -108, 0, -119, 81, 16, -123, 17,
108, 96, 6, 42, -8, 65, 91, 15, 72, -128, 28, -77, -120, 16,
-116, -64, -30, 25, 113, -120, 100, 36, -101, -15, 8, 24, -84,
80, 6, 46, -116, 93, 36, -124, -9, 1, 34, 120, -46, -109, 71,
-8, 33, 73, 16, 66, -122, 21, -12, -32, -108, 61, 40, 5, 47,
18, 48, -121, 62, -2, 113, 18, 58, 112, -62, 6, 18, 64, -53,
90, 50, 82, 49, 10, 40, -62, 41, 11, -63, 75, 94, -68, 32, 117,
106, -16, -93, 30, 18, 89, -53, 4, -60, 64, 52, 10, 81, -128,
47, 86, -64, 76, 102, -106, 34, 23, 47, -48, -126, 22, 28, 80,
76, 90, -34, 82, 32, 6, -56, -90, 54, 69, 25, 0, 38, -64, -126,
11, 71, 8, -89, 56, -107, -96, 8, 31, -104, -45, 7, 68, -32, 2,
55, -127, 72, -108, 11, -112, -95, 8, 49, -120, -89, 60, 71,
-15, -126, 122, 38, -32, -102, -56, 60, -120, 2, 110, 80, 51,
-124, 126, -58, -94, 8, -62, -88, -25, 49, -13, 41, 23, 5,
-112, -31, 6, 8, 93, 65, 64, -15, -39, -56, 117, 98, -124, 9,
51, -72, -59, 45, 56, -95, 78, -121, 6, -128, -96, 5, -39, 39,
67, 49, -54, -47, -114, 122, -44, 32, 1, 1, 0, 59 };
``` | Taking from [this forum on Sun's support site](http://forums.sun.com/thread.jspa?threadID=747860&messageID=4278559), no method can be more than 64 KB long:
When you have code (pseudo) like the following...
```
class MyClass
{
private String[] s = { "a", "b", "c"}
public MyClass()
{
}
```
The compiler ends up producing code that basically looks like the following.
```
class MyClass
{
private String[] s;
private void FunnyName$Method()
{
s[0] = "a";
s[1] = "b";
s[2] = "c";
}
public MyClass()
{
FunnyName$Method();
}
```
And as noted java limits all methods to 64k, even the ones the compiler creates.
It may be that Eclipse is doing something sneaky to get around this, but I assure you this is still possible in Eclipse because I have seen the same error message. A better solution is to just read from a static file, like this:
```
public class Icons
{
public static final byte[] compileIcon;
static
{
compileIcon = readFileToBytes("compileIcon.gif");
}
//... (I assume there are several other icons)
private static byte[] readFileToBytes(String filename)
{
try {
File file = new File(filename);
byte[] bytes = new byte[(int)file.length()];
FileInputStream fin = new FileInputStream(file);
fin.read(bytes);
fin.close();
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
``` |
115,691 | <p>In every MVC framework I've tried (Rails, Merb, Waves, Spring, and Struts), the idea of a Request (and Response) is tied to the HTTP notion of a Request. That is, even if there is an AbstractRequest that is a superclass of Request, the AbstractRequest has things like headers, request method (GET, POST, etc.), and all of the other things tied to HTTP.</p>
<p>I'd like to support a request-response cycle over SMS, Twitter, email, or any other medium for which I can make an adapter. Is there a framework that does this particularly well?</p>
<p>The only other option I've thought of is creating, for example, a Twitter poller that runs in a separate thread and translates messages into local HTTP requests, then sends the responses back out.</p>
<p>If there <em>were</em> a good framework for multiple request media, what would routing look like? In Rails, the HTTP routing looks something like:</p>
<pre><code>map.connect 'some/path/with/:parameter_1/:paramter_2', :controller => 'foo', :action => 'bar'
</code></pre>
<p>How would a Twitter or SMS route look? Regular expressions to match keywords and parameters?</p>
| [
{
"answer_id": 115823,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't seen one. The issue is that the request is also tied to the host, and the response is tied to the request.</p>\n\n<p>So if you get a request in via email, and a controller says to render view \"aboutus\", you'd need the MVC framework to know how to :</p>\n\n<ul>\n<li>get the request in the first place - the MVC framework would almost need to be a host (IIS doesn't get notified on new emails, so how does your email polling code get fired?)</li>\n<li>allow flexible route matching - matching by path/url wouldn't work for all, so request-specific controller routing would be needed</li>\n<li>use the aboutus <em>email</em> view rather than the SMS or HTTP view named \"aboutus\"</li>\n<li>send the response out via email, to the correct recipient</li>\n</ul>\n\n<p>A web MVC framework isn't going to cut it - you'll need a MVC \"host\" that can handle activation through web, sms, email, whatever. </p>\n"
},
{
"answer_id": 118197,
"author": "rjray",
"author_id": 6421,
"author_profile": "https://Stackoverflow.com/users/6421",
"pm_score": 1,
"selected": true,
"text": "<p>You seem to be working mostly with Java and/or Ruby, so forgive me that this answer is based on Perl :-).</p>\n\n<p>I'm very fond of the Catalyst MVC Framework (<a href=\"http://www.catalystframework.org/\" rel=\"nofollow noreferrer\">http://www.catalystframework.org/</a>). It delegates the actual mapping of requests (in the general, generic sense) to code via engines. Granted, all the engine classes are currently based on HTTP, but I have toyed with the idea of trying to write an engine class that wasn't based on HTTP (or was perhaps tied to something like Twitter, but was separated from the HTTP interactions that Twitter uses). At the very least, I'm convinced it can be done, even if I haven't gotten around to trying it yet.</p>\n"
},
{
"answer_id": 152649,
"author": "Andre Bossard",
"author_id": 21027,
"author_profile": "https://Stackoverflow.com/users/21027",
"pm_score": 0,
"selected": false,
"text": "<p>You could implement a <a href=\"http://en.wikipedia.org/wiki/Representational_State_Transfer\" rel=\"nofollow noreferrer\">REST-based</a> Adapter over your website, which replaces the templates and redirects according to the input parameters.</p>\n\n<p>All requestes coming in on <em>api</em>.yourhost.com will be handled by the REST based adapter.</p>\n\n<p>This adapter would allow to call your website programmatically and have the result in a parseable format.</p>\n\n<p>Practically this means: It replaces the Templates with an own Template Engine, on which this things happen:</p>\n\n<ul>\n<li>instead of the assigned template, a generic xml/json template is called, which just outputs a xml that contains all template vars</li>\n</ul>\n\n<p>then you can make your Twitter Poller, SMS Gateway or even call it from Javascript. </p>\n"
},
{
"answer_id": 192006,
"author": "Vihung",
"author_id": 15452,
"author_profile": "https://Stackoverflow.com/users/15452",
"pm_score": 1,
"selected": false,
"text": "<p>The Java Servlet specification was designed for Servlets to be protocol neutral, and to be extended in a protocol-specific way - HttpServlet being a protocol-specific Servlet extension. I always imagined that Sun, or other third poarty framework providers, would come up with other protocol-specific extensions like FtpServlet or MailServlet, or in this case SmsServlet and TwitterServlet.</p>\n\n<p>Instead what has happened is that people either completely bypassed the Servlet framework, or have built their protocols on top of HTTP.</p>\n\n<p>Of course, if you want to implement a protocol-specific extension for your required protocols, you would have to develop the whole stack - request object, response object, a mechanism of identifying sessions (for example using the MSISDN in an SMS instead of cookies), a templating and rendering framework (equivalent of JSP) - and then build an MVC framework on top of it.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
]
| In every MVC framework I've tried (Rails, Merb, Waves, Spring, and Struts), the idea of a Request (and Response) is tied to the HTTP notion of a Request. That is, even if there is an AbstractRequest that is a superclass of Request, the AbstractRequest has things like headers, request method (GET, POST, etc.), and all of the other things tied to HTTP.
I'd like to support a request-response cycle over SMS, Twitter, email, or any other medium for which I can make an adapter. Is there a framework that does this particularly well?
The only other option I've thought of is creating, for example, a Twitter poller that runs in a separate thread and translates messages into local HTTP requests, then sends the responses back out.
If there *were* a good framework for multiple request media, what would routing look like? In Rails, the HTTP routing looks something like:
```
map.connect 'some/path/with/:parameter_1/:paramter_2', :controller => 'foo', :action => 'bar'
```
How would a Twitter or SMS route look? Regular expressions to match keywords and parameters? | You seem to be working mostly with Java and/or Ruby, so forgive me that this answer is based on Perl :-).
I'm very fond of the Catalyst MVC Framework (<http://www.catalystframework.org/>). It delegates the actual mapping of requests (in the general, generic sense) to code via engines. Granted, all the engine classes are currently based on HTTP, but I have toyed with the idea of trying to write an engine class that wasn't based on HTTP (or was perhaps tied to something like Twitter, but was separated from the HTTP interactions that Twitter uses). At the very least, I'm convinced it can be done, even if I haven't gotten around to trying it yet. |
115,692 | <p>For example I have such query:</p>
<pre><code>Query q = sess.createQuery("from Cat cat");
List cats = q.list();
</code></pre>
<p>If I try to make something like this it shows the following warning </p>
<pre><code>Type safety: The expression of type List needs unchecked conversion to conform to List<Cat>
List<Cat> cats = q.list();
</code></pre>
<p>Is there a way to avoid it?</p>
| [
{
"answer_id": 115714,
"author": "tyshock",
"author_id": 16448,
"author_profile": "https://Stackoverflow.com/users/16448",
"pm_score": 3,
"selected": false,
"text": "<p>In our code we annotate the calling methods with:</p>\n\n<p>@SuppressWarnings(\"unchecked\")</p>\n\n<p>I know it seems like a hack, but a co-developer checked recently and found that was all we could do.</p>\n"
},
{
"answer_id": 115719,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 2,
"selected": false,
"text": "<p>No, but you can isolate it into specific query methods and suppress the warnings with a <code>@SuppressWarnings(\"unchecked\")</code> annotation.</p>\n"
},
{
"answer_id": 115952,
"author": "Joe Dean",
"author_id": 5917,
"author_profile": "https://Stackoverflow.com/users/5917",
"pm_score": -1,
"selected": false,
"text": "<p>If you don't want to use @SuppressWarnings(\"unchecked\") you can do the following.</p>\n\n<pre><code> Query q = sess.createQuery(\"from Cat cat\");\n List<?> results =(List<?>) q.list();\n List<Cat> cats = new ArrayList<Cat>();\n for(Object result:results) {\n Cat cat = (Cat) result;\n cats.add(cat);\n }\n</code></pre>\n\n<p>FYI - I created a util method that does this for me so it doesn't litter my code and I don't have to use @SupressWarning. </p>\n"
},
{
"answer_id": 116071,
"author": "cretzel",
"author_id": 18722,
"author_profile": "https://Stackoverflow.com/users/18722",
"pm_score": 4,
"selected": false,
"text": "<p>We use <code>@SuppressWarnings(\"unchecked\")</code> as well, but we most often try to use it only on the declaration of the variable, not on the method as a whole:</p>\n\n<pre><code>public List<Cat> findAll() {\n Query q = sess.createQuery(\"from Cat cat\");\n @SuppressWarnings(\"unchecked\")\n List<Cat> cats = q.list();\n return cats;\n}\n</code></pre>\n"
},
{
"answer_id": 118976,
"author": "Matt Quail",
"author_id": 15790,
"author_profile": "https://Stackoverflow.com/users/15790",
"pm_score": 8,
"selected": true,
"text": "<p>Using <code>@SuppressWarnings</code> everywhere, as suggested, is a good way to do it, though it does involve a bit of finger typing each time you call <code>q.list()</code>.</p>\n\n<p>There are two other techniques I'd suggest:</p>\n\n<p><strong>Write a cast-helper</strong></p>\n\n<p>Simply refactor all your <code>@SuppressWarnings</code> into one place:</p>\n\n<pre><code>List<Cat> cats = MyHibernateUtils.listAndCast(q);\n\n...\n\npublic static <T> List<T> listAndCast(Query q) {\n @SuppressWarnings(\"unchecked\")\n List list = q.list();\n return list;\n}\n</code></pre>\n\n<p><strong>Prevent Eclipse from generating warnings for unavoidable problems</strong> </p>\n\n<p>In Eclipse, go to Window>Preferences>Java>Compiler>Errors/Warnings and under Generic type, select the checkbox \n<code>Ignore unavoidable generic type problems due to raw APIs</code></p>\n\n<p>This will turn off unnecessary warnings for similar problems like the one described above which are unavoidable.</p>\n\n<p>Some comments:</p>\n\n<ul>\n<li>I chose to pass in the <code>Query</code> instead of the result of <code>q.list()</code> because that way this \"cheating\" method can only be used to cheat with Hibernate, and not for cheating any <code>List</code> in general.</li>\n<li>You could add similar methods for <code>.iterate()</code> etc.</li>\n</ul>\n"
},
{
"answer_id": 544475,
"author": "Pat",
"author_id": 20161,
"author_profile": "https://Stackoverflow.com/users/20161",
"pm_score": 1,
"selected": false,
"text": "<p>We had same problem. But it wasn't a big deal for us because we had to solve other more major issues with Hibernate Query and Session.</p>\n\n<p>Specifically:</p>\n\n<ol>\n<li>control when a transaction could be committed. (we wanted to count how many times a tx was \"started\" and only commit when the tx was \"ended\" the same number of times it was started. Useful for code that doesn't know if it needs to start a transaction. Now any code that needs a tx just \"starts\" one and ends it when done.)</li>\n<li>Performance metrics gathering.</li>\n<li>Delaying starting the transaction until it is known that something will actually be done.</li>\n<li>More gentle behavior for query.uniqueResult()</li>\n</ol>\n\n<p>So for us, we have:</p>\n\n<ol>\n<li>Create an interface (AmplafiQuery) that extends Query</li>\n<li>Create a class (AmplafiQueryImpl) that extends AmplafiQuery and wraps a org.hibernate.Query</li>\n<li>Create a Txmanager that returns a Tx.</li>\n<li>Tx has the various createQuery methods and returns AmplafiQueryImpl</li>\n</ol>\n\n<p>And lastly,</p>\n\n<p>AmplafiQuery has a \"asList()\" that is a generic enabled version of Query.list()\nAmplafiQuery has a \"unique()\" that is a generic enabled version of Query.uniqueResult() ( and just logs an issue rather than throwing an exception) </p>\n\n<p>This is a lot of work for just avoiding @SuppressWarnings. However, like I said (and listed) there are lots of other better! reasons to do the wrapping work.</p>\n"
},
{
"answer_id": 544561,
"author": "paulmurray",
"author_id": 63189,
"author_profile": "https://Stackoverflow.com/users/63189",
"pm_score": 2,
"selected": false,
"text": "<p>It's not an oversight or a mistake. The warning reflects a real underlying problem - there is no way that the java compiler can really be sure that the hibernate class is going to do it's job properly and that the list it returns will only contain Cats. Any of the suggestions here is fine.</p>\n"
},
{
"answer_id": 9969062,
"author": "Tony Shih",
"author_id": 1161713,
"author_profile": "https://Stackoverflow.com/users/1161713",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is older but 2 points to note as of today in Matt Quails Answer.</p>\n\n<h1>Point 1</h1>\n\n<p>This </p>\n\n<pre><code>List<Cat> cats = Collections.checkedList(Cat.class, q.list());\n</code></pre>\n\n<p>Should be this</p>\n\n<pre><code>List<Cat> cats = Collections.checkedList(q.list(), Cat.class);\n</code></pre>\n\n<h1>Point 2</h1>\n\n<p>From this</p>\n\n<pre><code>List list = q.list();\n</code></pre>\n\n<p>to this </p>\n\n<pre><code>List<T> list = q.list();\n</code></pre>\n\n<p>would reduce other warnings obviously in original reply tag markers were stripped by the browser.</p>\n"
},
{
"answer_id": 13729284,
"author": "Paulo Merson",
"author_id": 317522,
"author_profile": "https://Stackoverflow.com/users/317522",
"pm_score": 3,
"selected": false,
"text": "<p>Apparently, the Query.list() method in the Hibernate API is not type safe \"by design\", and there are <a href=\"https://forum.hibernate.org/viewtopic.php?f=9&t=948703&view=next\" rel=\"nofollow noreferrer\">no plans to change it</a>. </p>\n\n<p>I believe the simplest solution to avoid compiler warnings is indeed to add @SuppressWarnings(\"unchecked\"). This <a href=\"https://stackoverflow.com/questions/7387749/add-suppresswarningsunchecked-in-generics-to-single-line-generates-eclipse\">annotation can be placed</a> at the method level or, if inside a method, right before a variable declaration. </p>\n\n<p>In case you have a method that encapsulates Query.list() and returns List (or Collection), you also get a warning. But this one is suppressed using @SuppressWarnings(\"rawtypes\"). </p>\n\n<p>The listAndCast(Query) method proposed by Matt Quail is less flexible than Query.list(). \nWhile I can do:</p>\n\n<pre><code>Query q = sess.createQuery(\"from Cat cat\");\nArrayList cats = q.list();\n</code></pre>\n\n<p>If I try the code below:</p>\n\n<pre><code>Query q = sess.createQuery(\"from Cat cat\");\nArrayList<Cat> cats = MyHibernateUtils.listAndCast(q);\n</code></pre>\n\n<p>I'll get a compile error: <em>Type mismatch: cannot convert from List to ArrayList</em></p>\n"
},
{
"answer_id": 24768836,
"author": "Brian Ngure",
"author_id": 3842765,
"author_profile": "https://Stackoverflow.com/users/3842765",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>Query q = sess.createQuery(\"from Cat cat\");\nList<?> results = q.list();\nfor (Object obj : results) {\n Cat cat = (Cat) obj;\n}\n</code></pre>\n"
},
{
"answer_id": 30268139,
"author": "antonpp",
"author_id": 3008684,
"author_profile": "https://Stackoverflow.com/users/3008684",
"pm_score": 5,
"selected": false,
"text": "<p>It is been a long time since the question was asked but I hope my answer might be helpful to someone like me.</p>\n\n<p>If you take a look at javax.persistence <a href=\"http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#createQuery(java.lang.String,%20java.lang.Class)\">api docs</a>, you will see that some new methods have been added there since <code>Java Persistence 2.0</code>. One of them is <code>createQuery(String, Class<T>)</code> which returns <code>TypedQuery<T></code>. You can use <code>TypedQuery</code> just as you did it with <code>Query</code> with that small difference that all operations are type safe now.</p>\n\n<p>So, just change your code to smth like this:</p>\n\n<pre><code>Query q = sess.createQuery(\"from Cat cat\", Cat.class);\nList<Cat> cats = q.list();\n</code></pre>\n\n<p>And you are all set.</p>\n"
},
{
"answer_id": 33657790,
"author": "xjodoin",
"author_id": 1022974,
"author_profile": "https://Stackoverflow.com/users/1022974",
"pm_score": -1,
"selected": false,
"text": "<p>A good solution to avoid type safety warnings with hibernate query is to use a tool like <a href=\"http://torpedoquery.org\" rel=\"nofollow\">TorpedoQuery</a> to help you to build type safe hql.</p>\n\n<pre><code>Cat cat = from(Cat.class);\norg.torpedoquery.jpa.Query<Entity> select = select(cat);\nList<Cat> cats = select.list(entityManager);\n</code></pre>\n"
},
{
"answer_id": 36424573,
"author": "shivam oberoi",
"author_id": 1155906,
"author_profile": "https://Stackoverflow.com/users/1155906",
"pm_score": 4,
"selected": false,
"text": "<p>Try to use <code>TypedQuery</code> instead of <code>Query</code>.\nFor example instead of this:-</p>\n\n<pre><code>Query q = sess.createQuery(\"from Cat cat\", Cat.class);\nList<Cat> cats = q.list();\n</code></pre>\n\n<p>Use this:-</p>\n\n<pre><code>TypedQuery<Cat> q1 = sess.createQuery(\"from Cat cat\", Cat.class);\nList<Cat> cats = q1.list();\n</code></pre>\n"
},
{
"answer_id": 48717730,
"author": "David DeMar",
"author_id": 1236018,
"author_profile": "https://Stackoverflow.com/users/1236018",
"pm_score": 2,
"selected": false,
"text": "<p>Newer versions of Hibernate now support a type safe <code>Query<T></code> object so you no longer have to use <code>@SuppressWarnings</code> or implement some hack to make the compiler warnings go away. In the <a href=\"https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/Session.html#createQuery-java.lang.String-java.lang.Class-\" rel=\"nofollow noreferrer\">Session API</a>, <code>Session.createQuery</code> will now return a type safe <code>Query<T></code> object. You can use it this way:</p>\n\n<pre><code>Query<Cat> query = session.createQuery(\"FROM Cat\", Cat.class);\nList<Cat> cats = query.list();\n</code></pre>\n\n<p>You can also use it when the query result won't return a Cat:</p>\n\n<pre><code>public Integer count() {\n Query<Integer> query = sessionFactory.getCurrentSession().createQuery(\"SELECT COUNT(id) FROM Cat\", Integer.class);\n return query.getSingleResult();\n}\n</code></pre>\n\n<p>Or when doing a partial select:</p>\n\n<pre><code>public List<Object[]> String getName() {\n Query<Object[]> query = sessionFactory.getCurrentSession().createQuery(\"SELECT id, name FROM Cat\", Object[].class);\n return query.list();\n}\n</code></pre>\n"
},
{
"answer_id": 52361208,
"author": "Rakesh Singh Balhara",
"author_id": 3855723,
"author_profile": "https://Stackoverflow.com/users/3855723",
"pm_score": -1,
"selected": false,
"text": "<pre><code>TypedQuery<EntityName> createQuery = entityManager.createQuery(\"from EntityName\", EntityName.class);\nList<EntityName> resultList = createQuery.getResultList();\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20128/"
]
| For example I have such query:
```
Query q = sess.createQuery("from Cat cat");
List cats = q.list();
```
If I try to make something like this it shows the following warning
```
Type safety: The expression of type List needs unchecked conversion to conform to List<Cat>
List<Cat> cats = q.list();
```
Is there a way to avoid it? | Using `@SuppressWarnings` everywhere, as suggested, is a good way to do it, though it does involve a bit of finger typing each time you call `q.list()`.
There are two other techniques I'd suggest:
**Write a cast-helper**
Simply refactor all your `@SuppressWarnings` into one place:
```
List<Cat> cats = MyHibernateUtils.listAndCast(q);
...
public static <T> List<T> listAndCast(Query q) {
@SuppressWarnings("unchecked")
List list = q.list();
return list;
}
```
**Prevent Eclipse from generating warnings for unavoidable problems**
In Eclipse, go to Window>Preferences>Java>Compiler>Errors/Warnings and under Generic type, select the checkbox
`Ignore unavoidable generic type problems due to raw APIs`
This will turn off unnecessary warnings for similar problems like the one described above which are unavoidable.
Some comments:
* I chose to pass in the `Query` instead of the result of `q.list()` because that way this "cheating" method can only be used to cheat with Hibernate, and not for cheating any `List` in general.
* You could add similar methods for `.iterate()` etc. |
115,703 | <p>I have some template code that I would prefer to have stored in a CPP file instead of inline in the header. I know this can be done as long as you know which template types will be used. For example:</p>
<p><strong>.h file</strong></p>
<pre><code>class foo
{
public:
template <typename T>
void do(const T& t);
};
</code></pre>
<p><strong>.cpp file</strong></p>
<pre><code>template <typename T>
void foo::do(const T& t)
{
// Do something with t
}
template void foo::do<int>(const int&);
template void foo::do<std::string>(const std::string&);
</code></pre>
<p>Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link.</p>
<p>My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments.</p>
| [
{
"answer_id": 115731,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, that's the standard way to do <s>specializiation</s> explicit instantiation. As you stated, you cannot instantiate this template with other types.</p>\n\n<p>Edit: corrected based on comment.</p>\n"
},
{
"answer_id": 115735,
"author": "Aaron N. Tubbs",
"author_id": 4810,
"author_profile": "https://Stackoverflow.com/users/4810",
"pm_score": 9,
"selected": true,
"text": "<p>The problem you describe can be solved by defining the template in the header, or via the approach you describe above.</p>\n\n<p>I recommend reading the following points from the <a href=\"https://isocpp.org/wiki/faq/templates\" rel=\"noreferrer\">C++ FAQ Lite</a>: </p>\n\n<ul>\n<li><a href=\"https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl\" rel=\"noreferrer\">Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?</a></li>\n<li><a href=\"https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl\" rel=\"noreferrer\">How can I avoid linker errors with my template functions?</a></li>\n<li><a href=\"https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl-export-keyword\" rel=\"noreferrer\">How does the C++ keyword export help with template linker errors?</a></li>\n</ul>\n\n<p>They go into a lot of detail about these (and other) template issues.</p>\n"
},
{
"answer_id": 115743,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 4,
"selected": false,
"text": "<p>This should work fine everywhere templates are supported. Explicit template instantiation is part of the C++ standard.</p>\n"
},
{
"answer_id": 115792,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 2,
"selected": false,
"text": "<p>There is, in the latest standard, a keyword (<code>export</code>) that would help alleviate this issue, but it isn't implemented in any compiler that I'm aware of, other than Comeau.</p>\n\n<p>See the <a href=\"http://www.parashift.com/c++-faq-lite/templates.html#faq-35.14\" rel=\"nofollow noreferrer\">FAQ-lite</a> about this.</p>\n"
},
{
"answer_id": 115821,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<p>This code is well-formed. You only have to pay attention that the definition of the template is visible at the point of instantiation. To quote the standard, § 14.7.2.4:</p>\n\n<blockquote>\n <p>The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.</p>\n</blockquote>\n"
},
{
"answer_id": 240246,
"author": "Benoît",
"author_id": 31640,
"author_profile": "https://Stackoverflow.com/users/31640",
"pm_score": 0,
"selected": false,
"text": "<p>There is nothing wrong with the example you have given. But i must say i believe it's not efficient to store function definitions in a cpp file. I only understand the need to separate the function's declaration and definition.</p>\n\n<p>When used together with explicit class instantiation, the Boost Concept Check Library (BCCL) can help you generate template function code in cpp files.</p>\n"
},
{
"answer_id": 8030638,
"author": "Red XIII",
"author_id": 339249,
"author_profile": "https://Stackoverflow.com/users/339249",
"pm_score": 3,
"selected": false,
"text": "<p>This is definitely not a nasty hack, but be aware of the fact that you will have to do it (the explicit template specialization) for every class/type you want to use with the given template. In case of MANY types requesting template instantiation there can be A LOT of lines in your .cpp file. To remedy this problem you can have a TemplateClassInst.cpp in every project you use so that you have greater control what types will be instantiated. Obviously this solution will not be perfect (aka silver bullet) as you might end up breaking the ODR :).</p>\n"
},
{
"answer_id": 13952386,
"author": "namespace sid",
"author_id": 708995,
"author_profile": "https://Stackoverflow.com/users/708995",
"pm_score": 7,
"selected": false,
"text": "<p>For others on this page wondering what the correct syntax is (as did I) for explicit template specialisation (or at least in VS2008), its the following...</p>\n\n<p>In your .h file...</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>template<typename T>\nclass foo\n{\npublic:\n void bar(const T &t);\n};\n</code></pre>\n\n<p>And in your .cpp file</p>\n\n<pre><code>template <class T>\nvoid foo<T>::bar(const T &t)\n{ }\n\n// Explicit template instantiation\ntemplate class foo<int>;\n</code></pre>\n"
},
{
"answer_id": 15561347,
"author": "Didii",
"author_id": 2158015,
"author_profile": "https://Stackoverflow.com/users/2158015",
"pm_score": 1,
"selected": false,
"text": "<p>Time for an update! Create an inline (.inl, or probably any other) file and simply copy all your definitions in it. Be sure to add the template above each function (<code>template <typename T, ...></code>). Now instead of including the header file in the inline file you do the opposite. Include the inline file <strong>after</strong> the declaration of your class (<code>#include \"file.inl\"</code>).</p>\n\n<p>I don't really know why no one has mentioned this. I see no immediate drawbacks.</p>\n"
},
{
"answer_id": 41292751,
"author": "Cameron Tacklind",
"author_id": 4612476,
"author_profile": "https://Stackoverflow.com/users/4612476",
"pm_score": 5,
"selected": false,
"text": "<p>Your example is correct but not very portable.\nThere is also a slightly cleaner syntax that can be used (as pointed out by @namespace-sid, among others).</p>\n<p>However, suppose the templated class is part of some library that is to be shared...</p>\n<p>Should other versions of the templated class be compiled?</p>\n<p>Is the library maintainer supposed to anticipate all possible templated uses of the class?</p>\n<h1>An Alternate Approach</h1>\n<p>Add a third file that is the template implementation/instantiation file in your sources.</p>\n<p><strong><code>lib/foo.hpp</code></strong> - <em>from library</em></p>\n<pre><code>#pragma once\n\ntemplate <typename T>\nclass foo {\npublic:\n void bar(const T&);\n};\n</code></pre>\n<p><strong><code>lib/foo.cpp</code></strong> - <em>compiling this file directly just wastes compilation time</em></p>\n<pre><code>// Include guard here, just in case\n#pragma once\n\n#include "foo.hpp"\n\ntemplate <typename T>\nvoid foo::bar(const T& arg) {\n // Do something with `arg`\n}\n</code></pre>\n<p><strong><code>foo.MyType.cpp</code></strong> - <em>using the library, explicit template instantiation of <code>foo<MyType></code></em></p>\n<pre><code>// Consider adding "anti-guard" to make sure it's not included in other translation units\n#if __INCLUDE_LEVEL__\n #error "Don't include this file"\n#endif\n\n// Yes, we include the .cpp file\n#include <lib/foo.cpp>\n#include "MyType.hpp"\n\ntemplate class foo<MyType>;\n</code></pre>\n<p>Organize your implementations as desired:</p>\n<ul>\n<li>All implementations in one file</li>\n<li>Multiple implementation files, one for each type</li>\n<li>An implementation file for each set of types</li>\n</ul>\n<h2>Why??</h2>\n<p>This setup should reduce compile times, especially for heavily used complicated templated code, because you're not recompiling the same header file in each\ntranslation unit.\nIt also enables better detection of which code needs to be recompiled, by compilers and build scripts, reducing incremental build burden.</p>\n<h2>Usage Examples</h2>\n<p><strong><code>foo.MyType.hpp</code></strong> - <em>needs to know about <code>foo<MyType></code>'s public interface but not <code>.cpp</code> sources</em></p>\n<pre><code>#pragma once\n\n#include <lib/foo.hpp>\n#include "MyType.hpp"\n\n// Declare `temp`. Doesn't need to include `foo.cpp`\nextern foo<MyType> temp;\n</code></pre>\n<p><strong><code>examples.cpp</code></strong> - <em>can reference local declaration but also doesn't recompile <code>foo<MyType></code></em></p>\n<pre><code>#include "foo.MyType.hpp"\n\nMyType instance;\n\n// Define `temp`. Doesn't need to include `foo.cpp`\nfoo<MyType> temp;\n\nvoid example_1() {\n // Use `temp`\n temp.bar(instance);\n}\n\nvoid example_2() {\n // Function local instance\n foo<MyType> temp2;\n\n // Use templated library function\n temp2.bar(instance);\n}\n</code></pre>\n<p><strong><code>error.cpp</code></strong> - <em>example that would work with pure header templates but doesn't here</em></p>\n<pre><code>#include <lib/foo.hpp>\n\n// Causes compilation errors at link time since we never had the explicit instantiation:\n// template class foo<int>;\n// GCC linker gives an error: "undefined reference to `foo<int>::bar()'"\nfoo<int> nonExplicitlyInstantiatedTemplate;\nvoid linkerError() {\n nonExplicitlyInstantiatedTemplate.bar();\n}\n</code></pre>\n<p><em>Note: Most compilers/linters/code helpers won't detect this as an error, since there is no error according to C++ standard.\nBut when you go to link this translation unit into a complete executable, the linker won't find a defined version of <code>foo<int></code>.</em></p>\n<hr />\n\n<p>Alternate approach from: <a href=\"https://stackoverflow.com/a/495056/4612476\">https://stackoverflow.com/a/495056/4612476</a></p>\n"
},
{
"answer_id": 51954331,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>That is a standard way to define template functions. I think there are three methods I read for defining templates. Or probably 4. Each with pros and cons.</p>\n\n<ol>\n<li><p>Define in class definition. I don't like this at all because I think class definitions are strictly for reference and should be easy to read. However it is much less tricky to define templates in class than outside. And not all template declarations are on the same level of complexity. This method also makes the template a true template.</p></li>\n<li><p>Define the template in the same header, but outside of the class. This is my preferred way most of the times. It keeps your class definition tidy, the template remains a true template. It however requires full template naming which can be tricky. Also, your code is available to all. But if you need your code to be inline this is the only way. You can also accomplish this by creating a .INL file at the end of your class definitions.</p></li>\n<li><p>Include the header.h and implementation.CPP into your main.CPP. I think that's how its done. You won't have to prepare any pre instantiations, it will behave like a true template. The problem I have with it is that it is not natural. We don't normally include and expect to include source files. I guess since you included the source file, the template functions can be inlined.</p></li>\n<li><p>This last method, which was the posted way, is defining the templates in a source file, just like number 3; but instead of including the source file, we pre instantiate the templates to ones we will need. I have no problem with this method and it comes in handy sometimes. We have one big code, it cannot benefit from being inlined so just put it in a CPP file. And if we know common instantiations and we can predefine them. This saves us from writing basically the same thing 5, 10 times. This method has the benefit of keeping our code proprietary. But I don't recommend putting tiny, regularly used functions in CPP files. As this will reduce the performance of your library. </p></li>\n</ol>\n\n<p>Note, I am not aware of the consequences of a bloated obj file.</p>\n"
},
{
"answer_id": 56801030,
"author": "TarmoPikaro",
"author_id": 2338477,
"author_profile": "https://Stackoverflow.com/users/2338477",
"pm_score": 3,
"selected": false,
"text": "<p>Let's take one example, let's say for some reason you want to have a template class:</p>\n\n<pre><code>//test_template.h:\n#pragma once\n#include <cstdio>\n\ntemplate <class T>\nclass DemoT\n{\npublic:\n void test()\n {\n printf(\"ok\\n\");\n }\n};\n\ntemplate <>\nvoid DemoT<int>::test()\n{\n printf(\"int test (int)\\n\");\n}\n\n\ntemplate <>\nvoid DemoT<bool>::test()\n{\n printf(\"int test (bool)\\n\");\n}\n</code></pre>\n\n<p>If you compile this code with Visual Studio - it works out of box.\ngcc will produce linker error (if same header file is used from multiple .cpp files):</p>\n\n<pre><code>error : multiple definition of `DemoT<int>::test()'; your.o: .../test_template.h:16: first defined here\n</code></pre>\n\n<p>It's possible to move implementation to .cpp file, but then you need to declare class like this - </p>\n\n<pre><code>//test_template.h:\n#pragma once\n#include <cstdio>\n\ntemplate <class T>\nclass DemoT\n{\npublic:\n void test()\n {\n printf(\"ok\\n\");\n }\n};\n\ntemplate <>\nvoid DemoT<int>::test();\n\ntemplate <>\nvoid DemoT<bool>::test();\n\n// Instantiate parametrized template classes, implementation resides on .cpp side.\ntemplate class DemoT<bool>;\ntemplate class DemoT<int>;\n</code></pre>\n\n<p>And then .cpp will look like this:</p>\n\n<pre><code>//test_template.cpp:\n#include \"test_template.h\"\n\ntemplate <>\nvoid DemoT<int>::test()\n{\n printf(\"int test (int)\\n\");\n}\n\n\ntemplate <>\nvoid DemoT<bool>::test()\n{\n printf(\"int test (bool)\\n\");\n}\n</code></pre>\n\n<p>Without two last lines in header file - gcc will work fine, but Visual studio will produce an error:</p>\n\n<pre><code> error LNK2019: unresolved external symbol \"public: void __cdecl DemoT<int>::test(void)\" (?test@?$DemoT@H@@QEAAXXZ) referenced in function\n</code></pre>\n\n<p>template class syntax is optional in case if you want to expose function via .dll export, but this is applicable only for windows platform - so test_template.h could look like this:</p>\n\n<pre><code>//test_template.h:\n#pragma once\n#include <cstdio>\n\ntemplate <class T>\nclass DemoT\n{\npublic:\n void test()\n {\n printf(\"ok\\n\");\n }\n};\n\n#ifdef _WIN32\n #define DLL_EXPORT __declspec(dllexport) \n#else\n #define DLL_EXPORT\n#endif\n\ntemplate <>\nvoid DLL_EXPORT DemoT<int>::test();\n\ntemplate <>\nvoid DLL_EXPORT DemoT<bool>::test();\n</code></pre>\n\n<p>with .cpp file from previous example.</p>\n\n<p>This however gives more headache to linker, so it's recommended to use previous example if you don't export .dll function.</p>\n"
},
{
"answer_id": 61783715,
"author": "KronuZ",
"author_id": 3165824,
"author_profile": "https://Stackoverflow.com/users/3165824",
"pm_score": 2,
"selected": false,
"text": "<p>None of above worked for me, so here is how y solved it, my class have only 1 method templated..</p>\n\n<p>.h</p>\n\n<pre><code>class Model\n{\n template <class T>\n void build(T* b, uint32_t number);\n};\n</code></pre>\n\n<p>.cpp</p>\n\n<pre><code>#include \"Model.h\"\ntemplate <class T>\nvoid Model::build(T* b, uint32_t number)\n{\n //implementation\n}\n\nvoid TemporaryFunction()\n{\n Model m;\n m.build<B1>(new B1(),1);\n m.build<B2>(new B2(), 1);\n m.build<B3>(new B3(), 1);\n}\n</code></pre>\n\n<p>this avoid linker errors, and no need to call TemporaryFunction at all</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
| I have some template code that I would prefer to have stored in a CPP file instead of inline in the header. I know this can be done as long as you know which template types will be used. For example:
**.h file**
```
class foo
{
public:
template <typename T>
void do(const T& t);
};
```
**.cpp file**
```
template <typename T>
void foo::do(const T& t)
{
// Do something with t
}
template void foo::do<int>(const int&);
template void foo::do<std::string>(const std::string&);
```
Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link.
My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments. | The problem you describe can be solved by defining the template in the header, or via the approach you describe above.
I recommend reading the following points from the [C++ FAQ Lite](https://isocpp.org/wiki/faq/templates):
* [Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?](https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl)
* [How can I avoid linker errors with my template functions?](https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl)
* [How does the C++ keyword export help with template linker errors?](https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl-export-keyword)
They go into a lot of detail about these (and other) template issues. |
115,720 | <p>Is there a command in classic ASP I can use to tell the browser not to pull the page from it's cache, or, to not cache, or clear the cache of my page?</p>
| [
{
"answer_id": 115734,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>If you put</p>\n\n<pre><code>Response.Expires = -1\n</code></pre>\n\n<p>in you classic ASP-page it will instruct the browser not to cache the contents. If the user clicks \"back\" or navigating to the page in another way, the browser will refresh the page from the server.</p>\n"
},
{
"answer_id": 115747,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 2,
"selected": false,
"text": "<p>Not asp related, this is a HTTP question. You do it by modifying some aspect of http caching like Cache-Control, etag, Expires etc. Read <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616.html\" rel=\"nofollow noreferrer\">RFC2616</a> especially <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html\" rel=\"nofollow noreferrer\">Caching in HTTP</a> and set the appropriate header.</p>\n"
},
{
"answer_id": 115756,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 4,
"selected": true,
"text": "<p>You can use HTML meta tags:</p>\n\n<pre><code><meta http-equiv=\"Pragma\" content=\"no-cache\" />\n<meta http-equiv=\"Expires\" content=\"Fri, 01 Jan 1999 1:00:00 GMT\" />\n<meta http-equiv=\"Last-Modified\" content=\"0\" />\n<meta http-equiv=\"Cache-Control\" content=\"no-cache, must-revalidate\" />\n</code></pre>\n\n<p>Or you can use ASP response headers:</p>\n\n<pre><code><% \n Response.CacheControl = \"no-cache\"\n Response.AddHeader \"Pragma\", \"no-cache\"\n Response.Expires = -1\n%>\n</code></pre>\n"
},
{
"answer_id": 115843,
"author": "WolfmanDragon",
"author_id": 13491,
"author_profile": "https://Stackoverflow.com/users/13491",
"pm_score": -1,
"selected": false,
"text": "<p>Because of the way that different browsers handle caching both the Expires and the no-cache commands need to be used. Here is an <a href=\"http://aspalliance.com/articleViewer.aspx?aId=694&pId=-1\" rel=\"nofollow noreferrer\">article</a> showing the correct way to do this.</p>\n"
},
{
"answer_id": 115937,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 2,
"selected": false,
"text": "<p>Ignore everybody telling you to use <code><meta></code> elements or <code>Pragma</code>. They are very unreliable. You need to set the appropriate HTTP headers. A good tutorial on how to decide which HTTP headers are appropriate for you is available <a href=\"http://www.mnot.net/cache_docs/\" rel=\"nofollow noreferrer\">here</a>. <code>Cache-Control: no-cache</code> is probably all you need, but read the tutorial as there are many project-specific reasons why you might want something different.</p>\n"
},
{
"answer_id": 119384,
"author": "Aravind",
"author_id": 19536,
"author_profile": "https://Stackoverflow.com/users/19536",
"pm_score": -1,
"selected": false,
"text": "<p>Can be done by making sure that you have correct values set for Reponse.cachecontrol, response.expires etc according to your need. This link may be helpful in understanding what they mean. <a href=\"http://aspjavascript.com/lesson07.asp\" rel=\"nofollow noreferrer\">http://aspjavascript.com/lesson07.asp</a> </p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5836/"
]
| Is there a command in classic ASP I can use to tell the browser not to pull the page from it's cache, or, to not cache, or clear the cache of my page? | You can use HTML meta tags:
```
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="Fri, 01 Jan 1999 1:00:00 GMT" />
<meta http-equiv="Last-Modified" content="0" />
<meta http-equiv="Cache-Control" content="no-cache, must-revalidate" />
```
Or you can use ASP response headers:
```
<%
Response.CacheControl = "no-cache"
Response.AddHeader "Pragma", "no-cache"
Response.Expires = -1
%>
``` |
115,764 | <p>I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file.</p>
<p>The calendar object just has a method that adds events as they get parsed.</p>
<p>Now I want to create a factory function that creates a calendar from a file object, path, or URL.</p>
<p>I've been using the <a href="http://codespeak.net/icalendar/" rel="nofollow noreferrer">iCalendar python module</a>, which implements a factory function as a class method directly on the Class that it returns an instance of:</p>
<pre><code>cal = icalendar.Calendar.from_string(data)
</code></pre>
<p>From what little I know about Java, this is a common pattern in Java code, though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from.</p>
<p>The question is, is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ?</p>
| [
{
"answer_id": 115777,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 3,
"selected": false,
"text": "<p>It's pythonic not to think about esoteric difference in some pattern you read somewhere and now want to use everywhere, like the factory pattern.</p>\n\n<p>Most of the time you would think of a @staticmethod as a solution it's probably better to use a module function, except when you stuff multiple classes in one module and each has a different implementation of the same interface, then it's better to use a @staticmethod</p>\n\n<p>Ultimately weather you create your instances by a @staticmethod or by module function makes little difference.</p>\n\n<p>I'd probably use the initializer ( __init__ ) of a class because one of the more accepted \"patterns\" in python is that the factory for a class is the class initialization.</p>\n"
},
{
"answer_id": 115802,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 0,
"selected": false,
"text": "<p>The factory pattern has its own <a href=\"http://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">strengths and weaknesses</a>. However, choosing one way to create instances usually has little pragmatic effect on your code.</p>\n"
},
{
"answer_id": 115807,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 2,
"selected": false,
"text": "<p>IMHO a module-level method is a cleaner solution. It hides behind the Python module system that gives it a unique namespace prefix, something the \"factory pattern\" is commonly used for. </p>\n"
},
{
"answer_id": 115853,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": false,
"text": "<p>[<strong>Note</strong>. Be very cautious about separating \"Calendar\" a collection of events, and \"Event\" - a single event on a calendar. In your question, it seems like there could be some confusion.]</p>\n\n<p>There are many variations on the Factory design pattern.</p>\n\n<ol>\n<li><p>A stand-alone convenience function (e.g., calendarMaker(data))</p></li>\n<li><p>A separate class (e.g., CalendarParser) which builds your target class (Calendar).</p></li>\n<li><p>A class-level method (e.g. Calendar.from_string) method.</p></li>\n</ol>\n\n<p>These have different purposes. All are Pythonic, the questions are \"what do you <em>mean</em>?\" and \"what's likely to change?\" Meaning is everything; change is important.</p>\n\n<p>Convenience functions are Pythonic. Languages like Java can't have free-floating functions; you must wrap a lonely function in a class. Python allows you to have a lonely function without the overhead of a class. A function is relevant when your constructor has no state changes or alternate strategies or any memory of previous actions. </p>\n\n<p>Sometimes folks will define a class and then provide a convenience function that makes an instance of the class, sets the usual parameters for state and strategy and any other configuration, and then calls the single relevant method of the class. This gives you both the statefulness of class plus the flexibility of a stand-alone function.</p>\n\n<p>The class-level method pattern is used, but it has limitations. One, it's forced to rely on class-level variables. Since these can be confusing, a complex constructor as a static method runs into problems when you need to add features (like statefulness or alternative strategies.) Be sure you're never going to expand the static method.</p>\n\n<p>Two, it's more-or-less irrelevant to the rest of the class methods and attributes. This kind of <code>from_string</code> is just one of many alternative encodings for your Calendar objects. You might have a <code>from_xml</code>, <code>from_JSON</code>, <code>from_YAML</code> and on and on. None of this has the least relevance to what a Calendar IS or what it DOES. These methods are all about how a Calendar is encoded for transmission.</p>\n\n<p>What you'll see in the mature Python libraries is that factories are separate from the things they create. Encoding (as strings, XML, JSON, YAML) is subject to a great deal of more-or-less random change. The essential thing, however, rarely changes.</p>\n\n<p>Separate the two concerns. Keep encoding and representation as far away from state and behavior as you can.</p>\n"
},
{
"answer_id": 115933,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 0,
"selected": false,
"text": "<p>A staticmethod rarely has value, but a classmethod may be useful. It depends on what you want the class and the factory function to actually do.</p>\n\n<p>A factory function in a module would always make an instance of the 'right' type (where 'right' in your case is the 'Calendar' class always, but you might also make it dependant on the contents of what it is creating the instance out of.)</p>\n\n<p>Use a classmethod if you wish to make it dependant not on the data, but on the class you call it on. A classmethod is like a staticmethod in that you can call it on the class, without an instance, but it receives the class it was called on as first argument. This allows you to actually create an instance of <em>that class</em>, which may be a subclass of the original class. An example of a classmethod is dict.fromkeys(), which creates a dict from a list of keys and a single value (defaulting to None.) Because it's a classmethod, when you subclass dict you get the 'fromkeys' method entirely for free. Here's an example of how one could write dict.fromkeys() oneself:</p>\n\n<pre><code>class dict_with_fromkeys(dict):\n @classmethod\n def fromkeys(cls, keys, value=None):\n self = cls()\n for key in keys:\n self[key] = value\n return self\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2900/"
]
| I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file.
The calendar object just has a method that adds events as they get parsed.
Now I want to create a factory function that creates a calendar from a file object, path, or URL.
I've been using the [iCalendar python module](http://codespeak.net/icalendar/), which implements a factory function as a class method directly on the Class that it returns an instance of:
```
cal = icalendar.Calendar.from_string(data)
```
From what little I know about Java, this is a common pattern in Java code, though I seem to find more references to a factory method being on a different class than the class you actually want to instantiate instances from.
The question is, is this also considered Pythonic ? Or is it considered more pythonic to just create a module-level method as the factory function ? | [**Note**. Be very cautious about separating "Calendar" a collection of events, and "Event" - a single event on a calendar. In your question, it seems like there could be some confusion.]
There are many variations on the Factory design pattern.
1. A stand-alone convenience function (e.g., calendarMaker(data))
2. A separate class (e.g., CalendarParser) which builds your target class (Calendar).
3. A class-level method (e.g. Calendar.from\_string) method.
These have different purposes. All are Pythonic, the questions are "what do you *mean*?" and "what's likely to change?" Meaning is everything; change is important.
Convenience functions are Pythonic. Languages like Java can't have free-floating functions; you must wrap a lonely function in a class. Python allows you to have a lonely function without the overhead of a class. A function is relevant when your constructor has no state changes or alternate strategies or any memory of previous actions.
Sometimes folks will define a class and then provide a convenience function that makes an instance of the class, sets the usual parameters for state and strategy and any other configuration, and then calls the single relevant method of the class. This gives you both the statefulness of class plus the flexibility of a stand-alone function.
The class-level method pattern is used, but it has limitations. One, it's forced to rely on class-level variables. Since these can be confusing, a complex constructor as a static method runs into problems when you need to add features (like statefulness or alternative strategies.) Be sure you're never going to expand the static method.
Two, it's more-or-less irrelevant to the rest of the class methods and attributes. This kind of `from_string` is just one of many alternative encodings for your Calendar objects. You might have a `from_xml`, `from_JSON`, `from_YAML` and on and on. None of this has the least relevance to what a Calendar IS or what it DOES. These methods are all about how a Calendar is encoded for transmission.
What you'll see in the mature Python libraries is that factories are separate from the things they create. Encoding (as strings, XML, JSON, YAML) is subject to a great deal of more-or-less random change. The essential thing, however, rarely changes.
Separate the two concerns. Keep encoding and representation as far away from state and behavior as you can. |
115,773 | <p>I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 but not through the IP or the windows machine name. It could be a machine configuration difference or a newer version of CherryPy or Python. Any ideas how I can bind to the correct IP address?</p>
<p>Edit: to make it clear, I currently don't have a config file at all.</p>
| [
{
"answer_id": 115826,
"author": "nosklo",
"author_id": 17160,
"author_profile": "https://Stackoverflow.com/users/17160",
"pm_score": 5,
"selected": true,
"text": "<p>That depends on how you are running the cherrypy init.</p>\n\n<p>If using cherrypy 3.1 syntax, that wold do it:</p>\n\n<pre><code>cherrypy.server.socket_host = 'www.machinename.com'\ncherrypy.engine.start()\ncherrypy.engine.block()\n</code></pre>\n\n<p>Of course you can have something more fancy, like subclassing the server class, or using config files. Those uses are covered in <a href=\"http://www.cherrypy.org/wiki/ServerAPI\" rel=\"noreferrer\" title=\"Cherrypy Server API documentation\">the documentation</a>.</p>\n\n<p>But that should be enough. If not just tell us what you are doing and cherrypy version, and I will edit this answer.</p>\n"
},
{
"answer_id": 152012,
"author": "fumanchu",
"author_id": 23692,
"author_profile": "https://Stackoverflow.com/users/23692",
"pm_score": 5,
"selected": false,
"text": "<pre><code>server.socket_host: '0.0.0.0'\n</code></pre>\n\n<p>...would also work. That's IPv4 INADDR_ANY, which means, \"listen on all interfaces\".</p>\n\n<p>In a config file, the syntax is:</p>\n\n<pre><code>[global]\nserver.socket_host: '0.0.0.0'\n</code></pre>\n\n<p>In code:</p>\n\n<pre><code>cherrypy.server.socket_host = '0.0.0.0'\n</code></pre>\n"
},
{
"answer_id": 41367529,
"author": "mzobe",
"author_id": 7351049,
"author_profile": "https://Stackoverflow.com/users/7351049",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import cherrypy\n\nclass HelloWorld(object):\n def index(self):\n return \"Hello World!\"\n index.exposed = True\n\ncherrypy.server.socket_host = '0.0.0.0' # put it here \ncherrypy.quickstart(HelloWorld())\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852/"
]
| I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 but not through the IP or the windows machine name. It could be a machine configuration difference or a newer version of CherryPy or Python. Any ideas how I can bind to the correct IP address?
Edit: to make it clear, I currently don't have a config file at all. | That depends on how you are running the cherrypy init.
If using cherrypy 3.1 syntax, that wold do it:
```
cherrypy.server.socket_host = 'www.machinename.com'
cherrypy.engine.start()
cherrypy.engine.block()
```
Of course you can have something more fancy, like subclassing the server class, or using config files. Those uses are covered in [the documentation](http://www.cherrypy.org/wiki/ServerAPI "Cherrypy Server API documentation").
But that should be enough. If not just tell us what you are doing and cherrypy version, and I will edit this answer. |
115,789 | <p>It's my understanding that nulls are not indexable in DB2, so assuming we have a huge table (Sales) with a date column (sold_on) which is normally a date, but is occasionally (10% of the time) null.</p>
<p>Furthermore, let's assume that it's a legacy application that we can't change, so those nulls are staying there and mean something (let's say sales that were returned).</p>
<p>We can make the following query fast by putting an index on the sold_on and total columns</p>
<pre><code>Select * from Sales
where
Sales.sold_on between date1 and date2
and Sales.total = 9.99
</code></pre>
<p>But an index won't make this query any faster:</p>
<pre><code>Select * from Sales
where
Sales.sold_on is null
and Sales.total = 9.99
</code></pre>
<p>Because the indexing is done on the value.</p>
<p>Can I index nulls? Maybe by changing the index type? Indexing the indicator column?</p>
| [
{
"answer_id": 115824,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 3,
"selected": true,
"text": "<p>I'm no DB2 expert, but if 10% of your values are null, I don't think an index on that column alone will ever help your query. 10% is too many to bother using an index for -- it'll just do a table scan. If you were talking about 2-3%, I think it would actually use your index.</p>\n\n<p>Think about how many records are on a page/block -- say 20. The reason to use an index is to avoid fetching pages you don't need. The odds that a given page will contain 0 records that are null is (90%)^20, or 12%. Those aren't good odds -- you're going to need 88% of your pages to be fetched anyway, using the index isn't very helpful.</p>\n\n<p>If, however, your select clause only included a few columns (and not *) -- say just salesid, you could probably get it to use an index on (sold_on,salesid), as the read of the data page wouldn't be needed -- all the data would be in the index.</p>\n"
},
{
"answer_id": 116116,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 1,
"selected": false,
"text": "<p>The rule of thumb is that an index is useful for values up on to 15% of the records. ... so an index might be useful here. </p>\n\n<p>If DB2 won't index nulls, then I would suggest adding a boolean field, IsSold, and set it to true whenever the sold_on date gets set (this could be done in a trigger). </p>\n\n<p>That's not the nicest solution, but it might be what you need. </p>\n"
},
{
"answer_id": 405522,
"author": "Troels Arvin",
"author_id": 4462,
"author_profile": "https://Stackoverflow.com/users/4462",
"pm_score": 3,
"selected": false,
"text": "<p>From where did you get the impression that DB2 doesn't index NULLs? I can't find anything in documentation or articles supporting the claim. And I just performed a query in a large table using a IS NULL restriction involving an indexed column containing a small fraction of NULLs; in this case, DB2 certainly used the index (verified by an EXPLAIN, and by observing that the database responded instantly instead of spending time to perform a table scan).</p>\n\n<p>So: I claim that DB2 has no problem with NULLs in non-primary key indexes.</p>\n\n<p>But as others have written: Your data may be composed in a way where DB2 thinks that using an index will not be quicker. Or the database's statistics aren't up-to-date for the involved table(s).</p>\n"
},
{
"answer_id": 1004725,
"author": "Fred Sobotka",
"author_id": 123875,
"author_profile": "https://Stackoverflow.com/users/123875",
"pm_score": 0,
"selected": false,
"text": "<p>Troels is correct; even rows with a SOLD_ON value of NULL will benefit from an index on that column. If you're doing ranged searches on SOLD_ON, you may benefit even more by creating a clustered index that begins with SOLD_ON. In this particular example, it may not require much additional overhead to maintain the clustering order based on SOLD_ON, since newer rows added will most likely have a newer SOLD_ON date.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9056/"
]
| It's my understanding that nulls are not indexable in DB2, so assuming we have a huge table (Sales) with a date column (sold\_on) which is normally a date, but is occasionally (10% of the time) null.
Furthermore, let's assume that it's a legacy application that we can't change, so those nulls are staying there and mean something (let's say sales that were returned).
We can make the following query fast by putting an index on the sold\_on and total columns
```
Select * from Sales
where
Sales.sold_on between date1 and date2
and Sales.total = 9.99
```
But an index won't make this query any faster:
```
Select * from Sales
where
Sales.sold_on is null
and Sales.total = 9.99
```
Because the indexing is done on the value.
Can I index nulls? Maybe by changing the index type? Indexing the indicator column? | I'm no DB2 expert, but if 10% of your values are null, I don't think an index on that column alone will ever help your query. 10% is too many to bother using an index for -- it'll just do a table scan. If you were talking about 2-3%, I think it would actually use your index.
Think about how many records are on a page/block -- say 20. The reason to use an index is to avoid fetching pages you don't need. The odds that a given page will contain 0 records that are null is (90%)^20, or 12%. Those aren't good odds -- you're going to need 88% of your pages to be fetched anyway, using the index isn't very helpful.
If, however, your select clause only included a few columns (and not \*) -- say just salesid, you could probably get it to use an index on (sold\_on,salesid), as the read of the data page wouldn't be needed -- all the data would be in the index. |
115,809 | <p>Many beginning programmers write code like this:</p>
<pre><code>sub copy_file ($$) {
my $from = shift;
my $to = shift;
`cp $from $to`;
}
</code></pre>
<p>Is this bad, and why? Should backticks ever be used? If so, how?</p>
| [
{
"answer_id": 115810,
"author": "raldi",
"author_id": 7598,
"author_profile": "https://Stackoverflow.com/users/7598",
"pm_score": 3,
"selected": false,
"text": "<p>Backticks should be used if and only if you need to capture the output of a command. Otherwise, system() should be used. And, of course, if there's a Perl function or CPAN module that does the job, this should be used instead of either.</p>\n\n<p>In either case, two things are strongly encouraged:</p>\n\n<p>First, <strong>sanitize all inputs:</strong> Use Taint mode (-T) if the code is exposed to possible untrusted input. Even if it's not, make sure to handle (or prevent) funky characters like space or the three kinds of quote.</p>\n\n<p>Second, <strong>check the return code</strong> to make sure the command succeeded. Here is an example of how to do so:</p>\n\n<pre><code>my $cmd = \"./do_something.sh foo bar\";\nmy $output = `$cmd`;\n\nif ($?) {\n die \"Error running [$cmd]\";\n}\n</code></pre>\n"
},
{
"answer_id": 115814,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>Your example's bad because there are perl builtins to do that which are portable and usually more efficient than the backtick alternative.</p>\n\n<p>They should be used only when there's no Perl builtin (or module) alternative. This is both for backticks and system() calls. Backticks are intended for capturing output of the executed command.</p>\n"
},
{
"answer_id": 115817,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 3,
"selected": false,
"text": "<p>Use backticks when you want to collect the output from the command.</p>\n\n<p>Otherwise <code>system()</code> is a better choice, especially if you don't need to invoke a shell to handle metacharacters or command parsing. You can avoid that by passing a list to system(), eg <code>system('cp', 'foo', 'bar')</code> (however you'd probably do better to use a module for that <em>particular</em> example :))</p>\n"
},
{
"answer_id": 115846,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 2,
"selected": false,
"text": "<p>In Perl, there's always more than one way to do anything you want. The primary point of backticks is to get the standard output of the shell command into a Perl variable. (In your example, anything that the cp command prints will be returned to the caller.) The downside of using backticks in your example is you don't check the shell command's return value; cp could fail and you wouldn't notice. You can use this with the special Perl variable $?. When I want to execute a shell command, I tend to use <strong>system</strong>:</p>\n\n<pre><code>system(\"cp $from $to\") == 0\n or die \"Unable to copy $from to $to!\";\n</code></pre>\n\n<p>(Also observe that this will fail on filenames with embedded spaces, but I presume that's not the point of the question.)</p>\n\n<p>Here's a contrived example of where backticks might be useful:</p>\n\n<pre><code>my $user = `whoami`;\nchomp $user;\nprint \"Hello, $user!\\n\";\n</code></pre>\n\n<p>For more complicated cases, you can also use <strong>open</strong> as a pipe:</p>\n\n<pre><code>open WHO, \"who|\"\n or die \"who failed\";\nwhile(<WHO>) {\n # Do something with each line\n}\nclose WHO;\n</code></pre>\n"
},
{
"answer_id": 115893,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 1,
"selected": false,
"text": "<p>Backticks are only supposed to be used when you want to capture output. Using them here \"looks silly.\" It's going to clue anyone looking at your code into the fact that you aren't very familiar with Perl.</p>\n\n<p>Use backticks if you want to capture output.\nUse system if you want to run a command. One advantage you'll gain is the ability to check the return status.\nUse modules where possible for portability. In this case, File::Copy fits the bill.</p>\n"
},
{
"answer_id": 115931,
"author": "Ovid",
"author_id": 8003,
"author_profile": "https://Stackoverflow.com/users/8003",
"pm_score": 4,
"selected": false,
"text": "<p>The rule is simple: never use backticks if you can find a built-in to do the same job, or if their is a robust module on the CPAN which will do it for you. Backticks often rely on unportable code and even if you untaint the variables, you can still open yourself up to a lot of security holes.</p>\n\n<p><em>Never</em> use backticks with user data unless you have very tightly specified what is allowed (not what is disallowed -- you'll miss things)! This is very, very dangerous.</p>\n"
},
{
"answer_id": 116114,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 1,
"selected": false,
"text": "<p>In general, it's best to use <strong>system</strong> instead of backticks because:</p>\n\n<ol>\n<li><p><strong>system</strong> encourages the caller to check the return code of the command.</p></li>\n<li><p><strong>system</strong> allows \"indirect object\" notation, which is more secure and adds flexibility.</p></li>\n<li><p>Backticks are culturally tied to shell scripting, which might not be common among readers of the code.</p></li>\n<li><p>Backticks use minimal syntax for what can be a heavy command.</p></li>\n</ol>\n\n<p>One reason users might be temped to use backticks instead of <strong>system</strong> is to hide STDOUT from the user. This is more easily and flexibly accomplished by redirecting the STDOUT stream:</p>\n\n<pre><code>my $cmd = 'command > /dev/null';\nsystem($cmd) == 0 or die \"system $cmd failed: $?\"\n</code></pre>\n\n<p>Further, getting rid of STDERR is easily accomplished:</p>\n\n<pre><code>my $cmd = 'command 2> error_file.txt > /dev/null';\n</code></pre>\n\n<p>In situations where it makes sense to use backticks, I prefer to use the <strong>qx{}</strong> in order to emphasize that there is a heavy-weight command occurring.</p>\n\n<p>On the other hand, having Another Way to Do It can really help. Sometimes you just need to see what a command prints to STDOUT. Backticks, when used as in shell scripts are just the right tool for the job.</p>\n"
},
{
"answer_id": 116127,
"author": "Michael Cramer",
"author_id": 1496728,
"author_profile": "https://Stackoverflow.com/users/1496728",
"pm_score": 2,
"selected": false,
"text": "<p>From the \"perlop\" manpage:</p>\n\n<blockquote>\n <p>That doesn't mean you should go out of\n your way to avoid backticks when\n they're the right way to get something\n done. Perl was made to be a glue\n language, and one of the things it\n glues together is commands. Just\n understand what you're getting\n yourself into.</p>\n</blockquote>\n"
},
{
"answer_id": 116191,
"author": "Erik Johansen",
"author_id": 1214705,
"author_profile": "https://Stackoverflow.com/users/1214705",
"pm_score": 3,
"selected": false,
"text": "<p>Another way to capture stdout(in addition to pid and exit code) is to use <a href=\"http://search.cpan.org/%7Etty/kurila-1.13_0/lib/IPC/Open3.pm\" rel=\"nofollow noreferrer\">IPC::Open3</a> possibily negating the use of both system and backticks.</p>\n"
},
{
"answer_id": 116583,
"author": "Josh McAdams",
"author_id": 12731,
"author_profile": "https://Stackoverflow.com/users/12731",
"pm_score": 2,
"selected": false,
"text": "<p>For the case you are showing using the <a href=\"http://search.cpan.org/search?query=File+Copy&mode=module\" rel=\"nofollow noreferrer\">File::Copy</a> module is probably best. However, to answer your question, whenever I need to run a system command I typically rely on <a href=\"http://search.cpan.org/dist/IPC-Run3/\" rel=\"nofollow noreferrer\">IPC::Run3</a>. It provides a lot of functionality such as collecting the return code and the standard and error output.</p>\n"
},
{
"answer_id": 117306,
"author": "Sam Kington",
"author_id": 6832,
"author_profile": "https://Stackoverflow.com/users/6832",
"pm_score": 2,
"selected": false,
"text": "<p>Whatever you do, as well as sanitising input and checking the return value of your code, make sure you call any external programs with their explicit, full path. e.g. say</p>\n\n<pre><code>my $user = `/bin/whoami`;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>my $result = `/bin/cp $from $to`;\n</code></pre>\n\n<p>Saying just \"whoami\" or \"cp\" runs the risk of accidentally running a command other than what you intended, if the user's path changes - which is a security vulnerability that a malicious attacker could attempt to exploit.</p>\n"
},
{
"answer_id": 117636,
"author": "user19115",
"author_id": 19115,
"author_profile": "https://Stackoverflow.com/users/19115",
"pm_score": 0,
"selected": false,
"text": "<p>Perl has a split personality. On the one hand it is a great scripting language that can replace the use of a shell. In this kind of one-off I-watching-the-outcome use, backticks are convenient.\n<p>\nWhen used a programming language, backticks are to be avoided. This is a lack of error\nchecking and, if the separate program backticks execute can be avoided, efficiency is\ngained.\n<p>\nAside from the above, the system function should be used when the command's output is not being used.</p>\n"
},
{
"answer_id": 118904,
"author": "pjf",
"author_id": 19422,
"author_profile": "https://Stackoverflow.com/users/19422",
"pm_score": 6,
"selected": true,
"text": "<p>A few people have already mentioned that you should only use backticks when:</p>\n\n<ul>\n<li>You need to capture (or supress) the output.</li>\n<li>There exists no built-in function or Perl module to do the same task, or you have a good reason not to use the module or built-in.</li>\n<li>You sanitise your input.</li>\n<li>You check the return value.</li>\n</ul>\n\n<p>Unfortunately, things like checking the return value <em>properly</em> can be quite challenging. Did it die to a signal? Did it run to completion, but return a funny exit status? The standard ways of trying to interpret <code>$?</code> are just awful.</p>\n\n<p>I'd recommend using the <a href=\"http://search.cpan.org/perldoc?IPC::System::Simple\" rel=\"noreferrer\">IPC::System::Simple</a> module's <code>capture()</code> and <code>system()</code> functions rather than backticks. The <code>capture()</code> function works just like backticks, except that:</p>\n\n<ul>\n<li>It provides detailed diagnostics if the command doesn't start, is killed by a signal, or returns an unexpected exit value.</li>\n<li>It provides detailed diagnostics if passed tainted data.</li>\n<li>It provides an easy mechanism for specifying acceptable exit values.</li>\n<li>It allows you to call backticks without the shell, if you want to.</li>\n<li>It provides reliable mechanisms for avoiding the shell, even if you use a single argument.</li>\n</ul>\n\n<p>The commands also work consistently across operating systems and Perl versions, unlike Perl's built-in <code>system()</code> which may not check for tainted data when called with multiple arguments on older versions of Perl (eg, 5.6.0 with multiple arguments), or which may call the shell anyway under Windows.</p>\n\n<p>As an example, the following code snippet will save the results of a call to <code>perldoc</code> into a scalar, avoids the shell, and throws an exception if the page cannot be found (since perldoc returns 1).</p>\n\n<pre><code>#!/usr/bin/perl -w\nuse strict;\nuse IPC::System::Simple qw(capture);\n\n# Make sure we're called with command-line arguments.\n@ARGV or die \"Usage: $0 arguments\\n\";\n\nmy $documentation = capture('perldoc', @ARGV);\n</code></pre>\n\n<p><a href=\"http://search.cpan.org/perldoc?IPC::System::Simple\" rel=\"noreferrer\">IPC::System::Simple</a> is pure Perl, works on 5.6.0 and above, and doesn't have any dependencies that wouldn't normally come with your Perl distribution. (On Windows it depends upon a Win32:: module that comes with both ActiveState and Strawberry Perl).</p>\n\n<p>Disclaimer: I'm the author of <a href=\"http://search.cpan.org/perldoc?IPC::System::Simple\" rel=\"noreferrer\">IPC::System::Simple</a>, so I may show some bias.</p>\n"
},
{
"answer_id": 123033,
"author": "user21308",
"author_id": 21308,
"author_profile": "https://Stackoverflow.com/users/21308",
"pm_score": 0,
"selected": false,
"text": "<p>Backticks are for amateurs. The bullet-proof solution is a \"Safe Pipe Open\" (see \"man perlipc\"). You exec your command in another process, which allows you to first futz with STDERR, setuid, etc. Advantages: it does <em>not</em> rely on the shell to parse @ARGV, unlike open(\"$cmd $args|\"), which is unreliable. You can redirect STDERR and change user priviliges without changing the behavior of your main program. This is more verbose than backticks but you can wrap it in your own function like run_cmd($cmd,@args);</p>\n\n<pre><code>\nsub run_cmd {\n my $cmd = shift @_;\n my @args = @_;\n\n my $fh; # file handle\n my $pid = open($fh, '-|');\n defined($pid) or die \"Could not fork\";\n if ($pid == 0) {\n open STDERR, '>/dev/null';\n # setuid() if necessary\n exec ($cmd, @args) or exit 1;\n }\n wait; # may want to time out here?\n if ($? >> 8) { die \"Error running $cmd: [$?]\"; }\n while (<$fh>) {\n # Have fun with the output of $cmd\n }\n close $fh;\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
| Many beginning programmers write code like this:
```
sub copy_file ($$) {
my $from = shift;
my $to = shift;
`cp $from $to`;
}
```
Is this bad, and why? Should backticks ever be used? If so, how? | A few people have already mentioned that you should only use backticks when:
* You need to capture (or supress) the output.
* There exists no built-in function or Perl module to do the same task, or you have a good reason not to use the module or built-in.
* You sanitise your input.
* You check the return value.
Unfortunately, things like checking the return value *properly* can be quite challenging. Did it die to a signal? Did it run to completion, but return a funny exit status? The standard ways of trying to interpret `$?` are just awful.
I'd recommend using the [IPC::System::Simple](http://search.cpan.org/perldoc?IPC::System::Simple) module's `capture()` and `system()` functions rather than backticks. The `capture()` function works just like backticks, except that:
* It provides detailed diagnostics if the command doesn't start, is killed by a signal, or returns an unexpected exit value.
* It provides detailed diagnostics if passed tainted data.
* It provides an easy mechanism for specifying acceptable exit values.
* It allows you to call backticks without the shell, if you want to.
* It provides reliable mechanisms for avoiding the shell, even if you use a single argument.
The commands also work consistently across operating systems and Perl versions, unlike Perl's built-in `system()` which may not check for tainted data when called with multiple arguments on older versions of Perl (eg, 5.6.0 with multiple arguments), or which may call the shell anyway under Windows.
As an example, the following code snippet will save the results of a call to `perldoc` into a scalar, avoids the shell, and throws an exception if the page cannot be found (since perldoc returns 1).
```
#!/usr/bin/perl -w
use strict;
use IPC::System::Simple qw(capture);
# Make sure we're called with command-line arguments.
@ARGV or die "Usage: $0 arguments\n";
my $documentation = capture('perldoc', @ARGV);
```
[IPC::System::Simple](http://search.cpan.org/perldoc?IPC::System::Simple) is pure Perl, works on 5.6.0 and above, and doesn't have any dependencies that wouldn't normally come with your Perl distribution. (On Windows it depends upon a Win32:: module that comes with both ActiveState and Strawberry Perl).
Disclaimer: I'm the author of [IPC::System::Simple](http://search.cpan.org/perldoc?IPC::System::Simple), so I may show some bias. |
115,813 | <p>I have been trying to produce a statically linked "single binary" version of my game for windows. I want to link with sdl, sdl_image and sdl_mixer which in turn pull in a few support libraries. Unfortunately I haven't found a way to get them all to compile and link using cygwin/mingw/gcc. As far as I can tell all existing public versions are only shared libraries / dlls.</p>
<p>Please note that I'm not talking about licencing here. The source will be open thus the GPL/LGPLness of sdl is not relevant.</p>
| [
{
"answer_id": 115854,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 0,
"selected": false,
"text": "<p>That's because the SDL libs are under the LGPL-license.</p>\n\n<p>If you want to static link the libs (you can do that if your recompile them. It needs some hacking into the makefiles though) you have to place your game under some compatible open source license as well.</p>\n\n<p>The SDL-libs come as shared libraries because most programs that use them are closed source. The binary distribution comes in a form that most people need.</p>\n"
},
{
"answer_id": 511910,
"author": "David Locke",
"author_id": 1447,
"author_profile": "https://Stackoverflow.com/users/1447",
"pm_score": 2,
"selected": false,
"text": "<p>Via this <a href=\"http://lists.libsdl.org/pipermail/sdl-libsdl.org/2008-June/065521.html\" rel=\"nofollow noreferrer\">SDL mailing list post</a> it seems that the sdl development tools ship with a sdl-config script that you can use with the --static-libs flag to determine what linker flags you need to use.</p>\n"
},
{
"answer_id": 525124,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 6,
"selected": true,
"text": "<p>When compiling your project, you need to make just a couple changes to your makefile.</p>\n\n<ul>\n<li>Instead of <code>sdl-config --libs</code>, use <code>sdl-config --static-libs</code></li>\n<li>Surround the use of the above-mentioned <code>sdl-config --static-libs</code> with <code>-Wl,-Bstatic</code> and <code>-Wl,-Bdynamic</code>. This tells GCC to force static linking, but only for the libraries specified between them.</li>\n</ul>\n\n<p>If your makefile currently looks like:</p>\n\n<pre><code>SDLLIBS=`sdl-config --libs`\n</code></pre>\n\n<p>Change it to:</p>\n\n<pre><code>SDLLIBS=-Wl,-Bstatic `sdl-config --static-libs` -Wl,-Bdynamic\n</code></pre>\n\n<p>These are actually the same things you <em>should</em> do on Unix-like systems, but it usually doesn't cause as many errors on Unix-likes if you use the simpler <code>-static</code> flag to GCC, like it does on Windows.</p>\n"
},
{
"answer_id": 1416421,
"author": "singpolyma",
"author_id": 8611,
"author_profile": "https://Stackoverflow.com/users/8611",
"pm_score": 0,
"selected": false,
"text": "<p>On my system (Ubuntu) I have to use the following flags:</p>\n\n<pre><code>-Wl,Bstatic -lSDL_image `sdl-config --libs` -lpng12 -lz -ltiff -ljpeg -lasound -laudio -lesd -Wl,-Bdynamic `directfb-config --libs` -lpulse-simple -lcaca -laa -ldl\n</code></pre>\n\n<p>That links SDL, SDL<code>_</code>image, and many of their dependencies as static. libdl you never want static, so making a fully-static binary that uses SDL<code>_</code>image is a poor idea. pulse,caca,aa, and directfb can probably be made static. I haven't got far enough to figure them out yet.</p>\n"
},
{
"answer_id": 23585684,
"author": "Anónimo",
"author_id": 3624163,
"author_profile": "https://Stackoverflow.com/users/3624163",
"pm_score": 1,
"selected": false,
"text": "<p>Environment: VMWare Virtual Machine with Windows 7 x64 and Equipment we Dev c + + build 7.4.2.569, complilador g+ + (tdm-1) 4.6.1</p>\n\n<p>Once, SDL2-2.0.3 API installed as configuration Dev c ++ is not very clear what I've done as tradition requires command line.</p>\n\n<p>The first problem is that Windows 7 appears to have changed the methodology and they go to his ball. Inventory. Ref. <a href=\"https://stackoverflow.com/users/464581/cheers-and-hth-alf\">https://stackoverflow.com/users/464581/cheers-and-hth-alf</a></p>\n\n<p>After the first hurdle, SDL_platform.h is that bad, it's down another, I do not remember where I downloaded, but the next does not work in the indicated version.</p>\n\n<p>We must put SDL2.h ls in the directory of the executable.</p>\n\n<p><code>D:\\prg_desa\\zsdl2>g++ bar.cpp main.cpp -o pepe1 -ID:\\SDL2-2.0.3\\i686-w64-mingw32\\include\\SDL2 -LD:\\SDL2-2.0.3\\i686-w64-mingw32\\lib -lmingw32 -lSDL2main -lSDL2 -mwindow</code></p>\n\n<p>I've finally compiled and works SDL2 testing.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20555/"
]
| I have been trying to produce a statically linked "single binary" version of my game for windows. I want to link with sdl, sdl\_image and sdl\_mixer which in turn pull in a few support libraries. Unfortunately I haven't found a way to get them all to compile and link using cygwin/mingw/gcc. As far as I can tell all existing public versions are only shared libraries / dlls.
Please note that I'm not talking about licencing here. The source will be open thus the GPL/LGPLness of sdl is not relevant. | When compiling your project, you need to make just a couple changes to your makefile.
* Instead of `sdl-config --libs`, use `sdl-config --static-libs`
* Surround the use of the above-mentioned `sdl-config --static-libs` with `-Wl,-Bstatic` and `-Wl,-Bdynamic`. This tells GCC to force static linking, but only for the libraries specified between them.
If your makefile currently looks like:
```
SDLLIBS=`sdl-config --libs`
```
Change it to:
```
SDLLIBS=-Wl,-Bstatic `sdl-config --static-libs` -Wl,-Bdynamic
```
These are actually the same things you *should* do on Unix-like systems, but it usually doesn't cause as many errors on Unix-likes if you use the simpler `-static` flag to GCC, like it does on Windows. |
115,835 | <p>I am looking into an image processing problem for semi-real time detection of certain scenarios. My goal is to have the live video arrive as Motion JPEG frames in my Java code <em>somehow</em>. </p>
<p>I am familiar with the <a href="http://java.sun.com/javase/technologies/desktop/media/jmf/" rel="noreferrer">Java Media Framework</a> and, sadly, I think we can consider that an effectively dead API. I am also familiar with <a href="http://www.axis.com/" rel="noreferrer">Axis boxes</a> and, while I really like their solution, I would appreciate any critical feedback on my specific points of interest. </p>
<p>This is how I define "best" for the purpose of this discussion:</p>
<ul>
<li>Latency - if I'm controlling the camera using this video stream, I would like to keep my round-trip latency at less than 100 milliseconds if possible. That's measured as the time between my control input to the time when I see the visible change. EDIT some time later: another thing to keep in mind is that camera control is likely to be a combination of manual and automatic (event triggers). We need to see those pictures right away, even if the high quality feed is archived separately.</li>
<li>Cost - free / open source is better than not free.</li>
<li>Adjustable codec parameters - I need to be able to tune the codec for certain situations. Sometimes a high-speed low-resolution stream is actually easier to process.</li>
<li>"Integration" with Java - how much trouble is it to hook this solution to my code? Am I sending packets over a socket? Hitting URLs? Installing Direct3D / JNI combinations?</li>
<li>Windows / Linux / both? - I would prefer an operating system agnostic solution because I have to deliver to several flavors of OS but there may be a solution that is optimal for one but not the other.</li>
</ul>
<p>NOTE: I am aware of other image / video capture codecs and that is not the focus of this question. I am specifically <em>not</em> interested in streaming APIs (e.g., MPEG4) due to the loss of frame accuracy. However, if there is a solution to my question that delivers another frame-accurate data stream, please chime in.</p>
<p>Follow-up to this question: at this point, I am strongly inclined to buy appliances such as the <a href="http://www.axis.com/products/video/video_server/index.htm" rel="noreferrer">Axis video encoders</a> rather than trying to capture the video in software or on the PC directly. However, if someone has alternatives, I'd love to hear them.</p>
| [
{
"answer_id": 117412,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": -1,
"selected": false,
"text": "<p>Have you ever looked at <a href=\"http://processing.org/\" rel=\"nofollow noreferrer\">Processing.org</a>? It's basically a simplified application framework for developing \"artsy\" applications and physical computing platforms, but it's based on Java and you can dig down to the \"real\" Java underneath.</p>\n\n<p>The reason it came to mind is that there are several video <a href=\"http://processing.org/reference/libraries/index.html\" rel=\"nofollow noreferrer\">libraries</a> for Processing which are basically Java components (at least I think they are - the site has all the technical information you might need). There is a <a href=\"http://processing.org/learning/tutorials/eclipse/\" rel=\"nofollow noreferrer\">tutorial</a> on using the Processing libraries and tools in the Eclipse IDE. There are also numerous <a href=\"http://processing.org/learning/libraries/\" rel=\"nofollow noreferrer\">examples</a> on video capture and processing.</p>\n\n<p>Even if you can't use the libraries directly, Processing is a great language/environment for working out algorithms. There are several great examples of image and video capture and real-time processing there.</p>\n"
},
{
"answer_id": 154115,
"author": "Greg Mattes",
"author_id": 13940,
"author_profile": "https://Stackoverflow.com/users/13940",
"pm_score": 2,
"selected": false,
"text": "<p>Regarding the dead-ness of JMF, are you aware of the <a href=\"http://fmj-sf.net\" rel=\"nofollow noreferrer\">FMJ implementation</a>? I don't know whether it qualifies as the \"best\" solution, but it's probably worth adding to the discussion.</p>\n"
},
{
"answer_id": 403990,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>FMJ can definitely capture video and turn it into MJPEG frames.</p>\n"
},
{
"answer_id": 9046373,
"author": "gtiwari333",
"author_id": 607637,
"author_profile": "https://Stackoverflow.com/users/607637",
"pm_score": 3,
"selected": false,
"text": "<p>This JavaCV implementation works fine.</p>\n\n<p><strong>CODE:</strong></p>\n\n<pre><code>import com.googlecode.javacv.OpenCVFrameGrabber;\n\nimport com.googlecode.javacv.cpp.opencv_core.IplImage;\nimport static com.googlecode.javacv.cpp.opencv_highgui.*;\n\npublic class CaptureImage {\n private static void captureFrame() {\n // 0-default camera, 1 - next...so on\n final OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);\n try {\n grabber.start();\n IplImage img = grabber.grab();\n if (img != null) {\n cvSaveImage(\"capture.jpg\", img);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n public static void main(String[] args) {\n captureFrame();\n }\n}\n</code></pre>\n\n<p>There is also <a href=\"http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/javacv-capture-save-flip-show-live.html\" rel=\"noreferrer\">post on viewing live video</a> from Camera .And <a href=\"http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/opencv-javacv-eclipse-project.html\" rel=\"noreferrer\">configuration for JavaCV :</a> </p>\n\n<p>I think this will meet your requirements.</p>\n"
},
{
"answer_id": 15982439,
"author": "syb0rg",
"author_id": 1937270,
"author_profile": "https://Stackoverflow.com/users/1937270",
"pm_score": 0,
"selected": false,
"text": "<p>This is my JavaCV implementation with high resolution video output and no noticeable drop in the frame-rate than other solutions (only when my webcam refocuses do I notice a slight drop, only for a moment though).</p>\n\n<pre><code>import java.awt.image.BufferedImage;\nimport java.io.File;\n\nimport javax.swing.JFrame;\n\nimport com.googlecode.javacv.CanvasFrame;\nimport com.googlecode.javacv.OpenCVFrameGrabber;\nimport com.googlecode.javacv.OpenCVFrameRecorder;\nimport com.googlecode.javacv.cpp.opencv_core.IplImage;\n\npublic class Webcam implements Runnable {\n\n IplImage image;\n static CanvasFrame frame = new CanvasFrame(\"Web Cam\");\n public static boolean running = false;\n\n public Webcam()\n {\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n\n @Override\n public void run()\n {\n try\n {\n grabber.setImageWidth(800);\n grabber.setImageHeight(600);\n grabber.start();\n while (running)\n {\n IplImage cvimg = grabber.grab();\n BufferedImage image;\n if (cvimg != null)\n {\n // opencv_core.cvFlip(cvimg, cvimg, 1); // mirror\n // show image on window\n image = cvimg.getBufferedImage();\n frame.showImage(image);\n }\n }\n grabber.stop();\n frame.dispose();\n } catch (Exception e)\n {\n e.printStackTrace();\n }\n }\n\n public static void main(String... args)\n {\n Webcam webcam = new Webcam();\n webcam.start();\n }\n\n public void start()\n {\n new Thread(this).start();\n running = true;\n }\n\n public void stop()\n {\n running = false;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 17839510,
"author": "Gabriel Ambrósio Archanjo",
"author_id": 2420599,
"author_profile": "https://Stackoverflow.com/users/2420599",
"pm_score": 1,
"selected": false,
"text": "<p>Below is shown a very simple implementation using <a href=\"http://marvinproject.sourceforge.net\" rel=\"nofollow noreferrer\">Marvin Framework</a>. Using Marvin you can add real time video processing easily. </p>\n\n<pre><code>import javax.swing.JFrame;\nimport marvin.gui.MarvinImagePanel;\nimport marvin.image.MarvinImage;\nimport marvin.video.MarvinJavaCVAdapter;\nimport marvin.video.MarvinVideoInterface;\n\npublic class SimpleVideoTest extends JFrame implements Runnable{\n\n private MarvinVideoInterface videoAdapter;\n private MarvinImage image;\n private MarvinImagePanel videoPanel;\n\n public SimpleVideoTest(){\n super(\"Simple Video Test\");\n\n // Create the VideoAdapter and connect to the camera\n videoAdapter = new MarvinJavaCVAdapter();\n videoAdapter.connect(0);\n\n // Create VideoPanel\n videoPanel = new MarvinImagePanel();\n add(videoPanel);\n\n // Start the thread for requesting the video frames \n new Thread(this).start();\n\n setSize(800,600);\n setVisible(true);\n }\n\n public static void main(String[] args) {\n SimpleVideoTest t = new SimpleVideoTest();\n t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n\n @Override\n public void run() {\n while(true){\n // Request a video frame and set into the VideoPanel\n image = videoAdapter.getFrame();\n videoPanel.setImage(image);\n }\n }\n}\n</code></pre>\n\n<p>Another <a href=\"http://sourceforge.net/p/marvinproject/code/108/tree/dev/trunk/MarvinSamples/src/video/videoFilters/VideoFilters.java\" rel=\"nofollow noreferrer\">example</a> applying multiple algorithms for real time video processing.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5812/"
]
| I am looking into an image processing problem for semi-real time detection of certain scenarios. My goal is to have the live video arrive as Motion JPEG frames in my Java code *somehow*.
I am familiar with the [Java Media Framework](http://java.sun.com/javase/technologies/desktop/media/jmf/) and, sadly, I think we can consider that an effectively dead API. I am also familiar with [Axis boxes](http://www.axis.com/) and, while I really like their solution, I would appreciate any critical feedback on my specific points of interest.
This is how I define "best" for the purpose of this discussion:
* Latency - if I'm controlling the camera using this video stream, I would like to keep my round-trip latency at less than 100 milliseconds if possible. That's measured as the time between my control input to the time when I see the visible change. EDIT some time later: another thing to keep in mind is that camera control is likely to be a combination of manual and automatic (event triggers). We need to see those pictures right away, even if the high quality feed is archived separately.
* Cost - free / open source is better than not free.
* Adjustable codec parameters - I need to be able to tune the codec for certain situations. Sometimes a high-speed low-resolution stream is actually easier to process.
* "Integration" with Java - how much trouble is it to hook this solution to my code? Am I sending packets over a socket? Hitting URLs? Installing Direct3D / JNI combinations?
* Windows / Linux / both? - I would prefer an operating system agnostic solution because I have to deliver to several flavors of OS but there may be a solution that is optimal for one but not the other.
NOTE: I am aware of other image / video capture codecs and that is not the focus of this question. I am specifically *not* interested in streaming APIs (e.g., MPEG4) due to the loss of frame accuracy. However, if there is a solution to my question that delivers another frame-accurate data stream, please chime in.
Follow-up to this question: at this point, I am strongly inclined to buy appliances such as the [Axis video encoders](http://www.axis.com/products/video/video_server/index.htm) rather than trying to capture the video in software or on the PC directly. However, if someone has alternatives, I'd love to hear them. | This JavaCV implementation works fine.
**CODE:**
```
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
public class CaptureImage {
private static void captureFrame() {
// 0-default camera, 1 - next...so on
final OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
try {
grabber.start();
IplImage img = grabber.grab();
if (img != null) {
cvSaveImage("capture.jpg", img);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
captureFrame();
}
}
```
There is also [post on viewing live video](http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/javacv-capture-save-flip-show-live.html) from Camera .And [configuration for JavaCV :](http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/opencv-javacv-eclipse-project.html)
I think this will meet your requirements. |
115,862 | <p>I'm not sure about what's the difference between opening a JS script with </p>
<pre><code><SCRIPT language='JavaScript'>
</code></pre>
<p>or with:</p>
<pre><code><SCRIPT type="text/JavaScript">
</code></pre>
<p>Should JavaScript always be quoted (either with " " or with ' ') or that's not really important?</p>
<p>Thank you for any clarification on this topic!</p>
| [
{
"answer_id": 115871,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<p>Use both:</p>\n\n<pre><code><script language=\"javascript\" type=\"text/javascript\">\n</code></pre>\n"
},
{
"answer_id": 115911,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 4,
"selected": false,
"text": "<p>The language attribute was used in HTML 3.2. HTML 4.0 introduced type (which is consistent with other elements that refer to external media, such as <code><style></code>) and made it required. It also <a href=\"http://www.w3.org/TR/html401/conform.html#deprecated\" rel=\"nofollow noreferrer\">deprecated</a> language.</p>\n\n<p>Use <a href=\"http://www.w3.org/TR/html401/interact/scripts.html#adef-type-SCRIPT\" rel=\"nofollow noreferrer\">type</a>. Do not use <a href=\"http://www.w3.org/TR/html401/interact/scripts.html#adef-language\" rel=\"nofollow noreferrer\">language</a>.</p>\n\n<p>In HTML (and XHTML), there is no difference between <a href=\"http://www.w3.org/TR/html401/intro/sgmltut.html#h-3.2.2\" rel=\"nofollow noreferrer\">attribute values delimited using single or double quotes</a> (except that you can't use the character used to delimit the value inside the value without representing it with an entity).</p>\n"
},
{
"answer_id": 115912,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": -1,
"selected": false,
"text": "<p>You should always enclose attribute values in quotation marks (\"). Don't use apostraphes (').</p>\n\n<p><strong>Edit</strong>: Made opinion sound like fact here, my bad. Single quotes are technically legal, but in my experience they tend to lead to more issues than double quotes (they tend to crop up in attribute values more often amongst other things) so I always recommend sticking to the latter. Your mileage may vary though!</p>\n"
},
{
"answer_id": 115917,
"author": "Rich Bradshaw",
"author_id": 16511,
"author_profile": "https://Stackoverflow.com/users/16511",
"pm_score": 1,
"selected": false,
"text": "<p>Older browsers only support language - now the type method using a mimetype of text/javascript is the correct way.</p>\n\n<pre><code><script language=\"javascript\" type=\"text/javascript\">\n</code></pre>\n\n<p>is used to support older browsers as well as using the correct way.</p>\n\n<pre><code><style type=\"text/css\">\n</code></pre>\n\n<p>is another example of including something (stylesheet) using the correct standard.</p>\n"
},
{
"answer_id": 115956,
"author": "paulgreg",
"author_id": 3122,
"author_profile": "https://Stackoverflow.com/users/3122",
"pm_score": 0,
"selected": false,
"text": "<p>According to the <a href=\"http://www.w3.org/TR/html4/interact/scripts.html#edef-SCRIPT\" rel=\"nofollow noreferrer\">W3 HTML 4.01 reference</a>, only type attribute is required. The langage attribute is not part of the reference, but I think it comes from earlier days, when Microsoft fought against Netscape.</p>\n\n<p>Also, simple quotes are not valid in XHTML 1.0 (the parsing is more restrictive).\nThis may not be a problem but you should now that's always better to <a href=\"http://validator.w3.org/\" rel=\"nofollow noreferrer\">validate your html</a> (either HTML 4.01 or XHTML 1.0).</p>\n"
},
{
"answer_id": 115995,
"author": "Rahul",
"author_id": 16308,
"author_profile": "https://Stackoverflow.com/users/16308",
"pm_score": 2,
"selected": false,
"text": "<p>Refer to supreme deity <a href=\"http://javascript.crockford.com/code.html\" rel=\"nofollow noreferrer\">Douglas Crockford's Javascript Code Conventions</a> for all things Javascript:</p>\n\n<blockquote>\n <p>JavaScript Files</p>\n \n <p>JavaScript programs should be stored\n in and delivered as .js files.</p>\n \n <p>JavaScript code should not be embedded\n in HTML files unless the code is\n specific to a single session. Code in\n HTML adds significantly to pageweight\n with no opportunity for mitigation by\n caching and compression.</p>\n \n <p><script src=filename.js> tags should\n be placed as late in the body as\n possible. This reduces the effects of\n delays imposed by script loading on\n other page components. <strong>There is no\n need to use the language or type\n attributes. It is the server, not the\n script tag, that determines the MIME\n type.</strong></p>\n</blockquote>\n"
},
{
"answer_id": 120608,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 1,
"selected": false,
"text": "<p>You don't need the type and language attribute when using to an external JavaScript file:</p>\n\n<pre><code><script src=\"script.js\" />\n</code></pre>\n\n<p>Your browser will automatically figure out what to do, based on the extension of the file. You need type=\"text/javascript\" when doing script-blocks, though.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Some might say that this is awful, but these are in fact the words of a Yahoo! JavaScript evangelist (I think it was Douglas Crockford) in the context of website load-performance.</p>\n\n<p>Perhaps I should have elaborated a bit.</p>\n\n<p>Google was a great example of breaking standards without breaking the rendering of their website. (They are now complying to W3C standards, using JavaScript to render their pages). Because of the heavy load on their websites, they decided to strip down their markup to the bare minimum, and use depreciated tags like the dreaded <em>font</em> and <em>i</em> tags.</p>\n\n<p>It doesn't hurt to be pragmatic. Within reason, of course :)</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19159/"
]
| I'm not sure about what's the difference between opening a JS script with
```
<SCRIPT language='JavaScript'>
```
or with:
```
<SCRIPT type="text/JavaScript">
```
Should JavaScript always be quoted (either with " " or with ' ') or that's not really important?
Thank you for any clarification on this topic! | The language attribute was used in HTML 3.2. HTML 4.0 introduced type (which is consistent with other elements that refer to external media, such as `<style>`) and made it required. It also [deprecated](http://www.w3.org/TR/html401/conform.html#deprecated) language.
Use [type](http://www.w3.org/TR/html401/interact/scripts.html#adef-type-SCRIPT). Do not use [language](http://www.w3.org/TR/html401/interact/scripts.html#adef-language).
In HTML (and XHTML), there is no difference between [attribute values delimited using single or double quotes](http://www.w3.org/TR/html401/intro/sgmltut.html#h-3.2.2) (except that you can't use the character used to delimit the value inside the value without representing it with an entity). |
115,866 | <p>Convert mysql timestamp to epoch time in python - is there an easy way to do this?</p>
| [
{
"answer_id": 115903,
"author": "David Singer",
"author_id": 4618,
"author_profile": "https://Stackoverflow.com/users/4618",
"pm_score": 5,
"selected": false,
"text": "<p>Why not let MySQL do the hard work?</p>\n\n<pre><code>select unix_timestamp(fieldname) from tablename;\n</code></pre>\n"
},
{
"answer_id": 118236,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 3,
"selected": false,
"text": "<p>If you don't want to have MySQL do the work for some reason, then you can do this in Python easily enough. When you get a datetime column back from MySQLdb, you get a Python datetime.datetime object. To convert one of these, you can use time.mktime. For example:</p>\n\n<pre><code>import time\n# Connecting to database skipped (also closing connection later)\nc.execute(\"SELECT my_datetime_field FROM my_table\")\nd = c.fetchone()[0]\nprint time.mktime(d.timetuple())\n</code></pre>\n"
},
{
"answer_id": 126034,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 1,
"selected": false,
"text": "<p>I use something like the following to get seconds since the epoch (UTC) from a MySQL date (local time):</p>\n\n<pre><code>calendar.timegm(\n time.gmtime(\n time.mktime(\n time.strptime(t, \n \"%Y-%m-%d %H:%M:%S\"))))\n</code></pre>\n\n<p>More info in this question: <a href=\"https://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python\">How do I convert local time to UTC in Python?</a></p>\n"
},
{
"answer_id": 2407400,
"author": "bigredbob",
"author_id": 252091,
"author_profile": "https://Stackoverflow.com/users/252091",
"pm_score": 3,
"selected": false,
"text": "<p>converting mysql time to epoch:</p>\n\n<pre><code>>>> import time\n>>> import calendar\n>>> mysql_time = \"2010-01-02 03:04:05\"\n>>> mysql_time_struct = time.strptime(mysql_time, '%Y-%m-%d %H:%M:%S')\n>>> print mysql_time_struct\n(2010, 1, 2, 3, 4, 5, 5, 2, -1)\n>>> mysql_time_epoch = calendar.timegm(mysql_time_struct)\n>>> print mysql_time_epoch\n1262401445\n</code></pre>\n\n<p>converting epoch to something MySQL can use:</p>\n\n<pre><code>>>> import time\n>>> time_epoch = time.time()\n>>> print time_epoch\n1268121070.7\n>>> time_struct = time.gmtime(time_epoch)\n>>> print time_struct\n(2010, 3, 9, 7, 51, 10, 1, 68, 0)\n>>> time_formatted = time.strftime('%Y-%m-%d %H:%M:%S', time_struct)\n>>> print time_formatted\n2010-03-09 07:51:10\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Convert mysql timestamp to epoch time in python - is there an easy way to do this? | Why not let MySQL do the hard work?
```
select unix_timestamp(fieldname) from tablename;
``` |
115,868 | <p>I'd like to know how to grab the Window title of the current active window (i.e. the one that has focus) using C#. </p>
| [
{
"answer_id": 115891,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 2,
"selected": false,
"text": "<p>Use the Windows API. Call <code>GetForegroundWindow()</code>.</p>\n\n<p><code>GetForegroundWindow()</code> will give you a handle (named <code>hWnd</code>) to the active window.</p>\n\n<p>Documentation: <a href=\"http://msdn.microsoft.com/en-us/library/ms633505(VS.85).aspx\" rel=\"nofollow noreferrer\">GetForegroundWindow function | Microsoft Docs</a></p>\n"
},
{
"answer_id": 115905,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 9,
"selected": true,
"text": "<p>See example on how you can do this with full source code here:</p>\n\n<p><a href=\"http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/\" rel=\"noreferrer\">http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/</a></p>\n\n<pre><code>[DllImport(\"user32.dll\")]\nstatic extern IntPtr GetForegroundWindow();\n\n[DllImport(\"user32.dll\")]\nstatic extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);\n\nprivate string GetActiveWindowTitle()\n{\n const int nChars = 256;\n StringBuilder Buff = new StringBuilder(nChars);\n IntPtr handle = GetForegroundWindow();\n\n if (GetWindowText(handle, Buff, nChars) > 0)\n {\n return Buff.ToString();\n }\n return null;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Edited</strong> with @Doug McClean comments for better correctness.</p>\n"
},
{
"answer_id": 1342675,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Loop over <code>Application.Current.Windows[]</code> and find the one with <code>IsActive == true</code>.</p>\n"
},
{
"answer_id": 2652249,
"author": "Skvettn",
"author_id": 170655,
"author_profile": "https://Stackoverflow.com/users/170655",
"pm_score": 4,
"selected": false,
"text": "<p>If you were talking about WPF then use:</p>\n\n<pre><code> Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);\n</code></pre>\n"
},
{
"answer_id": 32558071,
"author": "Beshoy Nabeih",
"author_id": 5282703,
"author_profile": "https://Stackoverflow.com/users/5282703",
"pm_score": -1,
"selected": false,
"text": "<p>you can use process class it's very easy.\nuse this namespace </p>\n\n<pre><code>using System.Diagnostics;\n</code></pre>\n\n<p>if you want to make a button to get active window.</p>\n\n<pre><code>private void button1_Click(object sender, EventArgs e)\n { \n Process currentp = Process.GetCurrentProcess();\n TextBox1.Text = currentp.MainWindowTitle; //this textbox will be filled with active window.\n }\n</code></pre>\n"
},
{
"answer_id": 40220805,
"author": "Arthur Zennig",
"author_id": 1326106,
"author_profile": "https://Stackoverflow.com/users/1326106",
"pm_score": 0,
"selected": false,
"text": "<p>If it happens that you need the <strong><em>Current Active Form from your MDI application</em></strong>: (MDI- Multi Document Interface).</p>\n\n<pre><code>Form activForm;\nactivForm = Form.ActiveForm.ActiveMdiChild;\n</code></pre>\n"
},
{
"answer_id": 47466273,
"author": "Mohammad Dayyan",
"author_id": 191647,
"author_profile": "https://Stackoverflow.com/users/191647",
"pm_score": 3,
"selected": false,
"text": "<p>Based on <a href=\"https://msdn.microsoft.com/en-us/library/ms633505(VS.85).aspx\" rel=\"noreferrer\">GetForegroundWindow function | Microsoft Docs</a>:</p>\n\n<pre><code>[DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\nstatic extern IntPtr GetForegroundWindow();\n\n[DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\nstatic extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);\n\n[DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\nstatic extern int GetWindowTextLength(IntPtr hWnd);\n\nprivate string GetCaptionOfActiveWindow()\n{\n var strTitle = string.Empty;\n var handle = GetForegroundWindow();\n // Obtain the length of the text \n var intLength = GetWindowTextLength(handle) + 1;\n var stringBuilder = new StringBuilder(intLength);\n if (GetWindowText(handle, stringBuilder, intLength) > 0)\n {\n strTitle = stringBuilder.ToString();\n }\n return strTitle;\n}\n</code></pre>\n\n<p>It supports UTF8 characters.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1039/"
]
| I'd like to know how to grab the Window title of the current active window (i.e. the one that has focus) using C#. | See example on how you can do this with full source code here:
<http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/>
```
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
```
---
**Edited** with @Doug McClean comments for better correctness. |
115,916 | <p>I'm trying to convert a VARIANT from VT_DATE to an <strong>invariant</strong> VT_BSTR. The following code works on Windows XP:</p>
<pre><code>VARIANT va;
::VariantInit(&va);
// set the variant to VT_DATE
SYSTEMTIME st;
memset(&st, 0, sizeof(SYSTEMTIME));
st.wYear = 2008;
st.wMonth = 9;
st.wDay = 22;
st.wHour = 12;
st.wMinute = 30;
DATE date;
SystemTimeToVariantTime(&st, &date);
va.vt = VT_DATE;
va.date = date;
// change to a string
err = ::VariantChangeTypeEx(&va,
&va,
LOCALE_INVARIANT,
0,
VT_BSTR);
</code></pre>
<p>But on PPC 2003 and Windows Mobile 5, the above code returns E_FAIL. Can someone correct the above code or provide an alternative?</p>
<p><strong>EDIT</strong>: After converting the date to a string, I'm using the string to do a SQL update. I want the update to work regardless of the device's regional settings, so that's why I'm trying to convert it to an "invariant" format.</p>
<p>I'm now using the following to convert the date to a format that appears to work:</p>
<pre><code>err = ::VariantTimeToSystemTime(va.date, &time);
if (FAILED(err))
goto cleanup;
err = strDate.PrintF(_T("%04d-%02d-%02d %02d:%02d:%02d.%03d"),
time.wYear,
time.wMonth,
time.wDay,
time.wHour,
time.wMinute,
time.wSecond,
time.wMilliseconds);
</code></pre>
| [
{
"answer_id": 118962,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 1,
"selected": false,
"text": "<p>This isn't really an answer, but changing a date to a string <em>isn't</em> a Locale-invariant task - it highly depends on the locale. In this case, I'd convert the Variant Time to System Time, then use a sprintf-style function to convert it to a string</p>\n"
},
{
"answer_id": 121003,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 0,
"selected": false,
"text": "<p>Not certain in your context here, but it seems maybe you're on the wrong path. Why not use <a href=\"http://msdn.microsoft.com/en-us/library/ms891320.aspx\" rel=\"nofollow noreferrer\">VarBstrFromDate</a>? This aloows using a locale (or optionally ignoring one) and is probably far closer to what you want.</p>\n"
},
{
"answer_id": 121766,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 1,
"selected": false,
"text": "<p><em>(I'm sorry it's taken me a while to respond ('work', you know...))</em></p>\n\n<p>I don't see anything wrong with the code, from the COM point of view.</p>\n\n<p>Maybe the problem is with LOCALE_INVARIANT. It was introduced with Windows XP; maybe it's not supported in the Windows CE family?</p>\n\n<p>Try changing the locale to <strong>LOCALE_USER_DEFAULT</strong> and check to see if you still get an error. Most of the time this would be the most appropriate locale anyway; especially if you are trying to display the value to the user.</p>\n\n<p>If you truly need a specific format because you need to pass the value somewhere else that will parse it, try using a specific locale that matches your requirements; perhaps en_US.</p>\n\n<p>Please let us know how it goes.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2773/"
]
| I'm trying to convert a VARIANT from VT\_DATE to an **invariant** VT\_BSTR. The following code works on Windows XP:
```
VARIANT va;
::VariantInit(&va);
// set the variant to VT_DATE
SYSTEMTIME st;
memset(&st, 0, sizeof(SYSTEMTIME));
st.wYear = 2008;
st.wMonth = 9;
st.wDay = 22;
st.wHour = 12;
st.wMinute = 30;
DATE date;
SystemTimeToVariantTime(&st, &date);
va.vt = VT_DATE;
va.date = date;
// change to a string
err = ::VariantChangeTypeEx(&va,
&va,
LOCALE_INVARIANT,
0,
VT_BSTR);
```
But on PPC 2003 and Windows Mobile 5, the above code returns E\_FAIL. Can someone correct the above code or provide an alternative?
**EDIT**: After converting the date to a string, I'm using the string to do a SQL update. I want the update to work regardless of the device's regional settings, so that's why I'm trying to convert it to an "invariant" format.
I'm now using the following to convert the date to a format that appears to work:
```
err = ::VariantTimeToSystemTime(va.date, &time);
if (FAILED(err))
goto cleanup;
err = strDate.PrintF(_T("%04d-%02d-%02d %02d:%02d:%02d.%03d"),
time.wYear,
time.wMonth,
time.wDay,
time.wHour,
time.wMinute,
time.wSecond,
time.wMilliseconds);
``` | This isn't really an answer, but changing a date to a string *isn't* a Locale-invariant task - it highly depends on the locale. In this case, I'd convert the Variant Time to System Time, then use a sprintf-style function to convert it to a string |
115,928 | <p>I need to have a thread signal another if the user wishes to interrupt execution, however I'm unsure about how to implement the signaling/signal-checking mechanism. I wouldn't like to have a singleton in my project (like a global <code>bool</code>), but is there an alternative?</p>
<p>In <a href="https://stackoverflow.com/questions/34151/c-thread-question-setting-a-value-to-indicate-the-thread-has-finished">this thread</a> people suggest proper structures for that in C++, but I don't know about anything similar in .NET. Could somebody please shed some light?</p>
| [
{
"answer_id": 115935,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "<p>Look at the System.Runtime.Remoting namespace.</p>\n"
},
{
"answer_id": 115948,
"author": "Statement",
"author_id": 2166173,
"author_profile": "https://Stackoverflow.com/users/2166173",
"pm_score": 3,
"selected": false,
"text": "<p>A bit vague (short of time), but look into <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx\" rel=\"noreferrer\">ManualResetEvent and AutoResetEvent</a>. You also might want to look up Monitor and lock keyword.</p>\n"
},
{
"answer_id": 115962,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 4,
"selected": true,
"text": "<p>Try out <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow noreferrer\">BackgroundWorker</a>. It supports progress updates and cancellation of a running task.</p>\n\n<p>If you want one thread to wait until another thread has finished doing its thing, then Monitor.Wait and Monitor.Pulse are good, as is ManualResetEvent. However, these are not really of any use for cancelling a running task.</p>\n\n<p>If you want to write your own cancellation code, you could just have a field somewhere which both threads have access to. Mark it volatile, e.g.:</p>\n\n<pre><code>private volatile bool cancelling;\n</code></pre>\n\n<p>Have the main thread set it to true, and have the worker thread check it periodically and set it to false when it has finished.</p>\n\n<p>This is not really comparable to having a 'global variable', as you can still limit the scope of the semaphore variable to be private to a class.</p>\n"
},
{
"answer_id": 116009,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 2,
"selected": false,
"text": "<p>Look into Monitor.Wait and Monitor.Pulse. Here is an excellent article on Threading in .Net (very readable): <a href=\"http://www.albahari.com/threading/part4.aspx\" rel=\"nofollow noreferrer\">http://www.albahari.com/threading/part4.aspx</a></p>\n"
},
{
"answer_id": 116062,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>A simple solution, like a synchronized static boolean, should be all you need as opposed to a framework-based solution which copuld be overkill for your scenario. In case you still want a framework, have a look at the <a href=\"http://blogs.msdn.com/pfxteam/archive/tags/Parallel+Extensions/default.aspx\" rel=\"nofollow noreferrer\">parallel extensions to .NET</a> for ideas.</p>\n"
},
{
"answer_id": 116342,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on what kind of synchronization you need.\nIf you want to be able to run thread in a loop until some kind of end of execution is reached - all you need is a static bool variable.\nIf you want one thread to wait till another thread reach a point in execution you might want to use WaitEvents (AutoResetEvent or ManualResetEvent).\nIflyyou need to wait for multiple waitHandles you can use WaitHandle.WaitAll or WaitHandle.WaitAny.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4850/"
]
| I need to have a thread signal another if the user wishes to interrupt execution, however I'm unsure about how to implement the signaling/signal-checking mechanism. I wouldn't like to have a singleton in my project (like a global `bool`), but is there an alternative?
In [this thread](https://stackoverflow.com/questions/34151/c-thread-question-setting-a-value-to-indicate-the-thread-has-finished) people suggest proper structures for that in C++, but I don't know about anything similar in .NET. Could somebody please shed some light? | Try out [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx). It supports progress updates and cancellation of a running task.
If you want one thread to wait until another thread has finished doing its thing, then Monitor.Wait and Monitor.Pulse are good, as is ManualResetEvent. However, these are not really of any use for cancelling a running task.
If you want to write your own cancellation code, you could just have a field somewhere which both threads have access to. Mark it volatile, e.g.:
```
private volatile bool cancelling;
```
Have the main thread set it to true, and have the worker thread check it periodically and set it to false when it has finished.
This is not really comparable to having a 'global variable', as you can still limit the scope of the semaphore variable to be private to a class. |
115,955 | <p>I'm trying to run a LINQ to SQL query that returns a result in a grid view in a search engine style listing. </p>
<p>In the simplified example below, is it possible to populate the collection with a comma-separated list of any children that the parent has (NAMESOFCHILDREN) in a single query?</p>
<pre><code>var family = from p in db.Parents
where p.ParentId == Convert.ToInt32(Request.QueryString["parentId"])
join pcl in db.ParentChildLookup on p.ParentId equals pcl.ParentId
join c in db.Children on pcl.ChildId equals c.ChildId
select new
{
Family = "Name: " + p.ParentName + "<br />" +
"Children: " + NAMESOFCHILDREN? + "<br />"
};
</code></pre>
<p>Thanks in advance.</p>
| [
{
"answer_id": 115965,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "<p>Your joins are going to screw up your cardinality! You don't have a list of Parents!</p>\n\n<p>Here's some untested free-hand code. Adding the relationships in the Linq designer gives you relationship properties. String.Join will put the list together.</p>\n\n<p>I've added two optional method calls.</p>\n\n<p><em>Where ... Any</em> will filter the parents to only those parents that have children. I'm unsure of string.Join's behavior on an empty array.</p>\n\n<p><em>ToList</em> will yank Parents into memory, the children will be accessed by further database calls. This may be necessary if you get a runtime <em>string.Join is not supported by SQL translator</em> exception. This exception would mean that LINQ tried to translate the method call into something that SQL Server can understand - and failed.</p>\n\n<pre><code>int parentID = Convert.ToInt32(Request.QueryString[\"parentId\"]);\n\nList<string> result =\n db.Parents\n .Where(p => p.ParentId == parentID)\n //.Where(p => p.ParentChildLookup.Children.Any())\n //.ToList()\n .Select(p => \n \"Name: \" + p.ParentName + \"<br />\" + \n \"Children: \" + String.Join(\", \", p.ParentChildLookup.Children.Select(c => c.Name).ToArray() + \"<br />\"\n)).ToList();\n</code></pre>\n\n<p>Also note: generally you do not want to mix data and markup until the data is properly escaped for markup.</p>\n"
},
{
"answer_id": 116001,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 0,
"selected": false,
"text": "<p>you could try as follow: </p>\n\n<pre><code>var family = from p in db.Parents \n where p.ParentId == Convert.ToInt32(Request.QueryString[\"parentId\"]) \n join pcl in db.ParentChildLookup on p.ParentId equals pcl.ParentId \n select new { \n Family = \"Name: \" + p.ParentName + \"<br />\" + string.Join(\",\",(from c in db.Children where c.ChildId equals pcl.ChildId select c.ChildId.ToString()).ToArray());\n };\n</code></pre>\n"
},
{
"answer_id": 30127101,
"author": "gmail user",
"author_id": 344394,
"author_profile": "https://Stackoverflow.com/users/344394",
"pm_score": 0,
"selected": false,
"text": "<p>Posting an answer for an old question with <code>groupby</code>. Below query will produce company name, order count and order ids separated by comma from Northwind. </p>\n\n<pre><code>var query = from c in north.Customers\n join o in north.Orders on c.CustomerID equals o.CustomerID\n select new { c, o };\n\n var query2 = from q in query\n group q.o by q.c into g\n select new { CompanyName = g.Key.CompanyName, \n orderCount = g.Count(), \n orders = string.Join(\",\", g.Select(o => o.OrderID)) }\n into result\n orderby result.orderCount descending\n select result;\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034/"
]
| I'm trying to run a LINQ to SQL query that returns a result in a grid view in a search engine style listing.
In the simplified example below, is it possible to populate the collection with a comma-separated list of any children that the parent has (NAMESOFCHILDREN) in a single query?
```
var family = from p in db.Parents
where p.ParentId == Convert.ToInt32(Request.QueryString["parentId"])
join pcl in db.ParentChildLookup on p.ParentId equals pcl.ParentId
join c in db.Children on pcl.ChildId equals c.ChildId
select new
{
Family = "Name: " + p.ParentName + "<br />" +
"Children: " + NAMESOFCHILDREN? + "<br />"
};
```
Thanks in advance. | Your joins are going to screw up your cardinality! You don't have a list of Parents!
Here's some untested free-hand code. Adding the relationships in the Linq designer gives you relationship properties. String.Join will put the list together.
I've added two optional method calls.
*Where ... Any* will filter the parents to only those parents that have children. I'm unsure of string.Join's behavior on an empty array.
*ToList* will yank Parents into memory, the children will be accessed by further database calls. This may be necessary if you get a runtime *string.Join is not supported by SQL translator* exception. This exception would mean that LINQ tried to translate the method call into something that SQL Server can understand - and failed.
```
int parentID = Convert.ToInt32(Request.QueryString["parentId"]);
List<string> result =
db.Parents
.Where(p => p.ParentId == parentID)
//.Where(p => p.ParentChildLookup.Children.Any())
//.ToList()
.Select(p =>
"Name: " + p.ParentName + "<br />" +
"Children: " + String.Join(", ", p.ParentChildLookup.Children.Select(c => c.Name).ToArray() + "<br />"
)).ToList();
```
Also note: generally you do not want to mix data and markup until the data is properly escaped for markup. |
115,974 | <p>What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. </p>
| [
{
"answer_id": 115985,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Nohup\" rel=\"nofollow noreferrer\">nohup</a> </p>\n\n<p><a href=\"http://code.activestate.com/recipes/278731/\" rel=\"nofollow noreferrer\">Creating a daemon the Python way</a></p>\n"
},
{
"answer_id": 116035,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 5,
"selected": true,
"text": "<p>See <a href=\"http://www.kohala.com/start/\" rel=\"noreferrer\">Stevens</a> and also this <a href=\"http://code.activestate.com/recipes/278731/\" rel=\"noreferrer\">lengthy thread on activestate</a> which I found personally to be both mostly incorrect and much to verbose, and I came up with this:</p>\n\n<pre><code>from os import fork, setsid, umask, dup2\nfrom sys import stdin, stdout, stderr\n\nif fork(): exit(0)\numask(0) \nsetsid() \nif fork(): exit(0)\n\nstdout.flush()\nstderr.flush()\nsi = file('/dev/null', 'r')\nso = file('/dev/null', 'a+')\nse = file('/dev/null', 'a+', 0)\ndup2(si.fileno(), stdin.fileno())\ndup2(so.fileno(), stdout.fileno())\ndup2(se.fileno(), stderr.fileno())\n</code></pre>\n\n<p>If you need to stop that process again, it is required to know the pid, the usual solution to this is pidfiles. Do this if you need one</p>\n\n<pre><code>from os import getpid\noutfile = open(pid_file, 'w')\noutfile.write('%i' % getpid())\noutfile.close()\n</code></pre>\n\n<p>For security reasons you might consider any of these after demonizing</p>\n\n<pre><code>from os import setuid, setgid, chdir\nfrom pwd import getpwnam\nfrom grp import getgrnam\nsetuid(getpwnam('someuser').pw_uid)\nsetgid(getgrnam('somegroup').gr_gid)\nchdir('/') \n</code></pre>\n\n<p>You could also use <a href=\"http://en.wikipedia.org/wiki/Nohup\" rel=\"noreferrer\">nohup</a> but that does not work well with <a href=\"http://docs.python.org/lib/module-subprocess.html\" rel=\"noreferrer\">python's subprocess module</a></p>\n"
},
{
"answer_id": 116081,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"http://www.clapper.org/software/python/grizzled/\" rel=\"nofollow noreferrer\">grizzled.os.daemonize</a>:</p>\n\n<pre><code>$ easy_install grizzled\n\n>>> from grizzled.os import daemonize\n>>> daemon.daemonize()\n</code></pre>\n\n<p>To understand how this works or to do it yourself, read <a href=\"http://code.activestate.com/recipes/278731/\" rel=\"nofollow noreferrer\">the discussion on ActiveState</a>.</p>\n"
},
{
"answer_id": 117176,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 1,
"selected": false,
"text": "<p>If you do not care for actual discussions (which tend to go offtopic and do not offer authoritative response), you can choose some library that will make your tast easier. I'd recomment taking a look at <a href=\"http://www.livinglogic.de/Python/Download.html\" rel=\"nofollow noreferrer\">ll-xist</a>, this library contains large amount of life-saving code, like cron jobs helper, daemon framework, and (what is not interesting to you, but is really great) <em>object-oriented XSL</em> (ll-xist itself).</p>\n"
},
{
"answer_id": 3606303,
"author": "edomaur",
"author_id": 14262,
"author_profile": "https://Stackoverflow.com/users/14262",
"pm_score": 2,
"selected": false,
"text": "<p>I have recently used <a href=\"http://pypi.python.org/pypi/Turkmenbashi/1.0.0.01\" rel=\"nofollow noreferrer\">Turkmenbashi</a> :</p>\n\n<pre><code>$ easy_install turkmenbashi\nimport Turkmenbashi\n\nclass DebugDaemon (Turkmenbashi.Daemon):\n\n def config(self):\n self.debugging = True\n\n def go(self):\n self.debug('a debug message')\n self.info('an info message')\n self.warn('a warning message')\n self.error('an error message')\n self.critical('a critical message')\n\nif __name__==\"__main__\":\n d = DebugDaemon()\n d.config()\n d.setenv(30, '/var/run/daemon.pid', '/tmp', None)\n d.start(d.go)\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14262/"
]
| What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. | See [Stevens](http://www.kohala.com/start/) and also this [lengthy thread on activestate](http://code.activestate.com/recipes/278731/) which I found personally to be both mostly incorrect and much to verbose, and I came up with this:
```
from os import fork, setsid, umask, dup2
from sys import stdin, stdout, stderr
if fork(): exit(0)
umask(0)
setsid()
if fork(): exit(0)
stdout.flush()
stderr.flush()
si = file('/dev/null', 'r')
so = file('/dev/null', 'a+')
se = file('/dev/null', 'a+', 0)
dup2(si.fileno(), stdin.fileno())
dup2(so.fileno(), stdout.fileno())
dup2(se.fileno(), stderr.fileno())
```
If you need to stop that process again, it is required to know the pid, the usual solution to this is pidfiles. Do this if you need one
```
from os import getpid
outfile = open(pid_file, 'w')
outfile.write('%i' % getpid())
outfile.close()
```
For security reasons you might consider any of these after demonizing
```
from os import setuid, setgid, chdir
from pwd import getpwnam
from grp import getgrnam
setuid(getpwnam('someuser').pw_uid)
setgid(getgrnam('somegroup').gr_gid)
chdir('/')
```
You could also use [nohup](http://en.wikipedia.org/wiki/Nohup) but that does not work well with [python's subprocess module](http://docs.python.org/lib/module-subprocess.html) |
115,977 | <p>I would very much like to integrate <a href="http://www.logilab.org/857" rel="noreferrer">pylint</a> into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:<code>E1101: *%s %r has no %r
member*</code>--constantly reports errors when using common django fields,
for example:</p>
<pre><code>E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
</code></pre>
<p>which is caused by this code:</p>
<pre><code>def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
</code></pre>
<p>How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of <code>objects</code>, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)</p>
<p><strong>Edit:</strong> The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)</p>
<p>See <a href="http://creswick.github.io/blog/2008/09/05/wrestling-python/" rel="noreferrer">here</a> for a summary of the problems I've had with <code>pychecker</code> and <code>pyflakes</code> -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.)</p>
| [
{
"answer_id": 116025,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 4,
"selected": false,
"text": "<p>Because of how pylint works (it examines the source itself, without letting Python actually execute it) it's very hard for pylint to figure out how metaclasses and complex baseclasses actually affect a class and its instances. The 'pychecker' tool is a bit better in this regard, because it <em>does</em> actually let Python execute the code; it imports the modules and examines the resulting objects. However, that approach has other problems, because it does actually let Python execute the code :-)</p>\n\n<p>You could extend pylint to teach it about the magic Django uses, or to make it understand metaclasses or complex baseclasses better, or to just ignore such cases after detecting one or more features it doesn't quite understand. I don't think it would be particularly easy. You can also just tell pylint to not warn about these things, through special comments in the source, command-line options or a .pylintrc file.</p>\n"
},
{
"answer_id": 116047,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 3,
"selected": false,
"text": "<p>Try running pylint with</p>\n\n<pre><code>pylint --ignored-classes=Tags\n</code></pre>\n\n<p>If that works, add all the other Django classes - possibly using a script, in say, python :P </p>\n\n<p>The documentation for <code>--ignore-classes</code> is:</p>\n\n<blockquote>\n <p><code>--ignored-classes=<members names></code><br>\n List of classes names for which member\n attributes should not be checked\n (useful for classes with attributes\n dynamicaly set). [current: %default]</p>\n</blockquote>\n\n<p>I should add this is not a particular elegant solution in my view, but it should work.</p>\n"
},
{
"answer_id": 117299,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 3,
"selected": false,
"text": "<p>I resigned from using pylint/pychecker in favor of using pyflakes with Django code - it just tries to import module and reports any problem it finds, like unused imports or uninitialized local names.</p>\n"
},
{
"answer_id": 118375,
"author": "AdamKG",
"author_id": 16361,
"author_profile": "https://Stackoverflow.com/users/16361",
"pm_score": 3,
"selected": false,
"text": "<p>This is not a solution, but you can add <code>objects = models.Manager()</code> to your Django models without changing any behavior.</p>\n\n<p>I myself only use pyflakes, primarily due to some dumb defaults in pylint and laziness on my part (not wanting to look up how to change the defaults).</p>\n"
},
{
"answer_id": 410860,
"author": "max",
"author_id": 49407,
"author_profile": "https://Stackoverflow.com/users/49407",
"pm_score": 1,
"selected": false,
"text": "<p>So far I have found no real solution to that but work around:</p>\n\n<ul>\n<li>In our company we require a pylint\nscore > 8. This allows coding\npractices pylint doesn't understand\nwhile ensuring that the code isn't\ntoo \"unusual\". So far we havn't seen\nany instance where E1101 kept us\nfrom reaching a score of 8 or\nhigher.</li>\n<li>Our 'make check' targets\nfilter out \"for has no 'objects'\nmember\" messages to remove most of\nthe distraction caused by pylint not\nunderstanding Django.</li>\n</ul>\n"
},
{
"answer_id": 1416297,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>I use the following: <code>pylint --generated-members=objects</code></p>\n"
},
{
"answer_id": 2456436,
"author": "gurney alex",
"author_id": 281368,
"author_profile": "https://Stackoverflow.com/users/281368",
"pm_score": 4,
"selected": false,
"text": "<p>django-lint is a nice tool which wraps pylint with django specific settings : <a href=\"http://chris-lamb.co.uk/projects/django-lint/\" rel=\"nofollow noreferrer\">http://chris-lamb.co.uk/projects/django-lint/</a> </p>\n\n<p>github project: <a href=\"https://github.com/lamby/django-lint\" rel=\"nofollow noreferrer\">https://github.com/lamby/django-lint</a></p>\n"
},
{
"answer_id": 4162971,
"author": "simon",
"author_id": 88411,
"author_profile": "https://Stackoverflow.com/users/88411",
"pm_score": 5,
"selected": false,
"text": "<p>My ~/.pylintrc contains</p>\n\n<pre><code>[TYPECHECK]\ngenerated-members=REQUEST,acl_users,aq_parent,objects,_meta,id\n</code></pre>\n\n<p>the last two are specifically for Django.</p>\n\n<p>Note that there is a <a href=\"http://www.logilab.org/ticket/28796\" rel=\"noreferrer\">bug in PyLint 0.21.1</a> which needs patching to make this work.</p>\n\n<p>Edit: After messing around with this a little more, I decided to hack PyLint just a tiny bit to allow me to expand the above into:</p>\n\n<pre><code>[TYPECHECK]\ngenerated-members=REQUEST,acl_users,aq_parent,objects,_meta,id,[a-zA-Z]+_set\n</code></pre>\n\n<p>I simply added:</p>\n\n<pre><code> import re\n for pattern in self.config.generated_members:\n if re.match(pattern, node.attrname):\n return\n</code></pre>\n\n<p>after the fix mentioned in the bug report (i.e., at line 129).</p>\n\n<p>Happy days!</p>\n"
},
{
"answer_id": 5104874,
"author": "eric",
"author_id": 448268,
"author_profile": "https://Stackoverflow.com/users/448268",
"pm_score": 2,
"selected": false,
"text": "<p>The solution proposed in this <a href=\"https://stackoverflow.com/questions/3509599/can-an-api-tell-pylint-not-to-complain-in-the-client-code\">other question</a> it to simply add <strong>get_attr</strong> to your Tag class. Ugly, but works.</p>\n"
},
{
"answer_id": 31000713,
"author": "Tal Weiss",
"author_id": 78234,
"author_profile": "https://Stackoverflow.com/users/78234",
"pm_score": 7,
"selected": false,
"text": "<p>Do not disable or weaken Pylint functionality by adding <code>ignores</code> or <code>generated-members</code>.<br>\nUse an actively developed Pylint plugin that <strong>understands</strong> Django.<br>\n<a href=\"https://github.com/landscapeio/pylint-django\" rel=\"noreferrer\">This Pylint plugin for Django</a> works quite well:</p>\n\n<pre><code>pip install pylint-django\n</code></pre>\n\n<p>and when running pylint add the following flag to the command:</p>\n\n<pre><code>--load-plugins pylint_django\n</code></pre>\n\n<p>Detailed blog post <a href=\"https://blog.landscape.io/using-pylint-on-django-projects-with-pylint-django.html\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 47774655,
"author": "Thiago Falcao",
"author_id": 1532769,
"author_profile": "https://Stackoverflow.com/users/1532769",
"pm_score": 5,
"selected": false,
"text": "<p>If you use Visual Studio Code do this:</p>\n\n<p><code>pip install pylint-django</code></p>\n\n<p>And add to VSC config:</p>\n\n<pre><code>\"python.linting.pylintArgs\": [\n \"--load-plugins=pylint_django\"\n],\n</code></pre>\n"
},
{
"answer_id": 50857799,
"author": "Ganesh",
"author_id": 3021579,
"author_profile": "https://Stackoverflow.com/users/3021579",
"pm_score": 2,
"selected": false,
"text": "<p>For <code>neovim & vim8</code> use <code>w0rp's ale</code> plugin. If you have installed everything correctly including <code>w0rp's ale</code>, <code>pylint</code> & <code>pylint-django</code>. In your <code>vimrc</code> add the following line & have fun developing web apps using django.\nThanks.</p>\n\n<pre><code>let g:ale_python_pylint_options = '--load-plugins pylint_django'\n</code></pre>\n"
},
{
"answer_id": 72914402,
"author": "sage",
"author_id": 527489,
"author_profile": "https://Stackoverflow.com/users/527489",
"pm_score": 0,
"selected": false,
"text": "<p>For heroku users, you can also use <a href=\"https://stackoverflow.com/a/31000713/527489\">Tal Weiss's answer to this question</a> using the following syntax to run pylint with the pylint-django plugin (replace <code>timekeeping</code> with your app/package):</p>\n<pre><code># run on the entire timekeeping app/package\nheroku local:run pylint --load-plugins pylint_django timekeeping\n\n# run on the module timekeeping/report.py\nheroku local:run pylint --load-plugins pylint_django timekeeping/report.py\n\n# With temporary command line disables\nheroku local:run pylint --disable=invalid-name,missing-function-docstring --load-plugins pylint_django timekeeping/report.py\n</code></pre>\n<p>Note: I was unable to run without specifying project/package directories.</p>\n<p>If you have issues with <code>E5110: Django was not configured.</code>, you can also invoke as follows to try to work around that (again, change <code>timekeeping</code> to your app/package):</p>\n<pre><code>heroku local:run python manage.py shell -c 'from pylint import lint; lint.Run(args=["--load-plugins", "pylint_django", "timekeeping"])'\n\n# With temporary command line disables, specific module\nheroku local:run python manage.py shell -c 'from pylint import lint; lint.Run(args=["--load-plugins", "pylint_django", "--disable=invalid-name,missing-function-docstring", "timekeeping/report.py"])'\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446/"
]
| I would very much like to integrate [pylint](http://www.logilab.org/857) into the build process for
my python projects, but I have run into one show-stopper: One of the
error types that I find extremely useful--:`E1101: *%s %r has no %r
member*`--constantly reports errors when using common django fields,
for example:
```
E1101:125:get_user_tags: Class 'Tag' has no 'objects' member
```
which is caused by this code:
```
def get_user_tags(username):
"""
Gets all the tags that username has used.
Returns a query set.
"""
return Tag.objects.filter( ## This line triggers the error.
tagownership__users__username__exact=username).distinct()
# Here is the Tag class, models.Model is provided by Django:
class Tag(models.Model):
"""
Model for user-defined strings that help categorize Events on
on a per-user basis.
"""
name = models.CharField(max_length=500, null=False, unique=True)
def __unicode__(self):
return self.name
```
How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of `objects`, so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.)
**Edit:** The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :)
See [here](http://creswick.github.io/blog/2008/09/05/wrestling-python/) for a summary of the problems I've had with `pychecker` and `pyflakes` -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.) | Do not disable or weaken Pylint functionality by adding `ignores` or `generated-members`.
Use an actively developed Pylint plugin that **understands** Django.
[This Pylint plugin for Django](https://github.com/landscapeio/pylint-django) works quite well:
```
pip install pylint-django
```
and when running pylint add the following flag to the command:
```
--load-plugins pylint_django
```
Detailed blog post [here](https://blog.landscape.io/using-pylint-on-django-projects-with-pylint-django.html). |
115,983 | <p>How do I add an empty directory (that contains no files) to a Git repository?</p>
| [
{
"answer_id": 115992,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 10,
"selected": false,
"text": "<p>You can't. See the <a href=\"https://git.wiki.kernel.org/index.php/GitFaq#Can_I_add_empty_directories.3F\" rel=\"noreferrer\">Git FAQ</a>.</p>\n\n<blockquote>\n <p>Currently the design of the git index\n (staging area) only permits files to\n be listed, and nobody competent enough\n to make the change to allow empty\n directories has cared enough about\n this situation to remedy it.</p>\n \n <p>Directories are added automatically\n when adding files inside them. That\n is, directories never have to be added\n to the repository, and are not tracked\n on their own.</p>\n \n <p>You can say \"<code>git add <dir></code>\" and it\n will add files in there.</p>\n \n <p>If you really need a directory to\n exist in checkouts you should create a\n file in it. .gitignore works well for\n this purpose; you can leave it empty,\n or fill in the names of files you\n expect to show up in the directory.</p>\n</blockquote>\n"
},
{
"answer_id": 116252,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 6,
"selected": false,
"text": "<p>Andy Lester is right, but if your directory just needs to be empty, and not <em>empty</em> empty, you can put an empty <code>.gitignore</code> file in there as a workaround.</p>\n\n<p>As an aside, this is an implementation issue, not a fundamental Git storage design problem. As has been mentioned many times on the Git mailing list, the reason that this has not been implemented is that no one has cared enough to submit a patch for it, not that it couldn’t or shouldn’t be done.</p>\n"
},
{
"answer_id": 117111,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 3,
"selected": false,
"text": "<p>You can't. This is an intentional design decision by the Git maintainers. Basically, the purpose of a Source Code Management System like Git is managing source code and empty directories aren't source code. Git is also often described as a content tracker, and again, empty directories aren't content (quite the opposite, actually), so they are not tracked.</p>\n"
},
{
"answer_id": 125729,
"author": "Michael Johnson",
"author_id": 17688,
"author_profile": "https://Stackoverflow.com/users/17688",
"pm_score": 4,
"selected": false,
"text": "<p>When you add a <code>.gitignore</code> file, if you are going to put any amount of content in it (that you want Git to ignore) you might want to add a single line with just an asterisk <code>*</code> to make sure you don't add the ignored content accidentally. </p>\n"
},
{
"answer_id": 180917,
"author": "m104",
"author_id": 4039,
"author_profile": "https://Stackoverflow.com/users/4039",
"pm_score": 5,
"selected": false,
"text": "<p>Let's say you need an empty directory named <em>tmp</em> :</p>\n\n<pre><code>$ mkdir tmp\n$ touch tmp/.gitignore\n$ git add tmp\n$ echo '*' > tmp/.gitignore\n$ git commit -m 'Empty directory' tmp\n</code></pre>\n\n<p>In other words, you need to add the .gitignore file to the index before you can tell Git to ignore it (and everything else in the empty directory).</p>\n"
},
{
"answer_id": 932982,
"author": "Jamie Flournoy",
"author_id": 115218,
"author_profile": "https://Stackoverflow.com/users/115218",
"pm_score": 13,
"selected": true,
"text": "<p>Another way to make a directory stay (almost) empty (in the repository) is to create a <code>.gitignore</code> file inside that directory that contains these four lines:</p>\n\n<pre><code># Ignore everything in this directory\n*\n# Except this file\n!.gitignore\n</code></pre>\n\n<p>Then you don't have to get the order right the way that you have to do in m104's <a href=\"https://stackoverflow.com/a/180917/32453\">solution</a>.</p>\n\n<p>This also gives the benefit that files in that directory won't show up as \"untracked\" when you do a git status.</p>\n\n<p>Making <a href=\"https://stackoverflow.com/users/554807/greenasjade\">@GreenAsJade</a>'s comment persistent:</p>\n\n<blockquote>\n <p>I think it's worth noting that this solution does precisely what the question asked for, but is not perhaps what many people looking at this question will have been looking for. This solution guarantees that the directory remains empty. It says \"I truly never want files checked in here\". As opposed to \"I don't have any files to check in here, yet, but I need the directory here, files may be coming later\".</p>\n</blockquote>\n"
},
{
"answer_id": 1174855,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>I've been facing the issue with empty directories, too. The problem with using placeholder files is that you need to create them, and delete them, if they are not necessary anymore (because later on there were added sub-directories or files. With big source trees managing these placeholder files can be cumbersome and error prone.</p>\n\n<p>This is why I decided to write an open source tool which can manage the creation/deletion of such placeholder files automatically. It is written for .NET platform and runs under Mono (.NET for Linux) and Windows.</p>\n\n<p>Just have a look at: <a href=\"http://code.google.com/p/markemptydirs\" rel=\"noreferrer\">http://code.google.com/p/markemptydirs</a></p>\n"
},
{
"answer_id": 5305908,
"author": "John Mee",
"author_id": 75033,
"author_profile": "https://Stackoverflow.com/users/75033",
"pm_score": 9,
"selected": false,
"text": "<p>You could always put a README file in the directory with an explanation of why you want this, otherwise empty, directory in the repository.</p>\n"
},
{
"answer_id": 5537012,
"author": "Mild Fuzz",
"author_id": 445126,
"author_profile": "https://Stackoverflow.com/users/445126",
"pm_score": 3,
"selected": false,
"text": "<p>I always build a function to check for my desired folder structure and build it for me within the project. This gets around this problem as the empty folders are held in Git by proxy.</p>\n\n<pre><code>function check_page_custom_folder_structure () {\n if (!is_dir(TEMPLATEPATH.\"/page-customs\"))\n mkdir(TEMPLATEPATH.\"/page-customs\"); \n if (!is_dir(TEMPLATEPATH.\"/page-customs/css\"))\n mkdir(TEMPLATEPATH.\"/page-customs/css\");\n if (!is_dir(TEMPLATEPATH.\"/page-customs/js\"))\n mkdir(TEMPLATEPATH.\"/page-customs/js\");\n}\n</code></pre>\n\n<p>This is in PHP, but I am sure most languages support the same functionality, and because the creation of the folders is taken care of by the application, the folders will always be there.</p>\n"
},
{
"answer_id": 5717707,
"author": "Peter Hoeg",
"author_id": 15512,
"author_profile": "https://Stackoverflow.com/users/15512",
"pm_score": 3,
"selected": false,
"text": "<p>As mentioned it's not possible to add empty directories, but here is a one liner that adds empty .gitignore files to all directories. </p>\n\n<p><code>ruby -e 'require \"fileutils\" ; Dir.glob([\"target_directory\",\"target_directory/**\"]).each { |f| FileUtils.touch(File.join(f, \".gitignore\")) if File.directory?(f) }'</code></p>\n\n<p>I have stuck this in a Rakefile for easy access.</p>\n"
},
{
"answer_id": 5871742,
"author": "mjs",
"author_id": 11543,
"author_profile": "https://Stackoverflow.com/users/11543",
"pm_score": 7,
"selected": false,
"text": "<p>As described in other answers, Git is unable to represent empty directories in its staging area. (See the <a href=\"https://git.wiki.kernel.org/index.php/GitFaq#Can_I_add_empty_directories.3F\" rel=\"noreferrer\">Git FAQ</a>.) However, if, for your purposes, a directory is empty enough if it contains a <code>.gitignore</code> file only, then you can create <code>.gitignore</code> files in empty directories only via:</p>\n\n<pre><code>find . -type d -empty -exec touch {}/.gitignore \\;\n</code></pre>\n"
},
{
"answer_id": 5913813,
"author": "Lesmana",
"author_id": 360899,
"author_profile": "https://Stackoverflow.com/users/360899",
"pm_score": 5,
"selected": false,
"text": "<p>TL;DR: slap a file in the directory and it will be tracked by git. (seriously. that is the official workaround)</p>\n<p>But I recommend instead: let a build script or deploy script create the directory on site.</p>\n<hr />\n<p>more explanation:</p>\n<p>Git does not track empty directories. See the <a href=\"https://git.wiki.kernel.org/index.php/GitFaq#Can_I_add_empty_directories.3F\" rel=\"nofollow noreferrer\">official Git FAQ</a> for more detail. The suggested workaround is to put a <code>.gitignore</code> file in the empty directory. With the file in place the directory is no longer empty and will be tracked by git.</p>\n<p>I do not like that workaround. The file <code>.gitignore</code> is meant to ignore things. Here it is used for the opposite: to keep something instead of ignoring something.</p>\n<p>A common workaround (to the workaround) is to name the file <code>.gitkeep</code>. This at least conveys the intention in the filename. Also it seems to be a consensus among some projects. Git itself does not care what the file is named. It just cares if the directory is empty or not.</p>\n<p>There is a problem shared by both <code>.gitkeep</code> and <code>.gitignore</code>: the file is hidden by unix convention. Some tools like <code>ls</code> or <code>cp dir/*</code> will pretend the file does not exists and behave as if the directory is empty. Other tools like <code>find -empty</code> will not. Newbie unix users might get stumped on this. Seasoned unix users will deduce that there are hidden files and check for them. Regardless; this is an avoidable annoyance.</p>\n<p>A simple solution to the "hidden problematic" is to name the file <code>gitkeep</code> (without the leading dot). We can take this one step further and name the file <code>README</code>. Then, in the file, explain why the directory needs to be empty and be tracked in git. That way other developers (and future you) can read up why things are the way they are.</p>\n<p>Summary: slap a file in the directory and now the (formerly empty) directory is tracked by git.</p>\n<hr />\n<p>Potential Problem: the directory is no longer empty.</p>\n<p>If your workflow merely requires an existing directory, perhap to dump files in it, then no problem (yet). But if you want to process the files further then problems might appear. Because in the directory is not only the files you want but also one rogue <code>.gitkeep</code> or <code>README</code> or what have you. This might complicate simple bash constructs like <code>for file in dirname/*</code> because you need to exclude or special case the extra file.</p>\n<p>If instead your workflow requires a <em>truly</em> empty directory then you definitely have a problem because the directory is no longer empty.</p>\n<p>Git does not want to track empty directories. By trying to make git track the empty directory you sacrifice the very thing you were trying to preserve: the empty directory.</p>\n<hr />\n<p>Lets take a few steps back. To before you asked how to make git track an empty directory.</p>\n<p>The situation you had then was likely the following: you have a tool that needs an empty directory to work. You want to deploy/distribute this tool and you want the empty directory to also be deployed. Problem: git does not track empty directories.</p>\n<p>Now instead of trying to get git to track empty directories lets explore the other options. Maybe (hopefully) you have a deploy script. Let the deploy script create the directory after git clone. Or you have a build script. Let the build script create the directory after compiling. Or maybe even modify the tool itself to check for and create the directory before use.</p>\n<p>If the tool is meant to be used by humans in diverse environments then I would let the tool itself check and create the directories. If you cannot modify the tool, or the tool is used in a highly automatized manner (docker container deploy, work, destroy), then the deploy script would be good place to create the directories.</p>\n<p>I think this is the more sensible approach to the problem. Build scripts and deploy scripts are meant to prepare things to run the program. Your tool requires an empty directory. So use those scripts to create the empty directory.</p>\n<p>Bonus: the directory is virtually guaranteed to be truly empty when about to be used. Also other developers (and future you) will not stumble upon an "empty" directory in the repository and wonder why it needs to be there.</p>\n<p>Of course the <code>mkdir</code> in the build script can bit rot just like any other line of code. But that is an inherent problem of development. While spurious "empty" directories are an artificial problem-to-be that is avoidable.</p>\n<p>TL;DR: let the build script or the deploy script create the empty directory on site. or let the tool itself check for and create the directory before use.</p>\n<hr />\n<p>It is dangerous to go alone. Take these commands.</p>\n<p>To list every empty directory:</p>\n<pre><code>find -type d -empty\n</code></pre>\n<p>Same but avoid looking in the <code>.git</code> directory:</p>\n<pre><code>find -name .git -prune -o -type d -empty -print\n</code></pre>\n<p>The following commands might help you if you inherited a project containing "empty" directories.</p>\n<p>To list every directory containing a file named <code>.gitkeep</code>:</p>\n<pre><code>find -type f -name .gitkeep\n</code></pre>\n<p>To list every directory and the number of files it contains:</p>\n<pre><code>find -type f -printf "%h\\n" | sort | uniq -c | sort -n\n</code></pre>\n<p>Now you can examine all directories containing exactly one file and check if it is a "git keep" file. Note this command does not list directories that are truly empty.</p>\n"
},
{
"answer_id": 6487199,
"author": "user665190",
"author_id": 665190,
"author_profile": "https://Stackoverflow.com/users/665190",
"pm_score": 2,
"selected": false,
"text": "<p>You can save this code as create_readme.php and run the <a href=\"http://en.wikipedia.org/wiki/PHP\" rel=\"nofollow noreferrer\">PHP</a> code from the root directory of your Git project.</p>\n<pre class=\"lang-none prettyprint-override\"><code>php create_readme.php\n</code></pre>\n<p>It will add README files to all directories that are empty so those directories would be then added to the index.</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php\n $path = realpath('.');\n $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);\n foreach($objects as $name => $object){\n if ( is_dir($name) && ! is_empty_folder($name) ){\n echo "$name\\n" ;\n exec("touch ".$name."/"."README");\n }\n }\n\n function is_empty_folder($folder) {\n $files = opendir($folder);\n while ($file = readdir($files)) {\n if ($file != '.' && $file != '..')\n return true; // Not empty\n }\n }\n?>\n</code></pre>\n<p>Then do</p>\n<pre class=\"lang-none prettyprint-override\"><code>git commit -m "message"\ngit push\n</code></pre>\n"
},
{
"answer_id": 7905820,
"author": "Brent Bradburn",
"author_id": 86967,
"author_profile": "https://Stackoverflow.com/users/86967",
"pm_score": 4,
"selected": false,
"text": "<p>Maybe adding an empty directory seems like it would be the <em>path of least resistance</em> because you have scripts that expect that directory to exist (maybe because it is a target for generated binaries). Another approach would be to <strong>modify your scripts to create the directory as needed</strong>.</p>\n\n<pre><code>mkdir --parents .generated/bin ## create a folder for storing generated binaries\nmv myprogram1 myprogram2 .generated/bin ## populate the directory as needed\n</code></pre>\n\n<p>In this example, you might check in a (broken) symbolic link to the directory so that you can access it without the \".generated\" prefix (but this is optional).</p>\n\n<pre><code>ln -sf .generated/bin bin\ngit add bin\n</code></pre>\n\n<p>When you want to clean up your source tree you can just:</p>\n\n<pre><code>rm -rf .generated ## this should be in a \"clean\" script or in a makefile\n</code></pre>\n\n<p>If you take the oft-suggested approach of checking in an almost-empty folder, you have the minor complexity of deleting the contents without also deleting the \".gitignore\" file.</p>\n\n<p>You can ignore all of your generated files by adding the following to your root .gitignore:</p>\n\n<pre><code>.generated\n</code></pre>\n"
},
{
"answer_id": 8418403,
"author": "Artur79",
"author_id": 268780,
"author_profile": "https://Stackoverflow.com/users/268780",
"pm_score": 10,
"selected": false,
"text": "<p>Create an empty file called <code>.gitkeep</code> in the directory, and <code>git add</code> it.</p>\n<p>This will be a hidden file on Unix-like systems by default but it will force Git to acknowledge the existence of the directory since it now has content.</p>\n<p>Also note that there is nothing special about this file's name. You could have named it anything you wanted. All Git cares about is that the folder has something in it.</p>\n"
},
{
"answer_id": 8944077,
"author": "ofavre",
"author_id": 508831,
"author_profile": "https://Stackoverflow.com/users/508831",
"pm_score": 5,
"selected": false,
"text": "<p><strong>WARNING: This tweak is not truly working as it turns out.</strong> Sorry for the inconvenience.</p>\n\n<p><strong>Original post below:</strong></p>\n\n<p>I found a solution while playing with Git internals!</p>\n\n<ol>\n<li>Suppose you are in your repository.</li>\n<li><p>Create your empty directory:</p>\n\n<pre><code>$ mkdir path/to/empty-folder\n</code></pre></li>\n<li><p>Add it to the index using a plumbing command and the empty tree <a href=\"http://en.wikipedia.org/wiki/SHA-1\" rel=\"noreferrer\">SHA-1</a>:</p>\n\n<pre><code>$ git update-index --index-info\n040000 tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904 path/to/empty-folder\n</code></pre>\n\n<p>Type the command and then enter the second line. Press <kbd>Enter</kbd> and then <kbd>Ctrl</kbd> + <kbd>D</kbd> to terminate your input.\nNote: the format is <em>mode</em> [SPACE] <em>type</em> [SPACE] SHA-1hash <strong>[TAB]</strong> path (the tab is important, the answer formatting does not preserve it).</p></li>\n<li><p>That's it! Your empty folder is in your index. All you have to do is commit.</p></li>\n</ol>\n\n<p>This solution is short and apparently works fine (<strong>see the EDIT!</strong>), but it is not that easy to remember...</p>\n\n<p>The empty tree SHA-1 can be found by creating a new empty Git repository, <code>cd</code> into it and issue <code>git write-tree</code>, which outputs the empty tree SHA-1.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>I've been using this solution since I found it. It appears to work exactly the same way as creating a submodule, except that no module is defined anywhere.\nThis leads to errors when issuing <code>git submodule init|update</code>.\nThe problem is that <code>git update-index</code> rewrites the <code>040000 tree</code> part into <code>160000 commit</code>.</p>\n\n<p>Moreover, any file placed under that path won't ever be noticed by Git, as it thinks they belong to some other repository. This is nasty as it can easily be overlooked!</p>\n\n<p>However, if you don't already (and won't) use any Git submodules in your repository, and the \"empty\" folder will remain empty or if you want Git to know of its existence and ignore its content, you can go with this tweak. Going the usual way with submodules takes more steps that this tweak.</p>\n"
},
{
"answer_id": 13012436,
"author": "Thomas E",
"author_id": 1208895,
"author_profile": "https://Stackoverflow.com/users/1208895",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"http://en.wikipedia.org/wiki/Ruby_on_Rails\" rel=\"nofollow noreferrer\">Ruby on Rails</a> log folder creation way: </p>\n\n<pre><code>mkdir log && touch log/.gitkeep && git add log/.gitkeep\n</code></pre>\n\n<p>Now the log directory will be included in the tree. It is super-useful when deploying, so you won't have to write a routine to make log directories.</p>\n\n<p>The logfiles can be kept out by issuing, </p>\n\n<pre><code>echo log/dev.log >> .gitignore\n</code></pre>\n\n<p>but you probably knew that.</p>\n"
},
{
"answer_id": 20388370,
"author": "Cranio",
"author_id": 1403638,
"author_profile": "https://Stackoverflow.com/users/1403638",
"pm_score": 8,
"selected": false,
"text": "<h3>Why would we need empty versioned folders</h3>\n\n<p>First things first:</p>\n\n<blockquote>\n <p>An empty directory <em>cannot be part of a tree under the Git versioning system</em>.</p>\n</blockquote>\n\n<p>It simply won't be tracked. But there are scenarios in which \"versioning\" empty directories can be meaningful, for example:</p>\n\n<ul>\n<li>scaffolding a <strong>predefined folder structure</strong>, making it available to every user/contributor of the repository; or, as a specialized case of the above, creating a folder for <strong>temporary files</strong>, such as a <code>cache/</code> or <code>logs/</code> directories, where we want to provide the folder but <code>.gitignore</code> its contents</li>\n<li>related to the above, some projects <em>won't work without some folders</em> (which is often a hint of a poorly designed project, but it's a frequent real-world scenario and maybe there could be, say, permission problems to be addressed).</li>\n</ul>\n\n<h3>Some suggested workarounds</h3>\n\n<p>Many users suggest:</p>\n\n<ol>\n<li>Placing a <code>README</code> file or another file with some content in order to make the directory non-empty, or</li>\n<li>Creating a <code>.gitignore</code> file with a sort of \"reverse logic\" (i.e. to include all the files) which, at the end, serves the same purpose of approach #1.</li>\n</ol>\n\n<p>While <em>both solutions surely work</em> I find them inconsistent with a meaningful approach to Git versioning.</p>\n\n<ul>\n<li>Why are you supposed to put bogus files or READMEs that maybe you don't really want in your project?</li>\n<li>Why use <code>.gitignore</code> to do a thing (<em>keeping</em> files) that is the very opposite of what it's meant for (<em>excluding</em> files), even though it is possible?</li>\n</ul>\n\n<h3>.gitkeep approach</h3>\n\n<p>Use an <em>empty</em> file called <code>.gitkeep</code> in order to force the presence of the folder in the versioning system.</p>\n\n<p>Although it may seem not such a big difference:</p>\n\n<ul>\n<li><p>You use a file that has the <em>single</em> purpose of keeping the folder. You don't put there any info you don't want to put.</p>\n\n<p>For instance, you should use READMEs as, well, READMEs with useful information, not as an excuse to keep the folder.</p>\n\n<p>Separation of concerns is always a good thing, and you can still add a <code>.gitignore</code> to ignore unwanted files.</p></li>\n<li><p>Naming it <code>.gitkeep</code> makes it very clear and straightforward from the filename itself (and also <em>to other developers</em>, which is good for a shared project and one of the core purposes of a Git repository) that this file is</p>\n\n<ul>\n<li>A file unrelated to the code (because of the leading dot and the name)</li>\n<li>A file clearly related to Git</li>\n<li>Its purpose (<strong>keep</strong>) is clearly stated and consistent and semantically opposed in its meaning to <strong>ignore</strong></li>\n</ul></li>\n</ul>\n\n<h3>Adoption</h3>\n\n<p>I've seen the <code>.gitkeep</code> approach adopted by very important frameworks like <a href=\"https://laravel.com/\" rel=\"noreferrer\">Laravel</a>, <a href=\"https://github.com/angular/angular-cli\" rel=\"noreferrer\">Angular-CLI</a>.</p>\n"
},
{
"answer_id": 21422128,
"author": "Asclepius",
"author_id": 832230,
"author_profile": "https://Stackoverflow.com/users/832230",
"pm_score": 9,
"selected": false,
"text": "<pre><code>touch .placeholder\n</code></pre>\n<p>On Linux, this creates an empty file named <code>.placeholder</code>. For what it's worth, this name is agnostic to git, and this approach is used in various other places in the system, e.g. <code>/etc/cron.d/.placeholder</code>. Secondly, as another user has noted, the <code>.git</code> prefix convention can be reserved for files and directories that Git itself uses for configuration purposes.</p>\n<p>Alternatively, as noted in another <a href=\"https://stackoverflow.com/a/5305908/\">answer</a>, <strong>the directory can contain a descriptive <a href=\"https://stackoverflow.com/questions/8655937/github-readme-and-readme-md\"><code>README.md</code> file</a> instead</strong>.</p>\n<p>Either way this requires that the presence of the file won't cause your application to break.</p>\n"
},
{
"answer_id": 24351531,
"author": "Roman",
"author_id": 2139671,
"author_profile": "https://Stackoverflow.com/users/2139671",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/932982/456814\">The solution of Jamie Flournoy</a> works great. Here is a bit enhanced version to keep the <code>.htaccess</code> :</p>\n\n<pre><code># Ignore everything in this directory\n*\n# Except this file\n!.gitignore\n!.htaccess\n</code></pre>\n\n<p>With this solution you are able to commit a empty folder, for example <code>/log</code>, <code>/tmp</code> or <code>/cache</code> and the folder will stay empty.</p>\n"
},
{
"answer_id": 27635349,
"author": "Stanislav Bashkyrtsev",
"author_id": 886697,
"author_profile": "https://Stackoverflow.com/users/886697",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a hack, but it's funny that it works (Git 2.2.1). Similar to what @Teka suggested, but easier to remember:</p>\n\n<ul>\n<li>Add a submodule to any repository (<code>git submodule add path_to_repo</code>)</li>\n<li>This will add a folder and a file <code>.submodules</code>. Commit a change.</li>\n<li>Delete <code>.submodules</code> file and commit the change.</li>\n</ul>\n\n<p>Now, you have a directory that gets created when commit is checked out. An interesting thing though is that if you look at the content of tree object of this file you'll get:</p>\n\n<blockquote>\n <p>fatal: Not a valid object name\n b64338b90b4209263b50244d18278c0999867193</p>\n</blockquote>\n\n<p>I wouldn't encourage to use it though since it may stop working in the future versions of Git. Which may leave your repository corrupted.</p>\n"
},
{
"answer_id": 29064398,
"author": "user2334883",
"author_id": 2334883,
"author_profile": "https://Stackoverflow.com/users/2334883",
"pm_score": 4,
"selected": false,
"text": "<p>You can't and unfortunately will never be able to. This is a decision made by Linus Torvald himself. He knows what's good for us. </p>\n\n<p>There is a rant out there somewhere I read once. </p>\n\n<p>I found <em><a href=\"http://markmail.org/message/4eqjxx73opiswfis\" rel=\"noreferrer\">Re: Empty directories..</a></em>, but maybe there is another one.</p>\n\n<p>You have to live with the workarounds...unfortunately.</p>\n"
},
{
"answer_id": 29884569,
"author": "Zaz",
"author_id": 405550,
"author_profile": "https://Stackoverflow.com/users/405550",
"pm_score": 4,
"selected": false,
"text": "<p>There's no way to get Git to track directories, so the only solution is to add a placeholder file within the directory that you want Git to track.</p>\n\n<p>The file can be named and contain anything you want, but most people use an empty file named <code>.gitkeep</code> (although some people prefer the VCS-agnostic <code>.keep</code>).</p>\n\n<p>The prefixed <code>.</code> marks it as a hidden file.</p>\n\n<p>Another idea would be to add a <code>README</code> file explaining what the directory will be used for.</p>\n"
},
{
"answer_id": 37450055,
"author": "Mike",
"author_id": 1301994,
"author_profile": "https://Stackoverflow.com/users/1301994",
"pm_score": 3,
"selected": false,
"text": "<p>Adding one more option to the fray.</p>\n\n<p>Assuming you would like to add a directory to <code>git</code> that, for all purposes related to <code>git</code>, should remain empty and never have it's contents tracked, a <code>.gitignore</code> as suggested numerous times here, will do the trick.</p>\n\n<p>The format, as mentioned, is:</p>\n\n<pre><code>*\n!.gitignore\n</code></pre>\n\n<p>Now, if you want a way to do this at the command line, in one fell swoop, while <em>inside</em> the directory you want to add, you can execute:</p>\n\n<pre><code>$ echo \"*\" > .gitignore && echo '!.gitignore' >> .gitignore && git add .gitignore\n</code></pre>\n\n<p>Myself, I have a shell script that I use to do this. Name the script whatever you whish, and either add it somewhere in your include path, or reference it directly:</p>\n\n<pre><code>#!/bin/bash\n\ndir=''\n\nif [ \"$1\" != \"\" ]; then\n dir=\"$1/\"\nfi\n\necho \"*\" > $dir.gitignore && \\\necho '!.gitignore' >> $dir.gitignore && \\\ngit add $dir.gitignore\n</code></pre>\n\n<p>With this, you can either execute it from within the directory you wish to add, or reference the directory as it's first and only parameter:</p>\n\n<pre><code>$ ignore_dir ./some/directory\n</code></pre>\n\n<p>Another option (in response to a comment by @GreenAsJade), if you want to track an empty folder that <em>MAY</em> contain tracked files in the future, but will be empty for now, you can ommit the <code>*</code> from the <code>.gitignore</code> file, and check <em>that</em> in. Basically, all the file is saying is \"do not ignore <em>me</em>\", but otherwise, the directory is empty and tracked.</p>\n\n<p>Your <code>.gitignore</code> file would look like:</p>\n\n<pre><code>!.gitignore\n</code></pre>\n\n<p>That's it, check that in, and you have an empty, yet tracked, directory that you can track files in at some later time.</p>\n\n<p>The reason I suggest keeping that one line in the file is that it gives the <code>.gitignore</code> purpose. Otherwise, some one down the line may think to remove it. It may help if you place a comment above the line.</p>\n"
},
{
"answer_id": 37597601,
"author": "Trendfischer",
"author_id": 685551,
"author_profile": "https://Stackoverflow.com/users/685551",
"pm_score": 3,
"selected": false,
"text": "<p>Sometimes you have to deal with bad written libraries or software, which need a \"real\" empty and existing directory. Putting a simple <code>.gitignore</code> or <code>.keep</code> might break them and cause a bug. The following might help in these cases, but no guarantee...</p>\n\n<p>First create the needed directory:</p>\n\n<pre><code>mkdir empty\n</code></pre>\n\n<p>Then you add a broken symbolic link to this directory (but on any other case than the described use case above, please use a <code>README</code> with an explanation):</p>\n\n<pre><code>ln -s .this.directory empty/.keep\n</code></pre>\n\n<p>To ignore files in this directory, you can add it in your root <code>.gitignore</code>:</p>\n\n<pre><code>echo \"/empty\" >> .gitignore\n</code></pre>\n\n<p>To add the ignored file, use a parameter to force it:</p>\n\n<pre><code>git add -f empty/.keep\n</code></pre>\n\n<p>After the commit you have a broken symbolic link in your index and git creates the directory. The broken link has some advantages, since it is no regular file and points to no regular file. So it even fits to the part of the question \"(that contains no files)\", not by the intention but by the meaning, I guess:</p>\n\n<pre><code>find empty -type f\n</code></pre>\n\n<p>This commands shows an empty result, since no files are present in this directory. So most applications, which get all files in a directory usually do not see this link, at least if they do a \"file exists\" or a \"is readable\". Even some scripts will not find any files there:</p>\n\n<pre><code>$ php -r \"var_export(glob('empty/.*'));\"\narray (\n 0 => 'empty/.',\n 1 => 'empty/..',\n)\n</code></pre>\n\n<p>But I strongly recommend to use this solution only in special circumstances, a good written <code>README</code> in an empty directory is usually a better solution. (And I do not know if this works with a windows filesystem...)</p>\n"
},
{
"answer_id": 38313879,
"author": "Rahul Sinha",
"author_id": 3389121,
"author_profile": "https://Stackoverflow.com/users/3389121",
"pm_score": 2,
"selected": false,
"text": "<p>Sometimes I have repositories with folders that will only ever contain files considered to be \"content\"—that is, they are not files that I care about being versioned, and therefore should never be committed. With Git's .gitignore file, you can ignore entire directories. But there are times when having the folder in the repo would be beneficial. Here's a excellent solution for accomplishing this need.</p>\n\n<p>What I've done in the past is put a .gitignore file at the root of my repo, and then exclude the folder, like so:</p>\n\n<pre><code>/app/some-folder-to-exclude\n/another-folder-to-exclude/*\n</code></pre>\n\n<p>However, these folders then don't become part of the repo. You could add something like a README file in there. But then you have to tell your application not to worry about processing any README files.</p>\n\n<p>If your app depends on the folders being there (though empty), you can simply add a .gitignore file to the folder in question, and use it to accomplish two goals:</p>\n\n<p>Tell Git there's a file in the folder, which makes Git add it to the repo.\nTell Git to ignore the contents of this folder, minus this file itself.\nHere is the .gitignore file to put inside your empty directories:</p>\n\n<pre><code>*\n!.gitignore\n</code></pre>\n\n<p>The first line (*) tells Git to ignore everything in this directory. The second line tells Git not to ignore the .gitignore file. You can stuff this file into every empty folder you want added to the repository.</p>\n"
},
{
"answer_id": 43917066,
"author": "ajmedway",
"author_id": 2429318,
"author_profile": "https://Stackoverflow.com/users/2429318",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to add a folder that will house a lot of transient data in multiple semantic directories, then one approach is to add something like this to your root .gitignore...</p>\n\n<p><code>/app/data/**/*.*\n!/app/data/**/*.md</code></p>\n\n<p>Then you can commit descriptive README.md files (or blank files, doesn't matter, as long as you can target them uniquely like with the <code>*.md</code> in this case) in each directory to ensure that the directories all remain part of the repo but the files (with extensions) are kept ignored. LIMITATION: <code>.</code>'s are not allowed in the directory names!</p>\n\n<p>You can fill up all of these directories with xml/images files or whatever and add more directories under <code>/app/data/</code> over time as the storage needs for your app develop (with the README.md files serving to burn in a description of what each storage directory is for exactly).</p>\n\n<p>There is no need to further alter your <code>.gitignore</code> or decentralise by creating a new <code>.gitignore</code> for each new directory. Probably not the smartest solution but is terse gitignore-wise and always works for me. Nice and simple! ;)</p>\n\n<p><a href=\"https://i.stack.imgur.com/xNBNN.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/xNBNN.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 43987053,
"author": "Mig82",
"author_id": 4124574,
"author_profile": "https://Stackoverflow.com/users/4124574",
"pm_score": 4,
"selected": false,
"text": "<p>I like the answers <a href=\"https://stackoverflow.com/questions/115983/how-do-i-add-an-empty-directory-to-a-git-repository/8418403#8418403\">by Artur79</a> <a href=\"https://stackoverflow.com/questions/115983/how-do-i-add-an-empty-directory-to-a-git-repository/5871742#5871742\">and mjs</a>, so I've been using a combination of both and made it a standard for our projects.</p>\n<pre class=\"lang-none prettyprint-override\"><code>find . -type d -empty -exec touch {}/.gitkeep \\;\n</code></pre>\n<p>However, only a handful of our developers work on Mac or Linux. A lot work on Windows, and I could not find an equivalent simple one-liner to accomplish the same there. Some were lucky enough to have <a href=\"http://cygwin.com/\" rel=\"nofollow noreferrer\">Cygwin</a> installed for other reasons, but prescribing Cygwin just for this seemed overkill.</p>\n<p>So, since most of our developers already have <a href=\"http://ant.apache.org/\" rel=\"nofollow noreferrer\">Ant</a> installed, the first thing I thought of was to put together an Ant build file to accomplish this independently of the platform. This can still be found <a href=\"https://github.com/mig82/gitkeep\" rel=\"nofollow noreferrer\">here</a></p>\n<p><strong>However</strong>, it would be better to make this into a small utility command, so I recreated it using Python and published it to the PyPI <a href=\"https://pypi.org/project/gitkeep2/\" rel=\"nofollow noreferrer\">here</a>. You can install it by simply running:</p>\n<pre class=\"lang-none prettyprint-override\"><code>pip3 install gitkeep2\n</code></pre>\n<p>It will allow you to create and remove <code>.gitkeep</code> files recursively, and it will also allow you to add messages to them for your peers to understand why those directories are important. This last bit is bonus. I thought it would be nice if the <code>.gitkeep</code> files could be self-documenting.</p>\n<pre class=\"lang-none prettyprint-override\"><code>$ gitkeep --help\nUsage: gitkeep [OPTIONS] PATH\n\n Add a .gitkeep file to a directory in order to push them into a Git repo\n even if they're empty.\n\n Read more about why this is necessary at: https://git.wiki.kernel.org/inde\n x.php/Git_FAQ#Can_I_add_empty_directories.3F\n\nOptions:\n -r, --recursive Add or remove the .gitkeep files recursively for all\n sub-directories in the specified path.\n -l, --let-go Remove the .gitkeep files from the specified path.\n -e, --empty Create empty .gitkeep files. This will ignore any\n message provided\n -m, --message TEXT A message to be included in the .gitkeep file, ideally\n used to explain why it's important to push the specified\n directory to source control even if it's empty.\n -v, --verbose Print out everything.\n --help Show this message and exit.\n</code></pre>\n"
},
{
"answer_id": 56624980,
"author": "arcseldon",
"author_id": 1882064,
"author_profile": "https://Stackoverflow.com/users/1882064",
"pm_score": 3,
"selected": false,
"text": "<p>An easy way to do this is by adding a <code>.gitkeep</code> file to the directory you wish to (currently) keep empty. </p>\n\n<p>See this <a href=\"https://stackoverflow.com/a/7229996/1882064\">SOF answer</a> for further info - which also explains why some people find the competing convention of adding a .gitignore file (as stated in many answers here) confusing.</p>\n"
},
{
"answer_id": 57474959,
"author": "Hainan Zhao",
"author_id": 1350922,
"author_profile": "https://Stackoverflow.com/users/1350922",
"pm_score": 3,
"selected": false,
"text": "<p>A <a href=\"https://en.wikipedia.org/wiki/PowerShell\" rel=\"nofollow noreferrer\">PowerShell</a> version:</p>\n<blockquote>\n<p>Find all the empty folders in the directory</p>\n<p>Add a empty .gitkeep file in there</p>\n</blockquote>\n<pre><code>Get-ChildItem 'Path to your Folder' -Recurse -Directory | Where-Object {[System.IO.Directory]::GetFileSystemEntries($_.FullName).Count -eq 0} | ForEach-Object { New-Item ($_.FullName + "\\.gitkeep") -ItemType file}\n</code></pre>\n"
},
{
"answer_id": 58510582,
"author": "aball",
"author_id": 8213124,
"author_profile": "https://Stackoverflow.com/users/8213124",
"pm_score": 2,
"selected": false,
"text": "<p>To extend <a href=\"https://stackoverflow.com/a/932982/8213124\">Jamie Flournoy's solution</a> to a directory tree, you can put this <em><a href=\"https://git-scm.com/docs/gitignore\" rel=\"nofollow noreferrer\">.gitignore</a></em> file in the top-level directory and <code>touch .keepdir</code> in each subdirectory that Git should track. All other files are ignored. This is useful to ensure a consistent structure for build directories.</p>\n<pre><code># Ignore files but not directories. * matches both files and directories\n# but */ matches only directories. Both match at every directory level\n# at or below this one.\n*\n!*/\n\n# Git doesn't track empty directories, so track .keepdir files, which also\n# tracks the containing directory.\n!.keepdir\n\n# Keep this file and the explanation of how this works\n!.gitignore\n!Readme.md\n</code></pre>\n"
},
{
"answer_id": 58543445,
"author": "ntninja",
"author_id": 277882,
"author_profile": "https://Stackoverflow.com/users/277882",
"pm_score": 4,
"selected": false,
"text": "<p>Reading <a href=\"https://stackoverflow.com/a/8944077/277882\">ofavre's</a> and <a href=\"https://stackoverflow.com/a/27635349/277882\">stanislav-bashkyrtsev's answers</a> using broken Git submodule references to create the Git directories, I'm surprised that nobody has suggested yet this simple amendment of the idea to make the whole thing sane and safe:</p>\n<p>Rather than <em>hacking a fake submodule into Git</em>, just <strong>add an empty real one</strong>.</p>\n<h3>Enter: <a href=\"https://gitlab.com/empty-repo/empty.git\" rel=\"nofollow noreferrer\">https://gitlab.com/empty-repo/empty.git</a></h3>\n<p>A Git repository with exactly one commit:</p>\n<pre class=\"lang-none prettyprint-override\"><code>commit e84d7b81f0033399e325b8037ed2b801a5c994e0\nAuthor: Nobody <none>\nDate: Thu Jan 1 00:00:00 1970 +0000\n</code></pre>\n<p>No message, no committed files.</p>\n<h3>Usage</h3>\n<p>To add an empty directory to you GIT repo:</p>\n<pre class=\"lang-none prettyprint-override\"><code>git submodule add https://gitlab.com/empty-repo/empty.git path/to/dir\n</code></pre>\n<p>To convert all existing empty directories to submodules:</p>\n<pre class=\"lang-none prettyprint-override\"><code>find . -type d -empty -delete -exec git submodule add -f https://gitlab.com/empty-repo/empty.git \\{\\} \\;\n</code></pre>\n<p>Git will store the latest commit hash when creating the submodule reference, so you don't have to worry about me (or GitLab) using this to inject malicious files. Unfortunately I have not found any way to force which commit ID is used during checkout, so you'll have to manually check that the reference commit ID is <code>e84d7b81f0033399e325b8037ed2b801a5c994e0</code> using <code>git submodule status</code> after adding the repo.</p>\n<p>Still not a native solution, but the best we probably can have without somebody getting their hands <em>really</em>, <em>really</em> dirty in the GIT codebase.</p>\n<h3>Appendix: Recreating this commit</h3>\n<p>You should be able to recreate this exact commit using (in an empty directory):</p>\n<pre class=\"lang-none prettyprint-override\"><code># Initialize new GIT repository\ngit init\n\n# Set author data (don't set it as part of the `git commit` command or your default data will be stored as “commit author”)\ngit config --local user.name "Nobody"\ngit config --local user.email "none"\n\n# Set both the commit and the author date to the start of the Unix epoch (this cannot be done using `git commit` directly)\nexport GIT_AUTHOR_DATE="Thu Jan 1 00:00:00 1970 +0000"\nexport GIT_COMMITTER_DATE="Thu Jan 1 00:00:00 1970 +0000"\n\n# Add root commit\ngit commit --allow-empty --allow-empty-message --no-edit\n</code></pre>\n<p>Creating reproducible Git commits is surprisingly hard…</p>\n"
},
{
"answer_id": 58945680,
"author": "Yi Zhao",
"author_id": 6381094,
"author_profile": "https://Stackoverflow.com/users/6381094",
"pm_score": 0,
"selected": false,
"text": "<p>I search into this question because: I create a new directory and it contains many files. Among these files, some I want to add to Git repository and some not. But when I do "git status". It only shows:</p>\n<pre><code>Untracked files:\n (use "git add <file>..." to include in what will be committed)\n ../trine/device_android/\n</code></pre>\n<p>It does not list the separate files in this new directory. Then I think maybe I can add this directory only and then deal with the separate files. So I google "Git add directory only".</p>\n<p>In my situation, I found I can just add one file in the new directory that I am sure I want to add it to Git.</p>\n<pre><code>git add new_folder/some_file\n</code></pre>\n<p>After this, "git status" will show the status of separate files.</p>\n"
},
{
"answer_id": 63726420,
"author": "DevonDahon",
"author_id": 931247,
"author_profile": "https://Stackoverflow.com/users/931247",
"pm_score": 4,
"selected": false,
"text": "<p>This solution worked for me.</p>\n<h3>1. Add a <code>.gitignore</code> file to your empty directory:</h3>\n<pre><code>*\n*/\n!.gitignore\n</code></pre>\n<ul>\n<li><code>*</code> ignore all files in the folder</li>\n<li><code>*/</code> Ignore subdirectories</li>\n<li><code>!.gitignore</code> include the .gitignore file</li>\n</ul>\n<h3>2. Then remove your cache, stage your files, commit and push:</h3>\n<pre><code>git rm -r --cached .\ngit add . // or git stage .\ngit commit -m ".gitignore fix"\ngit push\n</code></pre>\n"
},
{
"answer_id": 63822216,
"author": "Aroo",
"author_id": 12019321,
"author_profile": "https://Stackoverflow.com/users/12019321",
"pm_score": -1,
"selected": false,
"text": "<p>Just add a <code>readme</code> or a <code>.gitignore</code> file and then delete it, but not from terminal, from the GitHub website. That will give an empty repository.</p>\n"
},
{
"answer_id": 64944116,
"author": "Sohel Ahmed Mesaniya",
"author_id": 3794786,
"author_profile": "https://Stackoverflow.com/users/3794786",
"pm_score": 2,
"selected": false,
"text": "<p>Just add an empty (with no content) <a href=\"https://git-scm.com/docs/gitignore\" rel=\"nofollow noreferrer\">.gitignore</a> file in the empty directory you want to track.</p>\n<p>E.g., if you want to track an empty directory, <code>/project/content/posts</code>, then create a new empty file, <code>/project/content/posts/.gitignore</code></p>\n<p>Note: <em>.gitkeep</em> is not part of official <a href=\"https://git-scm.com/\" rel=\"nofollow noreferrer\">Git</a>:</p>\n<p><a href=\"https://i.stack.imgur.com/u0lfD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/u0lfD.png\" alt=\"Enter image description here\" /></a></p>\n"
},
{
"answer_id": 70183273,
"author": "vidur punj",
"author_id": 1578898,
"author_profile": "https://Stackoverflow.com/users/1578898",
"pm_score": 5,
"selected": false,
"text": "<p>Add a <em>.gitkeep</em> file inside the empty directory and commit it.</p>\n<pre><code>touch .gitkeep\n</code></pre>\n<p>It is the standard followed by Git.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/115983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
]
| How do I add an empty directory (that contains no files) to a Git repository? | Another way to make a directory stay (almost) empty (in the repository) is to create a `.gitignore` file inside that directory that contains these four lines:
```
# Ignore everything in this directory
*
# Except this file
!.gitignore
```
Then you don't have to get the order right the way that you have to do in m104's [solution](https://stackoverflow.com/a/180917/32453).
This also gives the benefit that files in that directory won't show up as "untracked" when you do a git status.
Making [@GreenAsJade](https://stackoverflow.com/users/554807/greenasjade)'s comment persistent:
>
> I think it's worth noting that this solution does precisely what the question asked for, but is not perhaps what many people looking at this question will have been looking for. This solution guarantees that the directory remains empty. It says "I truly never want files checked in here". As opposed to "I don't have any files to check in here, yet, but I need the directory here, files may be coming later".
>
>
> |
116,002 | <p>We all know that RAW pointers need to be wrapped in some form of smart pointer to get Exception safe memory management. But when it comes to containers of pointers the issue becomes more thorny.</p>
<p>The std containers insist on the contained object being copyable so this rules out the use of std::auto_ptr, though you can still use boost::shared_ptr etc.</p>
<p>But there are also some boost containers designed explicitly to hold pointers safely:<br>
See <a href="http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/reference.html" rel="nofollow noreferrer">Pointer Container Library</a><br></p>
<p>The question is:
Under what conditions should I prefer to use the ptr_containers over a container of smart_pointers?</p>
<pre><code>boost::ptr_vector<X>
or
std::vector<boost::shared_ptr<X> >
</code></pre>
| [
{
"answer_id": 116045,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "<p>Well, overhead is one case.</p>\n\n<p>A vector of shared pointers will do a lot of extraneous copying that involves creating a new smart pointer, incrementing a reference, decrementing a reference, etc on a resize. All of this is avoided with a pointer container. </p>\n\n<p>Requires profiling to ensure the container operations are the bottleneck though :)</p>\n"
},
{
"answer_id": 116049,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 5,
"selected": true,
"text": "<p>Boost pointer containers have strict ownership over the resources they hold. A std::vector<boost::shared_ptr<X>> has shared ownership. There are reasons why that may be necessary, but in case it isn't, I would default to boost::ptr_vector<X>. YMMV.</p>\n"
},
{
"answer_id": 116087,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 2,
"selected": false,
"text": "<p>Steady on: smart pointers are a very good method of handling resource management, but not the only one. I agree you will see very few raw pointers in well-written C++ code, but in my experience you don't see that many smart pointers either. There are plenty of perfectly exception-safe classes implemented using containers of raw pointers.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14065/"
]
| We all know that RAW pointers need to be wrapped in some form of smart pointer to get Exception safe memory management. But when it comes to containers of pointers the issue becomes more thorny.
The std containers insist on the contained object being copyable so this rules out the use of std::auto\_ptr, though you can still use boost::shared\_ptr etc.
But there are also some boost containers designed explicitly to hold pointers safely:
See [Pointer Container Library](http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/reference.html)
The question is:
Under what conditions should I prefer to use the ptr\_containers over a container of smart\_pointers?
```
boost::ptr_vector<X>
or
std::vector<boost::shared_ptr<X> >
``` | Boost pointer containers have strict ownership over the resources they hold. A std::vector<boost::shared\_ptr<X>> has shared ownership. There are reasons why that may be necessary, but in case it isn't, I would default to boost::ptr\_vector<X>. YMMV. |
116,032 | <p>I've sometimes had a problem with my field-, table-, view- oder stored procedure names.
Example:</p>
<pre><code> SELECT from, to, rate FROM Table1
</code></pre>
<p>The Problem is that <strong><em>from</em></strong> is a reserved word in SQL-92.
You could put the fieldname in double quotes to fix this, but what if some other db tools wants to read your database?
It is your database design and it is your fault if other applications have problems with your db.</p>
<p>There are many other <a href="http://developer.mimer.com/validator/sql-reserved-words.tml" rel="nofollow noreferrer" title="SQL reserved words">reserved words</a> (~300) and we should avoid all of them.
If you change the DBMS from manufacturer A to B, your application can fail, because a some fieldnames are now reserved words.
A field called <strong><em>PERCENT</em></strong> may work for a oracle db, but on a MS SQL Server it must be treated as a reserved word.</p>
<p>I have a tool to check my database design against these reserved words ; you too?</p>
<p>Here are my rules</p>
<ol>
<li>don't use names longer than 32 chars (some DBMS can't handle longer names)</li>
<li>use only a-z, A-Z, 0-9 and the underscore (:-;,/&!=?+- are not allowed)</li>
<li>don't start a name with a digit</li>
<li>avoid these reserved words</li>
</ol>
| [
{
"answer_id": 116033,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 2,
"selected": false,
"text": "<p>Easy way: just make sure <em>every</em> field name is quoted.</p>\n\n<p>Edit: Any sensible DB tool worth its salt should be doing the same thing, I have certainly never encountered any problems (outside of my own code, at least!)</p>\n"
},
{
"answer_id": 116042,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 1,
"selected": false,
"text": "<p>Definitely. I have a SQL_RESERVED_WORDS table for that very purpose.</p>\n\n<p>Oracle can only handle 30 character table names BTW. And they're all upper case.</p>\n\n<p>It only takes an hour of so of unnecessary debugging before the table pays for itself.</p>\n"
},
{
"answer_id": 116056,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 2,
"selected": false,
"text": "<p>You shouldn't use reserved words as column names in a table, even if you can quote them away.</p>\n\n<p>Quoting them can make code really awkward as you have to escape the quote character all the time in your SQL statements within your code. It also makes the SQL command line a real PITA, in my opinion.</p>\n\n<p>In the end it just looks messy. Far better to spend the time to think up of a different word that doesn't clash with SQL keywords.</p>\n\n<p>Your rules look fine to me.</p>\n"
},
{
"answer_id": 116069,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 0,
"selected": false,
"text": "<p>Just avoid reserved words.</p>\n\n<p>Note that most databases (and database link-layers) have a way of programmatically listing all reserved words. You can use that as a sanity-check on application startup to ensure you haven't run astray.</p>\n\n<p>Quoting does work, so you could do that for safety. However this makes life really awkward for DBAs and people making custom reports against your app, so that should be used as a band-aid only.</p>\n"
},
{
"answer_id": 292411,
"author": "Yarik",
"author_id": 31415,
"author_profile": "https://Stackoverflow.com/users/31415",
"pm_score": 0,
"selected": false,
"text": "<p>Putting aside obvious confusions between names and reserved words, I think there are at least two very strong reasons to avoid using reserved words as names:</p>\n\n<ol>\n<li><p>You would not have to use quotes (or square braces in MS world) that substantially hurt readability.</p>\n\n<p><strong>NB:</strong> Readability may be especially damaged when you find yourself in need to generate SQL code from SQL (so-called \"dynamic SQL\" approach) or from other languages. You do not want extra double quotes inside single quotes, or extra repeated double quotes, or escaped quotes, or any other obscure stuff like that.</p>\n\n<p>For example, how would you like snippets like these:</p>\n\n<pre><code>-- SQL -----------------------\ndeclare @sql as varchar(4000)\nset @sql = 'select \"To\", \"From\" from MyTable'\n\n' VB -------------------------\nDim sql as String\nsql = \"select \"\"To\"\", \"\"From\"\" from MyTable\"\n\n// C++ -----------------------\nString sql = \"select \\\"To\\\", \\\"From\\\" from MyTable\"\n</code></pre></li>\n<li><p>Most of the reserved words are bad candidates for naming tables, columns, variables, etc. anyway. In the vast majority of cases nouns (sometimes adjectives) are much, much better for names than verbs, adverbs, and prepositions. :-)</p></li>\n</ol>\n"
},
{
"answer_id": 292446,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with Yarik's 2nd point about the suitability of reserved words. In the OPs example, he uses \"to\", \"from\" and \"rate\". The immediate question in my mind, and therefore possibly in that of a future developer is \"To and from what?\" Maybe consider renaming these columns to \"EffectiveFromDate\" and \"EffectiveUntilDate\", if that's what they represent.</p>\n\n<p></2c></p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20573/"
]
| I've sometimes had a problem with my field-, table-, view- oder stored procedure names.
Example:
```
SELECT from, to, rate FROM Table1
```
The Problem is that ***from*** is a reserved word in SQL-92.
You could put the fieldname in double quotes to fix this, but what if some other db tools wants to read your database?
It is your database design and it is your fault if other applications have problems with your db.
There are many other [reserved words](http://developer.mimer.com/validator/sql-reserved-words.tml "SQL reserved words") (~300) and we should avoid all of them.
If you change the DBMS from manufacturer A to B, your application can fail, because a some fieldnames are now reserved words.
A field called ***PERCENT*** may work for a oracle db, but on a MS SQL Server it must be treated as a reserved word.
I have a tool to check my database design against these reserved words ; you too?
Here are my rules
1. don't use names longer than 32 chars (some DBMS can't handle longer names)
2. use only a-z, A-Z, 0-9 and the underscore (:-;,/&!=?+- are not allowed)
3. don't start a name with a digit
4. avoid these reserved words | Easy way: just make sure *every* field name is quoted.
Edit: Any sensible DB tool worth its salt should be doing the same thing, I have certainly never encountered any problems (outside of my own code, at least!) |
116,038 | <p>How do I read a file into a <code>std::string</code>, i.e., read the whole file at once?</p>
<p>Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.</p>
<p>One way to do this would be to stat the filesize, resize the <code>std::string</code> and <code>fread()</code> into the <code>std::string</code>'s <code>const_cast<char*>()</code>'ed <code>data()</code>. This requires the <code>std::string</code>'s data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the <code>std::string</code>'s size may not equal the file's size.</p>
<p>A fully correct, standard-compliant and portable solutions could be constructed using <code>std::ifstream</code>'s <code>rdbuf()</code> into a <code>std::ostringstream</code> and from there into a <code>std::string</code>. However, this could copy the string data and/or needlessly reallocate memory. </p>
<ul>
<li>Are all relevant standard library implementations smart enough to avoid all unnecessary overhead? </li>
<li>Is there another way to do it? </li>
<li>Did I miss some hidden Boost function that already provides the desired functionality?</li>
</ul>
<p><br></p>
<pre><code>void slurp(std::string& data, bool is_binary)
</code></pre>
| [
{
"answer_id": 116083,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 5,
"selected": false,
"text": "<p>Use </p>\n\n<pre><code>#include <iostream>\n#include <sstream>\n#include <fstream>\n\nint main()\n{\n std::ifstream input(\"file.txt\");\n std::stringstream sstr;\n\n while(input >> sstr.rdbuf());\n\n std::cout << sstr.str() << std::endl;\n}\n</code></pre>\n\n<p>or something very close. I don't have a stdlib reference open to double-check myself.</p>\n\n<p>Yes, I understand I didn't write the <code>slurp</code> function as asked.</p>\n"
},
{
"answer_id": 116123,
"author": "Thorsten79",
"author_id": 19734,
"author_profile": "https://Stackoverflow.com/users/19734",
"pm_score": 0,
"selected": false,
"text": "<p>Never write into the std::string's const char * buffer. Never ever! Doing so is a massive mistake. </p>\n\n<p>Reserve() space for the whole string in your std::string, read chunks from your file of reasonable size into a buffer, and append() it. How large the chunks have to be depends on your input file size. I'm pretty sure all other portable and STL-compliant mechanisms will do the same (yet may look prettier).</p>\n"
},
{
"answer_id": 116177,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": false,
"text": "<p>The shortest variant: <strong><kbd><a href=\"http://coliru.stacked-crooked.com/a/ab16e6dd34c38b92\" rel=\"noreferrer\">Live On Coliru</a></kbd></strong></p>\n\n<pre><code>std::string str(std::istreambuf_iterator<char>{ifs}, {});\n</code></pre>\n\n<p>It requires the header <code><iterator></code>.</p>\n\n<p>There were some reports that this method is slower than preallocating the string and using <code>std::istream::read</code>. However, on a modern compiler with optimisations enabled this no longer seems to be the case, though the relative performance of various methods seems to be highly compiler dependent.</p>\n"
},
{
"answer_id": 116180,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 3,
"selected": false,
"text": "<p>Something like this shouldn't be too bad:</p>\n\n<pre><code>void slurp(std::string& data, const std::string& filename, bool is_binary)\n{\n std::ios_base::openmode openmode = ios::ate | ios::in;\n if (is_binary)\n openmode |= ios::binary;\n ifstream file(filename.c_str(), openmode);\n data.clear();\n data.reserve(file.tellg());\n file.seekg(0, ios::beg);\n data.append(istreambuf_iterator<char>(file.rdbuf()), \n istreambuf_iterator<char>());\n}\n</code></pre>\n\n<p>The advantage here is that we do the reserve first so we won't have to grow the string as we read things in. The disadvantage is that we do it char by char. A smarter version could grab the whole read buf and then call underflow.</p>\n"
},
{
"answer_id": 116192,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the 'std::getline' function, and specify 'eof' as the delimiter. The resulting code is a little bit obscure though:</p>\n\n<pre><code>std::string data;\nstd::ifstream in( \"test.txt\" );\nstd::getline( in, data, std::string::traits_type::to_char_type( \n std::string::traits_type::eof() ) );\n</code></pre>\n"
},
{
"answer_id": 116220,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "<p>One way is to flush the stream buffer into a separate memory stream, and then convert that to <code>std::string</code> (error handling omitted):</p>\n<pre><code>std::string slurp(std::ifstream& in) {\n std::ostringstream sstr;\n sstr << in.rdbuf();\n return sstr.str();\n}\n</code></pre>\n<p>This is nicely concise. However, as noted in the question this performs a redundant copy and unfortunately there is fundamentally no way of eliding this copy.</p>\n<p>The only real solution that avoids redundant copies is to do the reading manually in a loop, unfortunately. Since C++ now has guaranteed contiguous strings, one could write the following (≥C++17, error handling included):</p>\n<pre><code>auto read_file(std::string_view path) -> std::string {\n constexpr auto read_size = std::size_t(4096);\n auto stream = std::ifstream(path.data());\n stream.exceptions(std::ios_base::badbit);\n \n auto out = std::string();\n auto buf = std::string(read_size, '\\0');\n while (stream.read(& buf[0], read_size)) {\n out.append(buf, 0, stream.gcount());\n }\n out.append(buf, 0, stream.gcount());\n return out;\n}\n</code></pre>\n"
},
{
"answer_id": 525103,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 6,
"selected": false,
"text": "<p>See <a href=\"https://stackoverflow.com/questions/524591/performance-of-creating-a-c-stdstring-from-an-input-iterator/524843#524843\">this answer</a> on a similar question.</p>\n\n<p>For your convenience, I'm reposting CTT's solution:</p>\n\n<pre><code>string readFile2(const string &fileName)\n{\n ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);\n\n ifstream::pos_type fileSize = ifs.tellg();\n ifs.seekg(0, ios::beg);\n\n vector<char> bytes(fileSize);\n ifs.read(bytes.data(), fileSize);\n\n return string(bytes.data(), fileSize);\n}\n</code></pre>\n\n<p>This solution resulted in about 20% faster execution times than the other answers presented here, when taking the average of 100 runs against the text of Moby Dick (1.3M). Not bad for a portable C++ solution, I would like to see the results of mmap'ing the file ;) </p>\n"
},
{
"answer_id": 40903508,
"author": "Gabriel Majeri",
"author_id": 5723188,
"author_profile": "https://Stackoverflow.com/users/5723188",
"pm_score": 5,
"selected": false,
"text": "<p>If you have C++17 (std::filesystem), there is also this way (which gets the file's size through <code>std::filesystem::file_size</code> instead of <code>seekg</code> and <code>tellg</code>):</p>\n\n<pre><code>#include <filesystem>\n#include <fstream>\n#include <string>\n\nnamespace fs = std::filesystem;\n\nstd::string readFile(fs::path path)\n{\n // Open the stream to 'lock' the file.\n std::ifstream f(path, std::ios::in | std::ios::binary);\n\n // Obtain the size of the file.\n const auto sz = fs::file_size(path);\n\n // Create a buffer.\n std::string result(sz, '\\0');\n\n // Read the whole file into the buffer.\n f.read(result.data(), sz);\n\n return result;\n}\n</code></pre>\n\n<p><strong>Note</strong>: you may need to use <code><experimental/filesystem></code> and <code>std::experimental::filesystem</code> if your standard library doesn't yet fully support C++17. You might also need to replace <code>result.data()</code> with <code>&result[0]</code> if it doesn't support <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/data\" rel=\"noreferrer\">non-const std::basic_string data</a>.</p>\n"
},
{
"answer_id": 43009155,
"author": "Rick Ramstetter",
"author_id": 1519371,
"author_profile": "https://Stackoverflow.com/users/1519371",
"pm_score": 4,
"selected": false,
"text": "<p>I do not have enough reputation to comment directly on responses using <code>tellg()</code>.</p>\n\n<p>Please be aware that <code>tellg()</code> can return -1 on error. If you're passing the result of <code>tellg()</code> as an allocation parameter, you should sanity check the result first.</p>\n\n<p>An example of the problem:</p>\n\n<pre><code>...\nstd::streamsize size = file.tellg();\nstd::vector<char> buffer(size);\n...\n</code></pre>\n\n<p>In the above example, if <code>tellg()</code> encounters an error it will return -1. Implicit casting between signed (ie the result of <code>tellg()</code>) and unsigned (ie the arg to the <code>vector<char></code> constructor) will result in a your vector erroneously allocating a <strong>very</strong> large number of bytes. (Probably 4294967295 bytes, or 4GB.)</p>\n\n<p>Modifying paxos1977's answer to account for the above:</p>\n\n<pre><code>string readFile2(const string &fileName)\n{\n ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);\n\n ifstream::pos_type fileSize = ifs.tellg();\n if (fileSize < 0) <--- ADDED\n return std::string(); <--- ADDED\n\n ifs.seekg(0, ios::beg);\n\n vector<char> bytes(fileSize);\n ifs.read(&bytes[0], fileSize);\n\n return string(&bytes[0], fileSize);\n}\n</code></pre>\n"
},
{
"answer_id": 43027468,
"author": "tgnottingham",
"author_id": 1023121,
"author_profile": "https://Stackoverflow.com/users/1023121",
"pm_score": 3,
"selected": false,
"text": "<p>This solution adds error checking to the rdbuf()-based method.</p>\n\n<pre><code>std::string file_to_string(const std::string& file_name)\n{\n std::ifstream file_stream{file_name};\n\n if (file_stream.fail())\n {\n // Error opening file.\n }\n\n std::ostringstream str_stream{};\n file_stream >> str_stream.rdbuf(); // NOT str_stream << file_stream.rdbuf()\n\n if (file_stream.fail() && !file_stream.eof())\n {\n // Error reading file.\n }\n\n return str_stream.str();\n}\n</code></pre>\n\n<p>I'm adding this answer because adding error-checking to the original method is not as trivial as you'd expect. The original method uses stringstream's insertion operator (<code>str_stream << file_stream.rdbuf()</code>). The problem is that this sets the stringstream's failbit when no characters are inserted. That can be due to an error or it can be due to the file being empty. If you check for failures by inspecting the failbit, you'll encounter a false positive when you read an empty file. How do you disambiguate legitimate failure to insert any characters and \"failure\" to insert any characters because the file is empty?</p>\n\n<p>You might think to explicitly check for an empty file, but that's more code and associated error checking.</p>\n\n<p>Checking for the failure condition <code>str_stream.fail() && !str_stream.eof()</code> doesn't work, because the insertion operation doesn't set the eofbit (on the ostringstream nor the ifstream).</p>\n\n<p>So, the solution is to change the operation. Instead of using ostringstream's insertion operator (<<), use ifstream's extraction operator (>>), which does set the eofbit. Then check for the failiure condition <code>file_stream.fail() && !file_stream.eof()</code>.</p>\n\n<p>Importantly, when <code>file_stream >> str_stream.rdbuf()</code> encounters a legitimate failure, it shouldn't ever set eofbit (according to my understanding of the specification). That means the above check is sufficient to detect legitimate failures.</p>\n"
},
{
"answer_id": 57973715,
"author": "Paul Sumpner",
"author_id": 1429282,
"author_profile": "https://Stackoverflow.com/users/1429282",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include <string>\n#include <sstream>\n\nusing namespace std;\n\nstring GetStreamAsString(const istream& in)\n{\n stringstream out;\n out << in.rdbuf();\n return out.str();\n}\n\nstring GetFileAsString(static string& filePath)\n{\n ifstream stream;\n try\n {\n // Set to throw on failure\n stream.exceptions(fstream::failbit | fstream::badbit);\n stream.open(filePath);\n }\n catch (system_error& error)\n {\n cerr << \"Failed to open '\" << filePath << \"'\\n\" << error.code().message() << endl;\n return \"Open fail\";\n }\n\n return GetStreamAsString(stream);\n}\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>const string logAsString = GetFileAsString(logFilePath);\n</code></pre>\n"
},
{
"answer_id": 58737956,
"author": "David G",
"author_id": 1435420,
"author_profile": "https://Stackoverflow.com/users/1435420",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a version using the new filesystem library with reasonably robust error checking:</p>\n\n<pre><code>#include <cstdint>\n#include <exception>\n#include <filesystem>\n#include <fstream>\n#include <sstream>\n#include <string>\n\nnamespace fs = std::filesystem;\n\nstd::string loadFile(const char *const name);\nstd::string loadFile(const std::string &name);\n\nstd::string loadFile(const char *const name) {\n fs::path filepath(fs::absolute(fs::path(name)));\n\n std::uintmax_t fsize;\n\n if (fs::exists(filepath)) {\n fsize = fs::file_size(filepath);\n } else {\n throw(std::invalid_argument(\"File not found: \" + filepath.string()));\n }\n\n std::ifstream infile;\n infile.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n try {\n infile.open(filepath.c_str(), std::ios::in | std::ifstream::binary);\n } catch (...) {\n std::throw_with_nested(std::runtime_error(\"Can't open input file \" + filepath.string()));\n }\n\n std::string fileStr;\n\n try {\n fileStr.resize(fsize);\n } catch (...) {\n std::stringstream err;\n err << \"Can't resize to \" << fsize << \" bytes\";\n std::throw_with_nested(std::runtime_error(err.str()));\n }\n\n infile.read(fileStr.data(), fsize);\n infile.close();\n\n return fileStr;\n}\n\nstd::string loadFile(const std::string &name) { return loadFile(name.c_str()); };\n</code></pre>\n"
},
{
"answer_id": 61583878,
"author": "kiroma",
"author_id": 10286616,
"author_profile": "https://Stackoverflow.com/users/10286616",
"pm_score": 0,
"selected": false,
"text": "<p>An updated function which builds upon CTT's solution:</p>\n<pre><code>#include <string>\n#include <fstream>\n#include <limits>\n#include <string_view>\nstd::string readfile(const std::string_view path, bool binaryMode = true)\n{\n std::ios::openmode openmode = std::ios::in;\n if(binaryMode)\n {\n openmode |= std::ios::binary;\n }\n std::ifstream ifs(path.data(), openmode);\n ifs.ignore(std::numeric_limits<std::streamsize>::max());\n std::string data(ifs.gcount(), 0);\n ifs.seekg(0);\n ifs.read(data.data(), data.size());\n return data;\n}\n</code></pre>\n<p>There are two important differences:</p>\n<p><code>tellg()</code> is not guaranteed to return the offset in bytes since the beginning of the file. Instead, as Puzomor Croatia pointed out, it's more of a token which can be used within the fstream calls. <code>gcount()</code> however <em>does</em> return the amount of unformatted bytes last extracted. We therefore open the file, extract and discard all of its contents with <code>ignore()</code> to get the size of the file, and construct the output string based on that.</p>\n<p>Secondly, we avoid having to copy the data of the file from a <code>std::vector<char></code> to a <code>std::string</code> by writing to the string directly.</p>\n<p>In terms of performance, this should be the absolute fastest, allocating the appropriate sized string ahead of time and calling <code>read()</code> once. As an interesting fact, using <code>ignore()</code> and <code>countg()</code> instead of <code>ate</code> and <code>tellg()</code> on gcc compiles down to <a href=\"https://godbolt.org/z/8XvEvS\" rel=\"nofollow noreferrer\">almost the same thing</a>, bit by bit.</p>\n"
},
{
"answer_id": 62356271,
"author": "Mashaim Tahir",
"author_id": 13250230,
"author_profile": "https://Stackoverflow.com/users/13250230",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include <iostream>\n#include <fstream>\n#include <string.h>\nusing namespace std;\nmain(){\n fstream file;\n //Open a file\n file.open("test.txt");\n string copy,temp;\n //While loop to store whole document in copy string\n //Temp reads a complete line\n //Loop stops until temp reads the last line of document\n while(getline(file,temp)){\n //add new line text in copy\n copy+=temp;\n //adds a new line\n copy+="\\n";\n }\n //Display whole document\n cout<<copy;\n //close the document\n file.close();\n}\n</code></pre>\n"
},
{
"answer_id": 63847994,
"author": "b.g.",
"author_id": 6789049,
"author_profile": "https://Stackoverflow.com/users/6789049",
"pm_score": 3,
"selected": false,
"text": "<p>Since this seems like a widely used utility, my approach would be to search for and to prefer already available libraries to hand made solutions, especially if boost libraries are already linked(linker flags -lboost_system -lboost_filesystem) in your project. <a href=\"https://www.boost.org/doc/libs/1_74_0/boost/filesystem/string_file.hpp\" rel=\"noreferrer\">Here (and older boost versions too)</a>, boost provides a load_string_file utility:</p>\n<pre><code>#include <iostream>\n#include <string>\n#include <boost/filesystem/string_file.hpp>\n\nint main() {\n std::string result;\n boost::filesystem::load_string_file("aFileName.xyz", result);\n std::cout << result.size() << std::endl;\n}\n</code></pre>\n<p>As an advantage, this function doesn't seek an entire file to determine the size, instead uses stat() internally. As a possibly negligible disadvantage though, one could easily infer upon inspection of the source code: string is unnecessarily resized with <code>'\\0'</code> character which are rewritten by the file contents.</p>\n"
},
{
"answer_id": 69272011,
"author": "hanshenrik",
"author_id": 1067003,
"author_profile": "https://Stackoverflow.com/users/1067003",
"pm_score": 0,
"selected": false,
"text": "<p>this is the function i use, and when dealing with large files (1GB+) for some reason std::ifstream::read() is <em>much</em> faster than std::ifstream::rdbuf() when you know the filesize, so the whole "check filesize first" thing is actually a speed optimization</p>\n<pre><code>#include <string>\n#include <fstream>\n#include <sstream>\nstd::string file_get_contents(const std::string &$filename)\n{\n std::ifstream file($filename, std::ifstream::binary);\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n file.seekg(0, std::istream::end);\n const std::streampos ssize = file.tellg();\n if (ssize < 0)\n {\n // can't get size for some reason, fallback to slower "just read everything"\n // because i dont trust that we could seek back/fourth in the original stream,\n // im creating a new stream.\n std::ifstream file($filename, std::ifstream::binary);\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n std::ostringstream ss;\n ss << file.rdbuf();\n return ss.str();\n }\n file.seekg(0, std::istream::beg);\n std::string result(size_t(ssize), 0);\n file.read(&result[0], std::streamsize(ssize));\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 69513374,
"author": "Roflcopter4",
"author_id": 5511137,
"author_profile": "https://Stackoverflow.com/users/5511137",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is a positively ancient question with a plethora of answers, but not one of them mentions what I would have considered the most obvious way to do this. Yes, I know this is C++, and using libc is evil and wrong or whatever, but nuts to that. Using libc is fine, especially for such a simple thing as this.</p>\n<p>Essentially: just open the file, get it's size (not necessarily in that order), and read it.</p>\n<pre><code>#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <sys/stat.h>\n\nstatic constexpr char const filename[] = "foo.bar";\n\nint main(void)\n{\n FILE *fp = ::fopen(filename, "rb");\n if (!fp) {\n ::perror("fopen");\n ::exit(1);\n }\n\n struct stat st;\n if (::fstat(fileno(fp), &st) == (-1)) {\n ::perror("fstat");\n ::exit(1);\n }\n\n // You could simply allocate a buffer here and use std::string_view, or\n // even allocate a buffer and copy it to a std::string. Creating a\n // std::string and setting its size is simplest, but will pointlessly\n // initialize the buffer to 0. You can't win sometimes.\n std::string str;\n str.reserve(st.st_size + 1U);\n str.resize(st.st_size);\n ::fread(str.data(), 1, st.st_size, fp);\n str[st.st_size] = '\\0';\n ::fclose(fp);\n}\n</code></pre>\n<p>This doesn't really seem worse than some of the other solutions, in addition to being (in practice) completely portable. One could also throw an exception instead of exiting immediately, of course. It seriously irritates me that resizing the <code>std::string</code> always 0 initializes it, but it can't be helped.</p>\n<p><strong>PLEASE NOTE</strong> that this is only going to work as written for C++17 and later. Earlier versions (ought to) disallow editing <code>std::string::data()</code>. If working with an earlier version consider using <code>std::string_view</code> or simply copying a raw buffer.</p>\n"
},
{
"answer_id": 69789640,
"author": "Xavier",
"author_id": 256062,
"author_profile": "https://Stackoverflow.com/users/256062",
"pm_score": 0,
"selected": false,
"text": "<p>For performance I haven't found anything faster than the code below.</p>\n<pre><code>std::string readAllText(std::string const &path)\n{\n assert(path.c_str() != NULL);\n FILE *stream = fopen(path.c_str(), "r");\n assert(stream != NULL);\n fseek(stream, 0, SEEK_END);\n long stream_size = ftell(stream);\n fseek(stream, 0, SEEK_SET);\n void *buffer = malloc(stream_size);\n fread(buffer, stream_size, 1, stream);\n assert(ferror(stream) == 0);\n fclose(stream);\n std::string text((const char *)buffer, stream_size);\n assert(buffer != NULL);\n free((void *)buffer);\n return text;\n}\n</code></pre>\n"
},
{
"answer_id": 69854038,
"author": "Sergey Abbakumov",
"author_id": 2899779,
"author_profile": "https://Stackoverflow.com/users/2899779",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <a href=\"https://github.com/sabbakumov/rst/blob/master/rst/files/file_utils.h#L79\" rel=\"nofollow noreferrer\">rst</a> C++ library that I developed to do that:</p>\n<pre><code>#include "rst/files/file_utils.h"\n\nstd::filesystem::path path = ...; // Path to a file.\nrst::StatusOr<std::string> content = rst::ReadFile(path);\nif (content.err()) {\n // Handle error.\n}\n\nstd::cout << *content << ", " << content->size() << std::endl;\n</code></pre>\n"
},
{
"answer_id": 70499992,
"author": "Barrett",
"author_id": 17775972,
"author_profile": "https://Stackoverflow.com/users/17775972",
"pm_score": -1,
"selected": false,
"text": "<p>I know that I am late to the party, but now (2021) on my machine, this is the fastest implementation that I have tested:</p>\n<pre><code>#include <fstream>\n#include <string>\n\nbool fileRead( std::string &contents, const std::string &path ) {\n contents.clear();\n if( path.empty()) {\n return false;\n }\n std::ifstream stream( path );\n if( !stream ) {\n return false;\n }\n stream >> contents;\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 71066444,
"author": "Ritesh Saha",
"author_id": 14984346,
"author_profile": "https://Stackoverflow.com/users/14984346",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include <string>\n#include <fstream>\n\nint main()\n{\n std::string fileLocation = "C:\\\\Users\\\\User\\\\Desktop\\\\file.txt";\n std::ifstream file(fileLocation, std::ios::in | std::ios::binary);\n\n std::string data;\n\n if(file.is_open())\n {\n std::getline(file, data, '\\0');\n\n file.close();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 71813338,
"author": "Andrew",
"author_id": 1599699,
"author_profile": "https://Stackoverflow.com/users/1599699",
"pm_score": 1,
"selected": false,
"text": "<p>Pulling info from several places... This should be the fastest and best way:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <filesystem>\n#include <fstream>\n#include <string>\n\n//Returns true if successful.\nbool readInFile(std::string pathString)\n{\n //Make sure the file exists and is an actual file.\n if (!std::filesystem::is_regular_file(pathString))\n {\n return false;\n }\n //Convert relative path to absolute path.\n pathString = std::filesystem::weakly_canonical(pathString);\n //Open the file for reading (binary is fastest).\n std::wifstream in(pathString, std::ios::binary);\n //Make sure the file opened.\n if (!in)\n {\n return false;\n }\n //Wide string to store the file's contents.\n std::wstring fileContents;\n //Jump to the end of the file to determine the file size.\n in.seekg(0, std::ios::end);\n //Resize the wide string to be able to fit the entire file (Note: Do not use reserve()!).\n fileContents.resize(in.tellg());\n //Go back to the beginning of the file to start reading.\n in.seekg(0, std::ios::beg);\n //Read the entire file's contents into the wide string.\n in.read(fileContents.data(), fileContents.size());\n //Close the file.\n in.close();\n //Do whatever you want with the file contents.\n std::wcout << fileContents << L" " << fileContents.size();\n return true;\n}\n</code></pre>\n<p>This reads in wide characters into a <code>std::wstring</code>, but you can easily adapt if you just want regular characters and a <code>std::string</code>.</p>\n"
},
{
"answer_id": 72046987,
"author": "user1095108",
"author_id": 1095108,
"author_profile": "https://Stackoverflow.com/users/1095108",
"pm_score": -1,
"selected": false,
"text": "<pre><code>std::string get(std::string_view const& fn)\n{\n struct filebuf: std::filebuf\n {\n using std::filebuf::egptr;\n using std::filebuf::gptr;\n\n using std::filebuf::gbump;\n using std::filebuf::underflow;\n };\n\n std::string r;\n\n if (filebuf fb; fb.open(fn.data(), std::ios::binary | std::ios::in))\n {\n r.reserve(fb.pubseekoff({}, std::ios::end));\n fb.pubseekpos({});\n\n while (filebuf::traits_type::eof() != fb.underflow())\n {\n auto const gptr(fb.gptr());\n auto const sz(fb.egptr() - gptr);\n\n fb.gbump(sz);\n r.append(gptr, sz);\n }\n }\n\n return r;\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How do I read a file into a `std::string`, i.e., read the whole file at once?
Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.
One way to do this would be to stat the filesize, resize the `std::string` and `fread()` into the `std::string`'s `const_cast<char*>()`'ed `data()`. This requires the `std::string`'s data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the `std::string`'s size may not equal the file's size.
A fully correct, standard-compliant and portable solutions could be constructed using `std::ifstream`'s `rdbuf()` into a `std::ostringstream` and from there into a `std::string`. However, this could copy the string data and/or needlessly reallocate memory.
* Are all relevant standard library implementations smart enough to avoid all unnecessary overhead?
* Is there another way to do it?
* Did I miss some hidden Boost function that already provides the desired functionality?
```
void slurp(std::string& data, bool is_binary)
``` | One way is to flush the stream buffer into a separate memory stream, and then convert that to `std::string` (error handling omitted):
```
std::string slurp(std::ifstream& in) {
std::ostringstream sstr;
sstr << in.rdbuf();
return sstr.str();
}
```
This is nicely concise. However, as noted in the question this performs a redundant copy and unfortunately there is fundamentally no way of eliding this copy.
The only real solution that avoids redundant copies is to do the reading manually in a loop, unfortunately. Since C++ now has guaranteed contiguous strings, one could write the following (≥C++17, error handling included):
```
auto read_file(std::string_view path) -> std::string {
constexpr auto read_size = std::size_t(4096);
auto stream = std::ifstream(path.data());
stream.exceptions(std::ios_base::badbit);
auto out = std::string();
auto buf = std::string(read_size, '\0');
while (stream.read(& buf[0], read_size)) {
out.append(buf, 0, stream.gcount());
}
out.append(buf, 0, stream.gcount());
return out;
}
``` |
116,050 | <p>How do I programatically (Using C#) find out what the path is of my My Pictures folder? </p>
<p>Does this work on XP and Vista?</p>
| [
{
"answer_id": 116057,
"author": "neuroguy123",
"author_id": 12529,
"author_profile": "https://Stackoverflow.com/users/12529",
"pm_score": 3,
"selected": false,
"text": "<p>Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);</p>\n"
},
{
"answer_id": 116061,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 7,
"selected": true,
"text": "<p>The following will return a full-path to the location of the users picture folder (Username\\My Documents\\My Pictures on XP, Username\\Pictures on Vista)</p>\n\n<pre><code>Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);\n</code></pre>\n"
},
{
"answer_id": 116080,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 0,
"selected": false,
"text": "<p>Using Microsoft.VisualBasic.FileIO.SpecialDirectories.MyPictures you can get that, works in vista and XP.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5147/"
]
| How do I programatically (Using C#) find out what the path is of my My Pictures folder?
Does this work on XP and Vista? | The following will return a full-path to the location of the users picture folder (Username\My Documents\My Pictures on XP, Username\Pictures on Vista)
```
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
``` |
116,053 | <p>I'd like to show/hide a column at runtime based on a particular condition. I'm using "Print when expression" to conditionally show/hide this column (and it's header) in my report. When the column is hidden, the space it would have occupied is left blank, which is not particularly attractive.</p>
<p>I would prefer if the extra space was used in a more effective manner, possibilities include:</p>
<ul>
<li>the width of the report is reduced by the width of the hidden column</li>
<li>the extra space is distributed among the remaining columns</li>
</ul>
<p>In theory, I could achieve the first by setting the width of the column (and header) to 0, but also indicate that the column should resize to fit its contents. But JasperReports does not provide a "resize width to fit contents" option.</p>
<p>Another possibility is to generate reports using the Jasper API instead of defining the report template in XML. But that seems like a lot of effort for such a simple requirement.</p>
| [
{
"answer_id": 117847,
"author": "Jacob Schoen",
"author_id": 3340,
"author_profile": "https://Stackoverflow.com/users/3340",
"pm_score": 0,
"selected": false,
"text": "<p>If it is just one column, is it possible to place this column to the far right, and then use the print when expression. That way there is not a hole in the middle. I know this is not ideal, as I had tried to do what you are currently trying to accomplish in the past, and could not find what I call a good solution.</p>\n\n<p>A second idea would to be create a second report based on the first with out the column, and then when calling the report check the condition, to decide which one to call. Again not ideal, but would work.</p>\n\n<p>I know this is not really the answer you were looking for, but one of these suggestions may work for you.</p>\n"
},
{
"answer_id": 158525,
"author": "Doug",
"author_id": 10031,
"author_profile": "https://Stackoverflow.com/users/10031",
"pm_score": 1,
"selected": false,
"text": "<p>A slight variation on the \"second report\" theme that I have used is to isolate the part of the report where you have an optional column into it's own subreport, and then create two subreports, one with and one without the column, and then use conditions to determine which subreport to print.</p>\n"
},
{
"answer_id": 2186642,
"author": "Maksim",
"author_id": 51230,
"author_profile": "https://Stackoverflow.com/users/51230",
"pm_score": 0,
"selected": false,
"text": "<p>Check <a href=\"http://www.ibm.com/developerworks/websphere/library/techarticles/0505_olivieri/0505_olivieri.html\" rel=\"nofollow noreferrer\">THIS</a> In that tutorial they are using XML template with Velocity framework. This is pretty complex. And to make it simpler you can us <a href=\"http://dynamicjasper.sourceforge.net/\" rel=\"nofollow noreferrer\">DynamicJasper</a>. This library is an open source Java API that works over JasperReports that solves the dynamic columns issue.</p>\n"
},
{
"answer_id": 3579650,
"author": "Rudi",
"author_id": 432369,
"author_profile": "https://Stackoverflow.com/users/432369",
"pm_score": 2,
"selected": false,
"text": "<p>Remove line when blank: This option takes away the vertical space occupied by an object, if it is\nnot visible; the element visibility is determined by the value of the expression contained in the\nPrint when expression attribute. Think of the page as a grid where the elements are placed,\nwith a line being the space the element occupies. Figure 4-17 highlights the element A line; in\norder to really remove this line, all the elements that share a portion of the line have to be null\n(that is, they will not be printed).</p>\n"
},
{
"answer_id": 3888398,
"author": "Ricardo",
"author_id": 469949,
"author_profile": "https://Stackoverflow.com/users/469949",
"pm_score": 1,
"selected": false,
"text": "<p>I recommend to use <a href=\"http://dynamicreports.sourceforge.net\" rel=\"nofollow\">DynamicReports</a>, it's open source and based on JasperReports.\nThe main benefit of this library is a dynamic report design and no need for a visual report designer. </p>\n"
},
{
"answer_id": 10986150,
"author": "W. Goeman",
"author_id": 508760,
"author_profile": "https://Stackoverflow.com/users/508760",
"pm_score": 0,
"selected": false,
"text": "<p>I guess this answer comes way too late, but I add it for the record. In my case I could solve it without any additional dependencies or tools. In the JRXML file, I just added the textfields width a dynamic width multiple times. Once per possible width that is. Then on each textfield, I have set that it should only be printed in case of a certain condition.</p>\n\n<p>This might not be as elegant as setting the width dynamically, but it does the trick without any hassle with extra libraries.</p>\n"
},
{
"answer_id": 12472367,
"author": "Cid",
"author_id": 966078,
"author_profile": "https://Stackoverflow.com/users/966078",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/design/JasperDesign.html\" rel=\"nofollow\">JasperDesign</a> is used to modify the template object (JasperReport) from within the code at runtime. I guess this might fit in your case.</p>\n"
},
{
"answer_id": 36911788,
"author": "Petter Friberg",
"author_id": 5292302,
"author_profile": "https://Stackoverflow.com/users/5292302",
"pm_score": 4,
"selected": false,
"text": "<p>In later version (v5 or above) of jasper reports you can use the <code>jr:table</code> component and <strong>truly</strong> achieve this (without the use of java code as using dynamic-jasper or dynamic-reports).</p>\n\n<p>The method is using a <code><printWhenExpression/></code> under the <code><jr:column/></code></p>\n\n<h1>Example</h1>\n\n<p><strong>Sample Data</strong></p>\n\n<pre><code>+----------------+--------+\n| User | Rep |\n+----------------+--------+\n| Jon Skeet | 854503 |\n| Darin Dimitrov | 652133 |\n| BalusC | 639753 |\n| Hans Passant | 616871 |\n| Me | 6487 |\n+----------------+--------+\n</code></pre>\n\n<p><strong>Sample jrxml</strong></p>\n\n<p><strong>Note</strong>: the parameter <code>$P{displayRecordNumber}</code> and the <code><printWhenExpression></code> under first <code>jr:column</code></p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<jasperReport xmlns=\"http://jasperreports.sourceforge.net/jasperreports\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\" name=\"reputation\" pageWidth=\"595\" pageHeight=\"842\" columnWidth=\"555\" leftMargin=\"20\" rightMargin=\"20\" topMargin=\"20\" bottomMargin=\"20\" uuid=\"a88bd694-4f90-41fc-84d0-002b90b2d73e\">\n <style name=\"table\">\n <box>\n <pen lineWidth=\"1.0\" lineColor=\"#000000\"/>\n </box>\n </style>\n <style name=\"table_TH\" mode=\"Opaque\" backcolor=\"#F0F8FF\">\n <box>\n <pen lineWidth=\"0.5\" lineColor=\"#000000\"/>\n </box>\n </style>\n <style name=\"table_CH\" mode=\"Opaque\" backcolor=\"#BFE1FF\">\n <box>\n <pen lineWidth=\"0.5\" lineColor=\"#000000\"/>\n </box>\n </style>\n <style name=\"table_TD\" mode=\"Opaque\" backcolor=\"#FFFFFF\">\n <box>\n <pen lineWidth=\"0.5\" lineColor=\"#000000\"/>\n </box>\n </style>\n <subDataset name=\"tableDataset\" uuid=\"7a53770f-0350-4a73-bfc1-48a5f6386594\">\n <field name=\"User\" class=\"java.lang.String\"/>\n <field name=\"Rep\" class=\"java.math.BigDecimal\"/>\n </subDataset>\n <parameter name=\"displayRecordNumber\" class=\"java.lang.Boolean\">\n <defaultValueExpression><![CDATA[true]]></defaultValueExpression>\n </parameter>\n <queryString>\n <![CDATA[]]>\n </queryString>\n <title>\n <band height=\"50\">\n <componentElement>\n <reportElement key=\"table\" style=\"table\" x=\"0\" y=\"0\" width=\"555\" height=\"47\" uuid=\"76ab08c6-e757-4785-a43d-b65ad4ab1dd5\"/>\n <jr:table xmlns:jr=\"http://jasperreports.sourceforge.net/jasperreports/components\" xsi:schemaLocation=\"http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd\">\n <datasetRun subDataset=\"tableDataset\" uuid=\"07e5f1c2-af7f-4373-b653-c127c47c9fa4\">\n <dataSourceExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></dataSourceExpression>\n </datasetRun>\n <jr:column width=\"90\" uuid=\"918270fe-25c8-4a9b-a872-91299cddbc31\">\n <printWhenExpression><![CDATA[$P{displayRecordNumber}]]></printWhenExpression>\n <jr:columnHeader style=\"table_CH\" height=\"30\" rowSpan=\"1\">\n <staticText>\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"5cd6da41-01d5-4f74-99c2-06784f891d1e\"/>\n <textElement textAlignment=\"Center\" verticalAlignment=\"Middle\"/>\n <text><![CDATA[Record number]]></text>\n </staticText>\n </jr:columnHeader>\n <jr:detailCell style=\"table_TD\" height=\"30\" rowSpan=\"1\">\n <textField>\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"5fe48359-0e7e-44b2-93ac-f55404189832\"/>\n <textElement textAlignment=\"Center\" verticalAlignment=\"Middle\"/>\n <textFieldExpression><![CDATA[$V{REPORT_COUNT}]]></textFieldExpression>\n </textField>\n </jr:detailCell>\n </jr:column>\n <jr:column width=\"90\" uuid=\"7979d8a2-4e3c-42a7-9ff9-86f8e0b164bc\">\n <jr:columnHeader style=\"table_CH\" height=\"30\" rowSpan=\"1\">\n <staticText>\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"61d5f1b6-7677-4511-a10c-1fb8a56a4b2a\"/>\n <textElement textAlignment=\"Center\" verticalAlignment=\"Middle\"/>\n <text><![CDATA[Username]]></text>\n </staticText>\n </jr:columnHeader>\n <jr:detailCell style=\"table_TD\" height=\"30\" rowSpan=\"1\">\n <textField>\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"a3cdb99d-3bf6-4c66-b50c-259b9aabfaef\"/>\n <box leftPadding=\"3\" rightPadding=\"3\"/>\n <textElement verticalAlignment=\"Middle\"/>\n <textFieldExpression><![CDATA[$F{User}]]></textFieldExpression>\n </textField>\n </jr:detailCell>\n </jr:column>\n <jr:column width=\"90\" uuid=\"625e4e5e-5057-4eab-b4a9-c5b22844d25c\">\n <jr:columnHeader style=\"table_CH\" height=\"30\" rowSpan=\"1\">\n <staticText>\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"e1c07cb8-a44c-4a8d-8566-5c86d6671282\"/>\n <textElement textAlignment=\"Center\" verticalAlignment=\"Middle\"/>\n <text><![CDATA[Reputation]]></text>\n </staticText>\n </jr:columnHeader>\n <jr:detailCell style=\"table_TD\" height=\"30\" rowSpan=\"1\">\n <textField pattern=\"#,##0\">\n <reportElement x=\"0\" y=\"0\" width=\"90\" height=\"30\" uuid=\"6be2d79f-be82-4c7b-afd9-0039fb8b3189\"/>\n <box leftPadding=\"3\" rightPadding=\"3\"/>\n <textElement textAlignment=\"Right\" verticalAlignment=\"Middle\"/>\n <textFieldExpression><![CDATA[$F{Rep}]]></textFieldExpression>\n </textField>\n </jr:detailCell>\n </jr:column>\n </jr:table>\n </componentElement>\n </band>\n </title>\n</jasperReport>\n</code></pre>\n\n<p><strong>Output with $P{displayRecordNumber}=true</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/B4Lwv.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/B4Lwv.png\" alt=\"true\"></a></p>\n\n<p><strong>Output with $P{displayRecordNumber}=false</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/UsUo9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/UsUo9.png\" alt=\"false\"></a></p>\n\n<p><em>As you can see the columns adapts nicely on the basis of which are displayed.</em></p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
]
| I'd like to show/hide a column at runtime based on a particular condition. I'm using "Print when expression" to conditionally show/hide this column (and it's header) in my report. When the column is hidden, the space it would have occupied is left blank, which is not particularly attractive.
I would prefer if the extra space was used in a more effective manner, possibilities include:
* the width of the report is reduced by the width of the hidden column
* the extra space is distributed among the remaining columns
In theory, I could achieve the first by setting the width of the column (and header) to 0, but also indicate that the column should resize to fit its contents. But JasperReports does not provide a "resize width to fit contents" option.
Another possibility is to generate reports using the Jasper API instead of defining the report template in XML. But that seems like a lot of effort for such a simple requirement. | In later version (v5 or above) of jasper reports you can use the `jr:table` component and **truly** achieve this (without the use of java code as using dynamic-jasper or dynamic-reports).
The method is using a `<printWhenExpression/>` under the `<jr:column/>`
Example
=======
**Sample Data**
```
+----------------+--------+
| User | Rep |
+----------------+--------+
| Jon Skeet | 854503 |
| Darin Dimitrov | 652133 |
| BalusC | 639753 |
| Hans Passant | 616871 |
| Me | 6487 |
+----------------+--------+
```
**Sample jrxml**
**Note**: the parameter `$P{displayRecordNumber}` and the `<printWhenExpression>` under first `jr:column`
```
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="reputation" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a88bd694-4f90-41fc-84d0-002b90b2d73e">
<style name="table">
<box>
<pen lineWidth="1.0" lineColor="#000000"/>
</box>
</style>
<style name="table_TH" mode="Opaque" backcolor="#F0F8FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="table_CH" mode="Opaque" backcolor="#BFE1FF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<style name="table_TD" mode="Opaque" backcolor="#FFFFFF">
<box>
<pen lineWidth="0.5" lineColor="#000000"/>
</box>
</style>
<subDataset name="tableDataset" uuid="7a53770f-0350-4a73-bfc1-48a5f6386594">
<field name="User" class="java.lang.String"/>
<field name="Rep" class="java.math.BigDecimal"/>
</subDataset>
<parameter name="displayRecordNumber" class="java.lang.Boolean">
<defaultValueExpression><![CDATA[true]]></defaultValueExpression>
</parameter>
<queryString>
<![CDATA[]]>
</queryString>
<title>
<band height="50">
<componentElement>
<reportElement key="table" style="table" x="0" y="0" width="555" height="47" uuid="76ab08c6-e757-4785-a43d-b65ad4ab1dd5"/>
<jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
<datasetRun subDataset="tableDataset" uuid="07e5f1c2-af7f-4373-b653-c127c47c9fa4">
<dataSourceExpression><![CDATA[$P{REPORT_DATA_SOURCE}]]></dataSourceExpression>
</datasetRun>
<jr:column width="90" uuid="918270fe-25c8-4a9b-a872-91299cddbc31">
<printWhenExpression><![CDATA[$P{displayRecordNumber}]]></printWhenExpression>
<jr:columnHeader style="table_CH" height="30" rowSpan="1">
<staticText>
<reportElement x="0" y="0" width="90" height="30" uuid="5cd6da41-01d5-4f74-99c2-06784f891d1e"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Record number]]></text>
</staticText>
</jr:columnHeader>
<jr:detailCell style="table_TD" height="30" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="90" height="30" uuid="5fe48359-0e7e-44b2-93ac-f55404189832"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$V{REPORT_COUNT}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="90" uuid="7979d8a2-4e3c-42a7-9ff9-86f8e0b164bc">
<jr:columnHeader style="table_CH" height="30" rowSpan="1">
<staticText>
<reportElement x="0" y="0" width="90" height="30" uuid="61d5f1b6-7677-4511-a10c-1fb8a56a4b2a"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Username]]></text>
</staticText>
</jr:columnHeader>
<jr:detailCell style="table_TD" height="30" rowSpan="1">
<textField>
<reportElement x="0" y="0" width="90" height="30" uuid="a3cdb99d-3bf6-4c66-b50c-259b9aabfaef"/>
<box leftPadding="3" rightPadding="3"/>
<textElement verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{User}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
<jr:column width="90" uuid="625e4e5e-5057-4eab-b4a9-c5b22844d25c">
<jr:columnHeader style="table_CH" height="30" rowSpan="1">
<staticText>
<reportElement x="0" y="0" width="90" height="30" uuid="e1c07cb8-a44c-4a8d-8566-5c86d6671282"/>
<textElement textAlignment="Center" verticalAlignment="Middle"/>
<text><![CDATA[Reputation]]></text>
</staticText>
</jr:columnHeader>
<jr:detailCell style="table_TD" height="30" rowSpan="1">
<textField pattern="#,##0">
<reportElement x="0" y="0" width="90" height="30" uuid="6be2d79f-be82-4c7b-afd9-0039fb8b3189"/>
<box leftPadding="3" rightPadding="3"/>
<textElement textAlignment="Right" verticalAlignment="Middle"/>
<textFieldExpression><![CDATA[$F{Rep}]]></textFieldExpression>
</textField>
</jr:detailCell>
</jr:column>
</jr:table>
</componentElement>
</band>
</title>
</jasperReport>
```
**Output with $P{displayRecordNumber}=true**
[](https://i.stack.imgur.com/B4Lwv.png)
**Output with $P{displayRecordNumber}=false**
[](https://i.stack.imgur.com/UsUo9.png)
*As you can see the columns adapts nicely on the basis of which are displayed.* |
116,074 | <p>I just started using SVN, and I have a cache directory that I don't need under source control. How can I ignore the whole directory/folder with SVN?</p>
<p>I am using <a href="https://en.wikipedia.org/wiki/Comparison_of_Subversion_clients#Standalone_Subversion_clients_comparison_table" rel="noreferrer">Versions</a> and <a href="http://en.wikipedia.org/wiki/TextMate" rel="noreferrer">TextMate</a> on OS X and commandline.</p>
| [
{
"answer_id": 116075,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 11,
"selected": true,
"text": "<p>Set the <code>svn:ignore</code> property of the parent directory:</p>\n\n<pre><code>svn propset svn:ignore dirname .\n</code></pre>\n\n<p>If you have multiple things to ignore, separate by newlines in the property value. In that case it's easier to edit the property value using an external editor:</p>\n\n<pre><code>svn propedit svn:ignore .\n</code></pre>\n"
},
{
"answer_id": 116077,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 2,
"selected": false,
"text": "<p>Set the svn:ignore <a href=\"http://svnbook.red-bean.com/en/1.1/ch07s02.html\" rel=\"nofollow noreferrer\">property</a>. Most UI svn tools have a way to do this as well as the command line discussion in the link.</p>\n"
},
{
"answer_id": 116097,
"author": "Greg",
"author_id": 1916,
"author_profile": "https://Stackoverflow.com/users/1916",
"pm_score": 6,
"selected": false,
"text": "<p>To expand slightly, if you're doing this with the svn command-line tool, you want to type:</p>\n\n<pre><code>svn propedit svn:ignore path/to/dir\n</code></pre>\n\n<p>which will open your text-editor of choice, then type '*' to ignore everything inside it, and save+quit - this will include the directory itself in svn, but ignore all the files inside it, to ignore the directory, use the path of the parent, and then type the name of the directory in the file. After saving, run an update ('svn up'), and then check in the appropriate path.</p>\n"
},
{
"answer_id": 116099,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using a frontend for SVN like TortoiseSVN, or some sort of IDE integration, there should also be an ignore option in the same menu are as the commit/add operation.</p>\n"
},
{
"answer_id": 116101,
"author": "Michael Lang",
"author_id": 19452,
"author_profile": "https://Stackoverflow.com/users/19452",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using the particular SVN client <a href=\"http://en.wikipedia.org/wiki/TortoiseSVN\" rel=\"noreferrer\">TortoiseSVN</a>, then on commit, you have the option of right clicking items and selecting \"Add to ignore list\".</p>\n"
},
{
"answer_id": 116102,
"author": "The Digital Gabeg",
"author_id": 12782,
"author_profile": "https://Stackoverflow.com/users/12782",
"pm_score": 2,
"selected": false,
"text": "<p>If your project directory is named /Project, and your cache directory is named /Project/Cache, then you need to set a subversion property on /Project. The property name should be \"svn:ignore\" and the property value should be \"Cache\".</p>\n\n<p>Refer to <a href=\"http://svnbook.red-bean.com/en/1.1/ch07s02.html\" rel=\"nofollow noreferrer\">this</a> page in the Subversion manual for more on properties.</p>\n"
},
{
"answer_id": 116106,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 2,
"selected": false,
"text": "<p>Jason's answer will do the trick. However, instead of setting svn:ignore to \".\" on the cache directory, you may want to include \"cache\" in the <em>parent</em> directory's svn:ignore property, in case the cache directory is not always present. I do this on a number of \"throwaway\" folders.</p>\n"
},
{
"answer_id": 116108,
"author": "Frank Szczerba",
"author_id": 8964,
"author_profile": "https://Stackoverflow.com/users/8964",
"pm_score": 5,
"selected": false,
"text": "<p>Set the <code>svn:ignore</code> property on the parent directory:</p>\n\n<pre><code>$ cd parentdir\n$ svn ps svn:ignore . 'cachedir'\n</code></pre>\n\n<p>This will overwrite any current value of <code>svn:ignore</code>. You an edit the value with:</p>\n\n<pre><code>$ svn pe svn:ignore .\n</code></pre>\n\n<p>Which will open your editor. You can add multiple patterns, one per line.</p>\n\n<p>You can view the current value with:</p>\n\n<pre><code>$ svn pg svn:ignore .\n</code></pre>\n\n<p>If you are using a GUI there should be a menu option to do this.</p>\n"
},
{
"answer_id": 116131,
"author": "craigb",
"author_id": 18590,
"author_profile": "https://Stackoverflow.com/users/18590",
"pm_score": 9,
"selected": false,
"text": "<p>Here's an example directory structure:</p>\n<pre><code>\\project\n \\source\n \\cache\n \\other\n</code></pre>\n<p>When in <code>project</code> you see that your cache directory is not added and shows up as such.</p>\n<pre><code>> svn status\nM source\n? cache\n</code></pre>\n<p>To set the ignore property, do</p>\n<blockquote>\n<p>svn propset svn:ignore cache .</p>\n</blockquote>\n<p>where <code>svn:ignore</code> is the name of the property you're setting, <code>cache</code> is the value of the property, and <code>.</code> is the directory you're setting this property on. It should be the parent directory of the <code>cache</code> directory that needs the property.</p>\n<p>To check what properties are set:</p>\n<pre><code>> svn proplist\nProperties on '.':\n svn:ignore\n</code></pre>\n<p>To see the value of <code>svn:ignore</code>:</p>\n<pre><code>> svn propget svn:ignore\ncache\n</code></pre>\n<p>To delete properties previously set:</p>\n<pre><code>svn propdel svn:ignore\n</code></pre>\n"
},
{
"answer_id": 837581,
"author": "binco",
"author_id": 19671,
"author_profile": "https://Stackoverflow.com/users/19671",
"pm_score": 7,
"selected": false,
"text": "<p>Important to mention:</p>\n\n<p>On the commandline you can't use</p>\n\n<pre><code>svn add *\n</code></pre>\n\n<p>This will also add the ignored files, because the command line expands <code>*</code> and therefore <code>svn add</code> believes that you want all files to be added. Therefore use this instead:</p>\n\n<pre><code>svn add --force .\n</code></pre>\n"
},
{
"answer_id": 1650336,
"author": "Kai",
"author_id": 75458,
"author_profile": "https://Stackoverflow.com/users/75458",
"pm_score": 6,
"selected": false,
"text": "<p>Since I spent a while trying to get this to work, it should be noted that if the files already exist in SVN, you need to <code>svn delete</code> them, and then edit the <code>svn:ignore</code> property.</p>\n\n<p>I know that seems obvious, but they kept showing up as <code>?</code> in my <code>svn status</code> list, when I thought it would just ignore them locally.</p>\n"
},
{
"answer_id": 3854291,
"author": "brainycat",
"author_id": 465702,
"author_profile": "https://Stackoverflow.com/users/465702",
"pm_score": 3,
"selected": false,
"text": "<p>I had problems getting nested directories to be ignored; the top directory I wanted to ignore wouldn't show with 'svn status' but all the subdirs did. This is probably self-evident to everyone else, but I thought I'd share it:</p>\n<p>EXAMPLE:</p>\n<blockquote>\n<p>/trunk</p>\n<p>/trunk/cache</p>\n<p>/trunk/cache/subdir1</p>\n<p>/trunk/cache/subdir2</p>\n</blockquote>\n<pre><code>cd /trunk\nsvn ps svn:ignore . /cache\ncd /trunk/cache\nsvn ps svn:ignore . *\nsvn ci\n</code></pre>\n"
},
{
"answer_id": 4203434,
"author": "DerMike",
"author_id": 197574,
"author_profile": "https://Stackoverflow.com/users/197574",
"pm_score": 4,
"selected": false,
"text": "<p>...and if you want to ignore more than one directory (say <code>build/</code> <code>temp/</code> and <code>*.tmp</code> files), you could either do it in two steps (ignoring the first and edit ignore properties (see other answers here) or one could write something like</p>\n\n<pre><code>svn propset svn:ignore \"build\ntemp\n*.tmp\" .\n</code></pre>\n\n<p>on the command line.</p>\n"
},
{
"answer_id": 6689382,
"author": "James Stroud",
"author_id": 843981,
"author_profile": "https://Stackoverflow.com/users/843981",
"pm_score": 4,
"selected": false,
"text": "<p>The command to ignore multiple entries is a little tricky and requires backslashes.</p>\n\n<pre><code>svn propset svn:ignore \"cache\\\ntmp\\\nnull\\\nand_so_on\" .\n</code></pre>\n\n<p>This command will ignore anything named <code>cache</code>, <code>tmp</code>, <code>null</code>, and <code>and_so_on</code> in the current directory.</p>\n"
},
{
"answer_id": 7306138,
"author": "Fedir RYKHTIK",
"author_id": 634275,
"author_profile": "https://Stackoverflow.com/users/634275",
"pm_score": 3,
"selected": false,
"text": "<p>Bash oneliner for multiple ignores:</p>\n\n<pre><code>svn propset svn:ignore \".project\"$'\\n'\".settings\"$'\\n'\".buildpath\" \"yourpath\"\n</code></pre>\n"
},
{
"answer_id": 7396487,
"author": "Elliot Yap",
"author_id": 436558,
"author_profile": "https://Stackoverflow.com/users/436558",
"pm_score": 5,
"selected": false,
"text": "<p>Thanks for all the contributions above. I would just like to share some additional information from my experiences while ignoring files.</p>\n\n<hr>\n\n<p><strong>When the folders are already under revision control</strong></p>\n\n<p>After <em>svn import</em> and <em>svn co</em> the files, what we usually do for the first time.</p>\n\n<p>All runtime cache, attachments folders will be under version control.\nso, before <em>svn ps svn:ignore</em>, we need to delete it from the repository.</p>\n\n<p>With SVN version 1.5 above we can use <code>svn del --keep-local your_folder</code>,\nbut for an earlier version, my solution is:</p>\n\n<ol>\n<li><em>svn export</em> a clean copy of your folders (without <code>.svn</code> hidden folder)</li>\n<li><em>svn del</em> the local and repository,</li>\n<li><em>svn ci</em></li>\n<li>Copy back the folders</li>\n<li>Do <em>svn st</em> and confirm the folders are flagged as '?'</li>\n<li>Now we can do <em>svn ps</em> according to the solutions</li>\n</ol>\n\n<hr>\n\n<p><strong>When we need more than one folder to be ignored</strong></p>\n\n<ul>\n<li>In one directory I have two folders that need to be set as <code>svn:ignore</code></li>\n<li>If we set one, the other will be removed.</li>\n<li>Then we wonder we need <em>svn pe</em></li>\n</ul>\n\n<p><code>svn pe</code> will need to edit the text file, and you can use this command if required to set your text editor using <a href=\"http://en.wikipedia.org/wiki/Vi\" rel=\"noreferrer\">vi</a>:</p>\n\n<pre><code>export SVN_EDITOR=vi\n</code></pre>\n\n<ol>\n<li>With \"o\" you can open a new line</li>\n<li>Type in all the folder names you want to ignore</li>\n<li>Hit 'esc' key to escape from edit mode</li>\n<li>Type \":wq\" then hit <kbd>Enter</kbd> to save and quit</li>\n</ol>\n\n<p>The file looks something simply like this:</p>\n\n<pre><code>runtime\ncache\nattachments\nassets\n</code></pre>\n"
},
{
"answer_id": 11622983,
"author": "Andrew",
"author_id": 1200649,
"author_profile": "https://Stackoverflow.com/users/1200649",
"pm_score": 1,
"selected": false,
"text": "<p>Since you're using Versions it's actually really easy:</p>\n\n<ul>\n<li>Browse your checked-out copy</li>\n<li>Click the directory to ignore</li>\n<li>In the \"Ignore box on the right click Edit</li>\n<li>Type *.* to ignore all files (or *.jpg for just jpg files, etc.)</li>\n</ul>\n"
},
{
"answer_id": 12568040,
"author": "cdmo",
"author_id": 721065,
"author_profile": "https://Stackoverflow.com/users/721065",
"pm_score": 1,
"selected": false,
"text": "<p>Watch your trailing slashes too. I found that including <code>images/*</code> in my ignore setting file did not ignore <code>./images/</code>. When I ran <code>svn status -u</code> it still showed <code>? images</code>. So, I just changed the ignore setting to just <code>images</code>, no slashes. Ran a status check and that cleared it out.</p>\n"
},
{
"answer_id": 17347004,
"author": "matt burns",
"author_id": 276093,
"author_profile": "https://Stackoverflow.com/users/276093",
"pm_score": 5,
"selected": false,
"text": "<h2>Remove it first...</h2>\n\n<p>If your directory <code>foo</code> is already under version control, remove it first with:</p>\n\n<pre><code>svn rm --keep-local foo\n</code></pre>\n\n<h2>...then ignore:</h2>\n\n<pre><code>svn propset svn:ignore foo .\n</code></pre>\n"
},
{
"answer_id": 19240497,
"author": "Sam Watkins",
"author_id": 218294,
"author_profile": "https://Stackoverflow.com/users/218294",
"pm_score": 2,
"selected": false,
"text": "<p><em>\"Thank-you\"</em> svn for such a hideous, bogus and difficult way to ignore files.</p>\n\n<p>So I wrote a script <a href=\"http://sam.nipl.net/b/svn-ignore-all\" rel=\"nofollow\">svn-ignore-all</a>:</p>\n\n<pre><code>#!/bin/sh\n\n# svn-ignore-all\n\n# usage: \n# 1. run svn status to see what is going on at each step \n# 2. add or commit all files that you DO want to have in svn\n# 3. remove any random files that you don't want to svn:ignore\n# 4. run this script to svn:ignore everything marked '?' in output of `svn status`\n\nsvn status |\ngrep '^?' |\nsed 's/^? *//' |\nwhile read f; do\n d=`dirname \"$f\"`\n b=`basename \"$f\"`\n ignore=`svn propget svn:ignore \"$d\"`\n if [ -n \"$ignore\" ]; then\n ignore=\"$ignore\n\"\n fi\n ignore=\"$ignore$b\"\n svn propset svn:ignore \"$ignore\" \"$d\"\ndone\n</code></pre>\n\n<p>Also, to ignore specific list of files / pathnames, we can use this variant <a href=\"http://sam.nipl.net/b/svn-ignore\" rel=\"nofollow\">svn-ignore</a>. I guess svn-ignore-all should really be like xargs svn-ignore.</p>\n\n<pre><code>#!/bin/sh\n\n# svn-ignore\n\n# usage:\n# svn-ignore file/to/ignore ...\n\nfor f; do\n d=`dirname \"$f\"`\n b=`basename \"$f\"`\n ignore=`svn propget svn:ignore \"$d\"`\n if [ -n \"$ignore\" ]; then\n ignore=\"$ignore\n\"\n fi\n ignore=\"$ignore$b\"\n svn propset svn:ignore \"$ignore\" \"$d\"\ndone\n</code></pre>\n\n<p>One more thing: I tend to pollute my svn checkouts with many random files. When it's time to commit, I move those files into an 'old' subdirectory, and tell svn to ignore 'old'.</p>\n"
},
{
"answer_id": 21891291,
"author": "Bruno Lee",
"author_id": 2406796,
"author_profile": "https://Stackoverflow.com/users/2406796",
"pm_score": 1,
"selected": false,
"text": "<p>After losing a lot of time looking for how to do this simple activity, I decided to post it was not hard to find a decent explanation.</p>\n\n<p>First let the sample structure</p>\n\n<p>$ svn st\n? project/trunk/target\n? project/trunk/myfile.x</p>\n\n<p>1 – first configure the editor,in mycase vim\nexport SVN_EDITOR=vim</p>\n\n<p>2 – “svn propedit svn:ignore project/trunk/” will open a new file and you can add your files and subdirectory in us case type “target” save and close file and works</p>\n\n<p>$ svn st\n? project/trunk/myfile.x</p>\n\n<p>thanks.</p>\n"
},
{
"answer_id": 30824257,
"author": "sheasie",
"author_id": 2116408,
"author_profile": "https://Stackoverflow.com/users/2116408",
"pm_score": 2,
"selected": false,
"text": "<p><strong>TO KEEP DIRECTORIES THAT SVN WILL IGNORE:</strong></p>\n\n<ol>\n<li>this will delete the files from the repository, but keep the directory under SVN control:</li>\n</ol>\n\n<blockquote>\n <p>svn delete --keep-local path/directory_to_keep/*</p>\n</blockquote>\n\n<ol start=\"2\">\n<li>then set to ignore the directory (and all content):</li>\n</ol>\n\n<blockquote>\n <p>svn propset svn:ignore \"*\" path/directory_to_keep</p>\n</blockquote>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6305/"
]
| I just started using SVN, and I have a cache directory that I don't need under source control. How can I ignore the whole directory/folder with SVN?
I am using [Versions](https://en.wikipedia.org/wiki/Comparison_of_Subversion_clients#Standalone_Subversion_clients_comparison_table) and [TextMate](http://en.wikipedia.org/wiki/TextMate) on OS X and commandline. | Set the `svn:ignore` property of the parent directory:
```
svn propset svn:ignore dirname .
```
If you have multiple things to ignore, separate by newlines in the property value. In that case it's easier to edit the property value using an external editor:
```
svn propedit svn:ignore .
``` |
116,090 | <p>I have a scenario where I have to check whether user has already opened Microsoft Word. If he has, then I have to kill the winword.exe process and continue to execute my code. </p>
<p>Does any one have any straight-forward code for killing a process using vb.net or c#?</p>
| [
{
"answer_id": 116098,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 8,
"selected": true,
"text": "<p>You'll want to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx\" rel=\"noreferrer\">System.Diagnostics.Process.Kill</a> method. You can obtain the process you want using \n<a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx\" rel=\"noreferrer\">System.Diagnostics.Proccess.GetProcessesByName</a>.</p>\n\n<p>Examples have already been posted here, but I found that the non-.exe version worked better, so something like:</p>\n\n<pre><code>foreach ( Process p in System.Diagnostics.Process.GetProcessesByName(\"winword\") )\n{\n try\n {\n p.Kill();\n p.WaitForExit(); // possibly with a timeout\n }\n catch ( Win32Exception winException )\n {\n // process was terminating or can't be terminated - deal with it\n }\n catch ( InvalidOperationException invalidException )\n {\n // process has already exited - might be able to let this one go\n }\n}\n</code></pre>\n\n<p>You probably don't have to deal with <code>NotSupportedException</code>, which suggests that the process is remote.</p>\n"
},
{
"answer_id": 116107,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 4,
"selected": false,
"text": "<p>Here is an easy example of how to kill all Word Processes.</p>\n\n<pre><code>Process[] procs = Process.GetProcessesByName(\"winword\");\n\nforeach (Process proc in procs)\n proc.Kill();\n</code></pre>\n"
},
{
"answer_id": 116110,
"author": "Tomer Gabel",
"author_id": 11558,
"author_profile": "https://Stackoverflow.com/users/11558",
"pm_score": 1,
"selected": false,
"text": "<p>Something like this will work:</p>\n\n<pre><code>foreach ( Process process in Process.GetProcessesByName( \"winword\" ) )\n{\n process.Kill();\n process.WaitForExit();\n}\n</code></pre>\n"
},
{
"answer_id": 116153,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 5,
"selected": false,
"text": "<p>Killing the Word process outright is possible (see some of the other replies), but outright rude and dangerous: what if the user has important unsaved changes in an open document? Not to mention the stale temporary files this will leave behind...</p>\n\n<p>This is probably as far as you can go in this regard (VB.NET):</p>\n\n<pre><code> Dim proc = Process.GetProcessesByName(\"winword\")\n For i As Integer = 0 To proc.Count - 1\n proc(i).CloseMainWindow()\n Next i\n</code></pre>\n\n<p>This will close all open Word windows in an orderly fashion (prompting the user to save his/her work if applicable). Of course, the user can always click 'Cancel' in this scenario, so you should be able to handle this case as well (preferably by putting up a \"please close all Word instances, otherwise we can't continue\" dialog...)</p>\n"
},
{
"answer_id": 135767,
"author": "Chris Lawlor",
"author_id": 21245,
"author_profile": "https://Stackoverflow.com/users/21245",
"pm_score": 3,
"selected": false,
"text": "<p>You can bypass the security concerns, and create a much politer application by simply checking if the Word process is running, and asking the user to close it, then click a 'Continue' button in your app. This is the approach taken by many installers.</p>\n\n<pre><code>private bool isWordRunning() \n{\n return System.Diagnostics.Process.GetProcessesByName(\"winword\").Length > 0;\n}\n</code></pre>\n\n<p>Of course, you can only do this if your app has a GUI</p>\n"
},
{
"answer_id": 9394596,
"author": "Vova Popov",
"author_id": 724533,
"author_profile": "https://Stackoverflow.com/users/724533",
"pm_score": 3,
"selected": false,
"text": "<pre><code> public bool FindAndKillProcess(string name)\n {\n //here we're going to get a list of all running processes on\n //the computer\n foreach (Process clsProcess in Process.GetProcesses()) {\n //now we're going to see if any of the running processes\n //match the currently running processes by using the StartsWith Method,\n //this prevents us from incluing the .EXE for the process we're looking for.\n //. Be sure to not\n //add the .exe to the name you provide, i.e: NOTEPAD,\n //not NOTEPAD.EXE or false is always returned even if\n //notepad is running\n if (clsProcess.ProcessName.StartsWith(name))\n {\n //since we found the proccess we now need to use the\n //Kill Method to kill the process. Remember, if you have\n //the process running more than once, say IE open 4\n //times the loop thr way it is now will close all 4,\n //if you want it to just close the first one it finds\n //then add a return; after the Kill\n try \n {\n clsProcess.Kill();\n }\n catch\n {\n return false;\n }\n //process killed, return true\n return true;\n }\n }\n //process not found, return false\n return false;\n }\n</code></pre>\n"
},
{
"answer_id": 20119778,
"author": "MrVB.NET",
"author_id": 3014246,
"author_profile": "https://Stackoverflow.com/users/3014246",
"pm_score": 0,
"selected": false,
"text": "<p>It's better practise, safer and more polite to detect if the process is running and tell the user to close it manually. Of course you could also add a timeout and kill the process if they've gone away...</p>\n"
},
{
"answer_id": 29264826,
"author": "Ashok",
"author_id": 4713736,
"author_profile": "https://Stackoverflow.com/users/4713736",
"pm_score": -1,
"selected": false,
"text": "<p>Please see the example below <br /></p>\n\n<pre><code>public partial class Form1 : Form\n{\n [ThreadStatic()]\n static Microsoft.Office.Interop.Word.Application wordObj = null;\n\n public Form1()\n {\n InitializeComponent();\n }\n\n public bool OpenDoc(string documentName)\n {\n bool bSuccss = false;\n System.Threading.Thread newThread;\n int iRetryCount;\n int iWait;\n int pid = 0;\n int iMaxRetry = 3;\n\n try\n {\n iRetryCount = 1;\n\n TRY_OPEN_DOCUMENT:\n iWait = 0;\n newThread = new Thread(() => OpenDocument(documentName, pid));\n newThread.Start();\n\n WAIT_FOR_WORD:\n Thread.Sleep(1000);\n iWait = iWait + 1;\n\n if (iWait < 60) //1 minute wait\n goto WAIT_FOR_WORD;\n else\n {\n iRetryCount = iRetryCount + 1;\n newThread.Abort();\n\n //'-----------------------------------------\n //'killing unresponsive word instance\n if ((wordObj != null))\n {\n try\n {\n Process.GetProcessById(pid).Kill();\n Marshal.ReleaseComObject(wordObj);\n wordObj = null;\n }\n catch (Exception ex)\n {\n }\n }\n\n //'----------------------------------------\n if (iMaxRetry >= iRetryCount)\n goto TRY_OPEN_DOCUMENT;\n else\n goto WORD_SUCCESS;\n }\n }\n catch (Exception ex)\n {\n bSuccss = false;\n }\n WORD_SUCCESS:\n\n return bSuccss;\n }\n\n private bool OpenDocument(string docName, int pid)\n {\n bool bSuccess = false;\n Microsoft.Office.Interop.Word.Application tWord;\n DateTime sTime;\n DateTime eTime;\n\n try\n {\n tWord = new Microsoft.Office.Interop.Word.Application();\n sTime = DateTime.Now;\n wordObj = new Microsoft.Office.Interop.Word.Application();\n eTime = DateTime.Now;\n tWord.Quit(false);\n Marshal.ReleaseComObject(tWord);\n tWord = null;\n wordObj.Visible = false;\n pid = GETPID(sTime, eTime);\n\n //now do stuff\n wordObj.Documents.OpenNoRepairDialog(docName);\n //other code\n\n if (wordObj != null)\n {\n wordObj.Quit(false);\n Marshal.ReleaseComObject(wordObj);\n wordObj = null;\n }\n bSuccess = true;\n }\n catch\n { }\n\n return bSuccess;\n }\n\n private int GETPID(System.DateTime startTime, System.DateTime endTime)\n {\n int pid = 0;\n\n try\n {\n foreach (Process p in Process.GetProcessesByName(\"WINWORD\"))\n {\n if (string.IsNullOrEmpty(string.Empty + p.MainWindowTitle) & p.HasExited == false && (p.StartTime.Ticks >= startTime.Ticks & p.StartTime.Ticks <= endTime.Ticks))\n {\n pid = p.Id;\n break;\n }\n }\n }\n catch\n {\n }\n return pid;\n }\n</code></pre>\n"
},
{
"answer_id": 41041813,
"author": "tyler_mitchell",
"author_id": 2720927,
"author_profile": "https://Stackoverflow.com/users/2720927",
"pm_score": 2,
"selected": false,
"text": "<p>In my tray app, I needed to clean Excel and Word Interops. So This simple method kills processes generically. </p>\n\n<p>This uses a general exception handler, but could be easily split for multiple exceptions like stated in other answers. I may do this if my logging produces alot of false positives (ie can't kill already killed). But so far so guid (work joke).</p>\n\n<pre><code>/// <summary>\n/// Kills Processes By Name\n/// </summary>\n/// <param name=\"names\">List of Process Names</param>\nprivate void killProcesses(List<string> names)\n{\n var processes = new List<Process>();\n foreach (var name in names)\n processes.AddRange(Process.GetProcessesByName(name).ToList());\n foreach (Process p in processes)\n {\n try\n {\n p.Kill();\n p.WaitForExit();\n }\n catch (Exception ex)\n {\n // Logging\n RunProcess.insertFeedback(\"Clean Processes Failed\", ex);\n }\n }\n}\n</code></pre>\n\n<p>This is how i called it then:</p>\n\n<pre><code>killProcesses((new List<string>() { \"winword\", \"excel\" }));\n</code></pre>\n"
},
{
"answer_id": 62425307,
"author": "ha a",
"author_id": 1850364,
"author_profile": "https://Stackoverflow.com/users/1850364",
"pm_score": -1,
"selected": false,
"text": "<p>I opened one Word file,\n2. Now I open another word file through vb.net runtime programmatically.\n3. I want to kill the second process alone through programmatically.\n4. Do not kill first process</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13337/"
]
| I have a scenario where I have to check whether user has already opened Microsoft Word. If he has, then I have to kill the winword.exe process and continue to execute my code.
Does any one have any straight-forward code for killing a process using vb.net or c#? | You'll want to use the [System.Diagnostics.Process.Kill](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx) method. You can obtain the process you want using
[System.Diagnostics.Proccess.GetProcessesByName](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx).
Examples have already been posted here, but I found that the non-.exe version worked better, so something like:
```
foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") )
{
try
{
p.Kill();
p.WaitForExit(); // possibly with a timeout
}
catch ( Win32Exception winException )
{
// process was terminating or can't be terminated - deal with it
}
catch ( InvalidOperationException invalidException )
{
// process has already exited - might be able to let this one go
}
}
```
You probably don't have to deal with `NotSupportedException`, which suggests that the process is remote. |
116,140 | <p>I've got several AssemblyInfo.cs files as part of many projects in a single solution that I'm building automatically as part of TeamCity.</p>
<p>To make the msbuild script more maintainable I'd like to be able to use the AssemblyInfo community task in conjunction with an ItemGroup e.g.</p>
<pre><code><ItemGroup>
<AllAssemblyInfos Include="..\**\AssemblyInfo.cs" />
</ItemGroup>
<AssemblyInfo AssemblyTitle="" AssemblyProduct="$(Product)" AssemblyCompany="$(Company)" AssemblyCopyright="$(Copyright)"
ComVisible="false" CLSCompliant="false" CodeLanguage="CS" AssemblyDescription="$(Revision)$(BranchName)"
AssemblyVersion="$(FullVersion)" AssemblyFileVersion="$(FullVersion)" OutputFile="@(AllAssemblyInfos)" />
</code></pre>
<p>Which blatently doesn't work because OutputFile cannot be a referenced ItemGroup.</p>
<p>Anyone know how to make this work?</p>
| [
{
"answer_id": 116182,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 4,
"selected": false,
"text": "<p>We use \"linked\" files in project.\nSolution Explorer -> Add Existin Item -> .. select_file .. -> arrow_on_left_of_add_button -> Add As Link</p>\n\n<p>Then the selected file ( AssemblyInfo.cs for now ) is not copied to the direcotry of project, bud is only linked from specified path.</p>\n"
},
{
"answer_id": 116253,
"author": "evilhomer",
"author_id": 2806,
"author_profile": "https://Stackoverflow.com/users/2806",
"pm_score": 4,
"selected": true,
"text": "<p>Try changing the @ to a % as below</p>\n\n<pre><code><ItemGroup>\n <AllAssemblyInfos Include=\"..\\**\\AssemblyInfo.cs\" />\n</ItemGroup>\n\n<AssemblyInfo AssemblyTitle=\"\" AssemblyProduct=\"$(Product)\" AssemblyCompany=\"$(Company)\" AssemblyCopyright=\"$(Copyright)\" \n ComVisible=\"false\" CLSCompliant=\"false\" CodeLanguage=\"CS\" AssemblyDescription=\"$(Revision)$(BranchName)\" \n AssemblyVersion=\"$(FullVersion)\" AssemblyFileVersion=\"$(FullVersion)\" OutputFile=\"%(AllAssemblyInfos)\" />\n</code></pre>\n\n<p>This creates a call for every entry in AllAssemblyInfos.</p>\n\n<p>Have a look at this article too, should help.</p>\n\n<p><a href=\"http://blogs.msdn.com/aaronhallberg/archive/2006/09/05/msbuild-batching-generating-a-cross-product.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/aaronhallberg/archive/2006/09/05/msbuild-batching-generating-a-cross-product.aspx</a></p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
]
| I've got several AssemblyInfo.cs files as part of many projects in a single solution that I'm building automatically as part of TeamCity.
To make the msbuild script more maintainable I'd like to be able to use the AssemblyInfo community task in conjunction with an ItemGroup e.g.
```
<ItemGroup>
<AllAssemblyInfos Include="..\**\AssemblyInfo.cs" />
</ItemGroup>
<AssemblyInfo AssemblyTitle="" AssemblyProduct="$(Product)" AssemblyCompany="$(Company)" AssemblyCopyright="$(Copyright)"
ComVisible="false" CLSCompliant="false" CodeLanguage="CS" AssemblyDescription="$(Revision)$(BranchName)"
AssemblyVersion="$(FullVersion)" AssemblyFileVersion="$(FullVersion)" OutputFile="@(AllAssemblyInfos)" />
```
Which blatently doesn't work because OutputFile cannot be a referenced ItemGroup.
Anyone know how to make this work? | Try changing the @ to a % as below
```
<ItemGroup>
<AllAssemblyInfos Include="..\**\AssemblyInfo.cs" />
</ItemGroup>
<AssemblyInfo AssemblyTitle="" AssemblyProduct="$(Product)" AssemblyCompany="$(Company)" AssemblyCopyright="$(Copyright)"
ComVisible="false" CLSCompliant="false" CodeLanguage="CS" AssemblyDescription="$(Revision)$(BranchName)"
AssemblyVersion="$(FullVersion)" AssemblyFileVersion="$(FullVersion)" OutputFile="%(AllAssemblyInfos)" />
```
This creates a call for every entry in AllAssemblyInfos.
Have a look at this article too, should help.
<http://blogs.msdn.com/aaronhallberg/archive/2006/09/05/msbuild-batching-generating-a-cross-product.aspx> |
116,154 | <p>I would like to have something like this:</p>
<pre><code>class Foo {
private:
int bar;
public:
void setBar(int bar);
int getBar() const;
}
class MyDialog : public CDialogImpl<MyDialog> {
BEGIN_MODEL_MAPPING()
MAP_INT_EDITOR(m_editBar, m_model, getBar, setBar);
END_MODEL_MAPPING()
// other methods and message map
private:
Foo * m_model;
CEdit m_editBar;
}
</code></pre>
<p>Also it would be great if I could provide my custom validations:</p>
<pre><code>MAP_VALIDATED_INT_EDITOR(m_editBar, m_model, getBar, setBar, validateBar)
...
bool validateBar (int value) {
// custom validation
}
</code></pre>
<p>Have anybody seen something like this?</p>
<p>P.S. I don't like DDX because it's old and it's not flexible, and I cannot use getters and setters.</p>
| [
{
"answer_id": 120133,
"author": "vog",
"author_id": 19163,
"author_profile": "https://Stackoverflow.com/users/19163",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaBindings/CocoaBindings.html\" rel=\"nofollow noreferrer\">Cocoa Bindings</a> provide exactly what you want, but they are only available in the Mac / Objective-C word. <a href=\"http://www.mail-archive.com/[email protected]/msg01423.html\" rel=\"nofollow noreferrer\">GNUstep</a> is a free version of it, but it's still Objective-C, not C++.</p>\n\n<p>However, it might be a good inspiration for an own framework, or a good starting point for further research.</p>\n"
},
{
"answer_id": 161683,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 2,
"selected": false,
"text": "<p>The DDX map is just a series of <code>if</code> statements, so you can easily write your own DDX macro.</p>\n\n<pre><code>#define DDX_MAP_VALIDATED_INT_EDITOR(control, variable, getter, setter, validator)\\\n if(nCtlID==control.GetDlgCtrlID())\\\n {\\\n if(bSaveAndValidate)\\\n {\\\n int const value=control.GetDlgItemInt();\\\n if(validator(value))\\\n {\\\n variable->setter(value);\\\n }\\\n else\\\n {\\\n return false;\\\n }\\\n }\\\n else\\\n {\\\n control.SetDlgItemInt(variable->getter());\\\n }\\\n }\n</code></pre>\n\n<p>This is untested, but should work as per your example, if you put it in the DDX map. It should give you the idea. Of course you could extract this into a function, which is what the standard DDX macros do: they just do the outer <code>if</code> and then call a function. This would allow you to overload the function for different types of the <code>variable</code> (e.g. pointer vs reference/value)</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14535/"
]
| I would like to have something like this:
```
class Foo {
private:
int bar;
public:
void setBar(int bar);
int getBar() const;
}
class MyDialog : public CDialogImpl<MyDialog> {
BEGIN_MODEL_MAPPING()
MAP_INT_EDITOR(m_editBar, m_model, getBar, setBar);
END_MODEL_MAPPING()
// other methods and message map
private:
Foo * m_model;
CEdit m_editBar;
}
```
Also it would be great if I could provide my custom validations:
```
MAP_VALIDATED_INT_EDITOR(m_editBar, m_model, getBar, setBar, validateBar)
...
bool validateBar (int value) {
// custom validation
}
```
Have anybody seen something like this?
P.S. I don't like DDX because it's old and it's not flexible, and I cannot use getters and setters. | The DDX map is just a series of `if` statements, so you can easily write your own DDX macro.
```
#define DDX_MAP_VALIDATED_INT_EDITOR(control, variable, getter, setter, validator)\
if(nCtlID==control.GetDlgCtrlID())\
{\
if(bSaveAndValidate)\
{\
int const value=control.GetDlgItemInt();\
if(validator(value))\
{\
variable->setter(value);\
}\
else\
{\
return false;\
}\
}\
else\
{\
control.SetDlgItemInt(variable->getter());\
}\
}
```
This is untested, but should work as per your example, if you put it in the DDX map. It should give you the idea. Of course you could extract this into a function, which is what the standard DDX macros do: they just do the outer `if` and then call a function. This would allow you to overload the function for different types of the `variable` (e.g. pointer vs reference/value) |
116,163 | <p>I have a paradox table from a legacy system I need to run a single query on. The field names have spaces in them - i.e. "Street 1". When I try and formulate a query in delphi for only the "Street 1" field, I get an error - Invalid use of keyword. Token: 1, Line Number: 1</p>
<p>Delphi V7 - object pascal, standard Tquery object name query1.</p>
| [
{
"answer_id": 116257,
"author": "Jeremy Mullin",
"author_id": 7893,
"author_profile": "https://Stackoverflow.com/users/7893",
"pm_score": 2,
"selected": false,
"text": "<p>You normally need to quote the field name in this case. For example:</p>\n\n<p>select * from t1 where \"street 1\" = 'test';</p>\n\n<p>I tried this on a paradox 7 table and it worked. If that doesn't help, can you post the query you are trying to use? It would be easier to help with that info.</p>\n"
},
{
"answer_id": 116455,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I only need the street information from the address details held in the customer table. I can get it to work fine if I do a SELECT * FROM customers, however this is a very large table and returns numerous results. If I do SELECT \"Street 1\" FROM customers, the output is \"Street 1\" in every record returned - i.e. it does not return the actual data. It must be something to do with the use of \"</p>\n\n<p>Thanks for your help</p>\n\n<p>Joe</p>\n"
},
{
"answer_id": 116492,
"author": "Anya Shenanigans",
"author_id": 17833,
"author_profile": "https://Stackoverflow.com/users/17833",
"pm_score": 4,
"selected": true,
"text": "<p>You need to prefix the string with the table name in the query.</p>\n\n<p>For example: field name is 'Street 1', table is called customers the select is:</p>\n\n<pre><code>SELECT customers.\"Street 1\" FROM customers WHERE ...\n</code></pre>\n"
},
{
"answer_id": 117192,
"author": "Birger",
"author_id": 11485,
"author_profile": "https://Stackoverflow.com/users/11485",
"pm_score": -1,
"selected": false,
"text": "<p>I think you must use [ and ] instead of \":</p>\n\n<pre><code>SELECT customers.[Street 1] FROM customers WHERE ...\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a paradox table from a legacy system I need to run a single query on. The field names have spaces in them - i.e. "Street 1". When I try and formulate a query in delphi for only the "Street 1" field, I get an error - Invalid use of keyword. Token: 1, Line Number: 1
Delphi V7 - object pascal, standard Tquery object name query1. | You need to prefix the string with the table name in the query.
For example: field name is 'Street 1', table is called customers the select is:
```
SELECT customers."Street 1" FROM customers WHERE ...
``` |
116,188 | <p>I need to do the following for the purposes of paging a query in nHibernate:</p>
<pre><code>Select count(*) from
(Select e.ID,e.Name from Object as e where...)
</code></pre>
<p>I have tried the following, </p>
<pre><code>select count(*) from Object e where e = (Select distinct e.ID,e.Name from ...)
</code></pre>
<p>and I get an nHibernate Exception saying I cannot convert Object to int32.</p>
<p>Any ideas on the required syntax?</p>
<p><strong>EDIT</strong></p>
<p>The Subquery uses a distinct clause, I cannot replace the e.ID,e.Name with <code>Count(*)</code> because <code>Count(*) distinct</code> is not a valid syntax, and <code>distinct count(*)</code> is meaningless.</p>
| [
{
"answer_id": 116285,
"author": "user8456",
"author_id": 8456,
"author_profile": "https://Stackoverflow.com/users/8456",
"pm_score": 0,
"selected": false,
"text": "<p>If you just need <code>e.Id</code>,<code>e.Name</code>:</p>\n\n<p><code>select count(*) from Object where</code>.....</p>\n"
},
{
"answer_id": 117336,
"author": "Geir-Tore Lindsve",
"author_id": 4582,
"author_profile": "https://Stackoverflow.com/users/4582",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a draft of how I do it:</p>\n\n<p>Query:</p>\n\n<pre><code>public IList GetOrders(int pageindex, int pagesize)\n{\n IList results = session.CreateMultiQuery()\n .Add(session.CreateQuery(\"from Orders o\").SetFirstResult(pageindex).SetMaxResults(pagesize))\n .Add(session.CreateQuery(\"select count(*) from Orders o\"))\n .List();\n return results;\n}\n</code></pre>\n\n<p>ObjectDataSource:</p>\n\n<pre><code>[DataObjectMethod(DataObjectMethodType.Select)]\npublic DataTable GetOrders(int startRowIndex, int maximumRows)\n{\n IList result = dao.GetOrders(startRowIndex, maximumRows);\n _count = Convert.ToInt32(((IList)result[1])[0]);\n\n return DataTableFromIList((IList)result[0]); //Basically creates a DataTable from the IList of Orders\n}\n</code></pre>\n"
},
{
"answer_id": 117901,
"author": "ForCripeSake",
"author_id": 14833,
"author_profile": "https://Stackoverflow.com/users/14833",
"pm_score": 2,
"selected": false,
"text": "<p>Solved My own question by modifying Geir-Tore's answer.....</p>\n\n<pre><code> IList results = session.CreateMultiQuery()\n .Add(session.CreateQuery(\"from Orders o\").SetFirstResult(pageindex).SetMaxResults(pagesize))\n .Add(session.CreateQuery(\"select count(distinct e.Id) from Orders o where...\"))\n .List();\n return results;\n</code></pre>\n"
},
{
"answer_id": 118413,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 4,
"selected": false,
"text": "<pre><code>var session = GetSession();\nvar criteria = session.CreateCriteria(typeof(Order))\n .Add(Restrictions.Eq(\"Product\", product))\n .SetProjection(Projections.CountDistinct(\"Price\"));\nreturn (int) criteria.UniqueResult();\n</code></pre>\n"
},
{
"answer_id": 3283986,
"author": "Marcelo Salazar",
"author_id": 222369,
"author_profile": "https://Stackoverflow.com/users/222369",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer,</p>\n\n<pre><code> public IList GetOrders(int pageindex, int pagesize, out int total)\n {\n var results = session.CreateQuery().Add(session.CreateQuery(\"from Orders o\").SetFirstResult(pageindex).SetMaxResults(pagesize));\n\n var wCriteriaCount = (ICriteria)results.Clone());\n\n wCriteriaCount.SetProjection(Projections.RowCount());\n\n total = Convert.ToInt32(wCriteriaCount.UniqueResult());\n\n\n return results.List();\n }\n</code></pre>\n"
},
{
"answer_id": 4751382,
"author": "bipinkarms",
"author_id": 567072,
"author_profile": "https://Stackoverflow.com/users/567072",
"pm_score": 4,
"selected": false,
"text": "<p>NHibernate 3.0 allows Linq query.</p>\n\n<p>Try this</p>\n\n<pre><code>int count = session.QueryOver<Orders>().RowCount();\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14833/"
]
| I need to do the following for the purposes of paging a query in nHibernate:
```
Select count(*) from
(Select e.ID,e.Name from Object as e where...)
```
I have tried the following,
```
select count(*) from Object e where e = (Select distinct e.ID,e.Name from ...)
```
and I get an nHibernate Exception saying I cannot convert Object to int32.
Any ideas on the required syntax?
**EDIT**
The Subquery uses a distinct clause, I cannot replace the e.ID,e.Name with `Count(*)` because `Count(*) distinct` is not a valid syntax, and `distinct count(*)` is meaningless. | ```
var session = GetSession();
var criteria = session.CreateCriteria(typeof(Order))
.Add(Restrictions.Eq("Product", product))
.SetProjection(Projections.CountDistinct("Price"));
return (int) criteria.UniqueResult();
``` |
116,276 | <p>I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class.</p>
<p>Two Questions:</p>
<ol>
<li><p>I can't seem to get the input loop to work out, what's the best practice for doing so.</p></li>
<li><p>What is the object-type going to be for the reading method? A double[], or an ArrayList?</p>
<ol>
<li><p>How do I declare method-type to be an arraylist?</p></li>
<li><p>How do I prevent the array from having more than 1000 values stored within it?</p></li>
</ol></li>
</ol>
<p>Let me show what I have so far:</p>
<pre><code>public static java.util.ArrayList readRange(double end_signal){
//read in the range and stop at end_signal
ArrayList input = new ArrayList();
Scanner kbd = new Scanner( System.in );
int count = 0;
do{
input.add(kbd.nextDouble());
System.out.println(input); //debugging
++count;
} while(input(--count) != end_signal);
return input;
}
</code></pre>
<p>Any help would be appreciated, pardon my newbieness...</p>
| [
{
"answer_id": 116283,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 3,
"selected": false,
"text": "<p>What you need in your loop condition is:</p>\n\n<pre><code>while ( input.get( input.size()-1 ) != end_signal );\n</code></pre>\n\n<p>What you're doing is decrementing the counter variable.</p>\n\n<p>Also you should declare the <code>ArrayList</code> like so:</p>\n\n<pre><code>ArrayList<Double> list = new ArrayList<Double>();\n</code></pre>\n\n<p>This makes the list type-specific and allows the condition as given. Otherwise there's extra casting.</p>\n"
},
{
"answer_id": 116293,
"author": "l_39217_l",
"author_id": 13633,
"author_profile": "https://Stackoverflow.com/users/13633",
"pm_score": 0,
"selected": false,
"text": "<p>**</p>\n\n<pre><code>public static java.util.ArrayList readRange(double end_signal) {\n\n //read in the range and stop at end_signal\n\n ArrayList input = new ArrayList();\n\n Scanner kbd = new Scanner(System. in );\n int count = 0;\n\n do {\n input.add(Double.valueOf(kbd.next()));\n System.out.println(input); //debugging\n ++count;\n } while (input(--count) != end_signal);\n return input;\n}\n</code></pre>\n\n<p>**</p>\n"
},
{
"answer_id": 116532,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": true,
"text": "<p>Answers:</p>\n<p><em>>1. I can't seem to get the input loop to work out, what's the best practice for doing so.</em></p>\n<p>I would rather have a simple while loop instead of a do{}while... and place the condition in the while... In my example it read:</p>\n<p><em>while the read number is not end signal and count is lower than limit: do.</em></p>\n<p><em>>2. What is the object-type going to be for the reading method? A double[], or an ArrayList?</em></p>\n<p>An ArrayList, however I would strongly recommend you to use List ( java.util.List ) interface instead. It is a good OO practice to program to the interface rather to the implementation.</p>\n<p><em>>2.1How do I declare method-type to be an arraylist?</em></p>\n<p>See code below.</p>\n<p><em>>2.2. How do I prevent the array from having more than 1000 values stored within it?</em></p>\n<p>By adding this restriction in the while condition.</p>\n<pre><code>import java.util.Scanner;\nimport java.util.List;\nimport java.util.ArrayList;\n\npublic class InputTest{\n \n private int INPUT_LIMIT = 10000;\n\n public static void main( String [] args ) {\n InputTest test = new InputTest();\n System.out.println("Start typing numbers...");\n List list = test.readRange( 2.0 );\n System.out.println("The input was " + list );\n }\n\n /**\n * Read from the standar input until endSignal number is typed.\n * Also limits the amount of entered numbers to 10000;\n * @return a list with the numbers.\n */\n public List readRange( double endSignal ) {\n List<Double> input = new ArrayList<Double>();\n Scanner kdb = new Scanner( System.in );\n int count = 0;\n double number = 0;\n while( ( number = kdb.nextDouble() ) != endSignal && count < INPUT_LIMIT ){\n System.out.println( number );\n input.add( number );\n }\n return input;\n }\n}\n</code></pre>\n<p>Final remarks:</p>\n<p>It is preferred to have "instance methods" than class methods. This way if needed the "readRange" could be handled by a subclass without having to change the signature, thus In the sample I've removed the "static" keyword an create an instance of "InputTest" class</p>\n<p>In java code style the variable names should go in cammel case like in "endSignal" rather than "end_signal"</p>\n"
},
{
"answer_id": 116543,
"author": "GHad",
"author_id": 11705,
"author_profile": "https://Stackoverflow.com/users/11705",
"pm_score": 0,
"selected": false,
"text": "<p>I think you started out not bad, but here is my suggestion. I'll highlight the important differences and points below the code:</p>\n\n<p>package console;</p>\n\n<p>import java.util.<em>;\nimport java.util.regex.</em>;</p>\n\n<p>public class ArrayListInput {</p>\n\n<pre><code>public ArrayListInput() {\n // as list\n List<Double> readRange = readRange(1.5);\n\n System.out.println(readRange);\n // converted to an array\n Double[] asArray = readRange.toArray(new Double[] {});\n System.out.println(Arrays.toString(asArray));\n}\n\npublic static List<Double> readRange(double endWith) {\n String endSignal = String.valueOf(endWith);\n List<Double> result = new ArrayList<Double>();\n Scanner input = new Scanner(System.in);\n String next;\n while (!(next = input.next().trim()).equals(endSignal)) {\n if (isDouble(next)) {\n Double doubleValue = Double.valueOf(next);\n result.add(doubleValue);\n System.out.println(\"> Input valid: \" + doubleValue);\n } else {\n System.err.println(\"> Input invalid! Try again\");\n }\n }\n // result.add(endWith); // uncomment, if last input should be in the result\n return result;\n}\n\npublic static boolean isDouble(String in) {\n return Pattern.matches(fpRegex, in);\n}\n\npublic static void main(String[] args) {\n new ArrayListInput();\n}\n\nprivate static final String Digits = \"(\\\\p{Digit}+)\";\nprivate static final String HexDigits = \"(\\\\p{XDigit}+)\";\n// an exponent is 'e' or 'E' followed by an optionally\n// signed decimal integer.\nprivate static final String Exp = \"[eE][+-]?\" + Digits;\nprivate static final String fpRegex = (\"[\\\\x00-\\\\x20]*\" + // Optional leading \"whitespace\"\n \"[+-]?(\" + // Optional sign character\n \"NaN|\" + // \"NaN\" string\n \"Infinity|\" + // \"Infinity\" string\n\n // A decimal floating-point string representing a finite positive\n // number without a leading sign has at most five basic pieces:\n // Digits . Digits ExponentPart FloatTypeSuffix\n // \n // Since this method allows integer-only strings as input\n // in addition to strings of floating-point literals, the\n // two sub-patterns below are simplifications of the grammar\n // productions from the Java Language Specification, 2nd\n // edition, section 3.10.2.\n\n // Digits ._opt Digits_opt ExponentPart_opt FloatTypeSuffix_opt\n \"(((\" + Digits + \"(\\\\.)?(\" + Digits + \"?)(\" + Exp + \")?)|\" +\n\n // . Digits ExponentPart_opt FloatTypeSuffix_opt\n \"(\\\\.(\" + Digits + \")(\" + Exp + \")?)|\" +\n\n // Hexadecimal strings\n \"((\" +\n // 0[xX] HexDigits ._opt BinaryExponent FloatTypeSuffix_opt\n \"(0[xX]\" + HexDigits + \"(\\\\.)?)|\" +\n\n // 0[xX] HexDigits_opt . HexDigits BinaryExponent\n // FloatTypeSuffix_opt\n \"(0[xX]\" + HexDigits + \"?(\\\\.)\" + HexDigits + \")\" +\n\n \")[pP][+-]?\" + Digits + \"))\" + \"[fFdD]?))\" + \"[\\\\x00-\\\\x20]*\");// Optional\n // trailing\n // \"whitespace\"\n</code></pre>\n\n<p>}</p>\n\n<ol>\n<li><p>In Java it's a good thing to use generics. This way you give the compiler and virtual machine a hint about the types you are about to use. In this case its double and by declaring the resulting List to contain double values,\nyou are able to use the values without casting/type conversion:</p>\n\n<pre><code>if (!readRange.isEmpty()) {\n double last = readRange.get(readRange.size() - 1);\n}\n</code></pre></li>\n<li><p>It's better to return Interfaces when working with Java collections, as there are many implementations of specific lists (LinkedList, SynchronizedLists, ...). So if you need another type of List later on, you can easy change the concrete implementation inside the method and you don't need to change any further code.</p></li>\n<li><p>You may wonder why the while control statement works, but as you see, there are brackets around <strong>next = input.next().trim()</strong>. This way the variable assignment takes place right before the conditional testing. Also a trim takes playe to avoid whitespacing issues</p></li>\n<li><p>I'm not using <strong>nextDouble()</strong> here because whenever a user would input something that's not a double, well, you will get an exception. By using String I'm able to parse whatever input a user gives but also to test against the end signal.</p></li>\n<li><p>To be sure, a user really inputed a double, I used a regular expression from the JavaDoc of the <strong>Double.valueOf()</strong> method. If this expression matches, the value is converted, if not an error message will be printed.</p></li>\n<li><p>You used a counter for reasons I don't see in your code. If you want to know how many values have been inputed successfully, just call <strong>readRange.size()</strong>.</p></li>\n<li><p>If you want to work on with an array, the second part of the constructor shows out how to convert it.</p></li>\n<li><p>I hope you're not confused by me mixin up double and Double, but thanks to Java 1.5 feature Auto-Boxing this is no problem. And as <strong>Scanner.next()</strong> will never return null (afaik), this should't be a problem at all.</p></li>\n<li><p>If you want to limit the size of the Array, use </p></li>\n</ol>\n\n<p>Okay, I hope you're finding my solution and explanations usefull, use <strong>result.size()</strong> as indicator and the keyword <strong>break</strong> to leave the while control statement.</p>\n\n<p>Greetz, GHad</p>\n"
},
{
"answer_id": 56536105,
"author": "sagar_bhoi_188",
"author_id": 9103082,
"author_profile": "https://Stackoverflow.com/users/9103082",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public static ArrayList&lt;Double> readRange(double end_signal) {\n\n ArrayList<Double> input = new ArrayList<Double>();\n Scanner kbd = new Scanner( System.in );\n int count = 0;\n do{\n input.add(kbd.nextDouble());\n ++count;\n } while(input(--count) != end_signal);\nreturn input;\n}\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10636/"
]
| I'm used to python, so this is a bit confusing to me. I'm trying to take in input, line-by-line, until a user inputs a certain number. The numbers will be stored in an array to apply some statistical maths to them. Currently, I have a main class, the stats classes, and an "reading" class.
Two Questions:
1. I can't seem to get the input loop to work out, what's the best practice for doing so.
2. What is the object-type going to be for the reading method? A double[], or an ArrayList?
1. How do I declare method-type to be an arraylist?
2. How do I prevent the array from having more than 1000 values stored within it?
Let me show what I have so far:
```
public static java.util.ArrayList readRange(double end_signal){
//read in the range and stop at end_signal
ArrayList input = new ArrayList();
Scanner kbd = new Scanner( System.in );
int count = 0;
do{
input.add(kbd.nextDouble());
System.out.println(input); //debugging
++count;
} while(input(--count) != end_signal);
return input;
}
```
Any help would be appreciated, pardon my newbieness... | Answers:
*>1. I can't seem to get the input loop to work out, what's the best practice for doing so.*
I would rather have a simple while loop instead of a do{}while... and place the condition in the while... In my example it read:
*while the read number is not end signal and count is lower than limit: do.*
*>2. What is the object-type going to be for the reading method? A double[], or an ArrayList?*
An ArrayList, however I would strongly recommend you to use List ( java.util.List ) interface instead. It is a good OO practice to program to the interface rather to the implementation.
*>2.1How do I declare method-type to be an arraylist?*
See code below.
*>2.2. How do I prevent the array from having more than 1000 values stored within it?*
By adding this restriction in the while condition.
```
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class InputTest{
private int INPUT_LIMIT = 10000;
public static void main( String [] args ) {
InputTest test = new InputTest();
System.out.println("Start typing numbers...");
List list = test.readRange( 2.0 );
System.out.println("The input was " + list );
}
/**
* Read from the standar input until endSignal number is typed.
* Also limits the amount of entered numbers to 10000;
* @return a list with the numbers.
*/
public List readRange( double endSignal ) {
List<Double> input = new ArrayList<Double>();
Scanner kdb = new Scanner( System.in );
int count = 0;
double number = 0;
while( ( number = kdb.nextDouble() ) != endSignal && count < INPUT_LIMIT ){
System.out.println( number );
input.add( number );
}
return input;
}
}
```
Final remarks:
It is preferred to have "instance methods" than class methods. This way if needed the "readRange" could be handled by a subclass without having to change the signature, thus In the sample I've removed the "static" keyword an create an instance of "InputTest" class
In java code style the variable names should go in cammel case like in "endSignal" rather than "end\_signal" |
116,289 | <p>I have VB6 application , I want to put some good error handling finction in it which can tell me what was the error and exact place when it happened , can anyone suggest the good way to do this </p>
| [
{
"answer_id": 116312,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 5,
"selected": false,
"text": "<p>First of all, go get <a href=\"http://www.mztools.com/v3/mztools3.aspx\" rel=\"noreferrer\">MZTools for Visual Basic 6</a>, its free and invaluable. Second add a custom error handler on every function (yes, every function). The error handler we use looks something like this:</p>\n\n<pre><code>On Error GoTo {PROCEDURE_NAME}_Error\n\n{PROCEDURE_BODY}\n\n On Error GoTo 0\n Exit {PROCEDURE_TYPE}\n\n{PROCEDURE_NAME}_Error:\n\n LogError \"Error \" & Err.Number & \" (\" & Err.Description & \") in line \" & Erl & _\n \", in procedure {PROCEDURE_NAME} of {MODULE_TYPE} {MODULE_NAME}\"\n</code></pre>\n\n<p>Then create a LogError function that logs the error to disc. Next, before you release code add Line Numbers to every function (this is also built into MZTools). From now on you will know from the Error Logs everything that happens. If possible, also, upload the error logs and actually examine them live from the field. </p>\n\n<p>This is about the best you can do for unexpected global error handling in VB6 (one of its many defects), and really this should only be used to find unexpected errors. If you know that if there is the possibility of an error occurring in a certain situation, you should catch that particular error and handle for it. If you know that an error occurring in a certain section is going to cause instability (File IO, Memory Issues, etc) warn the user and know that you are in an \"unknown state\" and that \"bad things\" are probably going happen. Obviously use friendly terms to keep the user informed, but not frightened.</p>\n"
},
{
"answer_id": 116314,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 0,
"selected": false,
"text": "<p>Use the On Error statement and the Err object.</p>\n"
},
{
"answer_id": 116320,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 3,
"selected": true,
"text": "<p>ON ERROR GOTO</p>\n\n<p>and the</p>\n\n<pre><code>Err\n</code></pre>\n\n<p>object.</p>\n\n<p>There is a tutorial <a href=\"http://web.archive.org/web/20171020040908/http://www.vb6.us:80/tutorials/error-handling\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 116367,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, take Kris's advice and get MZTools.</p>\n\n<p>You can add line numbers to section off areas of complex procedures, which ERL will report in the error handler, to track down which area is causing the error.</p>\n\n<pre><code>10\n ...group of statements\n20\n ...group of statements\n30\n ...and so on\n</code></pre>\n"
},
{
"answer_id": 116498,
"author": "maero",
"author_id": 11977,
"author_profile": "https://Stackoverflow.com/users/11977",
"pm_score": 4,
"selected": false,
"text": "<p>a simple way without additional modules, useful for class modules:</p>\n\n<p>pre-empt each function/subs:</p>\n\n<pre><code>On Error Goto Handler\n</code></pre>\n\n<p>handler/bubbleup:</p>\n\n<pre><code>Handler:\n Err.Raise Err.Number, \"(function_name)->\" & Err.source, Err.Description\n</code></pre>\n\n<p>voila, ghetto stack trace.</p>\n"
},
{
"answer_id": 128613,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 2,
"selected": false,
"text": "<p>I use a home-grown <code>Error.bas</code> module to make reporting and re-raising less cumbersome.</p>\n\n<p>Here's its contents (edited for length):</p>\n\n<pre><code>Option Explicit\n\nPublic Sub ReportFrom(Source As Variant, Optional Procedure As String)\n If Err.Number Then\n 'Backup Error Contents'\n Dim ErrNumber As Long: ErrNumber = Err.Number\n Dim ErrSource As String: ErrSource = Err.Source\n Dim ErrDescription As String: ErrDescription = Err.Description\n Dim ErrHelpFile As String: ErrHelpFile = Err.HelpFile\n Dim ErrHelpContext As Long: ErrHelpContext = Err.HelpContext\n Dim ErrLastDllError As Long: ErrLastDllError = Err.LastDllError\n On Error Resume Next\n 'Retrieve Source Name'\n Dim SourceName As String\n If VarType(Source) = vbObject Then\n SourceName = TypeName(Source)\n Else\n SourceName = CStr(Source)\n End If\n If LenB(Procedure) Then\n SourceName = SourceName & \".\" & Procedure\n End If\n Err.Clear\n 'Do your normal error reporting including logging, etc'\n MsgBox \"Error \" & CStr(ErrNumber) & vbLf & \"Source: \" & ErrSource & vbCrLf & \"Procedure: \" & SourceName & vbLf & \"Description: \" & ErrDescription & vbLf & \"Last DLL Error: \" & Hex$(ErrLastDllError)\n 'Report failure in logging'\n If Err.Number Then\n MsgBox \"Additionally, the error failed to be logged properly\"\n Err.Clear\n End If\n End If\nEnd Sub\n\nPublic Sub Reraise(Optional ByVal NewSource As String)\n If LenB(NewSource) Then\n NewSource = NewSource & \" -> \" & Err.Source\n Else\n NewSource = Err.Source\n End If\n Err.Raise Err.Number, NewSource, Err.Description, Err.HelpFile, Err.HelpContext\nEnd Sub\n</code></pre>\n\n<p>Reporting an error is as simple as:</p>\n\n<pre><code>Public Sub Form_Load()\nOn Error Goto HError\n MsgBox 1/0\n Exit Sub\nHError:\n Error.ReportFrom Me, \"Form_Load\"\nEnd Sub\n</code></pre>\n\n<p>Reraising an error is as simple as calling <code>Error.Reraise</code> with the new source.</p>\n\n<p>Although it is possible to retrieve the <code>Source</code> and <code>Procedure</code> parameters from the call stack if you compile with symbolic debug info, it's not reliable enough to use in production applications</p>\n"
},
{
"answer_id": 39111123,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Use on</p>\n\n<pre><code>dim errhndl as string\non error goto errhndl\nerrhndl:\nmsgbox \"Error\"\n</code></pre>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14299/"
]
| I have VB6 application , I want to put some good error handling finction in it which can tell me what was the error and exact place when it happened , can anyone suggest the good way to do this | ON ERROR GOTO
and the
```
Err
```
object.
There is a tutorial [here](http://web.archive.org/web/20171020040908/http://www.vb6.us:80/tutorials/error-handling). |
116,402 | <p>I was given a task to display when a record in the database was added, however the previous developers never made a field for this, and I can't go back and make up dates for all the existing records. Is there an easy way to extract out a record Creation date from a <code>SQL server 2000</code> query. </p>
<pre><code>SELECT RECORD_CREATED_DATE FROM tblSomething WHERE idField = 1
</code></pre>
<p>The <code>RECORD_CREATED_DATE</code> isn't a field in the existing table. Is there some sort of SQL Function to get this information ?</p>
| [
{
"answer_id": 116407,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": true,
"text": "<p>If it's not stored as a field, the info is <em>lost</em> after the transaction log recycles (typically daily), and maybe even sooner.</p>\n"
},
{
"answer_id": 116433,
"author": "AR.",
"author_id": 1354,
"author_profile": "https://Stackoverflow.com/users/1354",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not aware of a way you can get this information for existing records. However, going forward you can create an audit table that stores the TableName and RecordCreateDate (or something similar.</p>\n\n<p>Then, for the relevant tables you can make an insert trigger:</p>\n\n<pre><code>CREATE TRIGGER trigger_RecordInsertDate\nON YourTableName\nAFTER INSERT\nAS\nBEGIN\n -- T-SQL code for inserting a record and timestamp\n -- to the audit table goes here\nEND\n</code></pre>\n"
},
{
"answer_id": 116511,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 2,
"selected": false,
"text": "<p>No, unfortunately date of insert or last update are not automatically stored with each record.</p>\n\n<p>To do that, you need to create two <strong>datetime</strong> columns in your table (e.g. <strong>CreatedOn</strong>, <strong>UpdatedOn</strong>) and then in an <strong>INSERT</strong> trigger set the <strong>CreatedOn = getdate()</strong> and in the <strong>UPDATE</strong> trigger set the <strong>UpdatedOn = getdate()</strong>.</p>\n\n<pre><code>CREATE TRIGGER tgr_tblMain_Insert\n ON dbo.tblMain\n AFTER INSERT\nAS \nBEGIN\n set nocount on\n\n update dbo.tblMain\n set CreatedOn = getdate(),\n CreatedBy = session_user\n where tblMain.ID = INSERTED.ID\n\nEND\n</code></pre>\n\n<p>I also like to create <strong>CreatedBy</strong> and <strong>UpdatedBy varchar(20)</strong> columns which I set to <strong>session_user</strong> or update through other methods.</p>\n"
},
{
"answer_id": 116518,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>create another column and give it a default of getdate() that will take care of inserted date, for updated date you will need to write an update trigger</p>\n"
},
{
"answer_id": 116755,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 1,
"selected": false,
"text": "<p>I would start with putting this information in from now on. Create two columns, InsertedDate, LastUpdatedDate. Use a default value of getdate() on the first and an update trigger to populate the second (might want to consider UpdatedBy as well). Then I would write a query to display the information using the CASE Statement to display the date if there is one and to display \"Unknown\" is the field is null. This gets more complicated if you need to store a record of all the updates. Then you need to use audit tables.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18893/"
]
| I was given a task to display when a record in the database was added, however the previous developers never made a field for this, and I can't go back and make up dates for all the existing records. Is there an easy way to extract out a record Creation date from a `SQL server 2000` query.
```
SELECT RECORD_CREATED_DATE FROM tblSomething WHERE idField = 1
```
The `RECORD_CREATED_DATE` isn't a field in the existing table. Is there some sort of SQL Function to get this information ? | If it's not stored as a field, the info is *lost* after the transaction log recycles (typically daily), and maybe even sooner. |
116,403 | <p>Let's say I have a string holding a mess of text and (x)HTML tags. I want to remove all instances of a given tag (and any attributes of that tag), leaving all other tags and text along. What's the best Regex to get this done?</p>
<p>Edited to add: Oh, I appreciate that using a Regex for this particular issue is not the best solution. However, for the sake of discussion can we assume that that particular technical decision was made a few levels over my pay grade? ;)</p>
| [
{
"answer_id": 116417,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 5,
"selected": true,
"text": "<p>Attempting to parse HTML with regular expressions is generally an <em>extremely</em> bad idea. Use a parser instead, there should be one available for your chosen language.</p>\n\n<p>You <strong>might</strong> be able to get away with something like this:</p>\n\n<pre><code></?tag[^>]*?>\n</code></pre>\n\n<p>But it depends on exactly what you're doing. For example, that won't remove the tag's content, and it may leave your HTML in an invalid state, depending on which tag you're trying to remove. It also copes badly with invalid HTML (and there's a lot of that about).</p>\n\n<p>Use a parser instead :)</p>\n"
},
{
"answer_id": 116425,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 0,
"selected": false,
"text": "<p>I think it might be Raymond Chen (blogs.msdn.com/oldnewthing) that I'm paraphrasing (badly!) here... But, you want a Regular Expression? \"Now you have two problems\" ... :=)</p>\n\n<p>If the string is well-formed (X)HTML, could you load it up into a parser (HTML/XML) and use this to remove any nodes of the offending variety? If it's not well-formed, then it becomes a bit more tricky, but, I suspect that a RegEx isn't the best way to go about this...</p>\n"
},
{
"answer_id": 116430,
"author": "AviD",
"author_id": 10080,
"author_profile": "https://Stackoverflow.com/users/10080",
"pm_score": 0,
"selected": false,
"text": "<p>There are just TOO many ways a single tag can appear, not to mention encodings, variants, etc.<br>\nI strongly suggest you rethink this approach.... you really shouldnt have to be handling HTML directly, anyway. </p>\n"
},
{
"answer_id": 116451,
"author": "Benjamin Autin",
"author_id": 1440933,
"author_profile": "https://Stackoverflow.com/users/1440933",
"pm_score": 0,
"selected": false,
"text": "<p>Off the top of my head, I'd say this will get you started in the right direction.</p>\n\n<pre><code>s/<TAG[^>]*>([^<]*)</TAG[^>]*>/\\1\n</code></pre>\n\n<p>Basically find the starting tag, any text in between the tags, and then the ending tag. Replace the whole thing with whatever was in between the tags.</p>\n"
},
{
"answer_id": 116488,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 4,
"selected": false,
"text": "<p>I think there is some serious anti-regex bigotry happening here. There are lots of times when you may want to strip a particular tag out of some markup when it doesn't make sense to use a full blown parser.</p>\n\n<p>Of course there are times when a parser might be the best option, but if you are looking for a regex then:</p>\n\n<pre><code><script[^>]*?>[\\s\\S]*?<\\/script>\n</code></pre>\n\n<p>That would remove script tags and their contents. Make sure that you use case-insensitive matching.</p>\n\n<p>If you don't want to remove the contents of the tag then you can use:</p>\n\n<pre><code><\\/?script[^>]*?>\n</code></pre>\n\n<p>An example of usage in javascript would be:</p>\n\n<pre><code>function stripScripts(markup) {\n return markup.replace(/<script[^>]*?>[\\s\\S]*?<\\/script>/gi, '');\n}\n\nvar safeText = stripScripts(textarea.value);\n</code></pre>\n"
},
{
"answer_id": 260586,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Corrected answer:</p>\n\n<pre><code></?TAG\\b[^>]*?>\n</code></pre>\n\n<p>Because Dans answer would remove <code><br /></code>, but you want only <code><b></code></p>\n"
},
{
"answer_id": 315885,
"author": "Jason Kelley",
"author_id": 36790,
"author_profile": "https://Stackoverflow.com/users/36790",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a regex I wrote for this purpose, it works in a few more situations:</p>\n\n<pre><code></?(?(?=b|img|a|script)notag|[a-zA-Z0-9]+)(?:\\s[a-zA-Z0-9\\-]+=?(?:([\"\",']?).*?\\1?)?)*\\s*/?>\n</code></pre>\n"
},
{
"answer_id": 878257,
"author": "garrow",
"author_id": 21095,
"author_profile": "https://Stackoverflow.com/users/21095",
"pm_score": 0,
"selected": false,
"text": "<p>While using regexes for parsing HTML is generally frowned upon or looked down on, you almost certainly don't want to write your own parser. </p>\n\n<p>You could however use some inbuilt or library functions to achieve what you need.</p>\n\n<ul>\n<li>JavaScript has <code>getElementsByTagName</code> and <code>getElementById</code>, not to mention <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a>.</li>\n<li>PHP has the <a href=\"http://au2.php.net/manual/en/intro.dom.php\" rel=\"nofollow noreferrer\">DOM</a> extension.</li>\n<li>Python has the awesome <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">Beautiful Soup</a></li>\n<li>...and many more.</li>\n</ul>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
]
| Let's say I have a string holding a mess of text and (x)HTML tags. I want to remove all instances of a given tag (and any attributes of that tag), leaving all other tags and text along. What's the best Regex to get this done?
Edited to add: Oh, I appreciate that using a Regex for this particular issue is not the best solution. However, for the sake of discussion can we assume that that particular technical decision was made a few levels over my pay grade? ;) | Attempting to parse HTML with regular expressions is generally an *extremely* bad idea. Use a parser instead, there should be one available for your chosen language.
You **might** be able to get away with something like this:
```
</?tag[^>]*?>
```
But it depends on exactly what you're doing. For example, that won't remove the tag's content, and it may leave your HTML in an invalid state, depending on which tag you're trying to remove. It also copes badly with invalid HTML (and there's a lot of that about).
Use a parser instead :) |
116,423 | <p>I've been reading a little about temporary tables in MySQL but I'm an admitted newbie when it comes to databases in general and MySQL in particular. I've looked at some examples and the MySQL documentation on how to create a temporary table, but I'm trying to determine just how temporary tables might benefit my applications and I guess secondly what sorts of issues I can run into. Granted, each situation is different, but I guess what I'm looking for is some general advice on the topic.</p>
<p>I did a little googling but didn't find exactly what I was looking for on the topic. If you have any experience with this, I'd love to hear about it.</p>
<p>Thanks,
Matt</p>
| [
{
"answer_id": 116443,
"author": "neuroguy123",
"author_id": 12529,
"author_profile": "https://Stackoverflow.com/users/12529",
"pm_score": 1,
"selected": false,
"text": "<p>I've used them in the past when I needed to create evaluated data. That was before the time of views and sub selects in MySQL though and I generally use those now where I would have needed a temporary table. The only time I might use them is if the evaluated data took a long time to create.</p>\n"
},
{
"answer_id": 116449,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 5,
"selected": true,
"text": "<p>Temporary tables are often valuable when you have a fairly complicated SELECT you want to perform and then perform a bunch of queries on that...</p>\n\n<p>You can do something like:</p>\n\n<pre><code>\nCREATE TEMPORARY TABLE myTopCustomers\n SELECT customers.*,count(*) num from customers join purchases using(customerID)\n join items using(itemID) GROUP BY customers.ID HAVING num > 10;\n</code></pre>\n\n<p>And then do a bunch of queries against myTopCustomers without having to do the joins to purchases and items on each query. Then when your application no longer needs the database handle, no cleanup needs to be done.</p>\n\n<p>Almost always you'll see temporary tables used for derived tables that were expensive to create.</p>\n"
},
{
"answer_id": 116453,
"author": "AaronS",
"author_id": 26932,
"author_profile": "https://Stackoverflow.com/users/26932",
"pm_score": 2,
"selected": false,
"text": "<p>The best place to use temporary tables is when you need to pull a bunch of data from multiple tables, do some work on that data, and then combine everything to one result set.</p>\n\n<p>In MS SQL, Temporary tables should also be used in place of cursors whenever possible because of the speed and resource impact associated with cursors.</p>\n"
},
{
"answer_id": 116484,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't done them in MySQL, but I've done them on other databases (Oracle, SQL Server, etc).</p>\n\n<p>Among other tasks, temporary tables provide a way for you to create a queryable (and returnable, say from a sproc) dataset that's purpose-built. Let's say you have several tables of figures -- you can use a temporary table to roll those figures up to nice, clean totals (or other math), then join that temp table to others in your schema for final output. (An example of this, in one of my projects, is calculating how many scheduled calls a given sales-related employee must make per week, bi-weekly, monthly, etc.)</p>\n\n<p>I also often use them as a means of \"tilting\" the data -- turning columns to rows, etc. They're good for advanced data processing -- but only use them when you need to. (My golden rule, as always, applies: If you don't know why you're using <em>x</em>, and you don't know how <em>x</em> works, then you probably shouldn't use it.) </p>\n\n<p>Generally, I wind up using them most in sprocs, where complex data processing is needed. I'd love to give a concrete example, but mine would be in T-SQL (as opposed to MySQL's more standard SQL), and also they're all client/production code which I can't share. I'm sure someone else here on SO will pick up and provide some genuine sample code; this was just to help you get the gist of what problem domain temp tables address.</p>\n"
},
{
"answer_id": 116715,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 4,
"selected": false,
"text": "<p>First a disclaimer - my job is reporting so I wind up with far more complex queries than any normal developer would. If you're writing a simple CRUD (Create Read Update Delete) application (this would be most web applications) then you really don't want to write complex queries, and you are probably doing something wrong if you need to create temporary tables.</p>\n\n<p>That said, I use temporary tables in Postgres for a number of purposes, and most will translate to MySQL. I use them to break up complex queries into a series of individually understandable pieces. I use them for consistency - by generating a complex report through a series of queries, and I can then offload some of those queries into modules I use in multiple places, I can make sure that different reports are consistent with each other. (And make sure that if I need to fix something, I only need to fix it once.) And, rarely, I deliberately use them to force a specific query plan. (Don't try this unless you really understand what you are doing!)</p>\n\n<p>So I think temp tables are great. But that said, it is <em>very</em> important for you to understand that databases generally come in two flavors. The first is optimized for pumping out lots of small transactions, and the other is optimized for pumping out a smaller number of complex reports. The two types need to be tuned differently, and a complex report run on a transactional database runs the risk of blocking transactions (and therefore making web pages not return quickly). Therefore you generally don't want to avoid using one database for both purposes.</p>\n\n<p>My guess is that you're writing a web application that needs a transactional database. In that case, you shouldn't use temp tables. And if you do need complex reports generated from your transactional data, a recommended best practice is to take regular (eg daily) backups, restore them on another machine, then run reports against that machine.</p>\n"
},
{
"answer_id": 144981,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 2,
"selected": false,
"text": "<p>If you are new to databases, there are some good books by Joe Kelko that review best practices for ANSI SQL. <a href=\"https://rads.stackoverflow.com/amzn/click/com/0123693799\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">SQL For Smarties</a> will describe in great detail the use of temp table, impact of indexes, where clauses, etc. It's a great reference book with in depth detail.</p>\n"
}
]
| 2008/09/22 | [
"https://Stackoverflow.com/questions/116423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7862/"
]
| I've been reading a little about temporary tables in MySQL but I'm an admitted newbie when it comes to databases in general and MySQL in particular. I've looked at some examples and the MySQL documentation on how to create a temporary table, but I'm trying to determine just how temporary tables might benefit my applications and I guess secondly what sorts of issues I can run into. Granted, each situation is different, but I guess what I'm looking for is some general advice on the topic.
I did a little googling but didn't find exactly what I was looking for on the topic. If you have any experience with this, I'd love to hear about it.
Thanks,
Matt | Temporary tables are often valuable when you have a fairly complicated SELECT you want to perform and then perform a bunch of queries on that...
You can do something like:
```
CREATE TEMPORARY TABLE myTopCustomers
SELECT customers.*,count(*) num from customers join purchases using(customerID)
join items using(itemID) GROUP BY customers.ID HAVING num > 10;
```
And then do a bunch of queries against myTopCustomers without having to do the joins to purchases and items on each query. Then when your application no longer needs the database handle, no cleanup needs to be done.
Almost always you'll see temporary tables used for derived tables that were expensive to create. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.