qid
int64 1
82.4k
| question
stringlengths 27
22.5k
| answers
stringlengths 509
252k
| date
stringlengths 10
10
| metadata
stringlengths 108
162
|
---|---|---|---|---|
70,575 |
<p>Is there any need of Virtual Constructors? If so can any one post a scenario?</p>
|
[{'answer_id': 70589, 'author': 'grigy', 'author_id': 1692070, 'author_profile': 'https://Stackoverflow.com/users/1692070', 'pm_score': 1, 'selected': False, 'text': '<p>In what language? In C++ for example the constructors can not be virtual.</p>\n'}, {'answer_id': 70597, 'author': 'Marcin Gil', 'author_id': 5731, 'author_profile': 'https://Stackoverflow.com/users/5731', 'pm_score': 2, 'selected': False, 'text': '<p>As always: look up at <a href="http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8" rel="nofollow noreferrer">C++ FAQ lite: virtual functions</a>.</p>\n\n<p>It will explain not only "virtual constructor" but destructors/functions too!</p>\n\n<p>This of course, if you wanted C++ in the first place...</p>\n'}, {'answer_id': 70618, 'author': 'grigy', 'author_id': 1692070, 'author_profile': 'https://Stackoverflow.com/users/1692070', 'pm_score': 0, 'selected': False, 'text': '<p>The constructor can not be virtual by definition. At the time of constructor call there is no object created yet, so the polymorphism does not make any sense.</p>\n'}, {'answer_id': 70634, 'author': 'Mark Ingram', 'author_id': 986, 'author_profile': 'https://Stackoverflow.com/users/986', 'pm_score': 3, 'selected': False, 'text': '<p>If you are talking about virtual destructors in C++ (there isn\'t any such thing as virtual constructors) then they should always be used if you are using your child classes polymorphically.</p>\n\n<pre><code>class A\n{\n ~A();\n}\n\nclass B : public A\n{\n ~B();\n}\n\nA* pB = new B();\ndelete pB; // NOTE: WILL NOT CALL B\'s destructor\n\nclass A\n{\n virtual ~A();\n}\n\nclass B : public A\n{\n virtual ~B();\n}\n\nA* pB = new B();\ndelete pB; // NOTE: WILL CALL B\'s destructor\n</code></pre>\n\n<p><strong>Edit:</strong> Not sure why I\'ve got a downvote for this (would be helpful if you left a comment...) but have a read here as well</p>\n\n<p><a href="http://blogs.msdn.com/oldnewthing/archive/2004/05/07/127826.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/oldnewthing/archive/2004/05/07/127826.aspx</a></p>\n'}, {'answer_id': 70693, 'author': 'Tim Jarvis', 'author_id': 10387, 'author_profile': 'https://Stackoverflow.com/users/10387', 'pm_score': 2, 'selected': False, 'text': '<p>Delphi is one language that supports virtual constructors.</p>\n\n<p>Typically they would be used in a class factory type scenario where you create a meta type i.e. that is a type that describes a type. You would then use that meta type to construct a concrete example of your descendant class</p>\n\n<p>Code would be something like....</p>\n\n<pre><code>type\n MyMetaTypeRef = class of MyBaseClass;\n\nvar\n theRef : MyMetaTypeRef;\n inst : MyBaseClass;\nbegin \n theRef := GetTheMetaTypeFromAFactory(); \n inst := theRef.Create(); // Use polymorphic behaviour to create the class\n</code></pre>\n'}, {'answer_id': 70697, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 2, 'selected': False, 'text': '<p>There are plenty of scenarios, for example if you want to create GUIs for more than one environment. Let\'s say you have classes for controls (“widgets”) but each environment actually has its own widget set. It\'s therefore logical to subclass the creation of these widgets for each environment. The way to do this (since, as has been unhelpfully pointed out, constructors can\'t actually be virtual in most languages), is to employ an <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern" rel="nofollow noreferrer">abstract factory</a> and the above example is actually the standard example used to describe this design pattern.</p>\n'}, {'answer_id': 70822, 'author': 'easeout', 'author_id': 10906, 'author_profile': 'https://Stackoverflow.com/users/10906', 'pm_score': 0, 'selected': False, 'text': '<p>In C++, there\'s no reason for constructors to ever be virtual, because they are static functions. That means they\'re statically bound, so you have to identify the very constructor function you\'re calling in order to call it at all. There\'s no uncertainty and nothing virtual about it.</p>\n\n<p>This also means that, no matter what, you need to know the class that your object is going to be. What you can do, however, is something like this:</p>\n\n<pre><code>Superclass *object = NULL;\nif (condition) {\n object = new Subclass1();\n}\nelse {\n object = new Subclass2();\n}\nobject.setMeUp(args);\n</code></pre>\n\n<p>... have a virtual function and call it after constructon. This is a standard pattern in Objective-C, in which first you call the class\'s "alloc" method to get an instance, and then you call the initilializer that suits your use.</p>\n\n<p>The person who mentioned the Abstract Factory pattern is probably more correct for C++ and Java though.</p>\n'}, {'answer_id': 11664488, 'author': 'Homer6', 'author_id': 278976, 'author_profile': 'https://Stackoverflow.com/users/278976', 'pm_score': -1, 'selected': False, 'text': '<p>In C++, all constructors are implicitly virtual (with a little extra). That is, the constructor of the base class is called before that of the derived class. So, it\'s like they\'re sort of virtual. Because, in a virtual method, if the derived class implements a method of the same signature, only the method in the derived class is invoked.</p>\n\n<p>However, <strong>in a constructor, BOTH METHODS ARE INVOKED</strong> (see example below).</p>\n\n<p>For a more complete explanation of why this is so, please see Item 9 of Effective C++, Third Edition, By Scott Meyers (Never call a virtual function during construction or destruction). The title of the item may be misleading in relation to the question, but if you read the explanation, it\'ll make perfect sense.</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n\nclass Animal {\n\n public:\n\n Animal(){\n std::cout << "Animal Constructor Invoked." << std::endl;\n }\n\n virtual void eat() {\n std::cout << "I eat like a generic animal.\\n";\n }\n\n //always make destructors virtual in base classes\n virtual ~Animal() {\n\n }\n\n};\n\nclass Wolf : public Animal {\n\n public:\n\n Wolf(){\n std::cout << "Wolf Constructor Invoked." << std::endl;\n }\n\n void eat() {\n std::cout << "I eat like a wolf!" << std::endl;\n }\n\n};\n\n\nint main() {\n\n Wolf wolf;\n std::cout << "-------------" << std::endl;\n wolf.eat();\n\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Animal Constructor Invoked.\nWolf Constructor Invoked.\n-------------\nI eat like a wolf!\n</code></pre>\n'}, {'answer_id': 14971562, 'author': 'rockstar', 'author_id': 803649, 'author_profile': 'https://Stackoverflow.com/users/803649', 'pm_score': -1, 'selected': False, 'text': '<p>Virtual constructors dont make sense in C++ . THis is because in C++ constructors do not have a return value . In some other programming languages this is not the case . In those languages the constructor can be called directly and the constructor has a return value . This makes them useful in implementing certain types of desgin patterns . In C++ however this is not the case . </p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11554/']
|
70,577 |
<p>I am new to any scripting language. But, Still I worked on scripting a bit like tailoring other scripts to work for my purpose. For me, What is the best online resource to learn Python?</p>
<p>[Response Summary:] </p>
<p>Some Online Resources:</p>
<p><a href="http://docs.python.org/tut/tut.html" rel="nofollow noreferrer"> <a href="http://docs.python.org/tut/tut.html" rel="nofollow noreferrer">http://docs.python.org/tut/tut.html</a></a> - Beginners</p>
<p><a href="http://diveintopython3.ep.io/" rel="nofollow noreferrer"> <a href="http://diveintopython3.ep.io/" rel="nofollow noreferrer">http://diveintopython3.ep.io/</a></a> - Intermediate</p>
<p><a href="http://www.pythonchallenge.com/" rel="nofollow noreferrer"><a href="http://www.pythonchallenge.com/" rel="nofollow noreferrer">http://www.pythonchallenge.com/</a></a> - Expert Skills</p>
<p><a href="http://docs.python.org/" rel="nofollow noreferrer"><a href="http://docs.python.org/" rel="nofollow noreferrer">http://docs.python.org/</a></a> - collection of all knowledge</p>
<p>Some more:</p>
<p><a href="http://www.swaroopch.com/notes/Python" rel="nofollow noreferrer"> A Byte of Python. </a></p>
<p><a href="http://rgruet.free.fr/PQR25/PQR2.5.html" rel="nofollow noreferrer">Python 2.5 Quick Reference</a></p>
<p><a href="http://www.edgewall.org/python-sidebar/" rel="nofollow noreferrer">Python Side bar</a></p>
<p><a href="http://www.learningpython.com/" rel="nofollow noreferrer">A Nice blog for beginners</a></p>
<p><a href="http://www.greenteapress.com/thinkpython/thinkpython.html" rel="nofollow noreferrer">Think Python: An Introduction to Software Design</a></p>
|
[{'answer_id': 70584, 'author': 'harriyott', 'author_id': 5744, 'author_profile': 'https://Stackoverflow.com/users/5744', 'pm_score': 0, 'selected': False, 'text': '<p>There are some screencasts on <a href="http://showmedo.com" rel="nofollow noreferrer">http://showmedo.com</a></p>\n'}, {'answer_id': 70596, 'author': 'Swaroop C H', 'author_id': 4869, 'author_profile': 'https://Stackoverflow.com/users/4869', 'pm_score': 3, 'selected': False, 'text': '<p>If you\'re a beginner, try my book <a href="http://www.swaroopch.com/notes/Python" rel="nofollow noreferrer">A Byte of Python</a>.</p>\n\n<p>If you\'re already experienced in programming, try <a href="http://www.diveintopython.org" rel="nofollow noreferrer">Dive Into Python</a>.</p>\n'}, {'answer_id': 70608, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I learned from the <a href="http://docs.python.org/tut/tut.html" rel="nofollow noreferrer">Python Tutorial</a>!</p>\n'}, {'answer_id': 70610, 'author': 'Bertrand', 'author_id': 11563, 'author_profile': 'https://Stackoverflow.com/users/11563', 'pm_score': 0, 'selected': False, 'text': '<p>+1 for <a href="http://www.diveintopython.org/" rel="nofollow noreferrer" title="Dive Into Python">Dive Into Python</a></p>\n'}, {'answer_id': 70616, 'author': 'cleg', 'author_id': 29503, 'author_profile': 'https://Stackoverflow.com/users/29503', 'pm_score': 6, 'selected': True, 'text': '<p>If you need to learn python from scratch - you can start here: <a href="http://docs.python.org/tut/tut.html" rel="nofollow noreferrer">http://docs.python.org/tut/tut.html</a> - good begginers guide</p>\n\n<p>If you need to extend your knowledge - continue here <a href="http://diveintopython3.ep.io/" rel="nofollow noreferrer">http://diveintopython3.ep.io/</a> - good intermediate level book</p>\n\n<p>If you need perfect skills - complete this <a href="http://www.pythonchallenge.com/" rel="nofollow noreferrer">http://www.pythonchallenge.com/</a> - outstanding and interesting challenge</p>\n\n<p>And the perfect source of knowledge is <a href="http://docs.python.org/" rel="nofollow noreferrer">http://docs.python.org/</a> - collection of all knowledge</p>\n'}, {'answer_id': 70619, 'author': 'Chris James', 'author_id': 3193, 'author_profile': 'https://Stackoverflow.com/users/3193', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://www.python.org/doc/current/tut/tut.html" rel="nofollow noreferrer">The python manual</a></p>\n\n<p>Its a bit long winded sometimes but it tells you all you need to know to get going.</p>\n'}, {'answer_id': 70626, 'author': 'Tommy Herbert', 'author_id': 11575, 'author_profile': 'https://Stackoverflow.com/users/11575', 'pm_score': 2, 'selected': False, 'text': '<p>The <a href="http://docs.python.org/tut/tut.html" rel="nofollow noreferrer">tutorial</a> at Python\'s homepage is a good place to start. Also, there are some screencasts <a href="http://showmedo.com" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 70677, 'author': 'Pierre-Jean Coudert', 'author_id': 8450, 'author_profile': 'https://Stackoverflow.com/users/8450', 'pm_score': 1, 'selected': False, 'text': '<p>These are unvaluable online reference tools:</p>\n\n<ul>\n<li><p><a href="http://rgruet.free.fr/PQR25/PQR2.5.html" rel="nofollow noreferrer">Python 2.5 Quick Reference</a> </p></li>\n<li><p><a href="http://www.edgewall.org/python-sidebar/" rel="nofollow noreferrer">Python Side bar</a></p></li>\n</ul>\n\n<p>Other online resources for beginners:</p>\n\n<ul>\n<li><p>A good python blog for beginners: <a href="http://www.learningpython.com/" rel="nofollow noreferrer">http://www.learningpython.com/</a></p></li>\n<li><p><a href="http://code.google.com/edu/languages/index.html#_python_understanding" rel="nofollow noreferrer">Python Video at Google Code</a></p></li>\n</ul>\n'}, {'answer_id': 70702, 'author': 'Vhaerun', 'author_id': 11234, 'author_profile': 'https://Stackoverflow.com/users/11234', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://pleac.sf.net" rel="nofollow noreferrer">PLEAC</a> , has a Python Cookbook , which is very helpful .</p>\n'}, {'answer_id': 70710, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://www.poromenos.org/tutorials/python" rel="nofollow noreferrer" title="Learn Python in 10 minutes">Learn Python in 10 minutes</a></p>\n'}, {'answer_id': 70897, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.greenteapress.com/thinkpython/thinkpython.html" rel="nofollow noreferrer">Think Python: An Introduction to Software Design</a></p>\n'}, {'answer_id': 71028, 'author': 'user9282', 'author_id': 9282, 'author_profile': 'https://Stackoverflow.com/users/9282', 'pm_score': 0, 'selected': False, 'text': '<p><a href="https://rads.stackoverflow.com/amzn/click/com/0596007973" rel="nofollow noreferrer" rel="nofollow noreferrer">The Cookbook</a> is absolutely essestial if you want to know idiomatic python.</p>\n'}, {'answer_id': 71158, 'author': 'Brutus', 'author_id': 11666, 'author_profile': 'https://Stackoverflow.com/users/11666', 'pm_score': 2, 'selected': False, 'text': '<p>I think <a href="http://www.pythonchallenge.com/" rel="nofollow noreferrer">Python Challenge</a> is great. </p>\n\n<p>It\'s not about learning Python (syntax) but presents you small and fun riddles. Solving the riddles is based on Python but you can use whatever fits (your calculator, bash scripts, Perl...). After you solved one, you get to see how others have solved it and can discuss the pros & cons of the different ways. </p>\n\n<p>Very nice <strong>to get a feel</strong> for how things could be done (<em>smart</em>) in Python. This site works especially well if you know a bit about other scripting languages or the commandline, etc.</p>\n'}, {'answer_id': 71227, 'author': 'Rorick', 'author_id': 11732, 'author_profile': 'https://Stackoverflow.com/users/11732', 'pm_score': 0, 'selected': False, 'text': '<p>I consider <a href="http://code.activestate.com/recipes/langs/python/" rel="nofollow noreferrer">ActiveState\'s Python community</a> to be a great resource. Also\n<a href="http://snippets.dzone.com/tag/python/" rel="nofollow noreferrer">DZone Snippets</a> can be useful.</p>\n'}, {'answer_id': 71324, 'author': 'jbdavid', 'author_id': 6314, 'author_profile': 'https://Stackoverflow.com/users/6314', 'pm_score': 0, 'selected': False, 'text': '<p>I first ran across <a href="http://swc.scipy.org/" rel="nofollow noreferrer">Software Carpentry</a> looking at lists of python tutorials.. but its a lot more than a tutorial on python. turns out what I really learned was how to use subversion, and that none of my projects are better suited to python than to perl... yet.</p>\n'}, {'answer_id': 74194, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Also consider [Hands-On Python](<a href="http://www.cs.luc.edu/~anh/python/hands-" rel="nofollow noreferrer">http://www.cs.luc.edu/~anh/python/hands-</a> on/). It is used as a primary text for Computer Science 150 at Loyola University. It is concise intro to Python while emphasizing good programming style and design.</p>\n'}, {'answer_id': 74436, 'author': 'Chris AtLee', 'author_id': 4558, 'author_profile': 'https://Stackoverflow.com/users/4558', 'pm_score': 1, 'selected': False, 'text': '<p>The <a href="http://docs.python.org/tut/tut.html" rel="nofollow noreferrer">Python tutorial</a> is actually pretty good.</p>\n\n<p>There\'s also a <a href="http://showmedo.com/videos/python" rel="nofollow noreferrer">video series on showmedo</a> about python.</p>\n\n<p>Between those two resources, you should have more than enough to learn the basics!</p>\n'}, {'answer_id': 76397, 'author': 'S.Lott', 'author_id': 10661, 'author_profile': 'https://Stackoverflow.com/users/10661', 'pm_score': 1, 'selected': False, 'text': '<p>You can look at <a href="http://homepage.mac.com/s_lott/books/python.html" rel="nofollow noreferrer">Building Skills in Python</a>, also. It presumes some level of experience in programming.</p>\n\n<p>If you\'re really new, try <a href="http://homepage.mac.com/s_lott/books/nonprogrammer.html" rel="nofollow noreferrer">Building Skills in Programming</a>. It includes a lot of background and fundamentals.</p>\n'}, {'answer_id': 122122, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://thehazeltree.org" rel="nofollow noreferrer">The Hazel Tree</a></p>\n'}, {'answer_id': 2554368, 'author': 'BrightChen', 'author_id': 306151, 'author_profile': 'https://Stackoverflow.com/users/306151', 'pm_score': 0, 'selected': False, 'text': '<p>Python Cookbook is very useful.</p>\n'}, {'answer_id': 6064659, 'author': 'Ray', 'author_id': 4872, 'author_profile': 'https://Stackoverflow.com/users/4872', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://code.google.com/edu/languages/google-python-class/" rel="nofollow">Google\'s Python Class</a></p>\n\n<blockquote>\n <p>Welcome to Google\'s Python Class --\n this is a free class for people with a\n little bit of programming experience\n who want to learn Python. The class\n includes written materials, lecture\n videos, and lots of code exercises to\n practice Python coding. These\n materials are used within Google to\n introduce Python to people who have\n just a little programming experience.\n The first exercises work on basic\n Python concepts like strings and\n lists, building up to the later\n exercises which are full programs\n dealing with text files, processes,\n and http connections. The class is\n geared for people who have a little\n bit of programming experience in some\n language, enough to know what a\n "variable" or "if statement" is.\n Beyond that, you do not need to be an\n expert programmer to use this\n material.</p>\n</blockquote>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70577', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11372/']
|
70,579 |
<p>When creating the <code>id</code> attributes for HTML elements, what rules are there for the value?</p>
|
[{'answer_id': 70586, 'author': 'Peter Hilton', 'author_id': 2670, 'author_profile': 'https://Stackoverflow.com/users/2670', 'pm_score': 8, 'selected': False, 'text': '<p>From the <a href="http://www.w3.org/TR/html4/types.html#type-id" rel="noreferrer">HTML 4 specification</a>:</p>\n\n<blockquote>\n <p>ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").</p>\n</blockquote>\n\n<p>A common mistake is to use an ID that starts with a digit.</p>\n'}, {'answer_id': 70599, 'author': 'Mr Shark', 'author_id': 6093, 'author_profile': 'https://Stackoverflow.com/users/6093', 'pm_score': 6, 'selected': False, 'text': '<p>Strictly it should match</p>\n<pre><code>[A-Za-z][-A-Za-z0-9_:.]*\n</code></pre>\n<p>But <a href="https://en.wikipedia.org/wiki/JQuery" rel="nofollow noreferrer">jQuery</a> seems to have problems with colons, so it might be better to avoid them.</p>\n'}, {'answer_id': 70607, 'author': 'Steve Morgan', 'author_id': 5806, 'author_profile': 'https://Stackoverflow.com/users/5806', 'pm_score': 4, 'selected': False, 'text': '<p>From the HTML 4 specification...</p>\n<p>The ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").</p>\n'}, {'answer_id': 70894, 'author': 'pdc', 'author_id': 8925, 'author_profile': 'https://Stackoverflow.com/users/8925', 'pm_score': 5, 'selected': False, 'text': '<p>In practice many sites use <code>id</code> attributes starting with numbers, even though this is technically not valid HTML.</p>\n\n<p>The <a href="http://www.w3.org/html/wg/html5/#id" rel="noreferrer">HTML 5 draft specification</a> loosens up the rules for the <code>id</code> and <code>name</code> attributes: they are now just opaque strings which cannot contain spaces.</p>\n'}, {'answer_id': 71734, 'author': 'Vordreller', 'author_id': 11795, 'author_profile': 'https://Stackoverflow.com/users/11795', 'pm_score': 4, 'selected': False, 'text': "<p>Also, never forget that an ID is unique. Once used, the ID value may not appear again anywhere in the document.</p>\n\n<p>You may have many ID's, but all must have a unique value.</p>\n\n<p>On the other hand, there is the class-element. Just like ID, it can appear many times, but the value may be used over and over again.</p>\n"}, {'answer_id': 72577, 'author': 'Michael Thompson', 'author_id': 12276, 'author_profile': 'https://Stackoverflow.com/users/12276', 'pm_score': 7, 'selected': False, 'text': '<p>You can technically use colons and periods in id/name attributes, but I would strongly suggest avoiding both.</p>\n\n<p>In CSS (and several JavaScript libraries like jQuery), both the period and the colon have special meaning and you will run into problems if you\'re not careful. Periods are class selectors and colons are pseudo-selectors (eg., ":hover" for an element when the mouse is over it).</p>\n\n<p>If you give an element the id "my.cool:thing", your CSS selector will look like this:</p>\n\n<pre><code>#my.cool:thing { ... /* some rules */ ... }\n</code></pre>\n\n<p>Which is really saying, "the element with an id of \'my\', a class of \'cool\' and the \'thing\' pseudo-selector" in CSS-speak.</p>\n\n<p>Stick to A-Z of any case, numbers, underscores and hyphens. And as said above, make sure your ids are unique.</p>\n\n<p>That should be your first concern.</p>\n'}, {'answer_id': 79022, 'author': 'dgvid', 'author_id': 9897, 'author_profile': 'https://Stackoverflow.com/users/9897', 'pm_score': 12, 'selected': True, 'text': '<p>For <a href="http://www.w3.org/TR/html4/types.html#type-id" rel="noreferrer">HTML 4</a>, the answer is technically:</p>\n\n<blockquote>\n <p>ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").</p>\n</blockquote>\n\n<p><a href="https://www.w3.org/TR/html5/dom.html#the-id-attribute" rel="noreferrer">HTML 5</a> is even more permissive, saying only that an id must contain at least one character and may not contain any space characters.</p>\n\n<p>The id attribute is case sensitive in <a href="https://www.w3.org/TR/xhtml1/diffs.html#h-4.2" rel="noreferrer">XHTML</a>.</p>\n\n<p>As a purely practical matter, you may want to avoid certain characters. Periods, colons and \'#\' have special meaning in CSS selectors, so you will have to escape those characters using a <a href="http://www.w3.org/TR/CSS2/syndata.html#value-def-identifier" rel="noreferrer">backslash in CSS</a> or a double backslash in a <a href="http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/" rel="noreferrer">selector string passed to jQuery</a>. Think about how often you will have to escape a character in your stylesheets or code before you go crazy with periods and colons in ids.</p>\n\n<p>For example, the HTML declaration <code><div id="first.name"></div></code> is valid. You can select that element in CSS as <code>#first\\.name</code> and in jQuery like so: <code>$(\'#first\\\\.name\').</code> But if you forget the backslash, <code>$(\'#first.name\')</code>, you will have a perfectly valid selector looking for an element with id <code>first</code> and also having class <code>name</code>. This is a bug that is easy to overlook. You might be happier in the long run choosing the id <code>first-name</code> (a hyphen rather than a period), instead.</p>\n\n<p>You can simplify your development tasks by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder "was it <code>firstName</code> or <code>FirstName</code>?" because you will always know that you should type <code>first_name</code>. Prefer camel case? Then limit yourself to that, no hyphens or underscores, and always, consistently use either upper-case or lower-case for the first character, don\'t mix them.</p>\n\n<hr>\n\n<p>A now very obscure problem was that at least one browser, Netscape 6, <a href="https://developer.mozilla.org/en-US/docs/Case_Sensitivity_in_class_and_id_Names" rel="noreferrer">incorrectly treated id attribute values as case-sensitive</a>. That meant that if you had typed <code>id="firstName"</code> in your HTML (lower-case \'f\') and <code>#FirstName { color: red }</code> in your CSS (upper-case \'F\'), that buggy browser would have failed to set the element\'s color to red. At the time of this edit, April 2015, I hope you aren\'t being asked to support Netscape 6. Consider this a historical footnote.</p>\n'}, {'answer_id': 431712, 'author': 'Álvaro González', 'author_id': 13508, 'author_profile': 'https://Stackoverflow.com/users/13508', 'pm_score': 6, 'selected': False, 'text': '<p>jQuery <strong>does</strong> handle any valid ID name. You just need to escape metacharacters (i.e., dots, semicolons, square brackets...). It\'s like saying that JavaScript has a problem with quotes only because you can\'t write</p>\n\n<pre><code>var name = \'O\'Hara\';\n</code></pre>\n\n<p><a href="http://docs.jquery.com/Selectors" rel="noreferrer">Selectors in jQuery API (see bottom note)</a></p>\n'}, {'answer_id': 776500, 'author': 'lstg', 'author_id': 94256, 'author_profile': 'https://Stackoverflow.com/users/94256', 'pm_score': 4, 'selected': False, 'text': '<p>It appears that, although colons (:) and periods (.) are valid in the HTML specification, they are invalid as id selectors in <a href="http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier" rel="nofollow noreferrer">CSS</a>, so they are probably best avoided if you intend to use them for that purpose.</p>\n'}, {'answer_id': 3193773, 'author': 'blacksun1', 'author_id': 385410, 'author_profile': 'https://Stackoverflow.com/users/385410', 'pm_score': 5, 'selected': False, 'text': '<p>Hyphens, underscores, periods, colons, numbers and letters are all valid for use with CSS and jQuery. The following should work, but it must be unique throughout the page and also must start with a letter [A-Za-z].</p>\n<p>Working with colons and periods needs a bit more work, but you can do it as the following example shows.</p>\n<pre><code><html>\n<head>\n<title>Cake</title>\n<style type="text/css">\n #i\\.Really\\.Like\\.Cake {\n color: green;\n }\n #i\\:Really\\:Like\\:Cake {\n color: blue;\n }\n</style>\n</head>\n<body>\n <div id="i.Really.Like.Cake">Cake</div>\n <div id="testResultPeriod"></div>\n\n <div id="i:Really:Like:Cake">Cake</div>\n <div id="testResultColon"></div>\n <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>\n <script type="text/javascript">\n $(function() {\n var testPeriod = $("#i\\\\.Really\\\\.Like\\\\.Cake");\n $("#testResultPeriod").html("found " + testPeriod.length + " result.");\n\n var testColon = $("#i\\\\:Really\\\\:Like\\\\:Cake");\n $("#testResultColon").html("found " + testColon.length + " result.");\n });\n </script>\n</body>\n</html>\n</code></pre>\n'}, {'answer_id': 12546546, 'author': 'Shashank N. Pandey', 'author_id': 1676940, 'author_profile': 'https://Stackoverflow.com/users/1676940', 'pm_score': -1, 'selected': False, 'text': "<p>alphabets → caps & small</p>\n<p>digits → 0-9</p>\n<p>special characters → ':', '-', '_', '.'</p>\n<p>The format should be either starting from '.' or an alphabet, followed by either of the special characters of more alphabets or numbers. The value of the id field must not end at an '_'.</p>\n<p>Also, spaces are not allowed, if provided, they are treated as different values, which is not valid in case of the id attributes.</p>\n"}, {'answer_id': 14394034, 'author': 'Zaheer Ahmed', 'author_id': 821057, 'author_profile': 'https://Stackoverflow.com/users/821057', 'pm_score': 6, 'selected': False, 'text': '<h2>HTML5:</h2>\n<p>It gets rid of the additional restrictions on the <em>id</em> attribute (<a href="http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute" rel="noreferrer">see here</a>). The only requirements left (apart from being unique in the document) are:</p>\n<ol>\n<li>the value must contain at least one character (can’t be empty)</li>\n<li>it can’t contain any space characters.</li>\n</ol>\n<hr />\n<h2>Pre-HTML5:</h2>\n<p>ID should match:</p>\n<pre><code>[A-Za-z][-A-Za-z0-9_:.]*\n</code></pre>\n<ol>\n<li>Must <em>start</em> with A-Z or a-z characters</li>\n<li>May contain <code>-</code> (hyphen), <code>_</code> (underscore), <code>:</code> (colon) and <code>.</code> (period)</li>\n</ol>\n<p>But one should avoid <code>:</code> and <code>.</code> because:</p>\n<p>For example, an ID could be labelled "a.b:c" and referenced in the style sheet as #a.b:c, but as well as being the id for the element, it could mean id "a", class "b", pseudo-selector "c". It is best to avoid the confusion and stay away from using <code>.</code> and <code>:</code> altogether.</p>\n'}, {'answer_id': 16331721, 'author': 'Web Designer cum Promoter', 'author_id': 1012591, 'author_profile': 'https://Stackoverflow.com/users/1012591', 'pm_score': 3, 'selected': False, 'text': '<ol>\n<li>IDs are best suited for naming parts of your layout, so you should not give the same name for ID and class</li>\n<li>ID allows alphanumeric and special characters</li>\n<li>but avoid using the <code># : . * !</code> symbols</li>\n<li>spaces are not allowed</li>\n<li>not started with numbers or a hyphen followed by a digit</li>\n<li>case sensitive</li>\n<li>using ID selectors is faster than using class selectors</li>\n<li>use hyphen "-" (underscore "_" can also be used, but it is not good for <a href="https://en.wikipedia.org/wiki/Search_engine_optimization" rel="nofollow noreferrer">SEO</a>) for long CSS class or Id rule names</li>\n<li>If a rule has an ID selector as its key selector, don’t add the tag name to the rule. Since IDs are unique, adding a tag name would slow down the matching process needlessly.</li>\n<li>In HTML5, the id attribute can be used on any HTML element and In HTML 4.01, the id attribute cannot be used with: <code><base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>.</code></li>\n</ol>\n'}, {'answer_id': 18355561, 'author': 'Kanishka Panamaldeniya', 'author_id': 733287, 'author_profile': 'https://Stackoverflow.com/users/733287', 'pm_score': 4, 'selected': False, 'text': '<p>For <a href="https://en.wikipedia.org/wiki/HTML5" rel="nofollow noreferrer">HTML5</a>:</p>\n<blockquote>\n<p>The value must be unique amongst all the IDs in the element’s home\nsubtree and must contain at least one character. The value must not\ncontain any space characters.</p>\n</blockquote>\n<p>At least one character, no spaces.</p>\n<p>This opens the door for valid use cases such as using accented characters. It also gives us plenty of more ammo to shoot ourselves in the foot with, since you can now use <em>id</em> values that will cause problems with both CSS and JavaScript unless you’re really careful.</p>\n'}, {'answer_id': 18453687, 'author': 'Sergio', 'author_id': 2256325, 'author_profile': 'https://Stackoverflow.com/users/2256325', 'pm_score': 5, 'selected': False, 'text': '<h2>HTML5</h2>\n<p>Keeping in mind that ID must be unique, i.e., there must not be multiple elements in a document that have the same id value.</p>\n<p>The rules about ID content in HTML5 are (apart from being unique):</p>\n<blockquote>\n<p>This attribute\'s value must not contain white spaces. [...]\nThough this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.</p>\n</blockquote>\n<p>This is the <strong>W3</strong> spec about ID (from MDN):</p>\n<blockquote>\n<p>Any string, with the following restrictions:</p>\n<ul>\n<li>must be at least one character long</li>\n<li>must not contain any space characters</li>\n</ul>\n<p>Previous versions of HTML placed greater restrictions on the content of ID values (for example, they did not permit ID values to begin with a number).</p>\n</blockquote>\n<h2>More information:</h2>\n<ul>\n<li><a href="http://www.w3.org/TR/html-markup/global-attributes.html#common.attrs.id" rel="nofollow noreferrer"><strong>W3</strong></a> - global attributes (<code>id</code>)</li>\n<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#id" rel="nofollow noreferrer"><strong>MDN</strong></a> attribute (<code>id</code>)</li>\n</ul>\n'}, {'answer_id': 19963415, 'author': 'Anthony', 'author_id': 1678151, 'author_profile': 'https://Stackoverflow.com/users/1678151', 'pm_score': 4, 'selected': False, 'text': "<p>To reference an id with a period in it, you need to use a backslash. I am not sure if it's the same for hyphens or underscores.</p>\n<p>For example:</p>\n<h3>HTML</h3>\n<pre><code><div id="maintenance.instrumentNumber">############0218</div>\n</code></pre>\n<p>CSS</p>\n<pre><code>#maintenance\\.instrumentNumber{word-wrap:break-word;}\n</code></pre>\n"}, {'answer_id': 31773673, 'author': 'Michael Benjamin', 'author_id': 3597276, 'author_profile': 'https://Stackoverflow.com/users/3597276', 'pm_score': 6, 'selected': False, 'text': '<h2>HTML5: Permitted Values for ID & Class Attributes</h2>\n\n<p>As of HTML5, the only restrictions on the value of an ID are:</p>\n\n<ol>\n<li>must be unique in the document</li>\n<li>must not contain any space characters</li>\n<li>must contain at least one character</li>\n</ol>\n\n<p>Similar rules apply to classes (except for the uniqueness, of course).</p>\n\n<p>So the value can be all digits, just one digit, just punctuation characters, include special characters, whatever. Just no whitespace. This is very different from HTML4.</p>\n\n<p>In HTML 4, ID values must begin with a letter, which can then be followed only by letters, digits, hyphens, underscores, colons and periods.</p>\n\n<p>In HTML5 these are valid:</p>\n\n<pre><code><div id="999"> ... </div>\n<div id="#%LV-||"> ... </div>\n<div id="____V"> ... </div>\n<div id="⌘⌥"> ... </div>\n<div id="♥"> ... </div>\n<div id="{}"> ... </div>\n<div id="©"> ... </div>\n<div id="♤₩¤☆€~¥"> ... </div>\n</code></pre>\n\n<p>Just bear in mind that using numbers, punctuation or special characters in the value of an ID may cause trouble in other contexts (e.g., CSS, JavaScript, regex).</p>\n\n<p>For example, the following ID is valid in HTML5:</p>\n\n<pre><code><div id="9lions"> ... </div>\n</code></pre>\n\n<p><strong><em>However, it is invalid in CSS:</em></strong></p>\n\n<p>From the CSS2.1 spec:</p>\n\n<blockquote>\n <p><a href="https://www.w3.org/TR/CSS21/syndata.html#characters" rel="noreferrer"><strong>4.1.3 Characters and case</strong></a></p>\n \n <p>In CSS, <em>identifiers</em> (including element names, classes, and IDs in\n selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646\n characters U+00A0 and higher, plus the hyphen (-) and the underscore\n (_); <strong><em>they cannot start with a digit, two hyphens, or a hyphen\n followed by a digit</em></strong>.</p>\n</blockquote>\n\n<p>In most cases you may be able to escape characters in contexts where they have restrictions or special meaning.</p>\n\n<hr>\n\n<p><strong>W3C References</strong></p>\n\n<p>HTML5</p>\n\n<blockquote>\n <p><a href="http://www.w3.org/TR/html5/dom.html#the-id-attribute" rel="noreferrer"><strong>3.2.5.1 The <code>id</code>\n attribute</strong></a></p>\n \n <p>The <code>id</code> attribute specifies its element\'s unique identifier (ID). </p>\n \n <p>The value must be unique amongst all the IDs in the element\'s home\n subtree and must contain at least one character. The value must not\n contain any space characters.</p>\n \n <p>Note: There are no other restrictions on what form an ID can take; in\n particular, IDs can consist of just digits, start with a digit, start\n with an underscore, consist of just punctuation, etc.</p>\n \n <p><a href="http://www.w3.org/TR/html5/dom.html#classes" rel="noreferrer"><strong>3.2.5.7 The <code>class</code>\n attribute</strong></a></p>\n \n <p>The attribute, if specified, must have a value that is a set of\n space-separated tokens representing the various classes that the\n element belongs to.</p>\n \n <p>The classes that an HTML element has assigned to it consists of all\n the classes returned when the value of the class attribute is split on\n spaces. (Duplicates are ignored.)</p>\n \n <p>There are no additional restrictions on the tokens authors can use in\n the class attribute, but authors are encouraged to use values that\n describe the nature of the content, rather than values that describe\n the desired presentation of the content.</p>\n</blockquote>\n'}, {'answer_id': 38396827, 'author': 'Bhavin Solanki', 'author_id': 3270866, 'author_profile': 'https://Stackoverflow.com/users/3270866', 'pm_score': 4, 'selected': False, 'text': "<p>A unique identifier for the element.</p>\n\n<p>There must not be multiple elements in a document that have the same id value.</p>\n\n<p>Any string, with the following restrictions:</p>\n\n<ol>\n<li>must be at least one character long</li>\n<li><p>must not contain any space characters:</p>\n\n<ul>\n<li>U+0020 SPACE</li>\n<li>U+0009 CHARACTER TABULATION (tab)</li>\n<li>U+000A LINE FEED (LF)</li>\n<li>U+000C FORM FEED (FF)</li>\n<li>U+000D CARRIAGE RETURN (CR)</li>\n</ul></li>\n</ol>\n\n<p>Using characters except <code>ASCII letters and digits, '_', '-' and '.'</code> may cause compatibility problems, as they weren't allowed in <code>HTML 4</code>. Though this restriction has been lifted in <code>HTML 5</code>, an ID should start with a letter for compatibility.</p>\n"}, {'answer_id': 40563537, 'author': 'Tazwar Utshas', 'author_id': 4464547, 'author_profile': 'https://Stackoverflow.com/users/4464547', 'pm_score': 3, 'selected': False, 'text': '<p>Any <strong>alpha-numeric value</strong>,"<strong>-</strong>", and "<strong>_</strong>" are valid. But, you should <em>start the id name</em> with any character between <strong>A-Z</strong> or <strong>a-z</strong>.</p>\n'}, {'answer_id': 43861092, 'author': 'Joel Wembo', 'author_id': 6437920, 'author_profile': 'https://Stackoverflow.com/users/6437920', 'pm_score': 3, 'selected': False, 'text': '<p>No spaces, and it must begin with at least a character from a to z and 0 to 9.</p>\n'}, {'answer_id': 56597185, 'author': 'Dev pokhariya', 'author_id': 7179457, 'author_profile': 'https://Stackoverflow.com/users/7179457', 'pm_score': 3, 'selected': False, 'text': "<p>In HTML</p>\n<p><strong>ID</strong> should start with <strong>{A-Z}</strong> or <strong>{a-z}</strong>. You can add <strong>digits, periods, hyphens, underscores, and colons.</strong></p>\n<p>For example:</p>\n<pre><code><span id="testID2"></span>\n<span id="test-ID2"></span>\n<span id="test_ID2"></span>\n<span id="test:ID2"></span>\n<span id="test.ID2"></span>\n</code></pre>\n<p>But even though you can make ID with colons (:) or period (<code>.</code>). It is hard for <strong>CSS</strong> to use these IDs as a selector. Mainly when you want to use pseudo elements (<code>:before</code> and <code>:after</code>).</p>\n<p>Also in JavaScript it is hard to select these ID's.\nSo you should use first four ID's as the preferred way by many developers around and if it's necessary then you can use the last two also.</p>\n"}, {'answer_id': 56920453, 'author': 'Jyotirmoy Bhattacharyya', 'author_id': 9342086, 'author_profile': 'https://Stackoverflow.com/users/9342086', 'pm_score': 3, 'selected': False, 'text': '<p>Walues can be: [a-z], [A-Z], [0-9], [* _ : -]</p>\n<p>It is used for HTML5...</p>\n<p>We can add id with any tag.</p>\n'}, {'answer_id': 57837637, 'author': 'NVRM', 'author_id': 2494754, 'author_profile': 'https://Stackoverflow.com/users/2494754', 'pm_score': 3, 'selected': False, 'text': '<p>Since <em>ES2015</em> we can as well use <em>almost</em> all <strong>Unicode characters</strong> for ID\'s, if the document character set is set to UTF-8.</p>\n<p>Test out here: <a href="https://mothereff.in/js-variables" rel="nofollow noreferrer">https://mothereff.in/js-variables</a></p>\n<p><a href="https://i.stack.imgur.com/E4FWL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E4FWL.png" alt="Enter image description here" /></a></p>\n<p>Read about it: <em><a href="https://mathiasbynens.be/notes/javascript-identifiers-es6" rel="nofollow noreferrer">Valid JavaScript variable names in ES2015</a></em></p>\n<blockquote>\n<p>In ES2015, identifiers must start with $, _, or any symbol with the\nUnicode derived core property ID_Start.</p>\n<p>The rest of the identifier can contain $, _, U+200C zero width\nnon-joiner, U+200D zero width joiner, or any symbol with the Unicode\nderived core property ID_Continue.</p>\n</blockquote>\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>const target = document.querySelector("div").id\n\nconsole.log("Div id:", target )\n\ndocument.getElementById(target).style.background = "chartreuse"</code></pre>\r\n<pre class="snippet-code-css lang-css prettyprint-override"><code>div {\n border: 5px blue solid;\n width: 100%;\n height: 200px\n}</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="H̹̙̦̮͉̩̗̗ͧ̇̏̊̾Eͨ͆͒̆ͮ̃͏̷̮̣̫̤̣Cͯ̂͐͏̨̛͔̦̟͈̻O̜͎͍͙͚̬̝̣̽ͮ͐͗̀ͤ̍̀͢M̴̡̲̭͍͇̼̟̯̦̉̒͠Ḛ̛̙̞̪̗ͥͤͩ̾͑̔͐ͅṮ̴̷̷̗̼͍̿̿̓̽͐H̙̙̔̄͜"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<p>Should you use it? Probably not a good idea!</p>\n<p>Read about it: <em><a href="https://stackoverflow.com/questions/11945216/javascript-syntax-error-missing-after-function-body/52799593#52799593">JavaScript: "Syntax error missing } after function body"</a></em></p>\n'}, {'answer_id': 66589027, 'author': "Danny '365CSI' Engelman", 'author_id': 2520800, 'author_profile': 'https://Stackoverflow.com/users/2520800', 'pm_score': 1, 'selected': False, 'text': '<p>Help, my Javascript is broken!</p>\n<p>Everyone says IDs can\'t be duplicates.</p>\n<p>Best tried in every browser but FireFox</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-html lang-html prettyprint-override"><code><div id="ONE"></div>\n<div id="ONE"></div>\n<div id="ONE"></div>\n<script>\n document.body.append( document.querySelectorAll("#ONE").length , \' DIVs!\')\n document.body.append( \' in a \', typeof ONE )\n console.log( ONE ); // a global var !!\n</script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h1><strong>Explanation</strong></h1>\n<p><img src="https://upload.wikimedia.org/wikipedia/commons/2/24/Browser_Wars_%28en%29.svg" alt="" /></p>\n<p>After the turn of the century Microsoft had 90% Browser Market share,</p>\n<p>and implemented Browser behaviours that where never standardized:</p>\n<p><strong>1. create global variables for every ID</strong></p>\n<p><strong>2. create an Array for <strong>duplicate</strong> IDs</strong></p>\n<p><strong>All</strong> later Browser vendors copied this behaviour, otherwise their browser wouldn\'t support older sites.</p>\n<p>Somewhere around 2015 Mozilla removed 2. from FireFox and 1. still works.</p>\n<p>All other browsers still do 1. and 2.</p>\n<p>I use it every day because typing <code>ONE</code> instead of <code>document.querySelector("#ONE")</code> helps me prototype faster; I do not use it in production.</p>\n'}, {'answer_id': 66898851, 'author': 'baijugoradia', 'author_id': 8696792, 'author_profile': 'https://Stackoverflow.com/users/8696792', 'pm_score': 0, 'selected': False, 'text': "<p><em><strong>Html ID</strong></em></p>\n<p>The id attribute specifies its element's unique identifier (ID).</p>\n<p>There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.</p>\n<p>An element's unique identifier can be used for a variety of purposes, most notably as a way to link to specific parts of a document using fragments, as a way to target an element when scripting, and as a way to style a specific element from CSS.</p>\n"}, {'answer_id': 66937072, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<ol>\n<li>Uppercase and lowercase alphabets works</li>\n<li>'_' and '-' works, too</li>\n<li>Numbers works</li>\n<li>Colons (,) and period (.) seems to work</li>\n<li>Interestingly, emojis work</li>\n</ol>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70579', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6093/']
|
70,600 |
<p>I'm trying to find a way of finding out who is downloading what image from an image gallery. Users can download using a button beside the thumbnail or right click and use the "save link as" Is it possible to relate a user session or ID to a "save link as" action from all browsers using either PHP or JavaScript.</p>
|
[{'answer_id': 70633, 'author': 'Jesper Blad Jensen', 'author_id': 11559, 'author_profile': 'https://Stackoverflow.com/users/11559', 'pm_score': 0, 'selected': False, 'text': '<p>You need a gateway script, like ImageDownload.php?picture=me.jpg, or something like that.</p>\n\n<p>That page whould return the image bytes, as well as logging that the image is downloaded.</p>\n'}, {'answer_id': 70639, 'author': 'Henry B', 'author_id': 6414, 'author_profile': 'https://Stackoverflow.com/users/6414', 'pm_score': 0, 'selected': False, 'text': "<p>Because the images being saved are on their computer locally there would be no way to get that kind of information as they have already retrieved the image from your system. Even with javascript the best I know that you could do is to log each time a user presses the second mousebutton using some kind of ajax'y stuff.</p>\n\n<p>I don't really like the idea, but if you wanted to log everytime someone downloaded an image you could host the images inside a flash or java app that made it a requirement to click a download image button. That way the only way for them to get the image without doing that would be to either capture packets as they came into their side or take a screenshot.</p>\n"}, {'answer_id': 70664, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Yes, my preferred way of doing this would be via PHP. You\'d have to set up a script which would load up the file and send it to the user browser. This script would also be able to log the download somewhere (e.g. your database).</p>\n\n<p>For example - in very rough pseudo-code:</p>\n\n<p>download.php</p>\n\n<pre><code>$file = $_GET[\'file\'];\nupdateFileCount($file);\nheader(\'Content-Type: image/jpeg\');\nsendFile($file);\n</code></pre>\n\n<p>Then, you just have your download link point to download.php instead of the actual file. (Note that updateFileCount and sendFile are functions that you would have to provide, of course - <a href="http://elouai.com/force-download.php" rel="nofollow noreferrer">this script</a> is an example of a download script which you could use)</p>\n\n<p>Note: I highly recommend avoiding the use of $_GET[\'file\'] to get the whole filename - malicious users could use it to retrieve sensitive files from your web server. But the safe use of PHP downloads is a topic for another question.</p>\n'}, {'answer_id': 70669, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 0, 'selected': False, 'text': '<p>Your server access logs should already have the request for the non-thumbnailed version of the file, so you just need to modify the log format to include the sessionid, which I presume you can map back to a user.</p>\n'}, {'answer_id': 96582, 'author': 'Laith', 'author_id': 5961, 'author_profile': 'https://Stackoverflow.com/users/5961', 'pm_score': 0, 'selected': False, 'text': "<p>I agree strongly with the suggestion put forward by Phill Sacre. For what you are looking for this is the way to go. </p>\n\n<p>It also has the benefit of being potentially able to keep the tracked files out of the direct web path so that they can't be direct linked to.</p>\n\n<p>I use this method in a client site where the images are paid content so must be restricted access.</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
70,602 |
<p>I have successfully connected to an Oracle database (10g) from C# (Visual Studio 2008) by downloading and installing the client administration tools and Visual Studio 2008 on my laptop.</p>
<p>The installation footprint for Oracle Client tools was over 200Mb, and quite long winded.</p>
<p>Does anyone know what the minimum workable footprint is? I am hoping that it's a single DLL and a register command, but I have the feeling I need to install an oracle home, and set various environment variables.</p>
<p>I am using Oracle.DataAccess in my code.</p>
|
[{'answer_id': 70711, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>ODAC xcopy will get you away with about 45MB.\n<a href="http://www.oracle.com/technology/software/tech/windows/odpnet/index.html" rel="nofollow noreferrer">http://www.oracle.com/technology/software/tech/windows/odpnet/index.html</a></p>\n'}, {'answer_id': 70744, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>DevArt <a href="http://www.devart.com/" rel="noreferrer">http://www.devart.com/</a>, formerly CoreLab (crlab.com) supplies a pure-C# Oracle client. That\'s a single dll, and it works fine.</p>\n'}, {'answer_id': 70901, 'author': 'Mac', 'author_id': 8696, 'author_profile': 'https://Stackoverflow.com/users/8696', 'pm_score': 7, 'selected': True, 'text': '<p>You need an Oracle Client to connect to an Oracle database. The easiest way is to install the <a href="http://www.oracle.com/technology/software/tech/windows/odpnet/index.html" rel="noreferrer">Oracle Data Access Components</a>.</p>\n\n<p>To minimize the footprint, I suggest the following :</p>\n\n<ul>\n<li>Use the Microsoft provider for Oracle (System.Data.OracleClient), which ships with the framework.</li>\n<li>Download the <a href="http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html" rel="noreferrer">Oracle Instant Client Package</a> - Basic Lite : this is a zip file with (almost) the bare minimum. I recommend version 10.2.0.4, which is much smaller than version 11.1.0.6.0.</li>\n<li>Unzip the following files in a specific folder :\n\n<ul>\n<li>v10 :\n\n<ul>\n<li>oci.dll</li>\n<li>orannzsbb10.dll</li>\n<li>oraociicus10.dll</li>\n</ul></li>\n<li>v11 :\n\n<ul>\n<li>oci.dll</li>\n<li>orannzsbb11.dll</li>\n<li>oraociei11.dll</li>\n</ul></li>\n</ul></li>\n<li>On a x86 platform, add the CRT DLL for Visual Studio 2003 (msvcr71.dll) to this folder, as Oracle guys forgot to <a href="http://support.microsoft.com/kb/326922" rel="noreferrer">read this</a>...</li>\n<li>Add this folder to the PATH environment variable.</li>\n<li>Use the <a href="http://download.oracle.com/docs/cd/B19306_01/network.102/b14212/naming.htm#ABC524382SRI12" rel="noreferrer">Easy Connect Naming</a> method in your application to get rid of the infamous TNSNAMES.ORA configuration file. It looks like this : <code>sales-server:1521/sales.us.acme.com</code>.</li>\n</ul>\n\n<p>This amounts to about <strong>19Mb</strong> (v10).</p>\n\n<p>If you do not care about sharing this folder between several applications, an alternative would be to ship the above mentioned DLLs along with your application binaries, and skip the PATH setting step.</p>\n\n<p>If you absolutely need to use the Oracle provider (Oracle.DataAccess), you will need :</p>\n\n<ul>\n<li>ODP .NET 11.1.0.6.20 (the first version which allegedly works with Instant Client).</li>\n<li>Instant Client 11.1.0.6.0, obviously.</li>\n</ul>\n\n<p>Note that I haven\'t tested this latest configuration...</p>\n'}, {'answer_id': 1409089, 'author': 'Fidel', 'author_id': 171846, 'author_profile': 'https://Stackoverflow.com/users/171846', 'pm_score': 4, 'selected': False, 'text': '<p>This way allows you to connect with ODP.net using 5 redistributable files from oracle:</p>\n\n<p><a href="http://splinter.com.au/using-the-new-odpnet-to-access-oracle-from-c" rel="noreferrer">Chris\'s blog entry: Using the new ODP.Net to access Oracle from C# with simple deployment</a></p>\n\n<p>Edit: In case the blog every goes down, here is a brief summary...</p>\n\n<ul>\n<li>oci.dll</li>\n<li>Oracle.DataAccess.dll</li>\n<li>oraociicus11.dll</li>\n<li>OraOps11w.dll</li>\n<li>orannzsbb11.dll</li>\n<li>oraocci11.dll</li>\n<li>ociw32.dll</li>\n</ul>\n\n<blockquote>\n <p>make sure you get ALL those DLL\'s from the same ODP.Net / ODAC distribution to avoid version number conflicts, and put them all in the same folder as your EXE</p>\n</blockquote>\n'}, {'answer_id': 1529296, 'author': 'Vincent De Smet', 'author_id': 138469, 'author_profile': 'https://Stackoverflow.com/users/138469', 'pm_score': 2, 'selected': False, 'text': '<p>I found this post on the Oracle forum very usefull as well:</p>\n<h2><a href="http://forums.oracle.com/forums/message.jspa?messageID=1418596#1418596" rel="nofollow noreferrer">How to setup Oracle Instant Client with Visual Studio</a></h2>\n<p>Remark: the ADO.NET team is deprecating System.Data.OracleClient so for future projects you should use ODP.NET</p>\n<p>Reproduction:</p>\n<blockquote>\n<p>Setup the following environment variables:</p>\n<ol>\n<li>make sure no other oracle directory is in your PATH</li>\n<li>set your <strong>PATH</strong> to point to your instant client</li>\n<li>set your <strong>TNS_ADMIN</strong> to point to where you tnsnames.ora file is\nlocated</li>\n<li>set your <strong>NLS_LANG</strong></li>\n<li>set your <strong>ORACLE_HOME</strong> to your instant client</li>\n</ol>\n<p>For me, I set NLS_LANG to</p>\n<p><a href="http://download-east.oracle.com/docs/html/A95493_01/gblsupp.htm#634282" rel="nofollow noreferrer">http://download-east.oracle.com/docs/html/A95493_01/gblsupp.htm#634282</a></p>\n<p>I verified this was using the correct client software by using the sqlplus add-on to the instant client.</p>\n<p>For me, I set:\nSET NLS_LANG=AMERICAN_AMERICA.WE8MSWIN1252</p>\n<p>Note: before you make any changes, back up your Oracle registry key (if exist) and backup the string for any environment variables.</p>\n<p><a href="http://www.oracle.com/technology/tech/oci/instantclient/ic-faq.html" rel="nofollow noreferrer">Read the Oracle Instant Client FAQ here</a></p>\n</blockquote>\n'}, {'answer_id': 6608906, 'author': 'kol', 'author_id': 600135, 'author_profile': 'https://Stackoverflow.com/users/600135', 'pm_score': 4, 'selected': False, 'text': '<p>I use the method suggested by Pandicus above, on Windows XP, using ODAC 11.2.0.2.1. The steps are as follows:</p>\n\n<ol>\n<li>Download the "ODAC 11.2 Release 3 (11.2.0.2.1) with Xcopy Deployment" package from oracle.com (53 MB), and extract the ZIP.</li>\n<li>Collect the following DLLs: oci.dll (1 MB), oraociei11.dll (130 MB!), OraOps11w.dll (0.4 MB), Oracle.DataAccess.dll (1 MB). The remaining stuff can be deleted, and nothing have to be installed.</li>\n<li>Add a reference to Oracle.DataAccess.dll, add <code>using Oracle.DataAccess.Client;</code> to your code and now you can use types like <code>OracleConnection</code>, <code>OracleCommand</code> and <code>OracleDataReader</code> to access an Oracle database. See the <a href="http://download.oracle.com/docs/cd/B19306_01/win.102/b14307/intro003.htm#BHCJFIAJ" rel="noreferrer">class documentation</a> for details. There is no need to use the tnsnames.ora configuration file, only the <a href="http://www.connectionstrings.com/oracle" rel="noreferrer">connection string </a> must be set properly. </li>\n<li>The above 4 DLLs have to be deployed along with your executable. </li>\n</ol>\n'}, {'answer_id': 23161879, 'author': 'DavidRR', 'author_id': 1497596, 'author_profile': 'https://Stackoverflow.com/users/1497596', 'pm_score': 3, 'selected': False, 'text': '<p>Here is an update for <strong>Oracle 11.2.0.4.0</strong>. I had success with the following procedure on <strong>Windows 7</strong> using <code>System.Data.OracleClient</code>.</p>\n\n<p><strong>1.</strong> Download <strong>Instant Client Package - Basic Lite</strong>: <a href="http://www.oracle.com/technetwork/topics/winsoft-085727.html" rel="nofollow noreferrer">Windows 32-Bit</a> or <a href="http://www.oracle.com/technetwork/topics/winx64soft-089540.html" rel="nofollow noreferrer">64-Bit</a>.</p>\n\n<p><strong>2.</strong> Copy the following files to a location in your system path:</p>\n\n<p><strong>32-Bit</strong>\n</p>\n\n<pre><code> 1,036,288 2013-10-11 oci.dll\n 348,160 2013-10-11 ociw32.dll\n 1,290,240 2013-09-21 orannzsbb11.dll\n 562,688 2013-10-11 oraocci11.dll\n36,286,464 2013-10-11 oraociicus11.dll\n</code></pre>\n\n<p><strong>64-Bit</strong></p>\n\n<pre class="lang-none prettyprint-override"><code> 691,712 2013-10-09 oci.dll\n 482,304 2013-10-09 ociw32.dll\n 1,603,072 2013-09-10 orannzsbb11.dll\n 1,235,456 2013-10-09 oraocci11.dll\n45,935,104 2013-10-09 oraociicus11.dll\n</code></pre>\n\n<p><strong>3.</strong> Construct a connection string that <a href="http://www.connectionstrings.com/oracle/" rel="nofollow noreferrer">omits the need for <strong>tnsnames.ora</strong></a>.</p>\n\n<p><em>(See examples in the test program below.)</em></p>\n\n<p><strong>4.</strong> Run this minimal C# program to test your installation:</p>\n\n<pre class="lang-cs prettyprint-override"><code>using System;\nusing System.Data;\nusing System.Data.OracleClient;\n\nclass TestOracleInstantClient\n{\n static public void Main(string[] args)\n {\n const string host = "yourhost.yourdomain.com";\n const string serviceName = "yourservice.yourdomain.com";\n const string userId = "foo";\n const string password = "bar";\n\n var conn = new OracleConnection();\n\n // Construct a connection string using Method 1 or 2.\n conn.ConnectionString =\n GetConnectionStringMethod1(host, serviceName, userId, password);\n\n try\n {\n conn.Open();\n Console.WriteLine("Connection succeeded.");\n // Do something with the connection.\n conn.Close();\n }\n catch (Exception e)\n {\n Console.WriteLine("Connection failed: " + e.Message);\n }\n }\n\n static private string GetConnectionStringMethod1(\n string host,\n string serviceName,\n string userId,\n string password\n )\n {\n string format =\n "SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)" +\n "(HOST={0})(PORT=1521))" +\n "(CONNECT_DATA=(SERVER=DEDICATED)" +\n "(SERVICE_NAME={1})));" +\n "uid={2};" +\n "pwd={3};"; // assumes port is 1521 (the default)\n\n return String.Format(format, host, serviceName, userId, password);\n }\n\n static private string GetConnectionStringMethod2(\n string host,\n string serviceName,\n string userId,\n string password\n )\n {\n string format =\n "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)" +\n "(HOST={0})(PORT=1521))" +\n "(CONNECT_DATA=(SERVER=DEDICATED)" +\n "(SERVICE_NAME={1})));" +\n "User Id={2};" +\n "Password={3};"; // assumes port is 1521 (the default)\n\n return String.Format(format, host, serviceName, userId, password);\n }\n}\n</code></pre>\n\n<p><strong>Final tip:</strong> If you encounter the error <em>"System.Data.OracleClient requires Oracle client software version 8.1.7"</em>, see <a href="https://stackoverflow.com/q/447983/1497596">this question</a>.</p>\n'}, {'answer_id': 26469797, 'author': 'ecoe', 'author_id': 1080804, 'author_profile': 'https://Stackoverflow.com/users/1080804', 'pm_score': 4, 'selected': False, 'text': '<p>As of 2014, the OPD.NET, Managed Driver is the smallest footprint.</p>\n\n<p>Here is a code usage comparison to the non-managed versions that previous (outdated) answers suggested:\n<a href="http://docs.oracle.com/cd/E51173_01/win.122/e17732/intro005.htm#ODPNT148">http://docs.oracle.com/cd/E51173_01/win.122/e17732/intro005.htm#ODPNT148</a></p>\n\n<p>You will need to download these dlls and reference <code>Oracle.ManagedDataAccess.dll</code> in your project: \nDownload the <a href="http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html">ODP.NET, Managed Driver Xcopy version only</a></p>\n\n<p>Here is a typical foot print you will need to package with your release:</p>\n\n<ol>\n<li><code>Oracle.ManagedDataAccess.dll</code></li>\n<li><code>Oracle.ManagedDataAccessDTC.dll</code> </li>\n</ol>\n\n<p>all together, a <em>whopping</em> 6.4 MB for .Net 4.0.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6910/']
|
70,614 |
<p>I've just introduced a friend to <strong>GNU Screen</strong> and they're having a hard time getting used to it. That makes me think about the essential things he needs to know about the excellent <strong>Screen</strong> utility, the same things that you'd think worthwhile to teach someone, a beginner, from the ground up. What are some analogies and handy tips for remembering binds, etc.?</p>
<p>It would be awesome.</p>
|
[{'answer_id': 70683, 'author': 'agnul', 'author_id': 6069, 'author_profile': 'https://Stackoverflow.com/users/6069', 'pm_score': 5, 'selected': False, 'text': '<p>If your friend is in the habit of pressing <code>^A</code> to get to the beginning of the line in Bash, he/she is in for some surprises, since <code>^A</code> is the screen command key binding. Usually I end up with a frozen screen, possibly because of some random key I pressed after <code>^A</code> :-) </p>\n\n<p>In those cases I try</p>\n\n<p><code>^A s</code> and <code>^A q</code> block/unblock terminal scrolling</p>\n\n<p>to fix that. To go to the beginning of a line inside screen, the key sequence is <code>^A a</code>.</p>\n'}, {'answer_id': 70716, 'author': 'tadeusz', 'author_id': 7593, 'author_profile': 'https://Stackoverflow.com/users/7593', 'pm_score': 3, 'selected': False, 'text': '<p><kbd>Ctrl</kbd>+<kbd>a</kbd> is a special key.</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>a</kbd> <kbd>d</kbd> - [d]etach, leave programs (irssi?) in background, go home.</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>a</kbd> <kbd>c</kbd> [c]reate a new window\n<kbd>Ctrl</kbd>+<kbd>a</kbd> <kbd>0-9</kbd> switch between windows by number</p>\n\n<p>screen -r - get back to detached session</p>\n\n<p>That covers 90% of use cases. Do not try to show all the functionality at the single time.</p>\n'}, {'answer_id': 70735, 'author': 'Niko Gunadi', 'author_id': 4499, 'author_profile': 'https://Stackoverflow.com/users/4499', 'pm_score': 3, 'selected': False, 'text': '<p><kbd>Ctrl</kbd>+<kbd>A</kbd> is the base command</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>A</kbd> <kbd>N</kbd> = go to the ***N***ext screen</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>A</kbd> <kbd>P</kbd> = go to the ***P***revious screen</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>A</kbd> <kbd>C</kbd> = ***C***reate new screen</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>A</kbd> <kbd>D</kbd> = ***D***etach your screen</p>\n'}, {'answer_id': 70765, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 8, 'selected': True, 'text': "<p>I've been using <code>Screen</code> for over 10 years and probably use less than half the features. So it's definitely not necessary to learn all its features right away (and I wouldn't recommend trying). My day-to-day commands are:</p>\n\n<pre><code>^A ^W - window list, where am I\n^A ^C - create new window\n^A space - next window\n^A p - previous window\n^A ^A - switch to previous screen (toggle)\n^A [0-9] - go to window [0-9]\n^A esc - copy mode, which I use for scrollback\n</code></pre>\n\n<p>I think that's it. I sometimes use the split screen features, but certainly not daily. The other tip is if screen seems to have locked up because you hit some random key combination by accident, do both <code>^Q</code> and <code>^A ^Q</code> to try to unlock it.</p>\n"}, {'answer_id': 70801, 'author': 'James Muscat', 'author_id': 11643, 'author_profile': 'https://Stackoverflow.com/users/11643', 'pm_score': 5, 'selected': False, 'text': '<p><kbd>Ctrl</kbd>+<kbd>A</kbd> ? - show the help screen!</p>\n'}, {'answer_id': 70882, 'author': 'Roel', 'author_id': 11449, 'author_profile': 'https://Stackoverflow.com/users/11449', 'pm_score': 5, 'selected': False, 'text': '<p>I couldn\'t get used to screen until I found a way to set a \'status bar\' at the bottom of the screen that shows what \'tab\' or \'virtual screen\' you\'re on and which other ones there are. Here is my setup:</p>\n\n<pre><code>[roel@roel ~]$ cat .screenrc\n# Here comes the pain...\ncaption always "%{=b dw}:%{-b dw}:%{=b dk}[ %{-b dw}%{-b dg}$USER%{-b dw}@%{-b dg}%H %{=b dk}] [ %= %?%{-b dg}%-Lw%?%{+b dk}(%{+b dw}%n:%t%{+b dk})%?(%u)%?%{-b dw}%?%{-b dg}%+Lw%? %{=b dk}]%{-b dw}:%{+b dw}:"\n\nbacktick 2 5 5 $HOME/scripts/meminfo\nhardstatus alwayslastline "%{+b dw}:%{-b dw}:%{+b dk}[%{-b dg} %0C:%s%a %{=b dk}]-[ %{-b dw}Load%{+b dk}:%{-b dg}%l %{+b dk}] [%{-b dg}%2`%{+b dk}] %=[ %{-b dg}%1`%{=b dk} ]%{-b dw}:%{+b dw}:%<"\n\nsorendition "-b dw"\n[roel@roel ~]$ cat ~/scripts/meminfo\n#!/bin/sh\nRAM=`cat /proc/meminfo | grep "MemFree" | awk -F" " \'{print $2}\'`\nSWAP=`cat /proc/meminfo | grep "SwapFree" | awk -F" " \'{print $2}\'`\necho -n "${RAM}kb/ram ${SWAP}kb/swap"\n[roel@roel ~]$\n</code></pre>\n'}, {'answer_id': 70985, 'author': 'Andrew Johnson', 'author_id': 5109, 'author_profile': 'https://Stackoverflow.com/users/5109', 'pm_score': 4, 'selected': False, 'text': '<p>You can remap the escape key from <kbd>Ctrl</kbd> + <kbd>A</kbd> to be another key of your choice, so if you do use it for something else, e.g. to go to the beginning of the line in bash, you just need to add a line to your ~/.screenrc file. To make it ^b or ^B, use:</p>\n\n<pre><code>escape ^bB\n</code></pre>\n\n<p>From the command line, use names sessions to keep multiple sessions under control. I use one session per task, each with multiple tabs:</p>\n\n<pre>\n screen -ls # Lists your current screen sessions\n screen -S <name> # Creates a new screen session called name\n screen -r <name> # Connects to the named screen sessions\n</pre>\n\n<p>When using screen you only need a few commands:</p>\n\n<pre>\n ^A c Create a new shell\n ^A [0-9] Switch shell\n ^A k Kill the current shell\n ^A d Disconnect from screen\n ^A ? Show the help\n</pre>\n\n<p>An excellent quick reference can be found <a href="http://aperiodic.net/screen/quick_reference" rel="nofollow noreferrer">here</a>. It is worth bookmarking.</p>\n'}, {'answer_id': 71055, 'author': 'dummy', 'author_id': 6297, 'author_profile': 'https://Stackoverflow.com/users/6297', 'pm_score': 0, 'selected': False, 'text': '<p>^A A switches back to the screen you just came from.</p>\n'}, {'answer_id': 106158, 'author': 'jkramer', 'author_id': 12523, 'author_profile': 'https://Stackoverflow.com/users/12523', 'pm_score': 2, 'selected': False, 'text': '<p>Not really essential not solely related to screen, but <a href="https://web.archive.org/web/20130313011037/http://www.frexx.de/xterm-256-notes/" rel="nofollow noreferrer">enabling 256 colors in my terminal, GNU Screen and Vim</a> improved my screen experience big time (especially since I code in Vim about 8h a day - there are some great eye-friendly colorschemes).</p>\n'}, {'answer_id': 117008, 'author': 'innaM', 'author_id': 7498, 'author_profile': 'https://Stackoverflow.com/users/7498', 'pm_score': 2, 'selected': False, 'text': '<p>I like to set up a screen session with descriptive names for the windows. ^a A will let you give a name to the current window and ^a " will give you a list of your windows.\nWhen done, detach the screen with ^a d and re-attach with screen -R</p>\n'}, {'answer_id': 117072, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://www.debian-administration.org/articles/34" rel="noreferrer">http://www.debian-administration.org/articles/34</a></p>\n\n<p>I wrote that a couple of years ago, but it is still a good introduction that gets a lot of positive feedback.</p>\n'}, {'answer_id': 157174, 'author': 'Zsolt Botykai', 'author_id': 11621, 'author_profile': 'https://Stackoverflow.com/users/11621', 'pm_score': 3, 'selected': False, 'text': '<p>I "must" add this: add</p>\n\n<pre><code>bind s\n</code></pre>\n\n<p>to your <code>.screenrc</code>, if You - like me - used to use split windows, as <code>C-a S</code> splits the actual window, but <code>C-a s</code> freezes it. So I just disabled the freeze shortcut.</p>\n'}, {'answer_id': 563876, 'author': 'David Dean', 'author_id': 67829, 'author_profile': 'https://Stackoverflow.com/users/67829', 'pm_score': 2, 'selected': False, 'text': '<p>There is some <a href="http://blog.dustinkirkland.com/2008/12/ubuntu-server-includes-window-manager.html" rel="nofollow noreferrer">interesting work</a> being done on getting a good GNU screen setup happening by default in the next version of Ubuntu Server, which includes using the bottom of the screen to show all the windows as well as other useful machine details (like number of updates available and whether the machine needs a reboot). You can probably grab their <code>.screenrc</code> and customise it to your needs.</p>\n\n<p>The most useful commands I have in my <code>.screenrc</code> are the following:</p>\n\n<pre><code>shelltitle "$ |bash" # Make screen assign window titles automatically\nhardstatus alwayslastline "%w" # Show all window titles at bottom line of term\n</code></pre>\n\n<p>This way I always know what windows are open, and what is running in them at the moment, too.</p>\n'}, {'answer_id': 894140, 'author': 'Gary Chambers', 'author_id': 103072, 'author_profile': 'https://Stackoverflow.com/users/103072', 'pm_score': 2, 'selected': False, 'text': "<p>The first modification I make to .screenrc is to change the escape command. Not unlike many of you, I do not like the default Ctrl-A sequence because of its interference with that fundamental functionality in almost every other context. In my .screenrc file, I add:</p>\n\n<p>escape `e</p>\n\n<p>That's backtick-e.</p>\n\n<p>This enables me to use the backtick as the escape key (e.g. to create a new screen, I press backtick-c, detach is backtick-d, backtick-? is help, backtick-backtick is previous screen, etc.). The only way it interferes (and I had to break myself of the habit) is using backtick on the command line to capture execution output, or pasting anything that contains a backtick. For the former, I've modified my habit by using the BASH $(command) convention. For the latter, I usually just pop open another xterm or detach from screen then paste the content containing the backtick. Finally, if I wish to insert a literal backtick, I simply press backtick-e.</p>\n"}, {'answer_id': 1236687, 'author': 'staticsan', 'author_id': 28832, 'author_profile': 'https://Stackoverflow.com/users/28832', 'pm_score': 3, 'selected': False, 'text': "<p>Some tips for those sorta familiar with screen, but who tend to not remember things they read in the man page:</p>\n\n<ul>\n<li>To change the name of a screen window is very easy: <kbd>ctrl</kbd>+<kbd>A</kbd> <kbd>shift</kbd>+<kbd>A</kbd>. </li>\n<li>Did you miss the last message from screen? <kbd>ctrl</kbd>+<kbd>a</kbd> <kbd>ctrl</kbd>+<kbd>m</kbd> will show it again for you.</li>\n<li>If you want to run something (like tailing a file) and have screen tell you when there's a change, use <kbd>ctrl</kbd>+<kbd>A</kbd> <kbd>shift</kbd>+<kbd>m</kbd> on the target window. Warning: it will let you know if <em>anything</em> changes.</li>\n<li>Want to select window 15 directly? Try these in your <code>.screenrc</code> file:</li>\n</ul>\n\n<blockquote>\n<pre><code>bind ! select 11\nbind @ select 12\nbind \\# select 13\nbind $ select 14\nbind % select 15\nbind \\^ select 16\nbind & select 17\nbind * select 18\nbind ( select 19\nbind ) select 10\n</code></pre>\n</blockquote>\n\n<p>That assigns <kbd>ctrl</kbd>+<kbd>a</kbd> <kbd>shift</kbd>+<kbd>0 through 9</kbd> for windows 10 through 19.</p>\n"}, {'answer_id': 1680589, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I use the following for <code>ssh</code>:</p>\n\n<pre><code>#!/bin/sh\n# scr - Runs a command in a fresh screen\n#\n# Get the current directory and the name of command\n\nwd=`pwd`\ncmd=$1\nshift\n\n# We can tell if we are running inside screen by looking\n# for the STY environment variable. If it is not set we\n# only need to run the command, but if it is set then\n# we need to use screen.\n\nif [ -z "$STY" ]; then\n $cmd $*\nelse\n # Screen needs to change directory so that\n # relative file names are resolved correctly.\n screen -X chdir $wd\n\n # Ask screen to run the command\n if [ $cmd == "ssh" ]; then\n screen -X screen -t ""${1##*@}"" $cmd $*\n else\n screen -X screen -t "$cmd $*" $cmd $*\n fi\nfi\n</code></pre>\n\n<p>Then I set the following bash aliases:</p>\n\n<pre><code>vim() {\n scr vim $*\n}\n\nman() {\n scr man $*\n}\n\ninfo() {\n scr info $*\n}\n\nwatch() {\n scr watch $*\n}\n\nssh() {\n scr ssh $*\n}\n</code></pre>\n\n<p>It opens a new screen for the above aliases and iff using ssh, it renames the screen title with the ssh hostname.</p>\n'}, {'answer_id': 4651572, 'author': 'bambams', 'author_id': 149184, 'author_profile': 'https://Stackoverflow.com/users/149184', 'pm_score': 1, 'selected': False, 'text': '<p>I like to use <code>screen -d -RR</code> to automatically create/attach to a given screen. I created bash functions to make it easier...</p>\n\n<pre><code>function mkscreen\n{\n local add=n\n\n if [ "$1" == \'-a\' ]; then\n add=y\n shift;\n fi\n\n local name=$1;\n shift;\n local command="$*";\n\n if [ -z "$name" -o -z "$command" ]; then\n echo \'Usage: mkscreen [ -a ] name command\n\n -a Add to .bashrc.\' 1>&2;\n return 1;\n fi\n\n if [ $add == y ]; then\n echo "mkscreen $name $command" >> $HOME/.bashrc;\n fi\n\n alias $name="/usr/bin/screen -d -RR -S $name $command";\n\n return 0;\n}\n\nfunction rmscreen\n{\n local delete=n\n\n if [ "$1" == \'-d\' ]; then\n delete=y\n shift;\n fi\n\n local name=$1;\n\n if [ -z "$name" ]; then\n echo \'Usage: rmscreen [ -d ] name\n\n -d Delete from .bashrc.\' 1>&2;\n return 1;\n fi\n\n if [ $delete == y ]; then\n sed -i -r "/^mkscreen $name .*/d" $HOME/.bashrc;\n fi\n\n unalias $name;\n\n return 0;\n}\n</code></pre>\n\n<p>They create an alias to <code>/usr/bin/screen -d -RR -S $name $command</code>. For example, I like to use irssi in a screen session, so in my .bashrc (beneath those functions), I have:</p>\n\n<pre><code>mkscreen irc /usr/bin/irssi\n</code></pre>\n\n<p>Then I can just type <code>irc</code> in a terminal to get into irssi. If the screen \'irc\' doesn\'t exist yet then it is created and /usr/bin/irssi is run from it (which connects automatically, of course). If it\'s already running then I just reattach to it, forcibly detaching any other instance that is already attached to it. It\'s quite nice.</p>\n\n<p>Another example is creating temporary screen aliases for perldocs as I come across them:</p>\n\n<pre><code>mkscreen perlipc perldoc perlipc\nperlipc # Start reading the perldoc, ^A d to detach.\n...\n# Later, when I\'m done reading it, or at least finished\n# with the alias, I remove it.\nrmscreen perlipc \n</code></pre>\n\n<p>The -a option (must be first argument) appends the screen alias to .bashrc (so it\'s persistent) and -d removes it (these can potentially be destructive, so use at own risk). xD</p>\n\n<p>Append:</p>\n\n<p>Another bash-ism that I find convenient when working a lot with screen:</p>\n\n<pre><code>alias sls=\'/usr/bin/screen -ls\'\n</code></pre>\n\n<p>That way you can list your screens with a lot fewer keystrokes. I don\'t know if <code>sls</code> collides with any existing utilities, but it didn\'t at the time on my system so I went for it.</p>\n'}, {'answer_id': 15283793, 'author': 'user2146463', 'author_id': 2146463, 'author_profile': 'https://Stackoverflow.com/users/2146463', 'pm_score': 0, 'selected': False, 'text': '<p><kbd>Ctrl</kbd> + <kbd>A</kbd> is a great special character for Unix people, but if you\'re using screen to talk to <a href="https://en.wikipedia.org/wiki/OpenVMS" rel="nofollow noreferrer">OpenVMS</a>, then not being able to ^A is going to make you bald prematurely.</p>\n\n<p>In <a href="https://en.wikipedia.org/wiki/OpenVMS#Origin_and_name_changes" rel="nofollow noreferrer">VMS</a>, if you\'re editing a <a href="https://en.wikipedia.org/wiki/DIGITAL_Command_Language" rel="nofollow noreferrer">DCL</a> command prior to execution from the history buffer, Insert mode is off (it has to be for a few reasons I won\'t get into here) ... to turn it on so you don\'t over-type your command rather than space things out, you have to hit `^A.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6414/']
|
70,625 |
<p>How would you refactor these two classes to abstract out the similarities? An abstract class? Simple inheritance? What would the refactored class(es) look like?</p>
<pre><code>public class LanguageCode
{
/// <summary>
/// Get the lowercase two-character ISO 639-1 language code.
/// </summary>
public readonly string Value;
public LanguageCode(string language)
{
this.Value = new CultureInfo(language).TwoLetterISOLanguageName;
}
public static LanguageCode TryParse(string language)
{
if (language == null)
{
return null;
}
if (language.Length > 2)
{
language = language.Substring(0, 2);
}
try
{
return new LanguageCode(language);
}
catch (ArgumentException)
{
return null;
}
}
}
public class RegionCode
{
/// <summary>
/// Get the uppercase two-character ISO 3166 region/country code.
/// </summary>
public readonly string Value;
public RegionCode(string region)
{
this.Value = new RegionInfo(region).TwoLetterISORegionName;
}
public static RegionCode TryParse(string region)
{
if (region == null)
{
return null;
}
if (region.Length > 2)
{
region = region.Substring(0, 2);
}
try
{
return new RegionCode(region);
}
catch (ArgumentException)
{
return null;
}
}
}
</code></pre>
|
[{'answer_id': 70645, 'author': 'Chris Kimpton', 'author_id': 48310, 'author_profile': 'https://Stackoverflow.com/users/48310', 'pm_score': 2, 'selected': False, 'text': '<p>It depends, if they are not going to do much more, then I would probably leave them as is - IMHO factoring out stuff is likely to be more complex, in this case.</p>\n'}, {'answer_id': 70662, 'author': 'Henry B', 'author_id': 6414, 'author_profile': 'https://Stackoverflow.com/users/6414', 'pm_score': 0, 'selected': False, 'text': "<p>This is a rather simple question and to me smells awefully like a homework assignment.</p>\n\n<p>You can obviously see the common bits in the code and I'm pretty sure you can make an attempt at it yourself by putting such things into a super-class.</p>\n"}, {'answer_id': 70667, 'author': 'Ben', 'author_id': 5005, 'author_profile': 'https://Stackoverflow.com/users/5005', 'pm_score': 0, 'selected': False, 'text': '<p>You could maybe combine them into a <code>Locale</code> class, which stores both Language code and Region code, has accessors for Region and Language plus one parse function which also allows for strings like "en_gb"...</p>\n\n<p>That\'s how I\'ve seen locales be handled in various frameworks.</p>\n'}, {'answer_id': 70671, 'author': 'Steve Morgan', 'author_id': 5806, 'author_profile': 'https://Stackoverflow.com/users/5806', 'pm_score': 0, 'selected': False, 'text': "<p>These two, as they stand, aren't going to refactor well because of the static methods.</p>\n\n<p>You'd either end up with some kind of factory method on a base class that returns an a type of that base class (which would subsequently need casting) or you'd need some kind of additional helper class.</p>\n\n<p>Given the amount of extra code and subsequent casting to the appropriate type, it's not worth it.</p>\n"}, {'answer_id': 70673, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 0, 'selected': False, 'text': "<p>I'm sure there is a better generics based solution. But still gave it a shot. </p>\n\n<p>EDIT: As the comment says, static methods can't be overridden so one option would be to retain it and use TwoLetterCode objects around and cast them, but, as some other person has already pointed out, that is rather useless. </p>\n\n<p>How about this?</p>\n\n<pre><code>public class TwoLetterCode {\n public readonly string Value;\n public static TwoLetterCode TryParseSt(string tlc) {\n if (tlc == null)\n {\n return null;\n }\n\n if (tlc.Length > 2)\n {\n tlc = tlc.Substring(0, 2);\n }\n\n try\n {\n return new TwoLetterCode(tlc);\n }\n catch (ArgumentException)\n {\n return null;\n }\n }\n}\n//Likewise for Region\npublic class LanguageCode : TwoLetterCode {\n public LanguageCode(string language)\n {\n this.Value = new CultureInfo(language).TwoLetterISOLanguageName;\n }\n public static LanguageCode TryParse(string language) {\n return (LanguageCode)TwoLetterCode.TryParseSt(language);\n }\n}\n</code></pre>\n"}, {'answer_id': 70684, 'author': 'Steve Cooper', 'author_id': 6722, 'author_profile': 'https://Stackoverflow.com/users/6722', 'pm_score': 0, 'selected': False, 'text': '<ol>\n<li>Create a generic base class (eg <code>AbstractCode<T></code>)</li>\n<li><p>add abstract methods like</p>\n\n<pre><code>protected T GetConstructor(string code);\n</code></pre></li>\n<li><p>override in base classes like</p>\n\n<pre><code>protected override RegionCode GetConstructor(string code)\n{\n return new RegionCode(code);\n}\n</code></pre></li>\n<li><p>Finally, do the same with <code>string GetIsoName(string code)</code>, eg</p>\n\n<pre><code>protected override GetIsoName(string code)\n{\n return new RegionCode(code).TowLetterISORegionName;\n}\n</code></pre></li>\n</ol>\n\n<p>That will refactor the both. Chris Kimpton does raise the important question as to whether the effort is worth it. </p>\n'}, {'answer_id': 70777, 'author': 'Jorge Ferreira', 'author_id': 6508, 'author_profile': 'https://Stackoverflow.com/users/6508', 'pm_score': 1, 'selected': True, 'text': '<p>Unless you have a strong reason for refactoring (because you are going to add more classes like those in near future) the penalty of changing the design for such a small and contrived example would overcome the gain in maintenance or overhead in this scenario. Anyhow here is a possible design based on generic and lambda expressions.</p>\n\n<pre><code>public class TwoLetterCode<T>\n{\n private readonly string value;\n\n public TwoLetterCode(string value, Func<string, string> predicate)\n {\n this.value = predicate(value);\n }\n\n public static T TryParse(string value, Func<string, T> predicate)\n {\n if (value == null)\n {\n return default(T);\n }\n\n if (value.Length > 2)\n {\n value = value.Substring(0, 2);\n }\n\n try\n {\n return predicate(value);\n }\n catch (ArgumentException)\n {\n return default(T);\n }\n }\n\n public string Value { get { return this.value; } }\n}\n\npublic class LanguageCode : TwoLetterCode<LanguageCode> {\n public LanguageCode(string language)\n : base(language, v => new CultureInfo(v).TwoLetterISOLanguageName)\n {\n }\n\n public static LanguageCode TryParse(string language)\n {\n return TwoLetterCode<LanguageCode>.TryParse(language, v => new LanguageCode(v));\n }\n}\n\npublic class RegionCode : TwoLetterCode<RegionCode>\n{\n public RegionCode(string language)\n : base(language, v => new CultureInfo(v).TwoLetterISORegionName)\n {\n }\n\n public static RegionCode TryParse(string language)\n {\n return TwoLetterCode<RegionCode>.TryParse(language, v => new RegionCode(v));\n }\n}\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11574/']
|
70,653 |
<p>I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.</p>
<p>I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).</p>
|
[{'answer_id': 70712, 'author': 'Toni Ruža', 'author_id': 6267, 'author_profile': 'https://Stackoverflow.com/users/6267', 'pm_score': 2, 'selected': False, 'text': '<p>I think you should make your own authentication method as you can make it fit your application best but use a library for encryption, such as <a href="http://www.pycrypto.org" rel="nofollow noreferrer">pycrypto</a> or some other more lightweight library.</p>\n\n<p>btw, if you need windows binaries for pycrypto you can get them <a href="http://www.voidspace.org.uk/python/modules.shtml#pycrypto" rel="nofollow noreferrer">here</a></p>\n'}, {'answer_id': 70832, 'author': 'Tony Meyer', 'author_id': 4966, 'author_profile': 'https://Stackoverflow.com/users/4966', 'pm_score': 0, 'selected': False, 'text': '<p>If you want simple, then use a dictionary where the keys are the usernames and the values are the passwords (encrypted with something like SHA256). <a href="http://docs.python.org/lib/module-pickle.html" rel="nofollow noreferrer">Pickle</a> it to/from disk (as this is a desktop application, I\'m assuming the overhead of keeping it in memory will be negligible).</p>\n\n<p>For example:</p>\n\n<pre><code>import pickle\nimport hashlib\n\n# Load from disk\npwd_file = "mypasswords"\nif os.path.exists(pwd_file):\n pwds = pickle.load(open(pwd_file, "rb"))\nelse:\n pwds = {}\n\n# Save to disk\npickle.dump(pwds, open(pwd_file, "wb"))\n\n# Add password\npwds[username] = hashlib.sha256(password).hexdigest()\n\n# Check password\nif pwds[username] = hashlib.sha256(password).hexdigest():\n print "Good"\nelse:\n print "No match"\n</code></pre>\n\n<p>Note that this stores the passwords as a <a href="http://docs.python.org/lib/module-hashlib.html" rel="nofollow noreferrer">hash</a> - so they are essentially unrecoverable. If you lose your password, you\'d get allocated a new one, not get the old one back.</p>\n'}, {'answer_id': 70915, 'author': 'dbr', 'author_id': 745, 'author_profile': 'https://Stackoverflow.com/users/745', 'pm_score': 1, 'selected': True, 'text': '<p>Treat the following as pseudo-code..</p>\n\n<pre><code>try:\n from hashlib import sha as hasher\nexcept ImportError:\n # You could probably exclude the try/except bit,\n # but older Python distros dont have hashlib.\n try:\n import sha as hasher\n except ImportError:\n import md5 as hasher\n\n\ndef hash_password(password):\n """Returns the hashed version of a string\n """\n return hasher.new( str(password) ).hexdigest()\n\ndef load_auth_file(path):\n """Loads a comma-seperated file.\n Important: make sure the username\n doesn\'t contain any commas!\n """\n # Open the file, or return an empty auth list.\n try:\n f = open(path)\n except IOError:\n print "Warning: auth file not found"\n return {}\n\n ret = {}\n for line in f.readlines():\n split_line = line.split(",")\n if len(split_line) > 2:\n print "Warning: Malformed line:"\n print split_line\n continue # skip it..\n else:\n username, password = split_line\n ret[username] = password\n #end if\n #end for\n return ret\n\ndef main():\n auth_file = "/home/blah/.myauth.txt"\n u = raw_input("Username:")\n p = raw_input("Password:") # getpass is probably better..\n if auth_file.has_key(u.strip()):\n if auth_file[u] == hash_password(p):\n # The hash matches the stored one\n print "Welcome, sir!"\n</code></pre>\n\n<p>Instead of using a comma-separated file, I would recommend using SQLite3 (which could be used for other settings and such.</p>\n\n<p>Also, remember that this isn\'t very secure - if the application is local, evil users could probably just replace the <code>~/.myauth.txt</code> file.. Local application auth is difficult to do well. You\'ll have to encrypt any data it reads using the users password, and generally be very careful.</p>\n'}, {'answer_id': 80008, 'author': 'tim.tadh', 'author_id': 14107, 'author_profile': 'https://Stackoverflow.com/users/14107', 'pm_score': 4, 'selected': False, 'text': '<p>dbr said:</p>\n\n<blockquote>\n<pre><code>def hash_password(password):\n """Returns the hashed version of a string\n """\n return hasher.new( str(password) ).hexdigest()\n</code></pre>\n</blockquote>\n\n<p>This is a really insecure way to hash passwords. You <em>don\'t</em> want to do this. If you want to know why read the <a href="http://www.openbsd.org/papers/bcrypt-paper.pdf" rel="noreferrer" title=""B-Crypt Paper">Bycrypt Paper</a> by the guys who did the password hashing system for OpenBSD. Additionally if want a good discussion on how passwords are broken check out <a href="http://www.securityfocus.com/columnists/388" rel="noreferrer">this interview</a> with the author of Jack the Ripper (the popular unix password cracker).</p>\n\n<p>Now B-Crypt is great but I have to admit I don\'t use this system because I didn\'t have the EKS-Blowfish algorithm available and did not want to implement it my self. I use a slightly updated version of the FreeBSD system which I will post below. The gist is this. Don\'t just hash the password. Salt the password then hash the password and repeat 10,000 or so times.</p>\n\n<p>If that didn\'t make sense here is the code: </p>\n\n<pre><code>#note I am using the Python Cryptography Toolkit\nfrom Crypto.Hash import SHA256\n\nHASH_REPS = 50000\n\ndef __saltedhash(string, salt):\n sha256 = SHA256.new()\n sha256.update(string)\n sha256.update(salt)\n for x in xrange(HASH_REPS): \n sha256.update(sha256.digest())\n if x % 10: sha256.update(salt)\n return sha256\n\ndef saltedhash_bin(string, salt):\n """returns the hash in binary format"""\n return __saltedhash(string, salt).digest()\n\ndef saltedhash_hex(string, salt):\n """returns the hash in hex format"""\n return __saltedhash(string, salt).hexdigest()\n</code></pre>\n\n<p>For deploying a system like this the key thing to consider is the HASH_REPS constant. This is the scalable cost factor in this system. You will need to do testing to determine what is the exceptable amount of time you want to wait for each hash to be computed versus the risk of an offline dictionary based attack on your password file. </p>\n\n<p>Security is hard, and the method I present is not the best way to do this, but it is significantly better than a simple hash. Additionally it is dead simple to implement. So even you don\'t choose a more complex solution this isn\'t the worst out there.</p>\n\n<p>hope this helps,\nTim</p>\n'}, {'answer_id': 1992484, 'author': 'Dustin Getz', 'author_id': 20003, 'author_profile': 'https://Stackoverflow.com/users/20003', 'pm_score': 0, 'selected': False, 'text': '<pre><code>import hashlib\nimport random\n\ndef gen_salt():\n salt_seed = str(random.getrandbits(128))\n salt = hashlib.sha256(salt_seed).hexdigest()\n return salt\n\ndef hash_password(password, salt):\n h = hashlib.sha256()\n h.update(salt)\n h.update(password)\n return h.hexdigest()\n\n#in datastore\npassword_stored_hash = "41e2282a9c18a6c051a0636d369ad2d4727f8c70f7ddeebd11e6f49d9e6ba13c"\nsalt_stored = "fcc64c0c2bc30156f79c9bdcabfadcd71030775823cb993f11a4e6b01f9632c3"\n\npassword_supplied = \'password\'\n\npassword_supplied_hash = hash_password(password_supplied, salt_stored)\nauthenticated = (password_supplied_hash == password_stored_hash)\nprint authenticated #True\n</code></pre>\n\n<p>see also <a href="https://stackoverflow.com/questions/1990722/gae-authenticate-to-a-3rd-party-site">gae-authenticate-to-a-3rd-party-site</a></p>\n'}, {'answer_id': 10495626, 'author': 'Anoop Augustine', 'author_id': 1322161, 'author_profile': 'https://Stackoverflow.com/users/1322161', 'pm_score': -1, 'selected': False, 'text': '<p>Use " md5 " it\'s much better than base64</p>\n\n<pre><code>>>> import md5\n>>> hh = md5.new()\n>>> hh.update(\'anoop\')\n>>> hh.digest\n<built-in method digest of _hashlib.HASH object at 0x01FE1E40>\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11563/']
|
70,668 |
<p>What is the best way to backup VMWare Servers (1.0.x)?
The virtual machines in question are our development environment, and run isololated from the main network (so you can't just copy data from virtual to real servers).</p>
<p>The image files are normally in use and locked when the server is running, so it is difficult to back these up with the machines running.</p>
<p>Currently: I manually pause the servers when I leave and have a scheduled task that runs at midnight to robocopy the images to a remote NAS. </p>
<p>Is there a better way to do this, ideally without having to remember to pause the virtual machines?</p>
|
[{'answer_id': 70692, 'author': 'Roger Lipscombe', 'author_id': 8446, 'author_profile': 'https://Stackoverflow.com/users/8446', 'pm_score': 0, 'selected': False, 'text': '<p>If I recall correctly, VMWare Server has a scripting interface, available via Perl or COM. You might be able to use that to automatically pause the VMs before running the backup.</p>\n\n<p>If your backup software was shadow-copy aware, that might work, too.</p>\n'}, {'answer_id': 70740, 'author': 'John Stauffer', 'author_id': 5874, 'author_profile': 'https://Stackoverflow.com/users/5874', 'pm_score': 4, 'selected': True, 'text': '<p>VMWare server includes the command line tool "vmware-cmd", which can be used to perform virtually any operation that can be performed through the console.</p>\n\n<p>In this case you would simply add a "vmware-cmd susepend" to your script before starting your backup, and a "vmware-cmd start" after the backup is completed.</p>\n\n<p>We use vmware-server as part of our build system to provide a known environment to run automated DB upgrades against, so we end up rolling back state as part of each build (driven by CruiseControl), and have found this interface to be rock solid.</p>\n\n<pre><code>Usage: /usr/bin/vmware-cmd <options> <vm-cfg-path> <vm-action> <arguments>\n /usr/bin/vmware-cmd -s <options> <server-action> <arguments>\n\n Options:\n Connection Options:\n -H <host> specifies an alternative host (if set, -U and -P must also be set)\n -O <port> specifies an alternative port\n -U <username> specifies a user\n -P <password> specifies a password\n General Options:\n -h More detailed help.\n -q Quiet. Minimal output\n -v Verbose.\n\n Server Operations:\n /usr/bin/vmware-cmd -l \n /usr/bin/vmware-cmd -s register <config_file_path>\n /usr/bin/vmware-cmd -s unregister <config_file_path>\n /usr/bin/vmware-cmd -s getresource <variable>\n /usr/bin/vmware-cmd -s setresource <variable> <value>\n\n VM Operations:\n /usr/bin/vmware-cmd <cfg> getconnectedusers\n /usr/bin/vmware-cmd <cfg> getstate\n /usr/bin/vmware-cmd <cfg> start <powerop_mode>\n /usr/bin/vmware-cmd <cfg> stop <powerop_mode>\n /usr/bin/vmware-cmd <cfg> reset <powerop_mode>\n /usr/bin/vmware-cmd <cfg> suspend <powerop_mode>\n /usr/bin/vmware-cmd <cfg> setconfig <variable> <value>\n /usr/bin/vmware-cmd <cfg> getconfig <variable>\n /usr/bin/vmware-cmd <cfg> setguestinfo <variable> <value>\n /usr/bin/vmware-cmd <cfg> getguestinfo <variable>\n /usr/bin/vmware-cmd <cfg> getid\n /usr/bin/vmware-cmd <cfg> getpid\n /usr/bin/vmware-cmd <cfg> getproductinfo <prodinfo>\n /usr/bin/vmware-cmd <cfg> connectdevice <device_name>\n /usr/bin/vmware-cmd <cfg> disconnectdevice <device_name>\n /usr/bin/vmware-cmd <cfg> getconfigfile\n /usr/bin/vmware-cmd <cfg> getheartbeat\n /usr/bin/vmware-cmd <cfg> getuptime\n /usr/bin/vmware-cmd <cfg> getremoteconnections\n /usr/bin/vmware-cmd <cfg> gettoolslastactive\n /usr/bin/vmware-cmd <cfg> getresource <variable>\n /usr/bin/vmware-cmd <cfg> setresource <variable> <value>\n /usr/bin/vmware-cmd <cfg> setrunasuser <username> <password>\n /usr/bin/vmware-cmd <cfg> getrunasuser\n /usr/bin/vmware-cmd <cfg> getcapabilities\n /usr/bin/vmware-cmd <cfg> addredo <disk_device_name>\n /usr/bin/vmware-cmd <cfg> commit <disk_device_name> <level> <freeze> <wait>\n /usr/bin/vmware-cmd <cfg> answer\n</code></pre>\n'}, {'answer_id': 129123, 'author': 'seisyll', 'author_id': 21815, 'author_profile': 'https://Stackoverflow.com/users/21815', 'pm_score': 0, 'selected': False, 'text': '<p>There is a tool called (ahem) Hobocopy which will copy locked VM files. I would recommend taking a snapshot of the VM and then backing up the VMDK. Then merge the snapshot after the copy is complete. </p>\n'}, {'answer_id': 551985, 'author': 'Martin Beckett', 'author_id': 10897, 'author_profile': 'https://Stackoverflow.com/users/10897', 'pm_score': 2, 'selected': False, 'text': '<p>Worth looking at rsync? If only part of a large image file is changing then rsync might be the fastest way to copy any changes.</p>\n'}, {'answer_id': 2129965, 'author': 'MadCAt', 'author_id': 258119, 'author_profile': 'https://Stackoverflow.com/users/258119', 'pm_score': 1, 'selected': False, 'text': '<p>I found an easy to follow guide for backing up VM\'s in vmware server 2 here: <a href="http://www.bdts.com.au/tips/46-vmware/57-backing-up-vmware-server-2-.html" rel="nofollow noreferrer">Backup VMware Server 2</a></p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11538/']
|
70,681 |
<p>Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection, like MySQLdb? The commented version of the below works with MySQLdb, the comments make it work with Psycopg2:</p>
<pre><code>results = {'felicitas': 3, 'volumes': 8, 'acillevs': 1, 'mosaics': 13, 'perat\xe9': 1, 'representative': 6....}
for item in sorted(results):
try:
cur.execute("""insert into resultstab values ('%s', %d)""" % (item, results[item]))
print item, results[item]
# conn.commit()
except:
# conn=psycopg2.connect(user='bvm', database='wdb', password='redacted')
# cur=conn.cursor()
print 'choked on', item
continue
</code></pre>
<p>This must slow things down, could anyone give a suggestion for passing over formatting errors? Obviously the above chokes on apostrophes, but is there a way to make it pass over that without getting something like the following, or committing, reconnecting, etc?:</p>
<pre><code>agreement 19
agreements 1
agrees 1
agrippa 9
choked on agrippa's
choked on agrippina
</code></pre>
|
[{'answer_id': 70692, 'author': 'Roger Lipscombe', 'author_id': 8446, 'author_profile': 'https://Stackoverflow.com/users/8446', 'pm_score': 0, 'selected': False, 'text': '<p>If I recall correctly, VMWare Server has a scripting interface, available via Perl or COM. You might be able to use that to automatically pause the VMs before running the backup.</p>\n\n<p>If your backup software was shadow-copy aware, that might work, too.</p>\n'}, {'answer_id': 70740, 'author': 'John Stauffer', 'author_id': 5874, 'author_profile': 'https://Stackoverflow.com/users/5874', 'pm_score': 4, 'selected': True, 'text': '<p>VMWare server includes the command line tool "vmware-cmd", which can be used to perform virtually any operation that can be performed through the console.</p>\n\n<p>In this case you would simply add a "vmware-cmd susepend" to your script before starting your backup, and a "vmware-cmd start" after the backup is completed.</p>\n\n<p>We use vmware-server as part of our build system to provide a known environment to run automated DB upgrades against, so we end up rolling back state as part of each build (driven by CruiseControl), and have found this interface to be rock solid.</p>\n\n<pre><code>Usage: /usr/bin/vmware-cmd <options> <vm-cfg-path> <vm-action> <arguments>\n /usr/bin/vmware-cmd -s <options> <server-action> <arguments>\n\n Options:\n Connection Options:\n -H <host> specifies an alternative host (if set, -U and -P must also be set)\n -O <port> specifies an alternative port\n -U <username> specifies a user\n -P <password> specifies a password\n General Options:\n -h More detailed help.\n -q Quiet. Minimal output\n -v Verbose.\n\n Server Operations:\n /usr/bin/vmware-cmd -l \n /usr/bin/vmware-cmd -s register <config_file_path>\n /usr/bin/vmware-cmd -s unregister <config_file_path>\n /usr/bin/vmware-cmd -s getresource <variable>\n /usr/bin/vmware-cmd -s setresource <variable> <value>\n\n VM Operations:\n /usr/bin/vmware-cmd <cfg> getconnectedusers\n /usr/bin/vmware-cmd <cfg> getstate\n /usr/bin/vmware-cmd <cfg> start <powerop_mode>\n /usr/bin/vmware-cmd <cfg> stop <powerop_mode>\n /usr/bin/vmware-cmd <cfg> reset <powerop_mode>\n /usr/bin/vmware-cmd <cfg> suspend <powerop_mode>\n /usr/bin/vmware-cmd <cfg> setconfig <variable> <value>\n /usr/bin/vmware-cmd <cfg> getconfig <variable>\n /usr/bin/vmware-cmd <cfg> setguestinfo <variable> <value>\n /usr/bin/vmware-cmd <cfg> getguestinfo <variable>\n /usr/bin/vmware-cmd <cfg> getid\n /usr/bin/vmware-cmd <cfg> getpid\n /usr/bin/vmware-cmd <cfg> getproductinfo <prodinfo>\n /usr/bin/vmware-cmd <cfg> connectdevice <device_name>\n /usr/bin/vmware-cmd <cfg> disconnectdevice <device_name>\n /usr/bin/vmware-cmd <cfg> getconfigfile\n /usr/bin/vmware-cmd <cfg> getheartbeat\n /usr/bin/vmware-cmd <cfg> getuptime\n /usr/bin/vmware-cmd <cfg> getremoteconnections\n /usr/bin/vmware-cmd <cfg> gettoolslastactive\n /usr/bin/vmware-cmd <cfg> getresource <variable>\n /usr/bin/vmware-cmd <cfg> setresource <variable> <value>\n /usr/bin/vmware-cmd <cfg> setrunasuser <username> <password>\n /usr/bin/vmware-cmd <cfg> getrunasuser\n /usr/bin/vmware-cmd <cfg> getcapabilities\n /usr/bin/vmware-cmd <cfg> addredo <disk_device_name>\n /usr/bin/vmware-cmd <cfg> commit <disk_device_name> <level> <freeze> <wait>\n /usr/bin/vmware-cmd <cfg> answer\n</code></pre>\n'}, {'answer_id': 129123, 'author': 'seisyll', 'author_id': 21815, 'author_profile': 'https://Stackoverflow.com/users/21815', 'pm_score': 0, 'selected': False, 'text': '<p>There is a tool called (ahem) Hobocopy which will copy locked VM files. I would recommend taking a snapshot of the VM and then backing up the VMDK. Then merge the snapshot after the copy is complete. </p>\n'}, {'answer_id': 551985, 'author': 'Martin Beckett', 'author_id': 10897, 'author_profile': 'https://Stackoverflow.com/users/10897', 'pm_score': 2, 'selected': False, 'text': '<p>Worth looking at rsync? If only part of a large image file is changing then rsync might be the fastest way to copy any changes.</p>\n'}, {'answer_id': 2129965, 'author': 'MadCAt', 'author_id': 258119, 'author_profile': 'https://Stackoverflow.com/users/258119', 'pm_score': 1, 'selected': False, 'text': '<p>I found an easy to follow guide for backing up VM\'s in vmware server 2 here: <a href="http://www.bdts.com.au/tips/46-vmware/57-backing-up-vmware-server-2-.html" rel="nofollow noreferrer">Backup VMware Server 2</a></p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11596/']
|
70,682 |
<p>I am looking for details of the VTable structure, order and contents, and the location of the vtable pointers within objects. </p>
<p>Ideally, this will cover single inheritance, multiple inheritance, and virtual inheritance.</p>
<p>References to external documentation would also be appreciated</p>
<p>Documentation of GCC 4.0x class layout is <a href="http://www.cse.wustl.edu/~mdeters/seminar/fall2005/mi.html#virtual" rel="noreferrer">here</a> and the Itanium, and more broadly GNU, ABI layout documents are <a href="http://www.codesourcery.com/public/cxx-abi/abi.html#general" rel="noreferrer">here</a>. </p>
|
[{'answer_id': 25674843, 'author': 'GlGuru', 'author_id': 497840, 'author_profile': 'https://Stackoverflow.com/users/497840', 'pm_score': -1, 'selected': False, 'text': '<p>Most of the compiler implementations that I have seen just "embed" the base object into the derived object. It becomes irrelevant where the vtable is kept because the relative offset into the object will just be added at compile time as references are evaluated. </p>\n\n<p>Multiple and virtual inheritance are more complicated and can require a different offset depending on what is being accessed. </p>\n\n<p>I highly recommend reading this article on Code Project: <a href="http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible" rel="nofollow">The Impossibly Fast C++ Delegates</a></p>\n\n<p>It brilliantly gives a broad picture of how different compilers handle various aspects of inheritance. Fantastic read if you are interested in the low level workings of different compilers. </p>\n\n<p>Edit: I linked the wrong article over there. Corrected. </p>\n'}, {'answer_id': 28155780, 'author': 'LThode', 'author_id': 3657206, 'author_profile': 'https://Stackoverflow.com/users/3657206', 'pm_score': 4, 'selected': False, 'text': '<p>A virtual table is generally treated as an array of function pointers, although compilers are free to put data pointers (in MI and VI scenarios, or to typeinfos), integers (for fixups), or sentinel elements (such as NULL pointers) into it as well. The layout is generally compiler-specific (or ABI-specific where multiple C++ compilers share an ABI), but stable provided the classes being compiled have stable interfaces (otherwise you\'d have to recompile your code all the time, and that\'s a drag). There are also additional tables that are needed to handle corner cases involving virtual and multiple inheritance, and to make sure that virtual calls during derived class construction behave as the Standard says they should under those circumstances (those are what the VTTs and construction tables in the output below are for).</p>\n\n<p>As to the specific case of GCC 4.x: the <code>-fdump-class-hierarchy</code> switch indeed acts as described (and then some). I tested it on <a href="http://coliru.stacked-crooked.com/a/16d53eb062d38bec" rel="noreferrer">Coliru</a> using the sample code below:</p>\n\n<pre><code>struct Base\n{\n virtual ~Base() {}\n virtual void f() = 0;\n};\n\nstruct OtherBase\n{\n virtual ~OtherBase() {}\n virtual void g() {}\n};\n\nstruct Derived: public Base\n{\n virtual ~Derived() {}\n virtual void f() {}\n};\n\nstruct MultiplyDerived: public Base, public OtherBase\n{\n virtual ~MultiplyDerived() {}\n virtual void f() {}\n virtual void g() {}\n};\n\nstruct OtherDerived: public Base\n{\n virtual ~OtherDerived() {}\n virtual void f() {}\n};\n\nstruct DiamondDerived: public Derived, public OtherDerived\n{\n virtual ~DiamondDerived() {}\n virtual void f() {}\n};\n\nstruct VirtuallyDerived: virtual public Base\n{\n virtual ~VirtuallyDerived() {}\n virtual void f() {}\n};\n\nstruct OtherVirtuallyDerived: virtual public Base\n{\n virtual ~OtherVirtuallyDerived() {}\n virtual void f() {}\n};\n\nstruct VirtuallyDiamondDerived: public VirtuallyDerived, public OtherVirtuallyDerived\n{\n virtual ~VirtuallyDiamondDerived() {}\n virtual void f() {}\n};\n\nstruct DoublyVirtuallyDiamondDerived: virtual public VirtuallyDerived, virtual public OtherVirtuallyDerived\n{\n virtual ~DoublyVirtuallyDiamondDerived() {}\n virtual void f() {}\n};\n\nstruct MixedVirtuallyDerived: virtual public Base, public OtherBase\n{\n virtual ~MixedVirtuallyDerived() {}\n};\n\nstruct MixedVirtuallyDiamondDerived: public VirtuallyDerived, public MixedVirtuallyDerived\n{\n virtual ~MixedVirtuallyDiamondDerived() {}\n virtual void f() {}\n virtual void g() {}\n};\n\nstruct VirtuallyMultiplyDerived: virtual public Base, virtual public OtherBase\n{\n virtual ~VirtuallyMultiplyDerived() {}\n};\n\nstruct OtherVirtuallyMultiplyDerived: virtual public Base, virtual public OtherBase\n{\n virtual ~OtherVirtuallyMultiplyDerived() {}\n};\n\nstruct MultiplyVirtuallyDiamondDerived: public VirtuallyMultiplyDerived, public OtherVirtuallyMultiplyDerived\n{\n virtual ~MultiplyVirtuallyDiamondDerived() {}\n virtual void f() {}\n virtual void g() {}\n};\n</code></pre>\n\n<p>and received from G++ (mangled name guide: TI\'s are typeinfos, TV\'s are vtables, and Th\'s and Tv\'s are thunks used to make correct virtual calls in the presence of multiple and/or virtual inheritance):</p>\n\n<pre>\nVtable for Base\n\nBase::_ZTV4Base: 5u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI4Base)\n\n16 0u\n\n24 0u\n\n32 (int (*)(...))__cxa_pure_virtual\n\n\nClass Base\n\n size=8 align=8\n\n base size=8 base align=8\n\nBase (0x0x7fd42c0355a0) 0 nearly-empty\n\n vptr=((& Base::_ZTV4Base) + 16u)\n\n\nVtable for OtherBase\n\nOtherBase::_ZTV9OtherBase: 5u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI9OtherBase)\n\n16 (int (*)(...))OtherBase::~OtherBase\n\n24 (int (*)(...))OtherBase::~OtherBase\n\n32 (int (*)(...))OtherBase::g\n\n\nClass OtherBase\n\n size=8 align=8\n\n base size=8 base align=8\n\nOtherBase (0x0x7fd42c035600) 0 nearly-empty\n\n vptr=((& OtherBase::_ZTV9OtherBase) + 16u)\n\n\nVtable for Derived\n\nDerived::_ZTV7Derived: 5u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI7Derived)\n\n16 (int (*)(...))Derived::~Derived\n\n24 (int (*)(...))Derived::~Derived\n\n32 (int (*)(...))Derived::f\n\n\nClass Derived\n\n size=8 align=8\n\n base size=8 base align=8\n\nDerived (0x0x7fd42c02d138) 0 nearly-empty\n\n vptr=((& Derived::_ZTV7Derived) + 16u)\n\n Base (0x0x7fd42c035660) 0 nearly-empty\n\n primary-for Derived (0x0x7fd42c02d138)\n\n\nVtable for MultiplyDerived\n\nMultiplyDerived::_ZTV15MultiplyDerived: 11u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI15MultiplyDerived)\n\n16 (int (*)(...))MultiplyDerived::~MultiplyDerived\n\n24 (int (*)(...))MultiplyDerived::~MultiplyDerived\n\n32 (int (*)(...))MultiplyDerived::f\n\n40 (int (*)(...))MultiplyDerived::g\n\n48 (int (*)(...))-8\n\n56 (int (*)(...))(& _ZTI15MultiplyDerived)\n\n64 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerivedD1Ev\n\n72 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerivedD0Ev\n\n80 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerived1gEv\n\n\nClass MultiplyDerived\n\n size=16 align=8\n\n base size=16 base align=8\n\nMultiplyDerived (0x0x7fd42c04aaf0) 0\n\n vptr=((& MultiplyDerived::_ZTV15MultiplyDerived) + 16u)\n\n Base (0x0x7fd42c0356c0) 0 nearly-empty\n\n primary-for MultiplyDerived (0x0x7fd42c04aaf0)\n\n OtherBase (0x0x7fd42c035720) 8 nearly-empty\n\n vptr=((& MultiplyDerived::_ZTV15MultiplyDerived) + 64u)\n\n\nVtable for OtherDerived\n\nOtherDerived::_ZTV12OtherDerived: 5u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI12OtherDerived)\n\n16 (int (*)(...))OtherDerived::~OtherDerived\n\n24 (int (*)(...))OtherDerived::~OtherDerived\n\n32 (int (*)(...))OtherDerived::f\n\n\nClass OtherDerived\n\n size=8 align=8\n\n base size=8 base align=8\n\nOtherDerived (0x0x7fd42c02d1a0) 0 nearly-empty\n\n vptr=((& OtherDerived::_ZTV12OtherDerived) + 16u)\n\n Base (0x0x7fd42c035780) 0 nearly-empty\n\n primary-for OtherDerived (0x0x7fd42c02d1a0)\n\n\nVtable for DiamondDerived\n\nDiamondDerived::_ZTV14DiamondDerived: 10u entries\n\n0 (int (*)(...))0\n\n8 (int (*)(...))(& _ZTI14DiamondDerived)\n\n16 (int (*)(...))DiamondDerived::~DiamondDerived\n\n24 (int (*)(...))DiamondDerived::~DiamondDerived\n\n32 (int (*)(...))DiamondDerived::f\n\n40 (int (*)(...))-8\n\n48 (int (*)(...))(& _ZTI14DiamondDerived)\n\n56 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerivedD1Ev\n\n64 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerivedD0Ev\n\n72 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerived1fEv\n\n\nClass DiamondDerived\n\n size=16 align=8\n\n base size=16 base align=8\n\nDiamondDerived (0x0x7fd42c0625b0) 0\n\n vptr=((& DiamondDerived::_ZTV14DiamondDerived) + 16u)\n\n Derived (0x0x7fd42c02d208) 0 nearly-empty\n\n primary-for DiamondDerived (0x0x7fd42c0625b0)\n\n Base (0x0x7fd42c0357e0) 0 nearly-empty\n\n primary-for Derived (0x0x7fd42c02d208)\n\n OtherDerived (0x0x7fd42c02d270) 8 nearly-empty\n\n vptr=((& DiamondDerived::_ZTV14DiamondDerived) + 56u)\n\n Base (0x0x7fd42c035840) 8 nearly-empty\n\n primary-for OtherDerived (0x0x7fd42c02d270)\n\n\nVtable for VirtuallyDerived\n\nVirtuallyDerived::_ZTV16VirtuallyDerived: 8u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI16VirtuallyDerived)\n\n40 (int (*)(...))VirtuallyDerived::~VirtuallyDerived\n\n48 (int (*)(...))VirtuallyDerived::~VirtuallyDerived\n\n56 (int (*)(...))VirtuallyDerived::f\n\n\nVTT for VirtuallyDerived\n\nVirtuallyDerived::_ZTT16VirtuallyDerived: 2u entries\n\n0 ((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u)\n\n8 ((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u)\n\n\nClass VirtuallyDerived\n\n size=8 align=8\n\n base size=8 base align=8\n\nVirtuallyDerived (0x0x7fd42c02d2d8) 0 nearly-empty\n\n vptridx=0u vptr=((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u)\n\n Base (0x0x7fd42c0358a0) 0 nearly-empty virtual\n\n primary-for VirtuallyDerived (0x0x7fd42c02d2d8)\n\n vptridx=8u vbaseoffset=-40\n\n\nVtable for OtherVirtuallyDerived\n\nOtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived: 8u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)\n\n40 (int (*)(...))OtherVirtuallyDerived::~OtherVirtuallyDerived\n\n48 (int (*)(...))OtherVirtuallyDerived::~OtherVirtuallyDerived\n\n56 (int (*)(...))OtherVirtuallyDerived::f\n\n\nVTT for OtherVirtuallyDerived\n\nOtherVirtuallyDerived::_ZTT21OtherVirtuallyDerived: 2u entries\n\n0 ((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u)\n\n8 ((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u)\n\n\nClass OtherVirtuallyDerived\n\n size=8 align=8\n\n base size=8 base align=8\n\nOtherVirtuallyDerived (0x0x7fd42c02d340) 0 nearly-empty\n\n vptridx=0u vptr=((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u)\n\n Base (0x0x7fd42c035900) 0 nearly-empty virtual\n\n primary-for OtherVirtuallyDerived (0x0x7fd42c02d340)\n\n vptridx=8u vbaseoffset=-40\n\n\nVtable for VirtuallyDiamondDerived\n\nVirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived: 16u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI23VirtuallyDiamondDerived)\n\n40 (int (*)(...))VirtuallyDiamondDerived::~VirtuallyDiamondDerived\n\n48 (int (*)(...))VirtuallyDiamondDerived::~VirtuallyDiamondDerived\n\n56 (int (*)(...))VirtuallyDiamondDerived::f\n\n64 18446744073709551608u\n\n72 18446744073709551608u\n\n80 18446744073709551608u\n\n88 (int (*)(...))-8\n\n96 (int (*)(...))(& _ZTI23VirtuallyDiamondDerived)\n\n104 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerivedD1Ev\n\n112 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerivedD0Ev\n\n120 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerived1fEv\n\n\nConstruction vtable for VirtuallyDerived (0x0x7fd42c02d3a8 instance) in VirtuallyDiamondDerived\n\nVirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI16VirtuallyDerived)\n\n40 0u\n\n48 0u\n\n56 (int (*)(...))VirtuallyDerived::f\n\n\nConstruction vtable for OtherVirtuallyDerived (0x0x7fd42c02d410 instance) in VirtuallyDiamondDerived\n\nVirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived: 15u entries\n\n0 18446744073709551608u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)\n\n40 0u\n\n48 0u\n\n56 (int (*)(...))OtherVirtuallyDerived::f\n\n64 8u\n\n72 8u\n\n80 (int (*)(...))8\n\n88 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)\n\n96 0u\n\n104 0u\n\n112 (int (*)(...))OtherVirtuallyDerived::_ZTv0_n32_N21OtherVirtuallyDerived1fEv\n\n\nVTT for VirtuallyDiamondDerived\n\nVirtuallyDiamondDerived::_ZTT23VirtuallyDiamondDerived: 7u entries\n\n0 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u)\n\n8 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n16 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n24 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 40u)\n\n32 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 96u)\n\n40 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u)\n\n48 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 104u)\n\n\nClass VirtuallyDiamondDerived\n\n size=16 align=8\n\n base size=16 base align=8\n\nVirtuallyDiamondDerived (0x0x7fd42c07e460) 0\n\n vptridx=0u vptr=((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u)\n\n VirtuallyDerived (0x0x7fd42c02d3a8) 0 nearly-empty\n\n primary-for VirtuallyDiamondDerived (0x0x7fd42c07e460)\n\n subvttidx=8u\n\n Base (0x0x7fd42c035960) 0 nearly-empty virtual\n\n primary-for VirtuallyDerived (0x0x7fd42c02d3a8)\n\n vptridx=40u vbaseoffset=-40\n\n OtherVirtuallyDerived (0x0x7fd42c02d410) 8 nearly-empty\n\n lost-primary\n\n subvttidx=24u vptridx=48u vptr=((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 104u)\n\n Base (0x0x7fd42c035960) alternative-path\n\n\nVtable for DoublyVirtuallyDiamondDerived\n\nDoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived: 18u entries\n\n0 8u\n\n8 0u\n\n16 0u\n\n24 0u\n\n32 0u\n\n40 (int (*)(...))0\n\n48 (int (*)(...))(& _ZTI29DoublyVirtuallyDiamondDerived)\n\n56 (int (*)(...))DoublyVirtuallyDiamondDerived::~DoublyVirtuallyDiamondDerived\n\n64 (int (*)(...))DoublyVirtuallyDiamondDerived::~DoublyVirtuallyDiamondDerived\n\n72 (int (*)(...))DoublyVirtuallyDiamondDerived::f\n\n80 18446744073709551608u\n\n88 18446744073709551608u\n\n96 18446744073709551608u\n\n104 (int (*)(...))-8\n\n112 (int (*)(...))(& _ZTI29DoublyVirtuallyDiamondDerived)\n\n120 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n24_N29DoublyVirtuallyDiamondDerivedD1Ev\n\n128 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n24_N29DoublyVirtuallyDiamondDerivedD0Ev\n\n136 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n32_N29DoublyVirtuallyDiamondDerived1fEv\n\n\nConstruction vtable for VirtuallyDerived in DoublyVirtuallyDiamondDerived\n\nDoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI16VirtuallyDerived)\n\n40 0u\n\n48 0u\n\n56 (int (*)(...))VirtuallyDerived::f\n\n\nConstruction vtable for OtherVirtuallyDerived in DoublyVirtuallyDiamondDerived\n\nDoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived: 15u entries\n\n0 18446744073709551608u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)\n\n40 0u\n\n48 0u\n\n56 (int (*)(...))OtherVirtuallyDerived::f\n\n64 8u\n\n72 8u\n\n80 (int (*)(...))8\n\n88 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)\n\n96 0u\n\n104 0u\n\n112 (int (*)(...))OtherVirtuallyDerived::_ZTv0_n32_N21OtherVirtuallyDerived1fEv\n\n\nVTT for DoublyVirtuallyDiamondDerived\n\nDoublyVirtuallyDiamondDerived::_ZTT29DoublyVirtuallyDiamondDerived: 8u entries\n\n0 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)\n\n8 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)\n\n16 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)\n\n24 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 120u)\n\n32 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n40 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n48 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 40u)\n\n56 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 96u)\n\n\nClass DoublyVirtuallyDiamondDerived\n\n size=16 align=8\n\n base size=8 base align=8\n\nDoublyVirtuallyDiamondDerived (0x0x7fd42c07ea10) 0 nearly-empty\n\n vptridx=0u vptr=((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)\n\n VirtuallyDerived (0x0x7fd42c02d478) 0 nearly-empty virtual\n\n primary-for DoublyVirtuallyDiamondDerived (0x0x7fd42c07ea10)\n\n subvttidx=32u vptridx=8u vbaseoffset=-48\n\n Base (0x0x7fd42c035a80) 0 nearly-empty virtual\n\n primary-for VirtuallyDerived (0x0x7fd42c02d478)\n\n vptridx=16u vbaseoffset=-40\n\n OtherVirtuallyDerived (0x0x7fd42c02d4e0) 8 nearly-empty virtual\n\n lost-primary\n\n subvttidx=48u vptridx=24u vbaseoffset=-56 vptr=((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 120u)\n\n Base (0x0x7fd42c035a80) alternative-path\n\n\nVtable for MixedVirtuallyDerived\n\nMixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived: 13u entries\n\n0 8u\n\n8 (int (*)(...))0\n\n16 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)\n\n24 0u\n\n32 0u\n\n40 (int (*)(...))OtherBase::g\n\n48 0u\n\n56 18446744073709551608u\n\n64 (int (*)(...))-8\n\n72 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)\n\n80 0u\n\n88 0u\n\n96 (int (*)(...))__cxa_pure_virtual\n\n\nVTT for MixedVirtuallyDerived\n\nMixedVirtuallyDerived::_ZTT21MixedVirtuallyDerived: 2u entries\n\n0 ((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 24u)\n\n8 ((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 80u)\n\n\nClass MixedVirtuallyDerived\n\n size=16 align=8\n\n base size=8 base align=8\n\nMixedVirtuallyDerived (0x0x7fd42c07eee0) 0 nearly-empty\n\n vptridx=0u vptr=((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 24u)\n\n Base (0x0x7fd42c035c60) 8 nearly-empty virtual\n\n vptridx=8u vbaseoffset=-24 vptr=((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 80u)\n\n OtherBase (0x0x7fd42c035cc0) 0 nearly-empty\n\n primary-for MixedVirtuallyDerived (0x0x7fd42c07eee0)\n\n\nVtable for MixedVirtuallyDiamondDerived\n\nMixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived: 15u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI28MixedVirtuallyDiamondDerived)\n\n40 (int (*)(...))MixedVirtuallyDiamondDerived::~MixedVirtuallyDiamondDerived\n\n48 (int (*)(...))MixedVirtuallyDiamondDerived::~MixedVirtuallyDiamondDerived\n\n56 (int (*)(...))MixedVirtuallyDiamondDerived::f\n\n64 (int (*)(...))MixedVirtuallyDiamondDerived::g\n\n72 18446744073709551608u\n\n80 (int (*)(...))-8\n\n88 (int (*)(...))(& _ZTI28MixedVirtuallyDiamondDerived)\n\n96 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerivedD1Ev\n\n104 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerivedD0Ev\n\n112 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerived1gEv\n\n\nConstruction vtable for VirtuallyDerived (0x0x7fd42c02d750 instance) in MixedVirtuallyDiamondDerived\n\nMixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries\n\n0 0u\n\n8 0u\n\n16 0u\n\n24 (int (*)(...))0\n\n32 (int (*)(...))(& _ZTI16VirtuallyDerived)\n\n40 0u\n\n48 0u\n\n56 (int (*)(...))VirtuallyDerived::f\n\n\nConstruction vtable for MixedVirtuallyDerived (0x0x7fd42c0b5380 instance) in MixedVirtuallyDiamondDerived\n\nMixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived: 13u entries\n\n0 18446744073709551608u\n\n8 (int (*)(...))0\n\n16 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)\n\n24 0u\n\n32 0u\n\n40 (int (*)(...))OtherBase::g\n\n48 0u\n\n56 8u\n\n64 (int (*)(...))8\n\n72 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)\n\n80 0u\n\n88 0u\n\n96 (int (*)(...))__cxa_pure_virtual\n\n\nVTT for MixedVirtuallyDiamondDerived\n\nMixedVirtuallyDiamondDerived::_ZTT28MixedVirtuallyDiamondDerived: 7u entries\n\n0 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u)\n\n8 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n16 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)\n\n24 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived) + 24u)\n\n32 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived) + 80u)\n\n40 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u)\n\n48 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 96u)\n\n\nClass MixedVirtuallyDiamondDerived\n\n size=16 align=8\n\n base size=16 base align=8\n\nMixedVirtuallyDiamondDerived (0x0x7fd42c0b5310) 0\n\n vptridx=0u vptr=((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u)\n\n VirtuallyDerived (0x0x7fd42c02d750) 0 nearly-empty\n\n primary-for MixedVirtuallyDiamondDerived (0x0x7fd42c0b5310)\n\n subvttidx=8u\n\n Base (0x0x7fd42c035d20) 0 nearly-empty virtual\n\n primary-for VirtuallyDerived (0x0x7fd42c02d750)\n\n vptridx=40u vbaseoffset=-40\n\n MixedVirtuallyDerived (0x0x7fd42c0b5380) 8 nearly-empty\n\n subvttidx=24u vptridx=48u vptr=((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 96u)\n\n Base (0x0x7fd42c035d20) alternative-path\n\n OtherBase (0x0x7fd42c035d80) 8 nearly-empty\n\n primary-for MixedVirtuallyDerived (0x0x7fd42c0b5380)\n\n\nVtable for VirtuallyMultiplyDerived\n\nVirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived: 16u entries\n\n0 8u\n\n8 0u\n\n16 0u\n\n24 0u\n\n32 (int (*)(...))0\n\n40 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)\n\n48 0u\n\n56 0u\n\n64 (int (*)(...))__cxa_pure_virtual\n\n72 0u\n\n80 18446744073709551608u\n\n88 (int (*)(...))-8\n\n96 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)\n\n104 0u\n\n112 0u\n\n120 (int (*)(...))OtherBase::g\n\n\nVTT for VirtuallyMultiplyDerived\n\nVirtuallyMultiplyDerived::_ZTT24VirtuallyMultiplyDerived: 3u entries\n\n0 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u)\n\n8 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u)\n\n16 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 104u)\n\n\nClass VirtuallyMultiplyDerived\n\n size=16 align=8\n\n base size=8 base align=8\n\nVirtuallyMultiplyDerived (0x0x7fd42c0b59a0) 0 nearly-empty\n\n vptridx=0u vptr=((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u)\n\n Base (0x0x7fd42c035e40) 0 nearly-empty virtual\n\n primary-for VirtuallyMultiplyDerived (0x0x7fd42c0b59a0)\n\n vptridx=8u vbaseoffset=-40\n\n OtherBase (0x0x7fd42c035ea0) 8 nearly-empty virtual\n\n vptridx=16u vbaseoffset=-48 vptr=((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 104u)\n\n\nVtable for OtherVirtuallyMultiplyDerived\n\nOtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived: 16u entries\n\n0 8u\n\n8 0u\n\n16 0u\n\n24 0u\n\n32 (int (*)(...))0\n\n40 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)\n\n48 0u\n\n56 0u\n\n64 (int (*)(...))__cxa_pure_virtual\n\n72 0u\n\n80 18446744073709551608u\n\n88 (int (*)(...))-8\n\n96 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)\n\n104 0u\n\n112 0u\n\n120 (int (*)(...))OtherBase::g\n\n\nVTT for OtherVirtuallyMultiplyDerived\n\nOtherVirtuallyMultiplyDerived::_ZTT29OtherVirtuallyMultiplyDerived: 3u entries\n\n0 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u)\n\n8 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u)\n\n16 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 104u)\n\n\nClass OtherVirtuallyMultiplyDerived\n\n size=16 align=8\n\n base size=8 base align=8\n\nOtherVirtuallyMultiplyDerived (0x0x7fd42c0b5d90) 0 nearly-empty\n\n vptridx=0u vptr=((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u)\n\n Base (0x0x7fd42c035f00) 0 nearly-empty virtual\n\n primary-for OtherVirtuallyMultiplyDerived (0x0x7fd42c0b5d90)\n\n vptridx=8u vbaseoffset=-40\n\n OtherBase (0x0x7fd42c035f60) 8 nearly-empty virtual\n\n vptridx=16u vbaseoffset=-48 vptr=((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 104u)\n\n\nVtable for MultiplyVirtuallyDiamondDerived\n\nMultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived: 26u entries\n\n0 16u\n\n8 0u\n\n16 0u\n\n24 0u\n\n32 (int (*)(...))0\n\n40 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived)\n\n48 (int (*)(...))MultiplyVirtuallyDiamondDerived::~MultiplyVirtuallyDiamondDerived\n\n56 (int (*)(...))MultiplyVirtuallyDiamondDerived::~MultiplyVirtuallyDiamondDerived\n\n64 (int (*)(...))MultiplyVirtuallyDiamondDerived::f\n\n72 (int (*)(...))MultiplyVirtuallyDiamondDerived::g\n\n80 8u\n\n88 18446744073709551608u\n\n96 18446744073709551608u\n\n104 18446744073709551608u\n\n112 (int (*)(...))-8\n\n120 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived)\n\n128 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZThn8_N31MultiplyVirtuallyDiamondDerivedD1Ev\n\n136 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZThn8_N31MultiplyVirtuallyDiamondDerivedD0Ev\n\n144 0u\n\n152 18446744073709551600u\n\n160 18446744073709551600u\n\n168 (int (*)(...))-16\n\n176 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived)\n\n184 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n24_N31MultiplyVirtuallyDiamondDerivedD1Ev\n\n192 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n24_N31MultiplyVirtuallyDiamondDerivedD0Ev\n\n200 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n32_N31MultiplyVirtuallyDiamondDerived1gEv\n\n\nConstruction vtable for VirtuallyMultiplyDerived (0x0x7fd42bcdf230 instance) in MultiplyVirtuallyDiamondDerived\n\nMultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived: 16u entries\n\n0 16u\n\n8 0u\n\n16 0u\n\n24 0u\n\n32 (int (*)(...))0\n\n40 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)\n\n48 0u\n\n56 0u\n\n64 (int (*)(...))__cxa_pure_virtual\n\n72 0u\n\n80 18446744073709551600u\n\n88 (int (*)(...))-16\n\n96 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)\n\n104 0u\n\n112 0u\n\n120 (int (*)(...))OtherBase::g\n\n\nConstruction vtable for OtherVirtuallyMultiplyDerived (0x0x7fd42bcdf2a0 instance) in MultiplyVirtuallyDiamondDerived\n\nMultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived: 23u entries\n\n0 8u\n\n8 18446744073709551608u\n\n16 18446744073709551608u\n\n24 0u\n\n32 (int (*)(...))0\n\n40 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)\n\n48 0u\n\n56 0u\n\n64 (int (*)(...))__cxa_pure_virtual\n\n72 0u\n\n80 8u\n\n88 (int (*)(...))8\n\n96 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)\n\n104 0u\n\n112 0u\n\n120 (int (*)(...))__cxa_pure_virtual\n\n128 0u\n\n136 18446744073709551608u\n\n144 (int (*)(...))-8\n\n152 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)\n\n160 0u\n\n168 0u\n\n176 (int (*)(...))OtherBase::g\n\n\nVTT for MultiplyVirtuallyDiamondDerived\n\nMultiplyVirtuallyDiamondDerived::_ZTT31MultiplyVirtuallyDiamondDerived: 10u entries\n\n0 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u)\n\n8 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 48u)\n\n16 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 48u)\n\n24 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 104u)\n\n32 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 48u)\n\n40 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 104u)\n\n48 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 160u)\n\n56 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u)\n\n64 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 184u)\n\n72 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 128u)\n\n\nClass MultiplyVirtuallyDiamondDerived\n\n size=24 align=8\n\n base size=16 base align=8\n\nMultiplyVirtuallyDiamondDerived (0x0x7fd42bcdf1c0) 0\n\n vptridx=0u vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u)\n\n VirtuallyMultiplyDerived (0x0x7fd42bcdf230) 0 nearly-empty\n\n primary-for MultiplyVirtuallyDiamondDerived (0x0x7fd42bcdf1c0)\n\n subvttidx=8u\n\n Base (0x0x7fd42bce2000) 0 nearly-empty virtual\n\n primary-for VirtuallyMultiplyDerived (0x0x7fd42bcdf230)\n\n vptridx=56u vbaseoffset=-40\n\n OtherBase (0x0x7fd42bce2060) 16 nearly-empty virtual\n\n vptridx=64u vbaseoffset=-48 vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 184u)\n\n OtherVirtuallyMultiplyDerived (0x0x7fd42bcdf2a0) 8 nearly-empty\n\n lost-primary\n\n subvttidx=32u vptridx=72u vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 128u)\n\n Base (0x0x7fd42bce2000) alternative-path\n\n OtherBase (0x0x7fd42bce2060) alternative-path\n</pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70682', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8516/']
|
70,685 |
<p>In the WCF application that I am working on, I need to access the generated source of a particular webpage (after all the AJAX calls on the page are made).</p>
<p>I have tried using <code>System.Net.WebRequest</code> but it just brings me back the original source of the page. Is there a way to execute a page and then get the source?</p>
<p>Else, is there a way to execute Javascript from within a WCF service? I could use the javascript and JSON response to create the HTML page from within my webservice then!</p>
|
[{'answer_id': 70852, 'author': 'cruizer', 'author_id': 6441, 'author_profile': 'https://Stackoverflow.com/users/6441', 'pm_score': 0, 'selected': False, 'text': '<p>Well, WCF is designed to be consumed by non-browsers, so there really is no way to expect that a WCF response can contain Javascript that will be automatically executed by the client.</p>\n'}, {'answer_id': 73876, 'author': 'Petar Vucetin', 'author_id': 10424, 'author_profile': 'https://Stackoverflow.com/users/10424', 'pm_score': 1, 'selected': False, 'text': '<p>You could use Javascript to traverse and pass the DOM than make a call into your WCF service from the Javascript when all the Ajax calls are complete. If you are after the data that is stored on the page after all the Ajax calls I would re-think your implementation...</p>\n\n<p>Petar</p>\n'}, {'answer_id': 74308, 'author': 'Adhip Gupta', 'author_id': 384, 'author_profile': 'https://Stackoverflow.com/users/384', 'pm_score': 0, 'selected': False, 'text': '<p>@Petar: Thanks for your input. Yes, I am after that data that will be stored in the page after the Ajax calls. And, somehow the third party vendor will not give me that data via some JSON calls which I could directly call from my own WCF service.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/384/']
|
70,689 |
<p>What is an efficient way to implement a singleton design pattern in Java?</p>
|
[{'answer_id': 70737, 'author': 'Neil Burroughs', 'author_id': 5166, 'author_profile': 'https://Stackoverflow.com/users/5166', 'pm_score': 6, 'selected': False, 'text': '<p>Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments against it.</p>\n<p>There\'s nothing inherently wrong with it I suppose, but it\'s just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I\'ve found <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection</a> (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.</p>\n'}, {'answer_id': 70749, 'author': 'macbirdie', 'author_id': 5049, 'author_profile': 'https://Stackoverflow.com/users/5049', 'pm_score': 4, 'selected': False, 'text': '<p>Wikipedia has some <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">examples</a> of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).</p>\n'}, {'answer_id': 70821, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Really consider why you need a singleton before writing it. There is a quasi-religious debate about using them which you can quite easily stumble over if you google singletons in Java.</p>\n<p>Personally, I try to avoid singletons as often as possible for many reasons, again most of which can be found by googling singletons. I feel that quite often singletons are abused because they\'re easy to understand by everybody. They\'re used as a mechanism for getting "global" data into an OO design and they are used because it is easy to circumvent object lifecycle management (or really thinking about how you can do A from inside B). Look at things like <a href="https://en.wikipedia.org/wiki/Inversion_of_control" rel="nofollow noreferrer">inversion of control</a> (IoC) or <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection</a> (DI) for a nice middle ground.</p>\n<p>If you really need one then Wikipedia has a good example of a proper implementation of a singleton.</p>\n'}, {'answer_id': 70824, 'author': 'Jonathan', 'author_id': 1772, 'author_profile': 'https://Stackoverflow.com/users/1772', 'pm_score': 7, 'selected': False, 'text': '<p>Forget <a href="https://en.wikipedia.org/wiki/Lazy_initialization" rel="nofollow noreferrer">lazy initialization</a>; it\'s too problematic. This is the simplest solution:</p>\n<pre><code>public class A { \n\n private static final A INSTANCE = new A();\n\n private A() {}\n\n public static A getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n'}, {'answer_id': 70829, 'author': 'Aleksi Yrttiaho', 'author_id': 11427, 'author_profile': 'https://Stackoverflow.com/users/11427', 'pm_score': 4, 'selected': False, 'text': "<p>If you do not need lazy loading then simply try:</p>\n<pre><code>public class Singleton {\n private final static Singleton INSTANCE = new Singleton();\n\n private Singleton() {}\n\n public static Singleton getInstance() { return Singleton.INSTANCE; }\n\n protected Object clone() {\n throw new CloneNotSupportedException();\n }\n}\n</code></pre>\n<p>If you want lazy loading and you want your singleton to be thread-safe, try the double-checking pattern:</p>\n<pre><code>public class Singleton {\n private static Singleton instance = null;\n\n private Singleton() {}\n\n public static Singleton getInstance() {\n if(null == instance) {\n synchronized(Singleton.class) {\n if(null == instance) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n }\n\n protected Object clone() {\n throw new CloneNotSupportedException();\n }\n}\n</code></pre>\n<p>As the double checking pattern is not guaranteed to work (due to some issue with compilers, I don't know anything more about that), you could also try to synchronize the whole getInstance-method or create a registry for all your singletons.</p>\n"}, {'answer_id': 70835, 'author': 'Stu Thompson', 'author_id': 2961, 'author_profile': 'https://Stackoverflow.com/users/2961', 'pm_score': 7, 'selected': False, 'text': "<p>Thread safe in Java 5+:</p>\n<pre><code>class Foo {\n private static volatile Bar bar = null;\n public static Bar getBar() {\n if (bar == null) {\n synchronized(Foo.class) {\n if (bar == null)\n bar = new Bar();\n }\n }\n return bar;\n }\n}\n</code></pre>\n<hr />\n<p>Pay attention to the <code>volatile</code> modifier here. :) It is important because without it, other threads are not guaranteed by the JMM (Java Memory Model) to see changes to its value. The synchronization <em>does not</em> take care of that--it only serializes access to that block of code.</p>\n<p>@Bno's answer details the approach recommended by Bill Pugh (FindBugs) and is arguable better. Go read and vote up his answer too.</p>\n"}, {'answer_id': 71399, 'author': 'Stephen Denne', 'author_id': 11721, 'author_profile': 'https://Stackoverflow.com/users/11721', 'pm_score': 11, 'selected': True, 'text': '<p>Use an enum:</p>\n\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n\n<p>Joshua Bloch explained this approach in his <a href="http://sites.google.com/site/io/effective-java-reloaded" rel="noreferrer">Effective Java Reloaded</a> talk at Google I/O 2008: <a href="http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s" rel="noreferrer">link to video</a>. Also see slides 30-32 of his presentation (<a href="https://14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/effective-java-reloaded/effective_java_reloaded.pdf?attachauth=ANoY7crKCOet2NEUGW7RV1XfM-Jn4z8YJhs0qJM11OhLRnFW_JbExkJtvJ3UJvTE40dhAciyWcRIeGJ-n3FLGnMOapHShHINh8IY05YViOJoZWzaohMtM-s4HCi5kjREagi8awWtcYD0_6G7GhKr2BndToeqLk5sBhZcQfcYIyAE5A4lGNosDCjODcBAkJn8EuO6572t2wU1LMSEUgjvqcf4I-Fp6VDhDvih_XUEmL9nuVJQynd2DRpxyuNH1SpJspEIdbLw-WWZ&attredirects=0" rel="noreferrer">effective_java_reloaded.pdf</a>):</p>\n\n<blockquote>\n <h3>The Right Way to Implement a Serializable Singleton</h3>\n\n<pre><code>public enum Elvis {\n INSTANCE;\n private final String[] favoriteSongs =\n { "Hound Dog", "Heartbreak Hotel" };\n public void printFavorites() {\n System.out.println(Arrays.toString(favoriteSongs));\n }\n}\n</code></pre>\n</blockquote>\n\n<p><strong>Edit:</strong> An <a href="http://www.ddj.com/java/208403883?pgno=3" rel="noreferrer">online portion of "Effective Java"</a> says: </p>\n\n<blockquote>\n <p>"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, <strong>a single-element enum type is the best way to implement a singleton</strong>."</p>\n</blockquote>\n'}, {'answer_id': 71574, 'author': 'Andrew Swan', 'author_id': 10433, 'author_profile': 'https://Stackoverflow.com/users/10433', 'pm_score': 4, 'selected': False, 'text': '<p>I\'m mystified by some of the answers that suggest <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection</a> (DI) as an alternative to using singletons; these are unrelated concepts. You can use DI to inject either singleton or non-singleton (e.g., per-thread) instances. At least this is true if you use Spring 2.x, I can\'t speak for other DI frameworks.</p>\n<p>So my answer to the OP would be (in all but the most trivial sample code) to:</p>\n<ol>\n<li>Use a DI framework like <a href="https://en.wikipedia.org/wiki/Spring_Framework" rel="nofollow noreferrer">Spring Framework</a>, then</li>\n<li>Make it part of your DI configuration whether your dependencies are singletons, request scoped, session scoped, or whatever.</li>\n</ol>\n<p>This approach gives you a nice decoupled (and therefore flexible and testable) architecture where whether to use a singleton is an easily reversible implementation detail (provided any singletons you use are threadsafe, of course).</p>\n'}, {'answer_id': 71683, 'author': 'Benno Richters', 'author_id': 3565, 'author_profile': 'https://Stackoverflow.com/users/3565', 'pm_score': 7, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java/70835#70835">The solution posted by Stu Thompson</a> is valid in Java\xa05.0 and later. But I would prefer not to use it because I think it is error prone.</p>\n<p>It\'s easy to forget the volatile statement and difficult to understand why it is necessary. Without the volatile this code would not be thread safe any more due to the double-checked locking antipattern. See more about this in paragraph 16.2.4 of <a href="http://jcip.net/" rel="nofollow noreferrer" title="Java Concurrency in Practice">Java Concurrency in Practice</a>. In short: This pattern (prior to Java\xa05.0 or without the volatile statement) could return a reference to the Bar object that is (still) in an incorrect state.</p>\n<p>This pattern was invented for performance optimization. But this is really not a real concern any more. The following lazy initialization code is fast and - more importantly - easier to read.</p>\n<pre><code>class Bar {\n private static class BarHolder {\n public static Bar bar = new Bar();\n }\n\n public static Bar getBar() {\n return BarHolder.bar;\n }\n}\n</code></pre>\n'}, {'answer_id': 73763, 'author': 'Roel Spilker', 'author_id': 12634, 'author_profile': 'https://Stackoverflow.com/users/12634', 'pm_score': 8, 'selected': False, 'text': "<p>Depending on the usage, there are several "correct" answers.</p>\n<p>Since Java 5, the best way to do it is to use an enum:</p>\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n<p>Pre Java 5, the most simple case is:</p>\n<pre><code>public final class Foo {\n\n private static final Foo INSTANCE = new Foo();\n\n private Foo() {\n if (INSTANCE != null) {\n throw new IllegalStateException("Already instantiated");\n }\n }\n\n public static Foo getInstance() {\n return INSTANCE;\n }\n\n public Object clone() throws CloneNotSupportedException{\n throw new CloneNotSupportedException("Cannot clone instance of this class");\n }\n}\n</code></pre>\n<p>Let's go over the code. First, you want the class to be final. In this case, I've used the <code>final</code> keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a <code>private static final Foo</code> field to hold the only instance, and a <code>public static Foo getInstance()</code> method to return it. The Java specification makes sure that the constructor is only called when the class is first used.</p>\n<p>When you have a very large object or heavy construction code <em>and</em> also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.</p>\n<p>You can use a <code>private static class</code> to load the instance. The code would then look like:</p>\n<pre><code>public final class Foo {\n\n private static class FooLoader {\n private static final Foo INSTANCE = new Foo();\n }\n\n private Foo() {\n if (FooLoader.INSTANCE != null) {\n throw new IllegalStateException("Already instantiated");\n }\n }\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>Since the line <code>private static final Foo INSTANCE = new Foo();</code> is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.</p>\n<p>When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.</p>\n<pre><code>public final class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private static class FooLoader {\n private static final Foo INSTANCE = new Foo();\n }\n\n private Foo() {\n if (FooLoader.INSTANCE != null) {\n throw new IllegalStateException("Already instantiated");\n }\n }\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n\n @SuppressWarnings("unused")\n private Foo readResolve() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>The method <code>readResolve()</code> will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.</p>\n"}, {'answer_id': 74905, 'author': 'Georgi', 'author_id': 13209, 'author_profile': 'https://Stackoverflow.com/users/13209', 'pm_score': -1, 'selected': False, 'text': '<p>Sometimes a simple "<strong><code>static Foo foo = new Foo();</code></strong>" is not enough. Just think of some basic data insertion you want to do.</p>\n\n<p>On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution is</p>\n\n<pre><code>public class Singleton {\n\n private static Singleton instance = null;\n\n static {\n instance = new Singleton();\n // do some of your instantiation stuff here\n }\n\n private Singleton() {\n if(instance!=null) {\n throw new ErrorYouWant("Singleton double-instantiation, should never happen!");\n }\n }\n\n public static getSingleton() {\n return instance;\n }\n\n}\n</code></pre>\n\n<p>Now what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the <strong>static { }</strong> - block. that\'s the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.</p>\n'}, {'answer_id': 117516, 'author': 'Matt', 'author_id': 20630, 'author_profile': 'https://Stackoverflow.com/users/20630', 'pm_score': 4, 'selected': False, 'text': '<p>I use the <a href="https://en.wikipedia.org/wiki/Spring_Framework" rel="nofollow noreferrer">Spring Framework</a> to manage my singletons.</p>\n<p>It doesn\'t enforce the "singleton-ness" of the class (which you can\'t really do anyway if there are multiple class loaders involved), but it provides a really easy way to build and configure different factories for creating different types of objects.</p>\n'}, {'answer_id': 6918352, 'author': 'Onur', 'author_id': 776658, 'author_profile': 'https://Stackoverflow.com/users/776658', 'pm_score': 2, 'selected': False, 'text': '<p>You need the <a href="http://en.wikipedia.org/wiki/Double-checked_locking" rel="nofollow noreferrer">double-checking</a> idiom if you need to load the instance variable of a class lazily. If you need to load a static variable or a singleton lazily, you need the <a href="http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom" rel="nofollow noreferrer">initialization on demand holder</a> idiom.</p>\n<p>In addition, if the singleton needs to be serializable, all other fields need to be transient and readResolve() method needs to be implemented in order to maintain the singleton object invariant. Otherwise, each time the object is deserialized, a new instance of the object will be created. What readResolve() does is replace the new object read by readObject(), which forced that new object to be garbage collected as there is no variable referring to it.</p>\n<pre><code>public static final INSTANCE == ....\nprivate Object readResolve() {\n return INSTANCE; // Original singleton instance.\n} \n</code></pre>\n'}, {'answer_id': 14372745, 'author': 'NullPoiиteя', 'author_id': 1723893, 'author_profile': 'https://Stackoverflow.com/users/1723893', 'pm_score': 3, 'selected': False, 'text': '<p>I would say an enum singleton.</p>\n<p>Singleton using an enum in Java is generally a way to declare an enum singleton. An enum singleton may contain instance variables and instance methods. For simplicity\'s sake, also note that if you are using any instance method then you need to ensure thread safety of that method if at all it affects the state of object.</p>\n<p>The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.</p>\n<pre><code>/**\n* Singleton pattern example using a Java Enum\n*/\npublic enum Singleton {\n INSTANCE;\n public void execute (String arg) {\n // Perform operation here\n }\n}\n</code></pre>\n<p>You can access it by <code>Singleton.INSTANCE</code>, and it is much easier than calling the <code>getInstance()</code> method on Singleton.</p>\n<blockquote>\n<p>1.12 Serialization of Enum Constants</p>\n<p>Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form. To serialize an enum constant, <code>ObjectOutputStream</code> writes the value returned by the enum constant\'s name method. To deserialize an enum constant, <code>ObjectInputStream</code> reads the constant name from the stream; the deserialized constant is then obtained by calling the <code>java.lang.Enum.valueOf</code> method, passing the constant\'s enum type along with the received constant name as arguments. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream.</p>\n<p>The process by which enum constants are serialized cannot be customized: any class-specific <code>writeObject</code>, <code>readObject</code>, <code>readObjectNoData</code>, <code>writeReplace</code>, and <code>readResolve</code> methods defined by enum types are ignored during serialization and deserialization. Similarly, any <code>serialPersistentFields</code> or <code>serialVersionUID</code> field declarations are also ignored--all enum types have a fixed <code>serialVersionUID</code> of <code>0L</code>. Documenting serializable fields and data for enum types is unnecessary, since there is no variation in the type of data sent.</p>\n<p><a href="http://docs.oracle.com/javase/1.5.0/docs/guide/serialization/spec/serial-arch.html#enum" rel="nofollow noreferrer">Quoted from Oracle documentation</a></p>\n</blockquote>\n<p>Another problem with conventional Singletons are that once you implement the <code>Serializable</code> interface, they no longer remain singleton because the <code>readObject()</code> method always return a new instance, like a constructor in Java. This can be avoided by using <code>readResolve()</code> and discarding the newly created instance by replacing with a singleton like below:</p>\n<pre><code> // readResolve to prevent another instance of Singleton\n private Object readResolve(){\n return INSTANCE;\n }\n</code></pre>\n<p>This can become even more complex if your <em>singleton class</em> maintains state, as you need to make them transient, but with in an enum singleton, serialization is guaranteed by the JVM.</p>\n<hr />\n<p><strong>Good Read</strong></p>\n<ol>\n<li><a href="http://www.oodesign.com/singleton-pattern.html" rel="nofollow noreferrer">Singleton Pattern</a></li>\n<li><a href="https://stackoverflow.com/questions/13219678/enums-singletons-and-deserialization">Enums, Singletons and Deserialization</a></li>\n<li><a href="http://www.ibm.com/developerworks/java/library/j-dcl/index.html" rel="nofollow noreferrer">Double-checked locking and the Singleton pattern</a></li>\n</ol>\n'}, {'answer_id': 14917772, 'author': 'Abhijit Gaikwad', 'author_id': 403872, 'author_profile': 'https://Stackoverflow.com/users/403872', 'pm_score': 4, 'selected': False, 'text': "<p>Following are three different approaches</p>\n<ol>\n<li><p>Enum</p>\n<pre><code> /**\n * Singleton pattern example using Java Enum\n */\n public enum EasySingleton {\n INSTANCE;\n }\n</code></pre>\n</li>\n<li><p>Double checked locking / lazy loading</p>\n<pre><code> /**\n * Singleton pattern example with Double checked Locking\n */\n public class DoubleCheckedLockingSingleton {\n private static volatile DoubleCheckedLockingSingleton INSTANCE;\n\n private DoubleCheckedLockingSingleton() {}\n\n public static DoubleCheckedLockingSingleton getInstance() {\n if(INSTANCE == null) {\n synchronized(DoubleCheckedLockingSingleton.class) {\n // Double checking Singleton instance\n if(INSTANCE == null) {\n INSTANCE = new DoubleCheckedLockingSingleton();\n }\n }\n }\n return INSTANCE;\n }\n }\n</code></pre>\n</li>\n<li><p>Static factory method</p>\n<pre><code> /**\n * Singleton pattern example with static factory method\n */\n\n public class Singleton {\n // Initialized during class loading\n private static final Singleton INSTANCE = new Singleton();\n\n // To prevent creating another instance of 'Singleton'\n private Singleton() {}\n\n public static Singleton getSingleton() {\n return INSTANCE;\n }\n }\n</code></pre>\n</li>\n</ol>\n"}, {'answer_id': 16580366, 'author': 'Ajinkya', 'author_id': 705773, 'author_profile': 'https://Stackoverflow.com/users/705773', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Disclaimer:</strong> I have just summarized all of the awesome answers and wrote it in my own words.</p>\n<hr />\n<p>While implementing Singleton we have two options:</p>\n<ol>\n<li>Lazy loading</li>\n<li>Early loading</li>\n</ol>\n<p>Lazy loading adds bit overhead (lots of to be honest), so use it only when you have a very large object or heavy construction code <em>and</em> also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization. Otherwise, choosing early loading is a good choice.</p>\n<p>The most simple way of implementing a singleton is:</p>\n<pre><code>public class Foo {\n\n // It will be our sole hero\n private static final Foo INSTANCE = new Foo();\n\n private Foo() {\n if (INSTANCE != null) {\n // SHOUT\n throw new IllegalStateException("Already instantiated");\n }\n }\n\n public static Foo getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>Everything is good except it\'s an early loaded singleton. Lets try lazy loaded singleton</p>\n<pre><code>class Foo {\n\n // Our now_null_but_going_to_be sole hero\n private static Foo INSTANCE = null;\n\n private Foo() {\n if (INSTANCE != null) {\n // SHOUT\n throw new IllegalStateException("Already instantiated");\n }\n }\n\n public static Foo getInstance() {\n // Creating only when required.\n if (INSTANCE == null) {\n INSTANCE = new Foo();\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>So far so good, but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero.\nSo let’s protect it from evil multi threading:</p>\n<pre><code>class Foo {\n\n private static Foo INSTANCE = null;\n\n // TODO Add private shouting constructor\n\n public static Foo getInstance() {\n // No more tension of threads\n synchronized (Foo.class) {\n if (INSTANCE == null) {\n INSTANCE = new Foo();\n }\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>But it is not enough to protect out hero, really!!! This is the best we can/should do to help our hero:</p>\n<pre><code>class Foo {\n\n // Pay attention to volatile\n private static volatile Foo INSTANCE = null;\n\n // TODO Add private shouting constructor\n\n public static Foo getInstance() {\n if (INSTANCE == null) { // Check 1\n synchronized (Foo.class) {\n if (INSTANCE == null) { // Check 2\n INSTANCE = new Foo();\n }\n }\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>This is called the "double-checked locking idiom". It\'s easy to forget the volatile statement and difficult to understand why it is necessary.\nFor details: <em><a href="http://www.cs.umd.edu/%7Epugh/java/memoryModel/DoubleCheckedLocking.html" rel="noreferrer">The "Double-Checked Locking is Broken" Declaration</a></em></p>\n<p>Now we are sure about evil threads, but what about the cruel serialization? We have to make sure even while de-serialiaztion no new object is created:</p>\n<pre><code>class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private static volatile Foo INSTANCE = null;\n\n // The rest of the things are same as above\n\n // No more fear of serialization\n @SuppressWarnings("unused")\n private Object readResolve() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>The method <code>readResolve()</code> will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.</p>\n<p>Finally, we have added enough protection against threads and serialization, but our code is looking bulky and ugly. Let’s give our hero a makeover:</p>\n<pre><code>public final class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n // Wrapped in a inner static class so that loaded only when required\n private static class FooLoader {\n\n // And no more fear of threads\n private static final Foo INSTANCE = new Foo();\n }\n\n // TODO add private shouting construcor\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n\n // Damn you serialization\n @SuppressWarnings("unused")\n private Foo readResolve() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>Yes, this is our very same hero :)</p>\n<p>Since the line <code>private static final Foo INSTANCE = new Foo();</code> is only executed when the class <code>FooLoader</code> is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread-safe.</p>\n<p>And we have come so far. Here is the best way to achieve everything we did is best possible way:</p>\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n<p>Which internally will be treated like</p>\n<pre><code>public class Foo {\n\n // It will be our sole hero\n private static final Foo INSTANCE = new Foo();\n}\n</code></pre>\n<p>That\'s it! No more fear of serialization, threads and ugly code. Also <a href="https://stackoverflow.com/questions/16771373/singleton-via-enum-way-is-lazy-initialized"><strong>ENUMS singleton are lazily initialized</strong></a>.</p>\n<blockquote>\n<p>This approach is functionally equivalent to the public field approach,\nexcept that it is more concise, provides the serialization machinery\nfor free, and provides an ironclad guarantee against multiple\ninstantiation, even in the face of sophisticated serialization or\nreflection attacks. While this approach has yet to be widely adopted,\na single-element enum type is the best way to implement a singleton.</p>\n</blockquote>\n<p>-Joshua Bloch in "Effective Java"</p>\n<p>Now you might have realized why ENUMS are considered as best way to implement a singleton and thanks for your patience :)</p>\n<p>Updated it on my <a href="http://ajinkyaparakh.blogspot.in/2013/05/implementing-singleton-in-java.html" rel="noreferrer"><strong>blog</strong></a>.</p>\n'}, {'answer_id': 16699497, 'author': 'raoadnan', 'author_id': 2392052, 'author_profile': 'https://Stackoverflow.com/users/2392052', 'pm_score': 2, 'selected': False, 'text': '<p>For JSE 5.0 and above, take the Enum approach. Otherwise, use the static singleton holder approach ((a lazy loading approach described by Bill Pugh). The latter solution is also thread-safe without requiring special language constructs (i.e., volatile or synchronized).</p>\n'}, {'answer_id': 19562324, 'author': 'rohan kamat', 'author_id': 2335562, 'author_profile': 'https://Stackoverflow.com/users/2335562', 'pm_score': 1, 'selected': False, 'text': '<p>Simplest singleton class:</p>\n<pre><code>public class Singleton {\n private static Singleton singleInstance = new Singleton();\n private Singleton() {}\n public static Singleton getSingleInstance() {\n return singleInstance;\n }\n}\n</code></pre>\n'}, {'answer_id': 19849576, 'author': 'somenath mukhopadhyay', 'author_id': 873952, 'author_profile': 'https://Stackoverflow.com/users/873952', 'pm_score': -1, 'selected': False, 'text': '<pre><code>public class Singleton {\n\n private static final Singleton INSTANCE = new Singleton();\n\n private Singleton() {\n if (INSTANCE != null)\n throw new IllegalStateException(“Already instantiated...”);\n }\n\n\n public synchronized static Singleton getInstance() {\n return INSTANCE;\n }\n\n}\n</code></pre>\n<p>As we have added the Synchronized keyword before getInstance, we have avoided the race condition in the case when two threads call the getInstance at the same time.</p>\n'}, {'answer_id': 27793921, 'author': 'shikjohari', 'author_id': 2595642, 'author_profile': 'https://Stackoverflow.com/users/2595642', 'pm_score': 0, 'selected': False, 'text': '<p>I still think after Java 1.5, enum is the best available singleton implementation available as it also ensures that, even in the multi threaded environments, only one instance is created.</p>\n<pre><code>public enum Singleton {\n INSTANCE;\n}\n</code></pre>\n<p>And you are done!</p>\n'}, {'answer_id': 29389322, 'author': 'coderz', 'author_id': 3275167, 'author_profile': 'https://Stackoverflow.com/users/3275167', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Version 1:</strong></p>\n\n<pre><code>public class MySingleton {\n private static MySingleton instance = null;\n private MySingleton() {}\n public static synchronized MySingleton getInstance() {\n if(instance == null) {\n instance = new MySingleton();\n }\n return instance;\n }\n}\n</code></pre>\n\n<p>Lazy loading, thread safe with blocking, low performance because of <code>synchronized</code>.</p>\n\n<p><strong>Version 2:</strong></p>\n\n<pre><code>public class MySingleton {\n private MySingleton() {}\n private static class MySingletonHolder {\n public final static MySingleton instance = new MySingleton();\n }\n public static MySingleton getInstance() {\n return MySingletonHolder.instance;\n }\n}\n</code></pre>\n\n<p>Lazy loading, thread safe with non-blocking, high performance.</p>\n'}, {'answer_id': 32130663, 'author': 'kenju', 'author_id': 2775013, 'author_profile': 'https://Stackoverflow.com/users/2775013', 'pm_score': 0, 'selected': False, 'text': '<p>Have a look at this post.</p>\n<p><a href="https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries">Examples of GoF Design Patterns in Java's core libraries</a></p>\n<p>From the best answer\'s "Singleton" section,</p>\n<blockquote>\n<h3>Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)</h3>\n<ul>\n<li>java.lang.Runtime#getRuntime()</li>\n<li>java.awt.Desktop#getDesktop()</li>\n<li>java.lang.System#getSecurityManager()</li>\n</ul>\n</blockquote>\n<p>You can also learn the example of Singleton from Java native classes themselves.</p>\n'}, {'answer_id': 32286179, 'author': 'Shailendra Singh', 'author_id': 2550410, 'author_profile': 'https://Stackoverflow.com/users/2550410', 'pm_score': 2, 'selected': False, 'text': '<p>Various ways to make a singleton object:</p>\n<ol>\n<li><p>As per <a href="https://en.wikipedia.org/wiki/Joshua_Bloch" rel="nofollow noreferrer">Joshua Bloch</a> - Enum would be the best.</p>\n</li>\n<li><p>You can use double check locking also.</p>\n</li>\n<li><p>Even an inner static class can be used.</p>\n</li>\n</ol>\n'}, {'answer_id': 32906229, 'author': 'Dan Moldovan', 'author_id': 2725534, 'author_profile': 'https://Stackoverflow.com/users/2725534', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Enum singleton</strong></p>\n<p>The simplest way to implement a singleton that is thread-safe is using an Enum:</p>\n<pre><code>public enum SingletonEnum {\n INSTANCE;\n public void doSomething(){\n System.out.println("This is a singleton");\n }\n}\n</code></pre>\n<p>This code works since the introduction of Enum in Java 1.5</p>\n<p><strong>Double checked locking</strong></p>\n<p>If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.</p>\n<pre><code>public class Singleton {\n\n private static volatile Singleton instance = null;\n\n private Singleton() {\n }\n\n public static Singleton getInstance() {\n if (instance == null) {\n synchronized (Singleton.class){\n if (instance == null) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n }\n}\n</code></pre>\n<p>This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.</p>\n<p><strong>Early loading singleton (works even before Java 1.5)</strong></p>\n<p>This implementation instantiates the singleton when the class is loaded and provides thread safety.</p>\n<pre><code>public class Singleton {\n\n private static final Singleton instance = new Singleton();\n\n private Singleton() {\n }\n\n public static Singleton getInstance() {\n return instance;\n }\n\n public void doSomething(){\n System.out.println("This is a singleton");\n }\n\n}\n</code></pre>\n'}, {'answer_id': 37305099, 'author': 'Nicolas Filotto', 'author_id': 1997376, 'author_profile': 'https://Stackoverflow.com/users/1997376', 'pm_score': 2, 'selected': False, 'text': '<p>This is how to implement a simple <a href="https://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">singleton</a>:</p>\n<pre><code>public class Singleton {\n // It must be static and final to prevent later modification\n private static final Singleton INSTANCE = new Singleton();\n /** The constructor must be private to prevent external instantiation */\n private Singleton(){}\n /** The public static method allowing to get the instance */\n public static Singleton getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>This is how to properly lazy create your singleton:</p>\n<pre><code>public class Singleton {\n // The constructor must be private to prevent external instantiation\n private Singleton(){}\n /** The public static method allowing to get the instance */\n public static Singleton getInstance() {\n return SingletonHolder.INSTANCE;\n }\n /**\n * The static inner class responsible for creating your instance only on demand,\n * because the static fields of a class are only initialized when the class\n * is explicitly called and a class initialization is synchronized such that only\n * one thread can perform it, this rule is also applicable to inner static class\n * So here INSTANCE will be created only when SingletonHolder.INSTANCE\n * will be called\n */\n private static class SingletonHolder {\n private static final Singleton INSTANCE = new Singleton();\n }\n}\n</code></pre>\n'}, {'answer_id': 38942086, 'author': 'user3792852', 'author_id': 3792852, 'author_profile': 'https://Stackoverflow.com/users/3792852', 'pm_score': 2, 'selected': False, 'text': '<p>Another argument often used against singletons is their testability problems. Singletons are not easily mockable for testing purposes. If this turns out to be a problem, I like to make the following slight modification:</p>\n<pre><code>public class SingletonImpl {\n\n private static SingletonImpl instance;\n\n public static SingletonImpl getInstance() {\n if (instance == null) {\n instance = new SingletonImpl();\n }\n return instance;\n }\n\n public static void setInstance(SingletonImpl impl) {\n instance = impl;\n }\n\n public void a() {\n System.out.println("Default Method");\n }\n}\n</code></pre>\n<p>The added <code>setInstance</code> method allows setting a mockup implementation of the singleton class during testing:</p>\n<pre><code>public class SingletonMock extends SingletonImpl {\n\n @Override\n public void a() {\n System.out.println("Mock Method");\n }\n\n}\n</code></pre>\n<p>This also works with early initialization approaches:</p>\n<pre><code>public class SingletonImpl {\n\n private static final SingletonImpl instance = new SingletonImpl();\n\n private static SingletonImpl alt;\n\n public static void setInstance(SingletonImpl inst) {\n alt = inst;\n }\n\n public static SingletonImpl getInstance() {\n if (alt != null) {\n return alt;\n }\n return instance;\n }\n\n public void a() {\n System.out.println("Default Method");\n }\n}\n\npublic class SingletonMock extends SingletonImpl {\n\n @Override\n public void a() {\n System.out.println("Mock Method");\n }\n\n}\n</code></pre>\n<p>This has the drawback of exposing this functionality to the normal application too. Other developers working on that code could be tempted to use the ´setInstance´ method to alter a specific function and thus changing the whole application behaviour, and therefore this method should contain at least a good warning in its javadoc.</p>\n<p>Still, for the possibility of mockup-testing (when needed), this code exposure may be an acceptable price to pay.</p>\n'}, {'answer_id': 39098595, 'author': 'Dheeraj Sachan', 'author_id': 3314058, 'author_profile': 'https://Stackoverflow.com/users/3314058', 'pm_score': 3, 'selected': False, 'text': '<p>There are four ways to create a singleton in Java.</p>\n<ol>\n<li><p>Eager initialization singleton</p>\n<pre><code> public class Test {\n private static final Test test = new Test();\n\n private Test() {\n }\n\n public static Test getTest() {\n return test;\n }\n }\n</code></pre>\n</li>\n<li><p>Lazy initialization singleton (thread safe)</p>\n<pre><code> public class Test {\n private static volatile Test test;\n\n private Test() {\n }\n\n public static Test getTest() {\n if(test == null) {\n synchronized(Test.class) {\n if(test == null) {\n test = new Test();\n }\n }\n }\n return test;\n }\n }\n</code></pre>\n</li>\n<li><p>Bill Pugh singleton with holder pattern (preferably the best one)</p>\n<pre><code> public class Test {\n\n private Test() {\n }\n\n private static class TestHolder {\n private static final Test test = new Test();\n }\n\n public static Test getInstance() {\n return TestHolder.test;\n }\n }\n</code></pre>\n</li>\n<li><p>Enum singleton</p>\n<pre><code> public enum MySingleton {\n INSTANCE;\n\n private MySingleton() {\n System.out.println("Here");\n }\n }\n</code></pre>\n</li>\n</ol>\n'}, {'answer_id': 45062746, 'author': 'Michael Andrews', 'author_id': 1829927, 'author_profile': 'https://Stackoverflow.com/users/1829927', 'pm_score': 4, 'selected': False, 'text': '<p>There is a lot of nuance around implementing a singleton. The holder pattern can not be used in many situations. And IMO when using a volatile - you should also use a local variable. Let\'s start at the beginning and iterate on the problem. You\'ll see what I mean.</p>\n<hr />\n<p>The first attempt might look something like this:</p>\n<pre><code>public class MySingleton {\n\n private static MySingleton INSTANCE;\n\n public static MySingleton getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new MySingleton();\n }\n return INSTANCE;\n }\n ...\n}\n</code></pre>\n<p>Here we have the MySingleton class which has a private static member called <em>INSTANCE</em>, and a public static method called getInstance(). The first time getInstance() is called, the <em>INSTANCE</em> member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the <em>INSTANCE</em> variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().</p>\n<p>But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the <em>INSTANCE</em> member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the <em>INSTANCE</em> member.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static synchronized MySingleton getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new MySingleton();\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we’ve used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance; it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of <em>INSTANCE</em>. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronize(MySingleton.class) {\n INSTANCE = new MySingleton();\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we’ve moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we’ve also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the <em>INSTANCE</em> member as null.</p>\n<p>They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronized(MySingleton.class) {\n if (INSTANCE == null) {\n INSTANCE = createInstance();\n }\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we issue another check from <em>inside</em> the block. If the <em>INSTANCE</em> member has already been set, we’ll skip initialization. This is called double-checked locking.</p>\n<p>This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not “see” that the <em>INSTANCE</em> member has been updated. This is because of how Java optimizes memory operations.</p>\n<p>Threads copy the original values of variables from main memory into the CPU’s cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread\u200a—\u200abeing processed by a different CPU or core, using a different cache\u200a—\u200awill not see the changes made by the first. This will cause the second thread to see the <em>INSTANCE</em> member as null forcing a new instance of our singleton to be created.</p>\n<hr />\n<pre><code>private static volatile MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronized(MySingleton.class) {\n if (INSTANCE == null) {\n INSTANCE = createInstance();\n }\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>We solve this by using the <em>volatile</em> keyword on the declaration of the <em>INSTANCE</em> member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.</p>\n<p>But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile <em>INSTANCE</em> member\u200a—\u200awhich we do four times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.</p>\n<hr />\n<pre><code>private static volatile MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n MySingleton result = INSTANCE;\n if (result == null) {\n synchronized(MySingleton.class) {\n result = INSTANCE;\n if (result == null) {\n INSTANCE = result = createInstance();\n }\n }\n }\n return result;\n}\n</code></pre>\n<p>Since the performance hit is due to operating directly on the volatile member, let’s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occurred while we were waiting for the lock.</p>\n<p>I wrote an article about this recently. <a href="https://medium.com/@michael.andrews/deconstructing-the-singleton-b5f881f85f5" rel="noreferrer">Deconstructing The Singleton</a>. You can find more information on these examples and an example of the "holder" pattern there. There is also a real-world example showcasing the double-checked volatile approach.</p>\n'}, {'answer_id': 52265460, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>The best singleton pattern I've ever seen uses the Supplier interface.</p>\n\n<ul>\n<li>It's generic and reusable</li>\n<li>It supports lazy initialization</li>\n<li>It's only synchronized until it has been initialized, then the blocking supplier is replaced with a non-blocking supplier.</li>\n</ul>\n\n<p>See below:</p>\n\n<pre><code>public class Singleton<T> implements Supplier<T> {\n\n private boolean initialized;\n private Supplier<T> singletonSupplier;\n\n public Singleton(T singletonValue) {\n this.singletonSupplier = () -> singletonValue;\n }\n\n public Singleton(Supplier<T> supplier) {\n this.singletonSupplier = () -> {\n // The initial supplier is temporary; it will be replaced after initialization\n synchronized (supplier) {\n if (!initialized) {\n T singletonValue = supplier.get();\n // Now that the singleton value has been initialized,\n // replace the blocking supplier with a non-blocking supplier\n singletonSupplier = () -> singletonValue;\n initialized = true;\n }\n return singletonSupplier.get();\n }\n };\n }\n\n @Override\n public T get() {\n return singletonSupplier.get();\n }\n}\n</code></pre>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11581/']
|
70,694 |
<p>I am trying to create a Task Scheduler task to start my SQL Server 2005 instance every morning, because something stops it every night. This is a temporary solution until I can diagnose the stoppage.</p>
<p>I created a task to run under my admin user, and to start the program, <em>cmd</em> with the arguments <em>/c net start mssqlserver</em>. When I manually run the command, in a console under my admin user, it runs, but when I try to manually execute the task, it logs the following message, and the service remains stopped:</p>
<p><em>action "C:\Windows\system32\cmd.EXE" with return code 2</em>.</p>
<p>Any suggestions?</p>
|
[{'answer_id': 70737, 'author': 'Neil Burroughs', 'author_id': 5166, 'author_profile': 'https://Stackoverflow.com/users/5166', 'pm_score': 6, 'selected': False, 'text': '<p>Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments against it.</p>\n<p>There\'s nothing inherently wrong with it I suppose, but it\'s just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I\'ve found <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection</a> (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.</p>\n'}, {'answer_id': 70749, 'author': 'macbirdie', 'author_id': 5049, 'author_profile': 'https://Stackoverflow.com/users/5049', 'pm_score': 4, 'selected': False, 'text': '<p>Wikipedia has some <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">examples</a> of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).</p>\n'}, {'answer_id': 70821, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Really consider why you need a singleton before writing it. There is a quasi-religious debate about using them which you can quite easily stumble over if you google singletons in Java.</p>\n<p>Personally, I try to avoid singletons as often as possible for many reasons, again most of which can be found by googling singletons. I feel that quite often singletons are abused because they\'re easy to understand by everybody. They\'re used as a mechanism for getting "global" data into an OO design and they are used because it is easy to circumvent object lifecycle management (or really thinking about how you can do A from inside B). Look at things like <a href="https://en.wikipedia.org/wiki/Inversion_of_control" rel="nofollow noreferrer">inversion of control</a> (IoC) or <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection</a> (DI) for a nice middle ground.</p>\n<p>If you really need one then Wikipedia has a good example of a proper implementation of a singleton.</p>\n'}, {'answer_id': 70824, 'author': 'Jonathan', 'author_id': 1772, 'author_profile': 'https://Stackoverflow.com/users/1772', 'pm_score': 7, 'selected': False, 'text': '<p>Forget <a href="https://en.wikipedia.org/wiki/Lazy_initialization" rel="nofollow noreferrer">lazy initialization</a>; it\'s too problematic. This is the simplest solution:</p>\n<pre><code>public class A { \n\n private static final A INSTANCE = new A();\n\n private A() {}\n\n public static A getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n'}, {'answer_id': 70829, 'author': 'Aleksi Yrttiaho', 'author_id': 11427, 'author_profile': 'https://Stackoverflow.com/users/11427', 'pm_score': 4, 'selected': False, 'text': "<p>If you do not need lazy loading then simply try:</p>\n<pre><code>public class Singleton {\n private final static Singleton INSTANCE = new Singleton();\n\n private Singleton() {}\n\n public static Singleton getInstance() { return Singleton.INSTANCE; }\n\n protected Object clone() {\n throw new CloneNotSupportedException();\n }\n}\n</code></pre>\n<p>If you want lazy loading and you want your singleton to be thread-safe, try the double-checking pattern:</p>\n<pre><code>public class Singleton {\n private static Singleton instance = null;\n\n private Singleton() {}\n\n public static Singleton getInstance() {\n if(null == instance) {\n synchronized(Singleton.class) {\n if(null == instance) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n }\n\n protected Object clone() {\n throw new CloneNotSupportedException();\n }\n}\n</code></pre>\n<p>As the double checking pattern is not guaranteed to work (due to some issue with compilers, I don't know anything more about that), you could also try to synchronize the whole getInstance-method or create a registry for all your singletons.</p>\n"}, {'answer_id': 70835, 'author': 'Stu Thompson', 'author_id': 2961, 'author_profile': 'https://Stackoverflow.com/users/2961', 'pm_score': 7, 'selected': False, 'text': "<p>Thread safe in Java 5+:</p>\n<pre><code>class Foo {\n private static volatile Bar bar = null;\n public static Bar getBar() {\n if (bar == null) {\n synchronized(Foo.class) {\n if (bar == null)\n bar = new Bar();\n }\n }\n return bar;\n }\n}\n</code></pre>\n<hr />\n<p>Pay attention to the <code>volatile</code> modifier here. :) It is important because without it, other threads are not guaranteed by the JMM (Java Memory Model) to see changes to its value. The synchronization <em>does not</em> take care of that--it only serializes access to that block of code.</p>\n<p>@Bno's answer details the approach recommended by Bill Pugh (FindBugs) and is arguable better. Go read and vote up his answer too.</p>\n"}, {'answer_id': 71399, 'author': 'Stephen Denne', 'author_id': 11721, 'author_profile': 'https://Stackoverflow.com/users/11721', 'pm_score': 11, 'selected': True, 'text': '<p>Use an enum:</p>\n\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n\n<p>Joshua Bloch explained this approach in his <a href="http://sites.google.com/site/io/effective-java-reloaded" rel="noreferrer">Effective Java Reloaded</a> talk at Google I/O 2008: <a href="http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s" rel="noreferrer">link to video</a>. Also see slides 30-32 of his presentation (<a href="https://14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/effective-java-reloaded/effective_java_reloaded.pdf?attachauth=ANoY7crKCOet2NEUGW7RV1XfM-Jn4z8YJhs0qJM11OhLRnFW_JbExkJtvJ3UJvTE40dhAciyWcRIeGJ-n3FLGnMOapHShHINh8IY05YViOJoZWzaohMtM-s4HCi5kjREagi8awWtcYD0_6G7GhKr2BndToeqLk5sBhZcQfcYIyAE5A4lGNosDCjODcBAkJn8EuO6572t2wU1LMSEUgjvqcf4I-Fp6VDhDvih_XUEmL9nuVJQynd2DRpxyuNH1SpJspEIdbLw-WWZ&attredirects=0" rel="noreferrer">effective_java_reloaded.pdf</a>):</p>\n\n<blockquote>\n <h3>The Right Way to Implement a Serializable Singleton</h3>\n\n<pre><code>public enum Elvis {\n INSTANCE;\n private final String[] favoriteSongs =\n { "Hound Dog", "Heartbreak Hotel" };\n public void printFavorites() {\n System.out.println(Arrays.toString(favoriteSongs));\n }\n}\n</code></pre>\n</blockquote>\n\n<p><strong>Edit:</strong> An <a href="http://www.ddj.com/java/208403883?pgno=3" rel="noreferrer">online portion of "Effective Java"</a> says: </p>\n\n<blockquote>\n <p>"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, <strong>a single-element enum type is the best way to implement a singleton</strong>."</p>\n</blockquote>\n'}, {'answer_id': 71574, 'author': 'Andrew Swan', 'author_id': 10433, 'author_profile': 'https://Stackoverflow.com/users/10433', 'pm_score': 4, 'selected': False, 'text': '<p>I\'m mystified by some of the answers that suggest <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow noreferrer">dependency injection</a> (DI) as an alternative to using singletons; these are unrelated concepts. You can use DI to inject either singleton or non-singleton (e.g., per-thread) instances. At least this is true if you use Spring 2.x, I can\'t speak for other DI frameworks.</p>\n<p>So my answer to the OP would be (in all but the most trivial sample code) to:</p>\n<ol>\n<li>Use a DI framework like <a href="https://en.wikipedia.org/wiki/Spring_Framework" rel="nofollow noreferrer">Spring Framework</a>, then</li>\n<li>Make it part of your DI configuration whether your dependencies are singletons, request scoped, session scoped, or whatever.</li>\n</ol>\n<p>This approach gives you a nice decoupled (and therefore flexible and testable) architecture where whether to use a singleton is an easily reversible implementation detail (provided any singletons you use are threadsafe, of course).</p>\n'}, {'answer_id': 71683, 'author': 'Benno Richters', 'author_id': 3565, 'author_profile': 'https://Stackoverflow.com/users/3565', 'pm_score': 7, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java/70835#70835">The solution posted by Stu Thompson</a> is valid in Java\xa05.0 and later. But I would prefer not to use it because I think it is error prone.</p>\n<p>It\'s easy to forget the volatile statement and difficult to understand why it is necessary. Without the volatile this code would not be thread safe any more due to the double-checked locking antipattern. See more about this in paragraph 16.2.4 of <a href="http://jcip.net/" rel="nofollow noreferrer" title="Java Concurrency in Practice">Java Concurrency in Practice</a>. In short: This pattern (prior to Java\xa05.0 or without the volatile statement) could return a reference to the Bar object that is (still) in an incorrect state.</p>\n<p>This pattern was invented for performance optimization. But this is really not a real concern any more. The following lazy initialization code is fast and - more importantly - easier to read.</p>\n<pre><code>class Bar {\n private static class BarHolder {\n public static Bar bar = new Bar();\n }\n\n public static Bar getBar() {\n return BarHolder.bar;\n }\n}\n</code></pre>\n'}, {'answer_id': 73763, 'author': 'Roel Spilker', 'author_id': 12634, 'author_profile': 'https://Stackoverflow.com/users/12634', 'pm_score': 8, 'selected': False, 'text': "<p>Depending on the usage, there are several "correct" answers.</p>\n<p>Since Java 5, the best way to do it is to use an enum:</p>\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n<p>Pre Java 5, the most simple case is:</p>\n<pre><code>public final class Foo {\n\n private static final Foo INSTANCE = new Foo();\n\n private Foo() {\n if (INSTANCE != null) {\n throw new IllegalStateException("Already instantiated");\n }\n }\n\n public static Foo getInstance() {\n return INSTANCE;\n }\n\n public Object clone() throws CloneNotSupportedException{\n throw new CloneNotSupportedException("Cannot clone instance of this class");\n }\n}\n</code></pre>\n<p>Let's go over the code. First, you want the class to be final. In this case, I've used the <code>final</code> keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a <code>private static final Foo</code> field to hold the only instance, and a <code>public static Foo getInstance()</code> method to return it. The Java specification makes sure that the constructor is only called when the class is first used.</p>\n<p>When you have a very large object or heavy construction code <em>and</em> also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.</p>\n<p>You can use a <code>private static class</code> to load the instance. The code would then look like:</p>\n<pre><code>public final class Foo {\n\n private static class FooLoader {\n private static final Foo INSTANCE = new Foo();\n }\n\n private Foo() {\n if (FooLoader.INSTANCE != null) {\n throw new IllegalStateException("Already instantiated");\n }\n }\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>Since the line <code>private static final Foo INSTANCE = new Foo();</code> is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.</p>\n<p>When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.</p>\n<pre><code>public final class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private static class FooLoader {\n private static final Foo INSTANCE = new Foo();\n }\n\n private Foo() {\n if (FooLoader.INSTANCE != null) {\n throw new IllegalStateException("Already instantiated");\n }\n }\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n\n @SuppressWarnings("unused")\n private Foo readResolve() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>The method <code>readResolve()</code> will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.</p>\n"}, {'answer_id': 74905, 'author': 'Georgi', 'author_id': 13209, 'author_profile': 'https://Stackoverflow.com/users/13209', 'pm_score': -1, 'selected': False, 'text': '<p>Sometimes a simple "<strong><code>static Foo foo = new Foo();</code></strong>" is not enough. Just think of some basic data insertion you want to do.</p>\n\n<p>On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution is</p>\n\n<pre><code>public class Singleton {\n\n private static Singleton instance = null;\n\n static {\n instance = new Singleton();\n // do some of your instantiation stuff here\n }\n\n private Singleton() {\n if(instance!=null) {\n throw new ErrorYouWant("Singleton double-instantiation, should never happen!");\n }\n }\n\n public static getSingleton() {\n return instance;\n }\n\n}\n</code></pre>\n\n<p>Now what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the <strong>static { }</strong> - block. that\'s the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.</p>\n'}, {'answer_id': 117516, 'author': 'Matt', 'author_id': 20630, 'author_profile': 'https://Stackoverflow.com/users/20630', 'pm_score': 4, 'selected': False, 'text': '<p>I use the <a href="https://en.wikipedia.org/wiki/Spring_Framework" rel="nofollow noreferrer">Spring Framework</a> to manage my singletons.</p>\n<p>It doesn\'t enforce the "singleton-ness" of the class (which you can\'t really do anyway if there are multiple class loaders involved), but it provides a really easy way to build and configure different factories for creating different types of objects.</p>\n'}, {'answer_id': 6918352, 'author': 'Onur', 'author_id': 776658, 'author_profile': 'https://Stackoverflow.com/users/776658', 'pm_score': 2, 'selected': False, 'text': '<p>You need the <a href="http://en.wikipedia.org/wiki/Double-checked_locking" rel="nofollow noreferrer">double-checking</a> idiom if you need to load the instance variable of a class lazily. If you need to load a static variable or a singleton lazily, you need the <a href="http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom" rel="nofollow noreferrer">initialization on demand holder</a> idiom.</p>\n<p>In addition, if the singleton needs to be serializable, all other fields need to be transient and readResolve() method needs to be implemented in order to maintain the singleton object invariant. Otherwise, each time the object is deserialized, a new instance of the object will be created. What readResolve() does is replace the new object read by readObject(), which forced that new object to be garbage collected as there is no variable referring to it.</p>\n<pre><code>public static final INSTANCE == ....\nprivate Object readResolve() {\n return INSTANCE; // Original singleton instance.\n} \n</code></pre>\n'}, {'answer_id': 14372745, 'author': 'NullPoiиteя', 'author_id': 1723893, 'author_profile': 'https://Stackoverflow.com/users/1723893', 'pm_score': 3, 'selected': False, 'text': '<p>I would say an enum singleton.</p>\n<p>Singleton using an enum in Java is generally a way to declare an enum singleton. An enum singleton may contain instance variables and instance methods. For simplicity\'s sake, also note that if you are using any instance method then you need to ensure thread safety of that method if at all it affects the state of object.</p>\n<p>The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.</p>\n<pre><code>/**\n* Singleton pattern example using a Java Enum\n*/\npublic enum Singleton {\n INSTANCE;\n public void execute (String arg) {\n // Perform operation here\n }\n}\n</code></pre>\n<p>You can access it by <code>Singleton.INSTANCE</code>, and it is much easier than calling the <code>getInstance()</code> method on Singleton.</p>\n<blockquote>\n<p>1.12 Serialization of Enum Constants</p>\n<p>Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form. To serialize an enum constant, <code>ObjectOutputStream</code> writes the value returned by the enum constant\'s name method. To deserialize an enum constant, <code>ObjectInputStream</code> reads the constant name from the stream; the deserialized constant is then obtained by calling the <code>java.lang.Enum.valueOf</code> method, passing the constant\'s enum type along with the received constant name as arguments. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream.</p>\n<p>The process by which enum constants are serialized cannot be customized: any class-specific <code>writeObject</code>, <code>readObject</code>, <code>readObjectNoData</code>, <code>writeReplace</code>, and <code>readResolve</code> methods defined by enum types are ignored during serialization and deserialization. Similarly, any <code>serialPersistentFields</code> or <code>serialVersionUID</code> field declarations are also ignored--all enum types have a fixed <code>serialVersionUID</code> of <code>0L</code>. Documenting serializable fields and data for enum types is unnecessary, since there is no variation in the type of data sent.</p>\n<p><a href="http://docs.oracle.com/javase/1.5.0/docs/guide/serialization/spec/serial-arch.html#enum" rel="nofollow noreferrer">Quoted from Oracle documentation</a></p>\n</blockquote>\n<p>Another problem with conventional Singletons are that once you implement the <code>Serializable</code> interface, they no longer remain singleton because the <code>readObject()</code> method always return a new instance, like a constructor in Java. This can be avoided by using <code>readResolve()</code> and discarding the newly created instance by replacing with a singleton like below:</p>\n<pre><code> // readResolve to prevent another instance of Singleton\n private Object readResolve(){\n return INSTANCE;\n }\n</code></pre>\n<p>This can become even more complex if your <em>singleton class</em> maintains state, as you need to make them transient, but with in an enum singleton, serialization is guaranteed by the JVM.</p>\n<hr />\n<p><strong>Good Read</strong></p>\n<ol>\n<li><a href="http://www.oodesign.com/singleton-pattern.html" rel="nofollow noreferrer">Singleton Pattern</a></li>\n<li><a href="https://stackoverflow.com/questions/13219678/enums-singletons-and-deserialization">Enums, Singletons and Deserialization</a></li>\n<li><a href="http://www.ibm.com/developerworks/java/library/j-dcl/index.html" rel="nofollow noreferrer">Double-checked locking and the Singleton pattern</a></li>\n</ol>\n'}, {'answer_id': 14917772, 'author': 'Abhijit Gaikwad', 'author_id': 403872, 'author_profile': 'https://Stackoverflow.com/users/403872', 'pm_score': 4, 'selected': False, 'text': "<p>Following are three different approaches</p>\n<ol>\n<li><p>Enum</p>\n<pre><code> /**\n * Singleton pattern example using Java Enum\n */\n public enum EasySingleton {\n INSTANCE;\n }\n</code></pre>\n</li>\n<li><p>Double checked locking / lazy loading</p>\n<pre><code> /**\n * Singleton pattern example with Double checked Locking\n */\n public class DoubleCheckedLockingSingleton {\n private static volatile DoubleCheckedLockingSingleton INSTANCE;\n\n private DoubleCheckedLockingSingleton() {}\n\n public static DoubleCheckedLockingSingleton getInstance() {\n if(INSTANCE == null) {\n synchronized(DoubleCheckedLockingSingleton.class) {\n // Double checking Singleton instance\n if(INSTANCE == null) {\n INSTANCE = new DoubleCheckedLockingSingleton();\n }\n }\n }\n return INSTANCE;\n }\n }\n</code></pre>\n</li>\n<li><p>Static factory method</p>\n<pre><code> /**\n * Singleton pattern example with static factory method\n */\n\n public class Singleton {\n // Initialized during class loading\n private static final Singleton INSTANCE = new Singleton();\n\n // To prevent creating another instance of 'Singleton'\n private Singleton() {}\n\n public static Singleton getSingleton() {\n return INSTANCE;\n }\n }\n</code></pre>\n</li>\n</ol>\n"}, {'answer_id': 16580366, 'author': 'Ajinkya', 'author_id': 705773, 'author_profile': 'https://Stackoverflow.com/users/705773', 'pm_score': 7, 'selected': False, 'text': '<p><strong>Disclaimer:</strong> I have just summarized all of the awesome answers and wrote it in my own words.</p>\n<hr />\n<p>While implementing Singleton we have two options:</p>\n<ol>\n<li>Lazy loading</li>\n<li>Early loading</li>\n</ol>\n<p>Lazy loading adds bit overhead (lots of to be honest), so use it only when you have a very large object or heavy construction code <em>and</em> also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization. Otherwise, choosing early loading is a good choice.</p>\n<p>The most simple way of implementing a singleton is:</p>\n<pre><code>public class Foo {\n\n // It will be our sole hero\n private static final Foo INSTANCE = new Foo();\n\n private Foo() {\n if (INSTANCE != null) {\n // SHOUT\n throw new IllegalStateException("Already instantiated");\n }\n }\n\n public static Foo getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>Everything is good except it\'s an early loaded singleton. Lets try lazy loaded singleton</p>\n<pre><code>class Foo {\n\n // Our now_null_but_going_to_be sole hero\n private static Foo INSTANCE = null;\n\n private Foo() {\n if (INSTANCE != null) {\n // SHOUT\n throw new IllegalStateException("Already instantiated");\n }\n }\n\n public static Foo getInstance() {\n // Creating only when required.\n if (INSTANCE == null) {\n INSTANCE = new Foo();\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>So far so good, but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero.\nSo let’s protect it from evil multi threading:</p>\n<pre><code>class Foo {\n\n private static Foo INSTANCE = null;\n\n // TODO Add private shouting constructor\n\n public static Foo getInstance() {\n // No more tension of threads\n synchronized (Foo.class) {\n if (INSTANCE == null) {\n INSTANCE = new Foo();\n }\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>But it is not enough to protect out hero, really!!! This is the best we can/should do to help our hero:</p>\n<pre><code>class Foo {\n\n // Pay attention to volatile\n private static volatile Foo INSTANCE = null;\n\n // TODO Add private shouting constructor\n\n public static Foo getInstance() {\n if (INSTANCE == null) { // Check 1\n synchronized (Foo.class) {\n if (INSTANCE == null) { // Check 2\n INSTANCE = new Foo();\n }\n }\n }\n return INSTANCE;\n }\n}\n</code></pre>\n<p>This is called the "double-checked locking idiom". It\'s easy to forget the volatile statement and difficult to understand why it is necessary.\nFor details: <em><a href="http://www.cs.umd.edu/%7Epugh/java/memoryModel/DoubleCheckedLocking.html" rel="noreferrer">The "Double-Checked Locking is Broken" Declaration</a></em></p>\n<p>Now we are sure about evil threads, but what about the cruel serialization? We have to make sure even while de-serialiaztion no new object is created:</p>\n<pre><code>class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n private static volatile Foo INSTANCE = null;\n\n // The rest of the things are same as above\n\n // No more fear of serialization\n @SuppressWarnings("unused")\n private Object readResolve() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>The method <code>readResolve()</code> will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.</p>\n<p>Finally, we have added enough protection against threads and serialization, but our code is looking bulky and ugly. Let’s give our hero a makeover:</p>\n<pre><code>public final class Foo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n // Wrapped in a inner static class so that loaded only when required\n private static class FooLoader {\n\n // And no more fear of threads\n private static final Foo INSTANCE = new Foo();\n }\n\n // TODO add private shouting construcor\n\n public static Foo getInstance() {\n return FooLoader.INSTANCE;\n }\n\n // Damn you serialization\n @SuppressWarnings("unused")\n private Foo readResolve() {\n return FooLoader.INSTANCE;\n }\n}\n</code></pre>\n<p>Yes, this is our very same hero :)</p>\n<p>Since the line <code>private static final Foo INSTANCE = new Foo();</code> is only executed when the class <code>FooLoader</code> is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread-safe.</p>\n<p>And we have come so far. Here is the best way to achieve everything we did is best possible way:</p>\n<pre><code>public enum Foo {\n INSTANCE;\n}\n</code></pre>\n<p>Which internally will be treated like</p>\n<pre><code>public class Foo {\n\n // It will be our sole hero\n private static final Foo INSTANCE = new Foo();\n}\n</code></pre>\n<p>That\'s it! No more fear of serialization, threads and ugly code. Also <a href="https://stackoverflow.com/questions/16771373/singleton-via-enum-way-is-lazy-initialized"><strong>ENUMS singleton are lazily initialized</strong></a>.</p>\n<blockquote>\n<p>This approach is functionally equivalent to the public field approach,\nexcept that it is more concise, provides the serialization machinery\nfor free, and provides an ironclad guarantee against multiple\ninstantiation, even in the face of sophisticated serialization or\nreflection attacks. While this approach has yet to be widely adopted,\na single-element enum type is the best way to implement a singleton.</p>\n</blockquote>\n<p>-Joshua Bloch in "Effective Java"</p>\n<p>Now you might have realized why ENUMS are considered as best way to implement a singleton and thanks for your patience :)</p>\n<p>Updated it on my <a href="http://ajinkyaparakh.blogspot.in/2013/05/implementing-singleton-in-java.html" rel="noreferrer"><strong>blog</strong></a>.</p>\n'}, {'answer_id': 16699497, 'author': 'raoadnan', 'author_id': 2392052, 'author_profile': 'https://Stackoverflow.com/users/2392052', 'pm_score': 2, 'selected': False, 'text': '<p>For JSE 5.0 and above, take the Enum approach. Otherwise, use the static singleton holder approach ((a lazy loading approach described by Bill Pugh). The latter solution is also thread-safe without requiring special language constructs (i.e., volatile or synchronized).</p>\n'}, {'answer_id': 19562324, 'author': 'rohan kamat', 'author_id': 2335562, 'author_profile': 'https://Stackoverflow.com/users/2335562', 'pm_score': 1, 'selected': False, 'text': '<p>Simplest singleton class:</p>\n<pre><code>public class Singleton {\n private static Singleton singleInstance = new Singleton();\n private Singleton() {}\n public static Singleton getSingleInstance() {\n return singleInstance;\n }\n}\n</code></pre>\n'}, {'answer_id': 19849576, 'author': 'somenath mukhopadhyay', 'author_id': 873952, 'author_profile': 'https://Stackoverflow.com/users/873952', 'pm_score': -1, 'selected': False, 'text': '<pre><code>public class Singleton {\n\n private static final Singleton INSTANCE = new Singleton();\n\n private Singleton() {\n if (INSTANCE != null)\n throw new IllegalStateException(“Already instantiated...”);\n }\n\n\n public synchronized static Singleton getInstance() {\n return INSTANCE;\n }\n\n}\n</code></pre>\n<p>As we have added the Synchronized keyword before getInstance, we have avoided the race condition in the case when two threads call the getInstance at the same time.</p>\n'}, {'answer_id': 27793921, 'author': 'shikjohari', 'author_id': 2595642, 'author_profile': 'https://Stackoverflow.com/users/2595642', 'pm_score': 0, 'selected': False, 'text': '<p>I still think after Java 1.5, enum is the best available singleton implementation available as it also ensures that, even in the multi threaded environments, only one instance is created.</p>\n<pre><code>public enum Singleton {\n INSTANCE;\n}\n</code></pre>\n<p>And you are done!</p>\n'}, {'answer_id': 29389322, 'author': 'coderz', 'author_id': 3275167, 'author_profile': 'https://Stackoverflow.com/users/3275167', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Version 1:</strong></p>\n\n<pre><code>public class MySingleton {\n private static MySingleton instance = null;\n private MySingleton() {}\n public static synchronized MySingleton getInstance() {\n if(instance == null) {\n instance = new MySingleton();\n }\n return instance;\n }\n}\n</code></pre>\n\n<p>Lazy loading, thread safe with blocking, low performance because of <code>synchronized</code>.</p>\n\n<p><strong>Version 2:</strong></p>\n\n<pre><code>public class MySingleton {\n private MySingleton() {}\n private static class MySingletonHolder {\n public final static MySingleton instance = new MySingleton();\n }\n public static MySingleton getInstance() {\n return MySingletonHolder.instance;\n }\n}\n</code></pre>\n\n<p>Lazy loading, thread safe with non-blocking, high performance.</p>\n'}, {'answer_id': 32130663, 'author': 'kenju', 'author_id': 2775013, 'author_profile': 'https://Stackoverflow.com/users/2775013', 'pm_score': 0, 'selected': False, 'text': '<p>Have a look at this post.</p>\n<p><a href="https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries">Examples of GoF Design Patterns in Java's core libraries</a></p>\n<p>From the best answer\'s "Singleton" section,</p>\n<blockquote>\n<h3>Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)</h3>\n<ul>\n<li>java.lang.Runtime#getRuntime()</li>\n<li>java.awt.Desktop#getDesktop()</li>\n<li>java.lang.System#getSecurityManager()</li>\n</ul>\n</blockquote>\n<p>You can also learn the example of Singleton from Java native classes themselves.</p>\n'}, {'answer_id': 32286179, 'author': 'Shailendra Singh', 'author_id': 2550410, 'author_profile': 'https://Stackoverflow.com/users/2550410', 'pm_score': 2, 'selected': False, 'text': '<p>Various ways to make a singleton object:</p>\n<ol>\n<li><p>As per <a href="https://en.wikipedia.org/wiki/Joshua_Bloch" rel="nofollow noreferrer">Joshua Bloch</a> - Enum would be the best.</p>\n</li>\n<li><p>You can use double check locking also.</p>\n</li>\n<li><p>Even an inner static class can be used.</p>\n</li>\n</ol>\n'}, {'answer_id': 32906229, 'author': 'Dan Moldovan', 'author_id': 2725534, 'author_profile': 'https://Stackoverflow.com/users/2725534', 'pm_score': 2, 'selected': False, 'text': '<p><strong>Enum singleton</strong></p>\n<p>The simplest way to implement a singleton that is thread-safe is using an Enum:</p>\n<pre><code>public enum SingletonEnum {\n INSTANCE;\n public void doSomething(){\n System.out.println("This is a singleton");\n }\n}\n</code></pre>\n<p>This code works since the introduction of Enum in Java 1.5</p>\n<p><strong>Double checked locking</strong></p>\n<p>If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.</p>\n<pre><code>public class Singleton {\n\n private static volatile Singleton instance = null;\n\n private Singleton() {\n }\n\n public static Singleton getInstance() {\n if (instance == null) {\n synchronized (Singleton.class){\n if (instance == null) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n }\n}\n</code></pre>\n<p>This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.</p>\n<p><strong>Early loading singleton (works even before Java 1.5)</strong></p>\n<p>This implementation instantiates the singleton when the class is loaded and provides thread safety.</p>\n<pre><code>public class Singleton {\n\n private static final Singleton instance = new Singleton();\n\n private Singleton() {\n }\n\n public static Singleton getInstance() {\n return instance;\n }\n\n public void doSomething(){\n System.out.println("This is a singleton");\n }\n\n}\n</code></pre>\n'}, {'answer_id': 37305099, 'author': 'Nicolas Filotto', 'author_id': 1997376, 'author_profile': 'https://Stackoverflow.com/users/1997376', 'pm_score': 2, 'selected': False, 'text': '<p>This is how to implement a simple <a href="https://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">singleton</a>:</p>\n<pre><code>public class Singleton {\n // It must be static and final to prevent later modification\n private static final Singleton INSTANCE = new Singleton();\n /** The constructor must be private to prevent external instantiation */\n private Singleton(){}\n /** The public static method allowing to get the instance */\n public static Singleton getInstance() {\n return INSTANCE;\n }\n}\n</code></pre>\n<p>This is how to properly lazy create your singleton:</p>\n<pre><code>public class Singleton {\n // The constructor must be private to prevent external instantiation\n private Singleton(){}\n /** The public static method allowing to get the instance */\n public static Singleton getInstance() {\n return SingletonHolder.INSTANCE;\n }\n /**\n * The static inner class responsible for creating your instance only on demand,\n * because the static fields of a class are only initialized when the class\n * is explicitly called and a class initialization is synchronized such that only\n * one thread can perform it, this rule is also applicable to inner static class\n * So here INSTANCE will be created only when SingletonHolder.INSTANCE\n * will be called\n */\n private static class SingletonHolder {\n private static final Singleton INSTANCE = new Singleton();\n }\n}\n</code></pre>\n'}, {'answer_id': 38942086, 'author': 'user3792852', 'author_id': 3792852, 'author_profile': 'https://Stackoverflow.com/users/3792852', 'pm_score': 2, 'selected': False, 'text': '<p>Another argument often used against singletons is their testability problems. Singletons are not easily mockable for testing purposes. If this turns out to be a problem, I like to make the following slight modification:</p>\n<pre><code>public class SingletonImpl {\n\n private static SingletonImpl instance;\n\n public static SingletonImpl getInstance() {\n if (instance == null) {\n instance = new SingletonImpl();\n }\n return instance;\n }\n\n public static void setInstance(SingletonImpl impl) {\n instance = impl;\n }\n\n public void a() {\n System.out.println("Default Method");\n }\n}\n</code></pre>\n<p>The added <code>setInstance</code> method allows setting a mockup implementation of the singleton class during testing:</p>\n<pre><code>public class SingletonMock extends SingletonImpl {\n\n @Override\n public void a() {\n System.out.println("Mock Method");\n }\n\n}\n</code></pre>\n<p>This also works with early initialization approaches:</p>\n<pre><code>public class SingletonImpl {\n\n private static final SingletonImpl instance = new SingletonImpl();\n\n private static SingletonImpl alt;\n\n public static void setInstance(SingletonImpl inst) {\n alt = inst;\n }\n\n public static SingletonImpl getInstance() {\n if (alt != null) {\n return alt;\n }\n return instance;\n }\n\n public void a() {\n System.out.println("Default Method");\n }\n}\n\npublic class SingletonMock extends SingletonImpl {\n\n @Override\n public void a() {\n System.out.println("Mock Method");\n }\n\n}\n</code></pre>\n<p>This has the drawback of exposing this functionality to the normal application too. Other developers working on that code could be tempted to use the ´setInstance´ method to alter a specific function and thus changing the whole application behaviour, and therefore this method should contain at least a good warning in its javadoc.</p>\n<p>Still, for the possibility of mockup-testing (when needed), this code exposure may be an acceptable price to pay.</p>\n'}, {'answer_id': 39098595, 'author': 'Dheeraj Sachan', 'author_id': 3314058, 'author_profile': 'https://Stackoverflow.com/users/3314058', 'pm_score': 3, 'selected': False, 'text': '<p>There are four ways to create a singleton in Java.</p>\n<ol>\n<li><p>Eager initialization singleton</p>\n<pre><code> public class Test {\n private static final Test test = new Test();\n\n private Test() {\n }\n\n public static Test getTest() {\n return test;\n }\n }\n</code></pre>\n</li>\n<li><p>Lazy initialization singleton (thread safe)</p>\n<pre><code> public class Test {\n private static volatile Test test;\n\n private Test() {\n }\n\n public static Test getTest() {\n if(test == null) {\n synchronized(Test.class) {\n if(test == null) {\n test = new Test();\n }\n }\n }\n return test;\n }\n }\n</code></pre>\n</li>\n<li><p>Bill Pugh singleton with holder pattern (preferably the best one)</p>\n<pre><code> public class Test {\n\n private Test() {\n }\n\n private static class TestHolder {\n private static final Test test = new Test();\n }\n\n public static Test getInstance() {\n return TestHolder.test;\n }\n }\n</code></pre>\n</li>\n<li><p>Enum singleton</p>\n<pre><code> public enum MySingleton {\n INSTANCE;\n\n private MySingleton() {\n System.out.println("Here");\n }\n }\n</code></pre>\n</li>\n</ol>\n'}, {'answer_id': 45062746, 'author': 'Michael Andrews', 'author_id': 1829927, 'author_profile': 'https://Stackoverflow.com/users/1829927', 'pm_score': 4, 'selected': False, 'text': '<p>There is a lot of nuance around implementing a singleton. The holder pattern can not be used in many situations. And IMO when using a volatile - you should also use a local variable. Let\'s start at the beginning and iterate on the problem. You\'ll see what I mean.</p>\n<hr />\n<p>The first attempt might look something like this:</p>\n<pre><code>public class MySingleton {\n\n private static MySingleton INSTANCE;\n\n public static MySingleton getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new MySingleton();\n }\n return INSTANCE;\n }\n ...\n}\n</code></pre>\n<p>Here we have the MySingleton class which has a private static member called <em>INSTANCE</em>, and a public static method called getInstance(). The first time getInstance() is called, the <em>INSTANCE</em> member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the <em>INSTANCE</em> variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().</p>\n<p>But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the <em>INSTANCE</em> member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the <em>INSTANCE</em> member.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static synchronized MySingleton getInstance() {\n if (INSTANCE == null) {\n INSTANCE = new MySingleton();\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we’ve used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance; it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of <em>INSTANCE</em>. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronize(MySingleton.class) {\n INSTANCE = new MySingleton();\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we’ve moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we’ve also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the <em>INSTANCE</em> member as null.</p>\n<p>They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.</p>\n<hr />\n<pre><code>private static MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronized(MySingleton.class) {\n if (INSTANCE == null) {\n INSTANCE = createInstance();\n }\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>Here we issue another check from <em>inside</em> the block. If the <em>INSTANCE</em> member has already been set, we’ll skip initialization. This is called double-checked locking.</p>\n<p>This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not “see” that the <em>INSTANCE</em> member has been updated. This is because of how Java optimizes memory operations.</p>\n<p>Threads copy the original values of variables from main memory into the CPU’s cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread\u200a—\u200abeing processed by a different CPU or core, using a different cache\u200a—\u200awill not see the changes made by the first. This will cause the second thread to see the <em>INSTANCE</em> member as null forcing a new instance of our singleton to be created.</p>\n<hr />\n<pre><code>private static volatile MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n if (INSTANCE == null) {\n synchronized(MySingleton.class) {\n if (INSTANCE == null) {\n INSTANCE = createInstance();\n }\n }\n }\n return INSTANCE;\n}\n</code></pre>\n<p>We solve this by using the <em>volatile</em> keyword on the declaration of the <em>INSTANCE</em> member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.</p>\n<p>But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile <em>INSTANCE</em> member\u200a—\u200awhich we do four times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.</p>\n<hr />\n<pre><code>private static volatile MySingleton INSTANCE;\n\npublic static MySingleton getInstance() {\n MySingleton result = INSTANCE;\n if (result == null) {\n synchronized(MySingleton.class) {\n result = INSTANCE;\n if (result == null) {\n INSTANCE = result = createInstance();\n }\n }\n }\n return result;\n}\n</code></pre>\n<p>Since the performance hit is due to operating directly on the volatile member, let’s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occurred while we were waiting for the lock.</p>\n<p>I wrote an article about this recently. <a href="https://medium.com/@michael.andrews/deconstructing-the-singleton-b5f881f85f5" rel="noreferrer">Deconstructing The Singleton</a>. You can find more information on these examples and an example of the "holder" pattern there. There is also a real-world example showcasing the double-checked volatile approach.</p>\n'}, {'answer_id': 52265460, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>The best singleton pattern I've ever seen uses the Supplier interface.</p>\n\n<ul>\n<li>It's generic and reusable</li>\n<li>It supports lazy initialization</li>\n<li>It's only synchronized until it has been initialized, then the blocking supplier is replaced with a non-blocking supplier.</li>\n</ul>\n\n<p>See below:</p>\n\n<pre><code>public class Singleton<T> implements Supplier<T> {\n\n private boolean initialized;\n private Supplier<T> singletonSupplier;\n\n public Singleton(T singletonValue) {\n this.singletonSupplier = () -> singletonValue;\n }\n\n public Singleton(Supplier<T> supplier) {\n this.singletonSupplier = () -> {\n // The initial supplier is temporary; it will be replaced after initialization\n synchronized (supplier) {\n if (!initialized) {\n T singletonValue = supplier.get();\n // Now that the singleton value has been initialized,\n // replace the blocking supplier with a non-blocking supplier\n singletonSupplier = () -> singletonValue;\n initialized = true;\n }\n return singletonSupplier.get();\n }\n };\n }\n\n @Override\n public T get() {\n return singletonSupplier.get();\n }\n}\n</code></pre>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70694', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8741/']
|
70,705 |
<p>In my day job I, and others on my team write a lot of hardware models in Verilog-AMS, a language supported primarily by commercial vendors and a few opensource simulator projects.
One thing that would make supporting each others code more helpful would be a LINTER that would check our code for common problems and assist with enforcing a shared code formatting style.
I of course want to be able to add my own rules and, after I prove their utility to myself, promote them to the rest of the team..
I don't mind doing the work that has to be done, but of course also want to leverage the work of other existing projects. </p>
<p>Does having the allowed language syntax in a yacc or bison format give me a leg up?
or should I just suck each language statement into a perl string, and use pattern matching to find the things I don't like? </p>
<p>(most syntax and compilation errors are easily caught by the commercial tools.. but we have some of our own extentions.) </p>
|
[{'answer_id': 70718, 'author': 'Chris Kimpton', 'author_id': 48310, 'author_profile': 'https://Stackoverflow.com/users/48310', 'pm_score': 0, 'selected': False, 'text': '<p>In trying to find my answer, I found this on <a href="http://www.ibm.com/developerworks/edu/au-dw-au-parsingwithantlr-i.html" rel="nofollow noreferrer">ANTLR</a> - might be of use</p>\n'}, {'answer_id': 70722, 'author': 'Chris Kimpton', 'author_id': 48310, 'author_profile': 'https://Stackoverflow.com/users/48310', 'pm_score': 0, 'selected': False, 'text': '<p>If you use Java at all (and thus IDEA), the IDE\'s <a href="http://www.jetbrains.com/idea/plugins/developing_custom_language_plugins.html" rel="nofollow noreferrer">extensions for custom languages</a> might be of use</p>\n'}, {'answer_id': 70723, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 0, 'selected': False, 'text': "<p><code>yacc</code>/<code>bison</code> definitely gives you a leg up, since good linting would require parsing the program. Regex (true regex, at least) might cover trivial cases, but it is easy to write code that the regexes don't match but are still bad style.</p>\n"}, {'answer_id': 70945, 'author': 'jbdavid', 'author_id': 6314, 'author_profile': 'https://Stackoverflow.com/users/6314', 'pm_score': 0, 'selected': False, 'text': "<p>ANTLR looks to be an alternative path to the more common (OK <em>I</em> heard about them before) YACC/BISON approach, which it turns out also commonly use LEX/FLEX as a front end. </p>\n\n<p>a Quick read of the FLEX man page kind of make me think It could be the framework for that regex type of idea.. </p>\n\n<p>Ok.. I'll let this stew a little longer, then see how quickly I can build a prototype parser in one or the other. </p>\n\n<p>and a little bit longer</p>\n"}, {'answer_id': 99954, 'author': 'Matt J', 'author_id': 18528, 'author_profile': 'https://Stackoverflow.com/users/18528', 'pm_score': 5, 'selected': True, 'text': "<p>lex/flex and yacc/bison provide easy-to-use, well-understood lexer- and parser-generators, and I'd really recommend doing something like that as opposed to doing it procedurally in e.g. Perl. Regular expressions are powerful stuff for ripping apart strings with relatively-, but not totally-fixed structure. With any real programming language, the size of your state machine gets to be simply unmanageable with anything short of a Real Lexer/Parser (tm). Imagine dealing with all possible interleavings of keywords, identifiers, operators, extraneous parentheses, extraneous semicolons, and comments that are allowed in something like Verilog AMS, with regular expressions and procedural code alone.</p>\n\n<p>There's no denying that there's a substantial learning curve there, but writing a grammar that you can use for flex and bison, and doing something useful on the syntax tree that comes out of bison, will be a much better use of your time than writing a ton of special-case string-processing code that's more naturally dealt with using a syntax-tree in the first place. Also, what you learn writing it this way will truly broaden your skillset in ways that writing a bunch of hacky Perl code just won't, so if you have the means, I highly recommend it ;-)</p>\n\n<p>Also, if you're lazy, check out the Eclipse plugins that do syntax highlighting and basic refactoring for Verilog and VHDL. They're in an incredibly primitive state, last I checked, but they may have some of the code you're looking for, or at least a baseline piece of code to look at to better inform your approach in rolling your own.</p>\n"}, {'answer_id': 294416, 'author': 'user37248', 'author_id': 37248, 'author_profile': 'https://Stackoverflow.com/users/37248', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve written a couple verilog parsers and I would suggest PCCTS/ANTLR if your favorite programming language is C/C++/Java. There is a <a href="http://www.antlr.org/grammar/verilog/verilog.g" rel="nofollow noreferrer">PCCTS/ANTLR Verilog grammar</a> that you can start with. My favorite parser generator is <a href="http://www.cliki.net/Zebu" rel="nofollow noreferrer">Zebu</a> which is based on Common Lisp.</p>\n\n<p>Of course the big job is to specify all the linting rules. It makes sense to make some kind of language to specify the linting rules as well.</p>\n'}, {'answer_id': 997554, 'author': 'd3jones', 'author_id': 111215, 'author_profile': 'https://Stackoverflow.com/users/111215', 'pm_score': 2, 'selected': False, 'text': "<p>Don't underestimate the amount of work that goes into a linter. Parsing is the easy part because you have tools (bison, flex, ANTLR/PCCTS) to automate much of it.</p>\n\n<p>But once you have a parse, then what? You must build a semantic tree for the design. Depending on how complicated your inputs are, you must elaborate the Verilog-AMS design (i.e. resolving parameters, unrolling generates, etc. If you use those features). And only then can you try to implement rules.</p>\n\n<p>I'd seriously consider other possible solutions before writing a linter, unless the number of users and potential time savings thereby justify the development time.</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6314/']
|
70,721 |
<p>Last Friday where I work, an oracle client was upgarded and our IIS server from version 9 to version 10. Now that its on version 10, we are seeing a lot of connections being open up to the database. It is opening up so many connections that we cannot log onto the database using tools like PlSQL developer or Toad. We never had an issue like this when the oracle client was at version 9. Because of the number of clients that exists on this particular box, i dont think it will be possible to revert back to the Oracle 9 client.
Is anyone aware of this problem or know of any possible work arounds?</p>
<p>Any help is greatly appreciated</p>
|
[{'answer_id': 70718, 'author': 'Chris Kimpton', 'author_id': 48310, 'author_profile': 'https://Stackoverflow.com/users/48310', 'pm_score': 0, 'selected': False, 'text': '<p>In trying to find my answer, I found this on <a href="http://www.ibm.com/developerworks/edu/au-dw-au-parsingwithantlr-i.html" rel="nofollow noreferrer">ANTLR</a> - might be of use</p>\n'}, {'answer_id': 70722, 'author': 'Chris Kimpton', 'author_id': 48310, 'author_profile': 'https://Stackoverflow.com/users/48310', 'pm_score': 0, 'selected': False, 'text': '<p>If you use Java at all (and thus IDEA), the IDE\'s <a href="http://www.jetbrains.com/idea/plugins/developing_custom_language_plugins.html" rel="nofollow noreferrer">extensions for custom languages</a> might be of use</p>\n'}, {'answer_id': 70723, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 0, 'selected': False, 'text': "<p><code>yacc</code>/<code>bison</code> definitely gives you a leg up, since good linting would require parsing the program. Regex (true regex, at least) might cover trivial cases, but it is easy to write code that the regexes don't match but are still bad style.</p>\n"}, {'answer_id': 70945, 'author': 'jbdavid', 'author_id': 6314, 'author_profile': 'https://Stackoverflow.com/users/6314', 'pm_score': 0, 'selected': False, 'text': "<p>ANTLR looks to be an alternative path to the more common (OK <em>I</em> heard about them before) YACC/BISON approach, which it turns out also commonly use LEX/FLEX as a front end. </p>\n\n<p>a Quick read of the FLEX man page kind of make me think It could be the framework for that regex type of idea.. </p>\n\n<p>Ok.. I'll let this stew a little longer, then see how quickly I can build a prototype parser in one or the other. </p>\n\n<p>and a little bit longer</p>\n"}, {'answer_id': 99954, 'author': 'Matt J', 'author_id': 18528, 'author_profile': 'https://Stackoverflow.com/users/18528', 'pm_score': 5, 'selected': True, 'text': "<p>lex/flex and yacc/bison provide easy-to-use, well-understood lexer- and parser-generators, and I'd really recommend doing something like that as opposed to doing it procedurally in e.g. Perl. Regular expressions are powerful stuff for ripping apart strings with relatively-, but not totally-fixed structure. With any real programming language, the size of your state machine gets to be simply unmanageable with anything short of a Real Lexer/Parser (tm). Imagine dealing with all possible interleavings of keywords, identifiers, operators, extraneous parentheses, extraneous semicolons, and comments that are allowed in something like Verilog AMS, with regular expressions and procedural code alone.</p>\n\n<p>There's no denying that there's a substantial learning curve there, but writing a grammar that you can use for flex and bison, and doing something useful on the syntax tree that comes out of bison, will be a much better use of your time than writing a ton of special-case string-processing code that's more naturally dealt with using a syntax-tree in the first place. Also, what you learn writing it this way will truly broaden your skillset in ways that writing a bunch of hacky Perl code just won't, so if you have the means, I highly recommend it ;-)</p>\n\n<p>Also, if you're lazy, check out the Eclipse plugins that do syntax highlighting and basic refactoring for Verilog and VHDL. They're in an incredibly primitive state, last I checked, but they may have some of the code you're looking for, or at least a baseline piece of code to look at to better inform your approach in rolling your own.</p>\n"}, {'answer_id': 294416, 'author': 'user37248', 'author_id': 37248, 'author_profile': 'https://Stackoverflow.com/users/37248', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve written a couple verilog parsers and I would suggest PCCTS/ANTLR if your favorite programming language is C/C++/Java. There is a <a href="http://www.antlr.org/grammar/verilog/verilog.g" rel="nofollow noreferrer">PCCTS/ANTLR Verilog grammar</a> that you can start with. My favorite parser generator is <a href="http://www.cliki.net/Zebu" rel="nofollow noreferrer">Zebu</a> which is based on Common Lisp.</p>\n\n<p>Of course the big job is to specify all the linting rules. It makes sense to make some kind of language to specify the linting rules as well.</p>\n'}, {'answer_id': 997554, 'author': 'd3jones', 'author_id': 111215, 'author_profile': 'https://Stackoverflow.com/users/111215', 'pm_score': 2, 'selected': False, 'text': "<p>Don't underestimate the amount of work that goes into a linter. Parsing is the easy part because you have tools (bison, flex, ANTLR/PCCTS) to automate much of it.</p>\n\n<p>But once you have a parse, then what? You must build a semantic tree for the design. Depending on how complicated your inputs are, you must elaborate the Verilog-AMS design (i.e. resolving parameters, unrolling generates, etc. If you use those features). And only then can you try to implement rules.</p>\n\n<p>I'd seriously consider other possible solutions before writing a linter, unless the number of users and potential time savings thereby justify the development time.</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11612/']
|
70,724 |
<p>In my job we have to deploy an application on various environments. It's a standard WAR file which needs a bit of configuration, deployed on Tomcat 6.</p>
<p>Is there any way of creating a 'deployment package' with Tomcat so that you just extract it and it sets up Tomcat as well as your application? I'm not sure that creating a .zip file with the Tomcat folder would work! It certainly wouldn't install the service.</p>
<p>Suggestions welcome!</p>
<p>I should note that - at the moment - all apps are deployed on Windows servers.</p>
<p>Thanks,
Phill</p>
|
[{'answer_id': 70718, 'author': 'Chris Kimpton', 'author_id': 48310, 'author_profile': 'https://Stackoverflow.com/users/48310', 'pm_score': 0, 'selected': False, 'text': '<p>In trying to find my answer, I found this on <a href="http://www.ibm.com/developerworks/edu/au-dw-au-parsingwithantlr-i.html" rel="nofollow noreferrer">ANTLR</a> - might be of use</p>\n'}, {'answer_id': 70722, 'author': 'Chris Kimpton', 'author_id': 48310, 'author_profile': 'https://Stackoverflow.com/users/48310', 'pm_score': 0, 'selected': False, 'text': '<p>If you use Java at all (and thus IDEA), the IDE\'s <a href="http://www.jetbrains.com/idea/plugins/developing_custom_language_plugins.html" rel="nofollow noreferrer">extensions for custom languages</a> might be of use</p>\n'}, {'answer_id': 70723, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 0, 'selected': False, 'text': "<p><code>yacc</code>/<code>bison</code> definitely gives you a leg up, since good linting would require parsing the program. Regex (true regex, at least) might cover trivial cases, but it is easy to write code that the regexes don't match but are still bad style.</p>\n"}, {'answer_id': 70945, 'author': 'jbdavid', 'author_id': 6314, 'author_profile': 'https://Stackoverflow.com/users/6314', 'pm_score': 0, 'selected': False, 'text': "<p>ANTLR looks to be an alternative path to the more common (OK <em>I</em> heard about them before) YACC/BISON approach, which it turns out also commonly use LEX/FLEX as a front end. </p>\n\n<p>a Quick read of the FLEX man page kind of make me think It could be the framework for that regex type of idea.. </p>\n\n<p>Ok.. I'll let this stew a little longer, then see how quickly I can build a prototype parser in one or the other. </p>\n\n<p>and a little bit longer</p>\n"}, {'answer_id': 99954, 'author': 'Matt J', 'author_id': 18528, 'author_profile': 'https://Stackoverflow.com/users/18528', 'pm_score': 5, 'selected': True, 'text': "<p>lex/flex and yacc/bison provide easy-to-use, well-understood lexer- and parser-generators, and I'd really recommend doing something like that as opposed to doing it procedurally in e.g. Perl. Regular expressions are powerful stuff for ripping apart strings with relatively-, but not totally-fixed structure. With any real programming language, the size of your state machine gets to be simply unmanageable with anything short of a Real Lexer/Parser (tm). Imagine dealing with all possible interleavings of keywords, identifiers, operators, extraneous parentheses, extraneous semicolons, and comments that are allowed in something like Verilog AMS, with regular expressions and procedural code alone.</p>\n\n<p>There's no denying that there's a substantial learning curve there, but writing a grammar that you can use for flex and bison, and doing something useful on the syntax tree that comes out of bison, will be a much better use of your time than writing a ton of special-case string-processing code that's more naturally dealt with using a syntax-tree in the first place. Also, what you learn writing it this way will truly broaden your skillset in ways that writing a bunch of hacky Perl code just won't, so if you have the means, I highly recommend it ;-)</p>\n\n<p>Also, if you're lazy, check out the Eclipse plugins that do syntax highlighting and basic refactoring for Verilog and VHDL. They're in an incredibly primitive state, last I checked, but they may have some of the code you're looking for, or at least a baseline piece of code to look at to better inform your approach in rolling your own.</p>\n"}, {'answer_id': 294416, 'author': 'user37248', 'author_id': 37248, 'author_profile': 'https://Stackoverflow.com/users/37248', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve written a couple verilog parsers and I would suggest PCCTS/ANTLR if your favorite programming language is C/C++/Java. There is a <a href="http://www.antlr.org/grammar/verilog/verilog.g" rel="nofollow noreferrer">PCCTS/ANTLR Verilog grammar</a> that you can start with. My favorite parser generator is <a href="http://www.cliki.net/Zebu" rel="nofollow noreferrer">Zebu</a> which is based on Common Lisp.</p>\n\n<p>Of course the big job is to specify all the linting rules. It makes sense to make some kind of language to specify the linting rules as well.</p>\n'}, {'answer_id': 997554, 'author': 'd3jones', 'author_id': 111215, 'author_profile': 'https://Stackoverflow.com/users/111215', 'pm_score': 2, 'selected': False, 'text': "<p>Don't underestimate the amount of work that goes into a linter. Parsing is the easy part because you have tools (bison, flex, ANTLR/PCCTS) to automate much of it.</p>\n\n<p>But once you have a parse, then what? You must build a semantic tree for the design. Depending on how complicated your inputs are, you must elaborate the Verilog-AMS design (i.e. resolving parameters, unrolling generates, etc. If you use those features). And only then can you try to implement rules.</p>\n\n<p>I'd seriously consider other possible solutions before writing a linter, unless the number of users and potential time savings thereby justify the development time.</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70724', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
70,732 |
<p>Lasty, I tried to implements an hybrid structure in Java, something that looks like:</p>
<pre><code>public class MapOfSet<K, V extends HasKey<K>> implements Set<V>, Map<K, Set<V>>
</code></pre>
<p>Where HasKey is the following interface:</p>
<pre><code>public interface HasKey<K> {
public K getKey();
}
</code></pre>
<p>Unfortunately, there are some conflicts between methos signature of the Set interface and the Map interface in Java. I've finally chosen to implements only the Set interface and to add the Map method without implementing this interface.</p>
<p>Do you see a nicer solution?</p>
<p>In response to the first comments, here is my goal:</p>
<blockquote>
<p>Have a set structure and be able to efficiently access to a subset of values of this set, corresponding to a given key value.
At the beginning I instantiated a map and a set, but I tried to joined the two structures to optimize performances.</p>
</blockquote>
|
[{'answer_id': 70760, 'author': 'Avi', 'author_id': 1605, 'author_profile': 'https://Stackoverflow.com/users/1605', 'pm_score': 0, 'selected': False, 'text': '<p>I would say that something that is meant to be sometimes used as a Map and sometimes as a Set should implement Map, since that can be viewed as a set of keys or values as well as a mapping between keys and values. That is what the Map.containsKey() and Map.containsValue() methods are for.</p>\n'}, {'answer_id': 70772, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 2, 'selected': False, 'text': '<p>What are you trying to accomplish? <code>Map</code> already exposes its keys as a <code>Set</code> via its [keySet()](<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet())" rel="nofollow noreferrer">http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet())</a> method. If you want a reliable iteratior order, there\'s <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html" rel="nofollow noreferrer">LinkedHashMap</a> and <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html" rel="nofollow noreferrer">TreeMap</a>.</p>\n\n<p>UPDATE: If you want to ensure that a value has only been inserted once, you can extend one of the classes I mentioned above to create something like a <code>SingleEntryMap</code> and override the implementation of <code>put(K key, V value)</code> to do a uniqueness check and throw an Exception when the value has already been inserted.</p>\n\n<p>UPDATE: Will something like this work? (I don\'t have my editor up, so this may not compile)</p>\n\n<pre><code>public final class KeyedSets<K, V> implements Map<K,Set<V>> {\n private final Map<K, Set<V>> internalMap = new TreeMap<K, Set<V>>;\n // delegate methods go here\n public Set<V> getSortedSuperset() {\n final Set<V> superset = new TreeSet<V>();\n for (final Map.Entry<K, V> entry : internalMap.entrySet()) {\n superset.addAll(entry.getValue());\n }\n return superset;\n }\n}\n</code></pre>\n'}, {'answer_id': 70962, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 2, 'selected': True, 'text': '<p>Perhaps you could add more information which operations do you really want. I guess you want to create a set which automatically groups their elements by a key, right? The question is which operations do you want to be able to have? How are elements added to the Set? Can elements be deleted by removing them from a grouped view? My proposal would be an interface like that:</p>\n\n<pre><code>public interface GroupedSet<K, V extends HasKey<K>> extends Set<V>{\n Set<V> havingKey(K k);\n}\n</code></pre>\n\n<p>If you want to be able to use the Set as map you can add another method</p>\n\n<pre><code>Map<K,Set<V>> asMap();\n</code></pre>\n\n<p>That avoids the use of multiple interface inheritance and the resulting problems.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1730/']
|
70,742 |
<p>I administrate several Oracle Apps environment, and currently check profile options in lots of environments by loading up forms in each environment, and manually checking each variable, which requires a lot of time.</p>
<p>Is there a snippet of code which will list profile options and at what level and who they are applied to?</p>
|
[{'answer_id': 71141, 'author': 'Sten Vesterli', 'author_id': 9363, 'author_profile': 'https://Stackoverflow.com/users/9363', 'pm_score': 2, 'selected': True, 'text': '<p>You\'ll want to query <code>APPLSYS.FND_PROFILE_OPTIONS</code> and <code>FND_PROFILE_OPTION_VALUES</code>. \nFor a comprehensive script that you can pick up the SQL from, look here: \n<a href="http://tipsnscripts.com/?p=16" rel="nofollow noreferrer">http://tipsnscripts.com/?p=16</a></p>\n'}, {'answer_id': 71387, 'author': 'Jonathan', 'author_id': 6910, 'author_profile': 'https://Stackoverflow.com/users/6910', 'pm_score': 0, 'selected': False, 'text': "<p>Armed with the knowledge of which tables to get (thanks Sten) and a bit of judicious editing, I have come up with a query which serves my needs:</p>\n\n<pre><code>SELECT SUBSTR(e.profile_option_name,1,30) PROFILE,\n DECODE(a.level_id,10001,'Site',10002,'Application',10003,'Responsibility',10004,'User') L,\n DECODE(a.level_id,10001,'Site',10002,c.application_short_name,10003,b.responsibility_name,10004,d.user_name) LValue,\n NVL(a.profile_option_value,'Is Null') Value,\n SUBSTR(a.last_update_date,1,25) UPDATED_DATE\nFROM fnd_profile_option_values a\nINNER JOIN fnd_profile_options e ON a.profile_option_id = e.profile_option_id \nLEFT OUTER JOIN fnd_responsibility_tl b ON a.level_value = b.responsibility_id\nLEFT OUTER JOIN fnd_application c ON a.level_value = c.application_id\nLEFT OUTER JOIN fnd_user d ON a.level_value = d.user_id\nWHERE e.profile_option_name LIKE '%&1%'\nORDER BY profile_option_name;\n</code></pre>\n"}, {'answer_id': 6454817, 'author': 'caodan740', 'author_id': 812300, 'author_profile': 'https://Stackoverflow.com/users/812300', 'pm_score': 0, 'selected': False, 'text': "<pre><code>SELECT SUBSTR(e.profile_option_name,1,30) PROFILE,\n DECODE(a.level_id,10001,'Site',10002,'Application',10003,'Responsibility',10004,'User') L,\n DECODE(a.level_id,10001,'Site',10002,c.application_short_name,10003,b.responsibility_name,10004,d.user_name) LValue,\n NVL(a.profile_option_value,'Is Null') Value,\n SUBSTR(a.last_update_date,1,25) UPDATED_DATE\nFROM fnd_profile_option_values a\nINNER JOIN fnd_profile_options e ON a.profile_option_id = e.profile_option_id \nLEFT OUTER JOIN fnd_responsibility_tl b ON a.level_value = b.responsibility_id\nLEFT OUTER JOIN fnd_application c ON a.level_value = c.application_id\nLEFT OUTER JOIN fnd_user d ON a.level_value = d.user_id\nWHERE e.profile_option_name LIKE '%&1%'\nORDER BY profile_option_name;\n</code></pre>\n"}, {'answer_id': 7261709, 'author': 'SJ-Admin', 'author_id': 922224, 'author_profile': 'https://Stackoverflow.com/users/922224', 'pm_score': 1, 'selected': False, 'text': '<p>I hope this will help you get more granular information when you try to track down changes by users.</p>\n\n<pre><code>SELECT FP.LEVEL_ID "Level ID", \n FPO.PROFILE_OPTION_NAME "PROFILE NAME",\n FP.LEVEL_VALUE "LEVEL VALUE",\n DECODE (FP.LEVEL_ID,\n 10001,\n \'SITE\',\n 10002,\n \'APPLICATION\',\n 10003,\n \'RESPONSIBILITY\',\n 10004,\n \'USER\')\n "LEVEL",\n DECODE (FP.LEVEL_ID,\n 10001,\n \'SITE\',\n 10002,\n APPLICATION_SHORT_NAME,\n 10003,\n RESPONSIBILITY_NAME,\n 10004,\n FL.USER_NAME)\n LVALUE,\n FPO.USER_PROFILE_OPTION_NAME "PROFILE DESCRIPTION",\n FP.PROFILE_OPTION_VALUE "PROFILE VALUE",\n FU.USER_NAME "USER NAME",\n FU.LAST_UPDATE_DATE\nFROM FND_PROFILE_OPTIONS_VL FPO,\n FND_PROFILE_OPTION_VALUES FP,\n FND_RESPONSIBILITY_TL,\n FND_APPLICATION FA,\n FND_USER FL,\n FND_USER FU\nWHERE FPO.APPLICATION_ID = FP.APPLICATION_ID\n AND FPO.PROFILE_OPTION_ID = FP.PROFILE_OPTION_ID\n AND FP.LEVEL_VALUE = FL.USER_ID(+)\n AND FP.LEVEL_VALUE = RESPONSIBILITY_ID(+)\n AND FP.LEVEL_VALUE = FA.APPLICATION_ID(+)\n AND FU.USER_ID = FP.LAST_UPDATED_BY\n AND FP.PROFILE_OPTION_VALUE IS NOT NULL\n AND (UPPER (FP.Profile_Option_Value) LIKE UPPER (\'%&1%\')\n OR UPPER (FP.Profile_Option_Value) LIKE UPPER (\'%&2%\'))\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70742', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6910/']
|
70,753 |
<p>I intend to use <strong>RADIX / MTRIE</strong> as my preferred data-structure for a routing implementation. </p>
<p>Is there a decent open source implementation available (apart from freebsd-net) which I can use for my purpose, or do I need to write one myself?</p>
|
[{'answer_id': 71021, 'author': 'prakash', 'author_id': 123, 'author_profile': 'https://Stackoverflow.com/users/123', 'pm_score': 0, 'selected': False, 'text': '<p>If you cant find anything else, you can always port this <a href="http://code.google.com/p/radixtree/" rel="nofollow noreferrer"><strong>java version from Google Code</strong>.</a> </p>\n'}, {'answer_id': 71063, 'author': 'Andrew Johnson', 'author_id': 5109, 'author_profile': 'https://Stackoverflow.com/users/5109', 'pm_score': 2, 'selected': True, 'text': '<p>There is a radix-tree implementation available under the GNU General Public License version 2, or (at your option) any later version: </p>\n\n<p><a href="http://www.gelato.unsw.edu.au/lxr/source/lib/radix-tree.c" rel="nofollow noreferrer">http://www.gelato.unsw.edu.au/lxr/source/lib/radix-tree.c</a></p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11605/']
|
70,755 |
<p>And if you do, can you give some background information on the implementation and the reasons for implementing this pattern?</p>
<p>The pattern is described in more detail in these articles:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms997506.aspx" rel="nofollow noreferrer">Microsoft Inductive User Interface
Guidelines</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms951103.aspx" rel="nofollow noreferrer">IUIs and Web-Style
Navigation in Windows Forms, Part 1</a> & <a href="http://msdn.microsoft.com/en-us/library/ms951278.aspx" rel="nofollow noreferrer">Part 2</a></li>
</ul>
|
[{'answer_id': 70831, 'author': 'John Sibly', 'author_id': 1078, 'author_profile': 'https://Stackoverflow.com/users/1078', 'pm_score': 4, 'selected': True, 'text': '<p>Yes - we had a problem in that many of the administrators of our software found it too difficult to use. To solve this we used Microsoft\'s WinForms IUI framework build a new configuration and management tool for our software. </p>\n\n<p>User feedback has been extremely positive, particularly with everything being task driven - i.e. the links on our home page include thing like "Create new user", "Create new department" - rather then the user having to discover how to do this by clicking through a series of menus. Since the inductive interface is more similar to a web-browser (hypertext links, back/forward buttons) it seems much easier for new users to learn.</p>\n'}, {'answer_id': 289543, 'author': 'Peter Gfader', 'author_id': 35693, 'author_profile': 'https://Stackoverflow.com/users/35693', 'pm_score': 2, 'selected': False, 'text': '<p>I would suggest to use IUI Interfaces, whenever you use a software not on a daily basis...</p>\n\n<p>Whenever you use an application only once a month, it could be very usefull to be guided through...</p>\n\n<p>I have implemented IUI always manual, or at least used a Wizard-User-Control.</p>\n'}, {'answer_id': 289585, 'author': 'smerten', 'author_id': 37288, 'author_profile': 'https://Stackoverflow.com/users/37288', 'pm_score': 1, 'selected': False, 'text': '<p>You should be careful about making a too simple system. Expert users (bankers, insurers, CRMs, etc) should have as much information an possibilites on the screen as possible. Proceeding through forms that validate slowly has been found to be annyoing if you use that form several times during the workday.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70755', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4830/']
|
70,756 |
<p>This confusion arises as most people are trained to evaluate arithmetic expressions as per <a href="http://en.wikipedia.org/wiki/PEMDAS#Mnemonics" rel="nofollow noreferrer">PEDMAS or BODMAS rule</a> whereas arithmetic expressions in programming languages like C# do not work in the same way.</p>
<p>What are your takes on it?</p>
|
[{'answer_id': 70851, 'author': 'benefactual', 'author_id': 6445, 'author_profile': 'https://Stackoverflow.com/users/6445', 'pm_score': 2, 'selected': False, 'text': '<p>I am not sure there really is a difference. The traditional BODMAS (brackets, orders, division, multiplication, addition, subtraction) or PEDMAS (parentheses, exponents, division, multiplication, addition, subtraction) are just subsets of all the possible operations and denote the order that such operations should be applied in. I don\'t know of any language in which the BODMAS/PEDMAS rules are violated, but each language typically adds various other operators - such as ++, --, = etc.</p>\n\n<p>I always keep a list of operator precedence close to hand in case of confusion. However when in doubt it is usually worth using some parentheses to make the meaning clear. Just be aware that parentheses do not have the highest precedence - see <a href="http://msdn.microsoft.com/en-us/library/126fe14k.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/126fe14k.aspx</a> for an example in C++.</p>\n'}, {'answer_id': 70861, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 2, 'selected': False, 'text': "<p>Precedence and associativity both specify how and in which order a term should be split into subterms. In other words does it specifies the rules where brackets are to be set implicitly if not specified explicitly.</p>\n\n<p>If you've got a term without brackets, you start with operators with lowest precedence and enclose it in brackets.</p>\n\n<p>For example:</p>\n\n<p>Precendences:</p>\n\n<ol>\n<li>.</li>\n<li>!</li>\n<li>*,/</li>\n<li>+,-</li>\n<li>==</li>\n<li>&& </li>\n</ol>\n\n<p>The term:</p>\n\n<pre><code>!person.isMarried && person.age == 25 + 2 * 5\n</code></pre>\n\n<p>would be grouped like that:</p>\n\n<ol>\n<li>!(person.isMarried) && (person.age) == 25 + 2 * 5</li>\n<li>(!(person.isMarried)) && (person.age) == 25 + 2 * 5</li>\n<li>(!(person.isMarried)) && (person.age) == 25 + (2 * 5)</li>\n<li>(!(person.isMarried)) && (person.age) == (25 + (2 * 5))</li>\n<li>(!(person.isMarried)) && ((person.age) == (25 + (2 * 5)))</li>\n<li>((!(person.isMarried)) && ((person.age) == (25 + (2 * 5))))</li>\n</ol>\n\n<p>One very common rule is the precedence of * and / before + and - .</p>\n\n<p>Associativity specifies in which direction operators of the same precedence are grouped. Most operators are left-to-right. Unary prefix operators are right-to-left.</p>\n\n<p>Example:</p>\n\n<pre><code>1 + 2 + 3 + 4\n</code></pre>\n\n<p>is grouped like that:</p>\n\n<ol>\n<li>(1 + 2) + 3 + 4</li>\n<li>((1 + 2) + 3) + 4</li>\n<li>(((1 + 2) + 3) + 4)</li>\n</ol>\n\n<p>while</p>\n\n<p>!!+1</p>\n\n<p>is grouped as</p>\n\n<ol>\n<li>!!(+1)</li>\n<li>!(!(+1))</li>\n<li>(!(!(+1)))</li>\n</ol>\n\n<p>So far everything complies to the BODMAS/PEDMAS rules which differences have you experienced?</p>\n"}, {'answer_id': 70881, 'author': 'Matej', 'author_id': 11457, 'author_profile': 'https://Stackoverflow.com/users/11457', 'pm_score': 3, 'selected': False, 'text': '<p><em>Precedence</em> rules specify priority of operators (which operators will be evaluated first, e.g. multiplication has higher precedence than addition, PEMDAS). </p>\n\n<p>The <em>associativity</em> rules tell how the operators of same precedence are grouped. Arithmetic operators are left-associative, but the assignment is right associative (e.g. a = b = c will be evaluated as b = c, a = b). </p>\n\n<p>The <em>order</em> is a result of applying the <em>precedence</em> and <em>associativity</em> rules and tells how the expression will be evaluated - which operators will be evaluated firs, which later, which at the end. The actual order can be changed by using <em>braces</em> (braces are also operator with the highest precedence). </p>\n\n<p>The <em>precedence</em> and <em>associativity</em> of operators in a programming language can be found in its language manual or specification. </p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4021/']
|
70,758 |
<p>I know you can put <% if %> statements in the ItemTemplate to hide controls but the column is still there.
You cannot put <% %> statements into the LayoutTemplate which is where the column headings are declared, hence the problem.
Does anyone know of a better way?</p>
|
[{'answer_id': 70955, 'author': 'Magnus Johansson', 'author_id': 3584, 'author_profile': 'https://Stackoverflow.com/users/3584', 'pm_score': 0, 'selected': False, 'text': "<p>You can always set the column width to 0 (zero) if you don't find a better way.</p>\n"}, {'answer_id': 71015, 'author': 'Jason', 'author_id': 7391, 'author_profile': 'https://Stackoverflow.com/users/7391', 'pm_score': 0, 'selected': False, 'text': '<p>The listview doesn\'t really have a concept of \'column\' since it is intended just to be, well, a list.</p>\n\n<p>I\'m going to assume that you are using databinding to attach a list of \'somethings\' to the ListView. If that is the case then you will just have a list of items and the html in the LayoutTemplate will decide on just how those items are displayed. If you are then talking about creating a table-style array of columns and rows then maybe a DataGrid would be a better choice since this gives much more programmatic control of specific columns.</p>\n\n<p>It may be that you are hoping to create the table layout entirely through CSS, which is an admirable decision <strong>if</strong> it is purely for layout purposes. However, your requirement to specifically hide one column indicates to me that a table is better placed to suit your needs. It\'s fine to use tables for tabular data...IMHO...</p>\n\n<p>If you really do need to use a ListView then you could always try binding against something in your data which determines whether an element should be shown or not, e.g.:</p>\n\n<pre><code>style=\'display: <%#Eval("DisplayStyle") %>;\'\n</code></pre>\n\n<p>Place this code within the html element that you want to control (in the LayoutTemplate). Then in the object you are binding to you would need a property \'DisplayStyle\' which was either set to \'block\' or \'none\'.</p>\n'}, {'answer_id': 71261, 'author': 'Dean Poulin', 'author_id': 5462, 'author_profile': 'https://Stackoverflow.com/users/5462', 'pm_score': 1, 'selected': False, 'text': '<p>The ListView gives you full control about how the data is rendered to the client. You specify the Layout Template, and give a placeholder which will be where each item is injected.</p>\n\n<p>The output of the below will give you a table, and each item will be a new TR.</p>\n\n<p>Notice the use of runat=\'server\' and <code>visible =\'<%# %>\'</code></p>\n\n<pre><code><asp:ListView ID="ListView1" runat="server" DataSourceID="MyDataSource" ItemPlaceholderID="itemPlaceHolder">\n <LayoutTemplate>\n <table>\n <asp:PlaceHolder ID="itemPlaceHolder" runat="server" />\n </table>\n </LayoutTemplate>\n <ItemTemplate>\n <tr>\n <td runat="server" id="myCol" visible=\'<%# (bool)Eval("IsSuperCool") %>\'>\n <%# Eval("SuperCoolIcon") %>\n </td>\n <td>\n <%# Eval("Name") %>\n </td>\n <td>\n <%# Eval("Age") %>\n </td>\n </tr>\n </ItemTemplate>\n</asp:ListView>\n</code></pre>\n'}, {'answer_id': 76264, 'author': 'Dean Poulin', 'author_id': 5462, 'author_profile': 'https://Stackoverflow.com/users/5462', 'pm_score': 5, 'selected': True, 'text': '<p>Here\'s another solution that I just did, seeing that I understand what you want to do:</p>\n\n<p><strong>Here\'s your ASCX / ASPX</strong></p>\n\n<pre><code> <asp:ListView ID="ListView1" runat="server" DataSourceID="MyDataSource" ItemPlaceholderID="itemPlaceHolder" OnDataBound="ListView1_DataBound">\n <LayoutTemplate>\n <table border="1">\n <tr>\n <td>Name</td>\n <td>Age</td>\n <td runat="server" id="tdIsSuperCool">IsSuperCool</td>\n </tr>\n <asp:PlaceHolder ID="itemPlaceHolder" runat="server" />\n </table>\n </LayoutTemplate>\n <ItemTemplate>\n <tr>\n <td><%# Eval("Name") %></td>\n <td><%# Eval("Age") %></td>\n <td runat="server" id="myCol" visible=\'<%# (bool)Eval("IsSuperCool") %>\'>true</td>\n </tr>\n </ItemTemplate>\n </asp:ListView>\n <asp:ObjectDataSource \n ID="MyDataSource" \n runat="server" \n DataObjectTypeName="BusinessLogicLayer.Thing" \n SelectMethod="SelectThings"\n TypeName="BusinessLogicLayer.MyObjectDataSource" />\n</code></pre>\n\n<p><strong>Here\'s the code behind</strong></p>\n\n<pre><code>/// <summary>\n/// Handles the DataBound event of the ListView1 control.\n/// </summary>\n/// <param name="sender">The source of the event.</param>\n/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>\nprotected void ListView1_DataBound(object sender, EventArgs e)\n{\n ListView1.FindControl("tdIsSuperCool").Visible = false;\n}\n</code></pre>\n\n<p>Do whatever you want in the databound. Because the column is now runat server, and you\'re handling the DataBound of the control, when you do ListView1.FindControl("tdIsSuperCool") you\'re in the Layout template so that works like a champ.</p>\n\n<p>Put whatever business logic that you want to control the visibility of the td and you\'re good.</p>\n'}, {'answer_id': 118758, 'author': 'Fred', 'author_id': 9012, 'author_profile': 'https://Stackoverflow.com/users/9012', 'pm_score': 2, 'selected': False, 'text': '<p>Try Using a Panel and you can turn it on / Off</p>\n\n<pre><code> foreach (ListViewItem item in ListView1.Items)\n {\n ((Panel)item.FindControl("myPanel")).Visible= False;\n }\n</code></pre>\n'}, {'answer_id': 5425699, 'author': 'yaktipper', 'author_id': 675730, 'author_profile': 'https://Stackoverflow.com/users/675730', 'pm_score': 0, 'selected': False, 'text': '<p>To access the layout template column header text, I made them labels in the template, and did a findcontrol in the prerender of the listview, then made the labels blank text if the column should be "off". This might not work for your intentions, but for me I still wanted the column space to be used, just appear blank.</p>\n\n<p>The further you go try to make a listview bend over backwards, the more you will wish you used a grid instead.</p>\n'}, {'answer_id': 41151941, 'author': 'jason', 'author_id': 1709186, 'author_profile': 'https://Stackoverflow.com/users/1709186', 'pm_score': 1, 'selected': False, 'text': '<p>I know it\'s a very old question, but I\'m actually having to do this and think I found a fairly nice way to do it through jquery and css.</p>\n\n<p>Add the following to the header:</p>\n\n<pre><code><script type="text/javascript" src="Scripts/jquery-1.7.1.min.js" ></script>\n <style>\n .hide {\n display:none;\n }\n .show {\n display:block;\n }\n </style>\n</code></pre>\n\n<p>For all columns that you want to hide, add a custom property to the td/th.</p>\n\n<pre><code><th runat="server" data-prop=\'authcheck\' id="tdcommentsHeader" >Comments</th>\n</code></pre>\n\n<p>I\'m advising to use a custom property because, long story short, it can kill a bunch of birds with one stone. You won\'t even need to change the value for each column, as you would if we based this on the id property.</p>\n\n<p>Next, ensure you have a hidden field that tells lets you know whether or not to hide the column. This can be an asp:HiddenField or any other so long as it\'s on the form.</p>\n\n<pre><code><asp:HiddenField runat="server" ID="IsAuthorized" Value="false" />\n</code></pre>\n\n<p>Finally, at the bottom of the page, do:</p>\n\n<pre><code> <script type="text/javascript">\n $(document).ready(function () {\n var isauth = $("[id=\'IsAuthorized\']").val();\n if (isauth==="false") {\n $("[data-prop=\'authcheck\']").addClass(\'hide\');\n //$("[id*=\'tdcomments\']").addClass(\'hide\'); \n }\n });\n </script>\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10186/']
|
70,762 |
<p>Suppose I've found a “text” somewhere in open access (say, on public network share). I have no means to contact the author, I even don't know who is the author.</p>
<p>What can I legally do with such “text”?</p>
<p><strong>Update:</strong> I am not going to publish that “text”, but rather learn from it myself.</p>
<p><strong>Update:</strong> So, if I ever see an anonymous code, article, whatever, shouldn't I even open it, because otherwise I'd copy its contents to my brain?</p>
|
[{'answer_id': 70795, 'author': 'warren', 'author_id': 4418, 'author_profile': 'https://Stackoverflow.com/users/4418', 'pm_score': 1, 'selected': False, 'text': '<p>As far as I <em>know</em> (without any legal training) - if you list the text or code or whathaveyou as "anonymous", you\'re OK. </p>\n\n<p>I believe that by listing it as anonymous you\'re indicating you do not know where it came from, but you\'re admitting you didn\'t create it as original work.</p>\n\n<p>Extending from that, you should be open to the actual author being able to prove they are the author, and changing your usage to reflect their name/license/copyright/whatever.</p>\n\n<p>You should check with an Intellectual Property lawyer for details and corrections to my understanding.</p>\n'}, {'answer_id': 70836, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 4, 'selected': True, 'text': '<p>IANAL: There is no license. The original author (whoever it may be) retains copyright and all the rights associated with it, and has not granted any explicit license to anyone to do anything with their work. Please do check with an actual lawyer versed in copyright, though, since it seems like there should be a way to use the text in your particular circumstances and (s)he would likely know what that way is.</p>\n\n<p>UPDATE: Copyright is chiefly concerned with (re)distribution; if you can read it, you\'re free to learn from it, although the <a href="http://en.wikipedia.org/wiki/Digital_Millennium_Copyright_Act" rel="nofollow noreferrer">DMCA</a> places legal restrictions on what steps you can take to be able to read it, e.g., you aren\'t supposed to use <a href="http://en.wikipedia.org/wiki/DeCSS" rel="nofollow noreferrer">DeCSS</a> to read subtitles since that is a "circumvention of access control".</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1764/']
|
70,773 |
<p>What are the pros / cons of using <code>pthread_cond_wait</code> or using a semaphore ?
I am waiting for a state change like this :</p>
<pre><code>pthread_mutex_lock(&cam->video_lock);
while(cam->status == WAIT_DISPLAY) {
pthread_cond_wait(&cam->video_cond, &cam->video_lock);
}
pthread_mutex_unlock(&cam->video_lock);
</code></pre>
<p>Using a properly initialised semaphore, I think I could do it like this :</p>
<pre><code>while(cam->status == WAIT_DISPLAY) {
sem_wait(&some_semaphore);
}
</code></pre>
<p>What are the pros and cons of each method ?</p>
|
[{'answer_id': 70924, 'author': 'Javier', 'author_id': 11649, 'author_profile': 'https://Stackoverflow.com/users/11649', 'pm_score': 0, 'selected': False, 'text': "<p>In your second snippet, you're getting the lock multitude of times, never releasing it.</p>\n\n<p>In general, the state you're waintin on can be completely expressed by a semaphore, then you can use just that. A lock structure is smaller in size, and it requires less atomic operations to check/set/release.</p>\n\n<p>Otherwise, if the state is complex, and different parts of the code wait on different conditions of the same variable (eg, here you want x<10; there you want y>x), use cond_wait.</p>\n"}, {'answer_id': 71301, 'author': 'freespace', 'author_id': 8297, 'author_profile': 'https://Stackoverflow.com/users/8297', 'pm_score': 4, 'selected': False, 'text': "<p>Conditionals let you do some things that semaphores won't.</p>\n\n<p>For example, suppose you have some code which requires a mutex, called <code>m</code>. It however needs to wait until some other thread has finish their task, so it waits on a semaphore called <code>s</code>. Now any thread which needs <code>m</code> is blocked from running, even though the thread which has <code>m</code> is waiting on <code>s</code>. These kind of situations can be resolved using conditionals. When you wait on a conditional, the mutex currently held is released, so other threads can acquire the mutex. So back to our example, and suppose conditional <code>c</code> was used instead of <code>s</code>. Our thread now acquires <code>m</code>, and then conditional waits on <code>c</code>. This releases <code>m</code> so other threads can proceed. When <code>c</code> becomes available, <code>m</code> is reacquired, and our original thread can continue merrily along its way.</p>\n\n<p>Conditional variables also allows you to let <em>all</em> threads waiting on a conditional variable to proceed via <code>pthread_cond_broadcast</code>. Additionally it also allows you to perform a <em>timed wait</em> so you don't end up waiting forever.</p>\n\n<p>Of course, sometimes you don't need conditional variables, so depending on your requirements, one or the other may be better. </p>\n"}, {'answer_id': 108918, 'author': 'Steve Jessop', 'author_id': 13005, 'author_profile': 'https://Stackoverflow.com/users/13005', 'pm_score': 7, 'selected': True, 'text': "<p>A semaphore is suited cleanly to a producer-consumer model, although it has other uses. Your program logic is responsible for ensuring that the right number of posts are made for the number of waits. If you post a semaphore and nobody is waiting on it yet, then when they do wait they continue immediately. If your problem is such that it can be explained in terms of the count value of a semaphore, then it should be easy to solve with a semaphore.</p>\n\n<p>A condition variable is a bit more forgiving in some respects. You can for example use cond_broadcast to wake up all waiters, without the producer knowing how many there are. And if you cond_signal a condvar with nobody waiting on it then nothing happens. This is good if you don't know whether there's going to be a listener interested. It is also why the listener should always check the state with the mutex held before waiting - if they don't then they can miss a signal and not wake up until the next one (which could be never).</p>\n\n<p>So a condition variable is suitable for notifying interested parties that state has changed: you acquire the mutex, change the state, signal (or broadcast) the condvar and release the mutex. If this describes your problem you're in condvar territory. If different listeners are interested in different states you can just broadcast and they'll each in turn wake up, figure out whether they've found the state they want, and if not wait again.</p>\n\n<p>It's very gnarly indeed to attempt this sort of thing with a mutex and a semaphore. The problem comes when you want to take the mutex, check some state, then wait on the semaphore for changes. Unless you can atomically release the mutex and wait on the semaphore (which in pthreads you can't), you end up waiting on the semaphore while holding the mutex. This blocks the mutex, meaning that others can't take it to make the change you care about. So you will be tempted to add another mutex in a way which depends on your specific requirements. And maybe another semaphore. The result is generally incorrect code with harmful race conditions.</p>\n\n<p>Condition variables escape this problem, because calling cond_wait automatically releases the mutex, freeing it for use by others. The mutex is regained before cond_wait returns.</p>\n\n<p>IIRC it is possible to implement a kind of condvar using only semaphores, but if the mutex you're implementing to go with the condvar is required to have trylock, then it's a serious head-scratcher, and timed waits are out. Not recommended. So don't assume that anything you can do with a condvar can be done with semaphores. Plus of course mutexes can have nice behaviours that semaphores lack, principally priority-inversion avoidance.</p>\n"}, {'answer_id': 434872, 'author': 'Blaisorblade', 'author_id': 53974, 'author_profile': 'https://Stackoverflow.com/users/53974', 'pm_score': 3, 'selected': False, 'text': '<p>The 2nd snippet is racy, don\'t do that.</p>\n\n<p>The other answers have a nice discussion of the relative merits; I\'ll just add that <code>pthread_cond_broadcast</code> is a clear advantage of condition variables.</p>\n\n<p>Beyond that, I\'m just more used to condition variables for that, as they are what you use in Java, even because they help you to avoid races when checking the shared flags.</p>\n\n<p>Indeed, in the 2nd snippet you don\'t have any lock protecting the read of cam->status, so it is accessed through a data race. Most platforms will let you get away with that in this particular example, but that has undefined semantics, by POSIX and by the memory model of the next C/C++ standards.</p>\n\n<p>In fact, a real race condition is possible if another thread allocates a new cam structure and overwrites cam; the waiting thread might see the update to the \'cam\' pointer without seeing the initialization of cam->status. Indeed, the 2nd snippet is asking for trouble, in this case and in general.</p>\n\n<p><a href="http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/" rel="noreferrer">http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/</a></p>\n'}, {'answer_id': 71291384, 'author': 'Abhishek Sagar', 'author_id': 756120, 'author_profile': 'https://Stackoverflow.com/users/756120', 'pm_score': 0, 'selected': False, 'text': '<pre><code>while(cam->status == WAIT_DISPLAY) {\n sem_wait(&some_semaphore);\n}\n</code></pre>\n<p>This is completely wrong. This is prone to race condition. By the time the thread blocks on sem_Wait, the condition cam->status == WAIT_DISPLAY may not hold good in the system as some other thread may have modified it. So, your thread is now sleeping for all wrong reasons.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11589/']
|
70,779 |
<p>I need to be able to quickly convert an image (inside a rails controller) so that the hosting company using managing our application can quickly test at any time to ensure that rmagick is not only successfully installed, but can be called throgh the rails stiack, what is the quickest clean code I can use to do this?</p>
|
[{'answer_id': 70932, 'author': 'tomafro', 'author_id': 7126, 'author_profile': 'https://Stackoverflow.com/users/7126', 'pm_score': 0, 'selected': False, 'text': "<p>I'd log on to the server and try out your code in script/console. This will still go through the rails stack, but will allow you to quickly check that your code works the way you expect and that RMagick and ImageMagick are correctly installed without having to deploy anything.</p>\n\n<p>When the time comes to write your actual code, I'd suggest putting the image conversion code inside a model, so you can call it outside the context of a controller.</p>\n"}, {'answer_id': 70952, 'author': 'Asaf Bartov', 'author_id': 7483, 'author_profile': 'https://Stackoverflow.com/users/7483', 'pm_score': 0, 'selected': False, 'text': "<p>Use script/console, and call code in a model or a controller that does something like the following:</p>\n\n<pre><code>require 'RMagick'\ninclude Magick\nimg = ImageList.new('myfile.jpg')\nimg.crop(0,0,10,10) # or whatever\nimg.write('mycroppedfile.jpg')\n</code></pre>\n"}, {'answer_id': 71527, 'author': 'Laurie Young', 'author_id': 7473, 'author_profile': 'https://Stackoverflow.com/users/7473', 'pm_score': 3, 'selected': True, 'text': '<p>I wanted to do this so that I can easily hit it with a web browser, as I\'m deployng to managed servers, which I do not have shell access onto (for increased security).</p>\n\n<p>So this is what I did</p>\n\n<pre><code>class DiagnosticsController < ApplicationController\n require \'RMagick\'\n\n def rmagick\n images_path = "public/images"\n file_name = "rmagick_generated_thumb.jpg"\n file_path = images_path + "/"+ file_name\n\n File.delete file_path if File.exists? file_path\n img = Magick::Image.read("lib/sample_images/magic.jpg").first\n thumb = img.scale(0.25)\n @path = file_name\n thumb.write file_path\n end\nend #------\n</code></pre>\n\n<p>and then in rmagick.html.erb</p>\n\n<pre><code><%= image_tag @path %>\n</code></pre>\n\n<p>Now I can hit the controller, and if I see an image, I know rmagic is installed.</p>\n'}, {'answer_id': 72582, 'author': 'Scott', 'author_id': 7399, 'author_profile': 'https://Stackoverflow.com/users/7399', 'pm_score': 4, 'selected': False, 'text': "<pre><code>require 'RMagick'\n\nimage = Magick::Image.new(110, 30){ self.background_color = 'white' }\nimage.write('/tmp/test.jpg')\n</code></pre>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7473/']
|
70,781 |
<p>I'm really interested to hear what you think about Model-driven Software Development for Java and/or .NET.</p>
<p>Does it save time? Does it improve quality?</p>
|
[{'answer_id': 70791, 'author': 'Maximilian', 'author_id': 1733, 'author_profile': 'https://Stackoverflow.com/users/1733', 'pm_score': 0, 'selected': False, 'text': '<p>It sure sounds nice but I have yet to see it implemented in a practially working way.</p>\n\n<p>I hold it like this: The Code is the model. That way your model and your code are always up to date :-)</p>\n'}, {'answer_id': 70810, 'author': 'Mendelt', 'author_id': 3320, 'author_profile': 'https://Stackoverflow.com/users/3320', 'pm_score': 3, 'selected': False, 'text': "<p>MDA is a bit of an overloaded concept. Sometimes it means turning UML or another type of diagrams in to executable code. I've never seen this work out well with the tools available nowadays. It usually causes projects to get results really fast and then cause a maintanance nightmare because the tools available don't really support big teams working on visual diagrams and because people start working in the diagrams as well as the generated code.</p>\n\n<p>I've seen something that looked a lot like domain driven design being referred to as MDA, if you mean that I'm all for it :-)</p>\n"}, {'answer_id': 155468, 'author': 'Lorenzo Boccaccia', 'author_id': 2273540, 'author_profile': 'https://Stackoverflow.com/users/2273540', 'pm_score': -1, 'selected': False, 'text': "<p>MDA usually make difficult to integrate the business rules inside the server side layer, as the model view mapping is handled by generated code and functional hooks are provided as event responders. </p>\n\n<p>Still I've not seen a MDA tool as powerful as Forté (or UDS, now dead) + Express were. I imagine that a MDA with the Forté capabilities plus better pattern to achieve an independent service layer (as ActiveRecord, or EntityTransactionManager patterns) would be a killer app for whatever platform.</p>\n\n<p>The problem with actual application aiming at the three tiered MDA approach is that those are terribly difficult to set up and adapt to specific requirements. Just think of ABAP and SAP rates</p>\n"}, {'answer_id': 155493, 'author': 'dacracot', 'author_id': 13930, 'author_profile': 'https://Stackoverflow.com/users/13930', 'pm_score': 1, 'selected': False, 'text': '<p>I think it preferable. That is what I was trying to imply on <a href="https://stackoverflow.com/questions/140098/is-mvc-ars-preferable-to-classic-mvc-to-prevent-overloading">this question</a> about MVC-ARS rather than MVC. The ARS (Action/Representation/State) is contained within the model by design and prevents the overloading of controller or view.</p>\n'}, {'answer_id': 277021, 'author': 'Ted Johnson', 'author_id': 30231, 'author_profile': 'https://Stackoverflow.com/users/30231', 'pm_score': 0, 'selected': False, 'text': "<p>Just to throw in two books I found useful in understanding MDA as stated above it is a broad subject. </p>\n\n<ul>\n<li>MDA Distilled - Principles of Model-Driven Architecture. (Mellor)</li>\n<li>Real-life MDA: Solving Business Problems with Model Driven Architecture (Guttman)</li>\n</ul>\n\n<p>You don't need to read all of the Guttman to get the idea as the case studies get boring, but the intro was pleasant to read.</p>\n"}, {'answer_id': 277481, 'author': 'akuhn', 'author_id': 24468, 'author_profile': 'https://Stackoverflow.com/users/24468', 'pm_score': 2, 'selected': False, 'text': '<p>Buzz.</p>\n\n<p>What I believe in, OTOH, is modeling at runtime. Instead of generating code, keep the model alive at runtime and let your application be a runtime interpreter of these models.</p>\n\n<p>I dont know if this has been done for Java. For Smalltalk see <a href="http://www.lukas-renggli.ch/smalltalk/magritte" rel="nofollow noreferrer">Magritte</a>, which is used in Seaside.</p>\n'}, {'answer_id': 820359, 'author': 'Mark Dalgarno', 'author_id': 50140, 'author_profile': 'https://Stackoverflow.com/users/50140', 'pm_score': 1, 'selected': False, 'text': "<p>Model-Driven Software Development isn't just about MDA, there are a set of other approaches including the, perhaps more popular, Domain-Specific Languages approach.</p>\n\n<p>Sure, the code is 'a' model, but capturing a higher-level model in a DSL is an even more concise way of expressing the same intent. The key is to <strong>always</strong> generate your code from the model rather than allowing independent modification of generated code.</p>\n\n<p>There's plenty of tooling available, and plenty of published material, including case studies, to tell you how to build your own generators if you're not happy buying an off-the-shelf generator. Arguably this gives you more control than working with a general-purpose programming language.</p>\n"}, {'answer_id': 1041384, 'author': 'Roland', 'author_id': 124408, 'author_profile': 'https://Stackoverflow.com/users/124408', 'pm_score': 4, 'selected': True, 'text': '<p>I am using MDSD in a project with IBM Rational Rhapsody for C++. The model is pretty close to UML, so there we do not really have a Domain-Specific-Language. But still I would claim to use MDSD. From my experience, there are many benefits with MDSD:</p>\n\n<p>a) Using MDSD helps to bring a SW architecture to a sophisticated level. You always work on a very abstract level, thinking about the big picture. Cowboy coding software usually lacks a good architecture, because a developer is stuck in details. With MDSD, I see a tendency in my work, to solve problems with adequate sized classes, nice patterns, or simply better code.</p>\n\n<p>b) Big picture documentation of the SW tends to be better with MDSD. Of course, there are tools that automatically generate a class diagram out of your code. But these diagrams consists of 1000 classes and you do not see the aspect of interest. With MDSD, you specifically draw one aspect of the system, and the very same diagram is also used to generate a part of your code.</p>\n\n<p>c) Modelling helps to deal with an inherent system complexity. I would say, some systems are just too complex to be built without support from computer-aided design. Nobody would design a CPU without the help of huge SW tools. Use SW to help you write even more complex SW.</p>\n\n<p>d) Using MDSD helps to adhere to coding style guidelines. There is no better way to get coherent code style than letting the code be generated by a rule set.</p>\n\n<p>There are of course also some downsides of MDSD:\nd) If you have a model, you want every line of code to come from that model. And it may be difficult to include external libraries to a project. So either you live with the fact, that your system is based on external components or you reinvent the wheel to get it into your model.</p>\n\n<p>e) Modelling tools might suffer from problems using versioning tools. Source code is usually simpler to merge than a model diagram. This forces a team to move from the copy-edit-merge to a lock-edit-merge workflow.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11562/']
|
70,782 |
<p>How to get a file's creation date or file size, for example this Hello.jpg at <a href="http://www.mywebsite.com/now/Hello.jpg(note" rel="nofollow noreferrer">http://www.mywebsite.com/now/Hello.jpg(note</a>: This URL does not exist)? The purpose of this question is to make my application re-download the files from the any website when it has detected that the website has an updated version of the files and the files in my local folder are out of date. Any ideas?</p>
|
[{'answer_id': 70803, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 4, 'selected': True, 'text': "<p>If you use the HEAD request it will send the headers for the resource, there you can check the cache control headers which will tell you if the resource has been modified, last modification time, size (content-length) and date. </p>\n\n<pre><code>$ telnet www.google.com 80\nTrying 216.239.59.103...\nConnected to www.l.google.com.\nEscape character is '^]'.\nHEAD /intl/en_ALL/images/logo.gif HTTP/1.0\n\nHTTP/1.0 200 OK\nContent-Type: image/gif\nLast-Modified: Wed, 07 Jun 2006 19:38:24 GMT\nExpires: Sun, 17 Jan 2038 19:14:07 GMT\nCache-Control: public\nDate: Tue, 16 Sep 2008 09:45:42 GMT\nServer: gws\nContent-Length: 8558\nConnection: Close\n\nConnection closed by foreign host.\n</code></pre>\n\n<p>Note that you'll probably have to decorate this basic and easy approach with many heuristics depending on the craziness of each webserver's admin, as each can send whatever headers they like. If they do not provide caching headers (Last-Modified, Expires, Cache-Control) nor Content-Length nor etag, you'd be stuck with redownloading it to test.</p>\n"}, {'answer_id': 70804, 'author': 'VolkerK', 'author_id': 4833, 'author_profile': 'https://Stackoverflow.com/users/4833', 'pm_score': 1, 'selected': False, 'text': '<p>The webserver might send a last-modified and/or etag header for that purpose.\nAnd you might send an if-modified-since header in your request.</p>\n\n<p>see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="nofollow noreferrer">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html</a>\nsections 14.19, 14.25 and 14.29</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
70,785 |
<p>We want to try Ext JS on new project. Is there any well-known best practice for integrating Ext JS with server side Java (Spring/Hibernate/JS) application? Is DWR a good choice for that?</p>
|
[{'answer_id': 70920, 'author': 'otto.poellath', 'author_id': 11678, 'author_profile': 'https://Stackoverflow.com/users/11678', 'pm_score': -1, 'selected': False, 'text': "<p>It's perfectly fine to build your application using Ext JS/DWR/Spring/Hibernate.</p>\n"}, {'answer_id': 71014, 'author': 'MatthieuGD', 'author_id': 3109, 'author_profile': 'https://Stackoverflow.com/users/3109', 'pm_score': 1, 'selected': False, 'text': '<p>Yes it\'s possible. </p>\n\n<p>I\'ve done the same thing with .NET : UI in ext-JS which communicates with the server trough JSON. In .NET world you can use DataContractSerializer (class from WCF) or JavascriptSerializer (ASP.NET)</p>\n\n<p>I\'m sure that there\'s several good JSON Serializer in the Java world too. I used <a href="http://jabsorb.org/" rel="nofollow noreferrer">Jabsorb</a> (but not enough to give you a solid feedback). It appears that other people have tried : [link text][2]</p>\n\n<p>[2]: <a href="http://extjs.com/forum/showthread.php?t=30759" rel="nofollow noreferrer">http://extjs.com/forum/showthread.php?t=30759</a> forum ext-js</p>\n'}, {'answer_id': 75007, 'author': 'noah', 'author_id': 12034, 'author_profile': 'https://Stackoverflow.com/users/12034', 'pm_score': 1, 'selected': False, 'text': '<p>In our application we subclass <a href="http://extjs.com/deploy/dev/docs/?class=Ext.data.DataProxy" rel="nofollow noreferrer">Ext.data.DataProxy</a> like this:</p>\n\n<pre><code>var MyProxy = function(fn) {\n this.fn = fn;\n};\nExt.extend( MyProxy, Ext.data.DataProxy, {\n load: function(params,reader,callback,scope,arg) {\n this.fn(params,function(data) {\n callback.call(scope,reader.readRecords(data),arg,true);\n });\n },\n update: function() {}\n});\n</code></pre>\n\n<p>You use it with a store like so:</p>\n\n<pre><code>var store = new Ext.data.Store({\n reader: myReader, proxy: new MyProxy(function(params,callback) {\n // params are used for paging and searching, if you need it\n callback(SomeService.getData(params));\n })\n // ...\n});\n</code></pre>\n\n<p>Our actual proxy class has some additional debug and error handling code that I left out for simplicity. You may also need to manipulate your data slightly so that the <a href="http://extjs.com/deploy/dev/docs/?class=Ext.data.JsonReader" rel="nofollow noreferrer">Ext.data.JsonReader</a> can handle it, but that\'s the basic idea. SomeService is the JavaScript name you specified for whatever bean you exposed in dwr.xml (or your Spring config).</p>\n'}, {'answer_id': 84955, 'author': 'big lep', 'author_id': 16318, 'author_profile': 'https://Stackoverflow.com/users/16318', 'pm_score': 4, 'selected': True, 'text': '<p>My team has been using Ext with DWR for almost year a year, and have had nothing but good things to say. If you take this approach, you will end up using DWR\'s generated JavaScript classes for making your requests to the server. This will often be done in place of using the Ext.Ajax and Ext.data.Connection classes. When you use a class that require an Ext.data.Store (e.g. grip, combo box, etc.) and you want to fetch data from the server, you will need to use a proxy that can link in with DWR. The user-community provided Ext.ux.data.DWRProxy has worked flawlessly for us: <a href="http://extjs.com/forum/showthread.php?t=23884" rel="noreferrer">http://extjs.com/forum/showthread.php?t=23884</a>.</p>\n'}, {'answer_id': 2892492, 'author': 'Erich Kitzmueller', 'author_id': 65464, 'author_profile': 'https://Stackoverflow.com/users/65464', 'pm_score': 0, 'selected': False, 'text': '<p>Take a look at Grails, it plays well together with ExtJS.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7292/']
|
70,797 |
<p>How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?</p>
|
[{'answer_id': 70814, 'author': 'lbz', 'author_id': 11530, 'author_profile': 'https://Stackoverflow.com/users/11530', 'pm_score': 9, 'selected': False, 'text': '<pre><code>var = raw_input("Please enter something: ")\nprint "you entered", var\n</code></pre>\n\n<p>Or for Python 3:</p>\n\n<pre><code>var = input("Please enter something: ")\nprint("You entered: " + var)\n</code></pre>\n'}, {'answer_id': 70818, 'author': 'David Webb', 'author_id': 3171, 'author_profile': 'https://Stackoverflow.com/users/3171', 'pm_score': 5, 'selected': False, 'text': '<p>The best way to process command line arguments is the <a href="https://docs.python.org/library/argparse.html" rel="noreferrer"><code>argparse</code> module.</a></p>\n\n<p>Use <code>raw_input()</code> to get user input. If you import the <a href="https://docs.python.org/library/readline.html" rel="noreferrer"><code>readline module</code></a> your users will have line editing and history.</p>\n'}, {'answer_id': 70833, 'author': 'Antti Rasinen', 'author_id': 8570, 'author_profile': 'https://Stackoverflow.com/users/8570', 'pm_score': 10, 'selected': True, 'text': '<p>To read user input you can try <a href="https://docs.python.org/dev/library/cmd.html" rel="noreferrer">the <code>cmd</code> module</a> for easily creating a mini-command line interpreter (with help texts and autocompletion) and <a href="https://docs.python.org/2/library/functions.html#raw_input" rel="noreferrer"><code>raw_input</code></a> (<a href="https://docs.python.org/dev/library/functions.html#input" rel="noreferrer"><code>input</code></a> for Python 3+) for reading a line of text from the user.</p>\n\n<pre><code>text = raw_input("prompt") # Python 2\ntext = input("prompt") # Python 3\n</code></pre>\n\n<p>Command line inputs are in <code>sys.argv</code>. Try this in your script:</p>\n\n<pre><code>import sys\nprint (sys.argv)\n</code></pre>\n\n<p>There are two modules for parsing command line options: <a href="https://docs.python.org/dev/library/optparse.html" rel="noreferrer"><s><code>optparse</code></s></a> (deprecated since Python 2.7, use <a href="https://docs.python.org/dev/library/argparse.html" rel="noreferrer"><code>argparse</code></a> instead) and <a href="https://docs.python.org/dev/library/getopt.html" rel="noreferrer"><code>getopt</code></a>. If you just want to input files to your script, behold the power of <a href="https://docs.python.org/dev/library/fileinput.html" rel="noreferrer"><code>fileinput</code></a>.</p>\n\n<p>The <a href="https://docs.python.org/dev/library/" rel="noreferrer">Python library reference</a> is your friend.</p>\n'}, {'answer_id': 70841, 'author': 'Simon Peverett', 'author_id': 6063, 'author_profile': 'https://Stackoverflow.com/users/6063', 'pm_score': 4, 'selected': False, 'text': '<p>Use \'raw_input\' for input from a console/terminal.</p>\n\n<p>if you just want a command line argument like a file name or something e.g. </p>\n\n<pre><code>$ python my_prog.py file_name.txt\n</code></pre>\n\n<p>then you can use sys.argv...</p>\n\n<pre><code>import sys\nprint sys.argv\n</code></pre>\n\n<p>sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be "file_name.txt"</p>\n\n<p>If you want to have full on command line options use the optparse module.</p>\n\n<p>Pev</p>\n'}, {'answer_id': 70869, 'author': 'Vhaerun', 'author_id': 11234, 'author_profile': 'https://Stackoverflow.com/users/11234', 'pm_score': 4, 'selected': False, 'text': "<p>Careful not to use the <code>input</code> function, unless you know what you're doing. Unlike <code>raw_input</code>, <code>input</code> will accept any python expression, so it's kinda like <code>eval</code></p>\n"}, {'answer_id': 3427325, 'author': 'GreenMatt', 'author_id': 197011, 'author_profile': 'https://Stackoverflow.com/users/197011', 'pm_score': 3, 'selected': False, 'text': '<p>As of Python <del>3.2</del> 2.7, there is now <a href="http://docs.python.org/dev/library/argparse.html" rel="noreferrer">argparse</a> for processing command line arguments.</p>\n'}, {'answer_id': 8334188, 'author': 'steampowered', 'author_id': 404699, 'author_profile': 'https://Stackoverflow.com/users/404699', 'pm_score': 8, 'selected': False, 'text': '<p><code>raw_input</code> is no longer available in Python 3.x. But <code>raw_input</code> was renamed <code>input</code>, so the same functionality exists.</p>\n\n<pre><code>input_var = input("Enter something: ")\nprint ("you entered " + input_var) \n</code></pre>\n\n<p><a href="http://docs.python.org/py3k/whatsnew/3.0.html#builtins" rel="noreferrer">Documentation of the change</a></p>\n'}, {'answer_id': 13089887, 'author': 'Matt Olan', 'author_id': 1776131, 'author_profile': 'https://Stackoverflow.com/users/1776131', 'pm_score': 3, 'selected': False, 'text': '<p>If you are running Python <2.7, you need <a href="http://docs.python.org/library/optparse.html" rel="noreferrer">optparse</a>, which as the doc explains will create an interface to the command line arguments that are called when your application is run.</p>\n\n<p>However, in Python ≥2.7, optparse has been deprecated, and was replaced with the <a href="http://docs.python.org/library/argparse.html" rel="noreferrer">argparse</a> as shown above. A quick example from the docs...</p>\n\n<blockquote>\n <p>The following code is a Python program that takes a list of integers\n and produces either the sum or the max:</p>\n</blockquote>\n\n<pre><code>import argparse\n\nparser = argparse.ArgumentParser(description=\'Process some integers.\')\nparser.add_argument(\'integers\', metavar=\'N\', type=int, nargs=\'+\',\n help=\'an integer for the accumulator\')\nparser.add_argument(\'--sum\', dest=\'accumulate\', action=\'store_const\',\n const=sum, default=max,\n help=\'sum the integers (default: find the max)\')\n\nargs = parser.parse_args()\nprint args.accumulate(args.integers)\n</code></pre>\n'}, {'answer_id': 30341035, 'author': 'Viswesn', 'author_id': 527813, 'author_profile': 'https://Stackoverflow.com/users/527813', 'pm_score': 4, 'selected': False, 'text': '<p>This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.</p>\n\n<pre><code>import argparse\nimport sys\n\ntry:\n parser = argparse.ArgumentParser()\n parser.add_argument("square", help="display a square of a given number",\n type=int)\n args = parser.parse_args()\n\n #print the square of user input from cmd line.\n print args.square**2\n\n #print all the sys argument passed from cmd line including the program name.\n print sys.argv\n\n #print the second argument passed from cmd line; Note it starts from ZERO\n print sys.argv[1]\nexcept:\n e = sys.exc_info()[0]\n print e\n</code></pre>\n\n<p>1) To find the square root of 5</p>\n\n<pre><code>C:\\Users\\Desktop>python -i emp.py 5\n25\n[\'emp.py\', \'5\']\n5\n</code></pre>\n\n<p>2) Passing invalid argument other than number</p>\n\n<pre><code>C:\\Users\\bgh37516\\Desktop>python -i emp.py five\nusage: emp.py [-h] square\nemp.py: error: argument square: invalid int value: \'five\'\n<type \'exceptions.SystemExit\'>\n</code></pre>\n'}, {'answer_id': 42305071, 'author': 'CorpseDead', 'author_id': 5539337, 'author_profile': 'https://Stackoverflow.com/users/5539337', 'pm_score': 3, 'selected': False, 'text': "<p>If it's a 3.x version then just simply use:</p>\n\n<pre><code>variantname = input()\n</code></pre>\n\n<p>For example, you want to input 8:</p>\n\n<pre><code>x = input()\n8\n</code></pre>\n\n<p>x will equal 8 but it's going to be a string except if you define it otherwise.</p>\n\n<p>So you can use the convert command, like:</p>\n\n<pre><code>a = int(x) * 1.1343\nprint(round(a, 2)) # '9.07'\n9.07\n</code></pre>\n"}, {'answer_id': 44314236, 'author': 'Mark', 'author_id': 8075198, 'author_profile': 'https://Stackoverflow.com/users/8075198', 'pm_score': 2, 'selected': False, 'text': "<p>In Python 2:</p>\n\n<pre><code>data = raw_input('Enter something: ')\nprint data\n</code></pre>\n\n<p>In Python 3:</p>\n\n<pre><code>data = input('Enter something: ')\nprint(data)\n</code></pre>\n"}, {'answer_id': 54241008, 'author': 'Will Charlton', 'author_id': 2517989, 'author_profile': 'https://Stackoverflow.com/users/2517989', 'pm_score': 2, 'selected': False, 'text': '<pre><code>import six\n\nif six.PY2:\n input = raw_input\n\nprint(input("What\'s your name? "))\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1384652/']
|
70,811 |
<p>For best performance, is it better to use a virtual IDE HDD or virtual SCSI HDD?
If, SCSI, does it matter whether you use an BusLogic or LSILogic?</p>
|
[{'answer_id': 70919, 'author': 'SilverViper', 'author_id': 3228, 'author_profile': 'https://Stackoverflow.com/users/3228', 'pm_score': 4, 'selected': True, 'text': '<p>Go for the SCSI and LSILogic. IDE and BusLogic are for compatibility reasons. Like when you do physical2virtual...</p>\n\n<p>There\'s a whitepaper from vmware showing the difference between LSILogic and BusLogic, which in my opinion is rather small:\n<a href="http://www.vmware.com/pdf/ESX2_Storage_Performance.pdf" rel="nofollow noreferrer">http://www.vmware.com/pdf/ESX2_Storage_Performance.pdf</a></p>\n\n<p>Edit after like three years:\nWith current ESX environments it\'s best to use the Paravirtual SCSI device.</p>\n'}, {'answer_id': 70982, 'author': 'λ Jonas Gorauskas', 'author_id': 11507, 'author_profile': 'https://Stackoverflow.com/users/11507', 'pm_score': 2, 'selected': False, 'text': "<p>I don't think that your choice of Virtual Disk type in VMWare matters for performance. What matters is the following: How much memory you have (the more the better), How many CPU cores you have (the more the better), and more specifically about disks, what matters most is the speed of the physical drive (a 15K RPM SCSI drive being best). If you have, for example, 3 physical HDs and 3 virtual HDs, then I would place one virtual HD in each physical HD. This is known to improve virtual HD performance. Also keep your virtual HDs defragmented.</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70811', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11538/']
|
70,816 |
<p>Is it possible to use the Asp.Net MVC framework within SharePoint sites?</p>
|
[{'answer_id': 70843, 'author': 'Aaron Powell', 'author_id': 11388, 'author_profile': 'https://Stackoverflow.com/users/11388', 'pm_score': 2, 'selected': False, 'text': "<p>I don't believe so, although you can upload standard ASPX files into SharePoint and have them operate I'm pretty sure that the URL rewritting is where it would come unstuck.</p>\n"}, {'answer_id': 70886, 'author': 'Magnus Johansson', 'author_id': 3584, 'author_profile': 'https://Stackoverflow.com/users/3584', 'pm_score': 4, 'selected': False, 'text': '<p>In ScottGu\'s <a href="http://weblogs.asp.net/scottgu/archive/2008/02/12/asp-net-mvc-framework-road-map-update.aspx" rel="noreferrer">blog from February 2008</a>, he writes:</p>\n\n<blockquote>\n <p>Currently MVC doesn\'t directly\n integrate with SharePoint. That is\n something we\'ll be looking at\n supporting in the future though.</p>\n</blockquote>\n\n<p>There\'s a project on CodePlex for getting ASP.NET MVC to work in SharePoint:\n<a href="http://www.codeplex.com/SharePointMVC" rel="noreferrer">http://www.codeplex.com/SharePointMVC</a></p>\n'}, {'answer_id': 359159, 'author': 'Simon', 'author_id': 53158, 'author_profile': 'https://Stackoverflow.com/users/53158', 'pm_score': 4, 'selected': False, 'text': '<p>This might be of interest to you <a href="http://www.codeplex.com/SharePointMVC" rel="nofollow noreferrer">http://www.codeplex.com/SharePointMVC</a></p>\n\n<p>It is basically a library to help rendering ASP.MVC inside a SharePoint masterpage.</p>\n\n<p>Still early days but you get the idea.</p>\n'}, {'answer_id': 1020882, 'author': 'Shiraz Bhaiji', 'author_id': 86611, 'author_profile': 'https://Stackoverflow.com/users/86611', 'pm_score': 2, 'selected': False, 'text': '<p>One possible architecture is to use an asp.net or an asp.net mvc frontend. Then accessing sharepoint functionality via web services.</p>\n\n<p>This has the benefit of giving you access to the functionality of sharepoint, without having the extra development cost of using sharepoint.</p>\n'}, {'answer_id': 1027839, 'author': 'jgarcia', 'author_id': 32633, 'author_profile': 'https://Stackoverflow.com/users/32633', 'pm_score': 2, 'selected': False, 'text': '<p>One thing you could do is create sharepoint "powered" apps with asp.net mvc just by referencing the SharePoint assembly. </p>\n\n<p>I guess the Sharepoint Object Model would be your M in MVC.</p>\n'}, {'answer_id': 2651719, 'author': 'martin bailey', 'author_id': 318325, 'author_profile': 'https://Stackoverflow.com/users/318325', 'pm_score': 4, 'selected': False, 'text': '<p>The following sharepoint site, www.themedicinecabinet.co.uk, was built using ASP.net MVC 2. This article explains how this was done\n<a href="http://vspug.com/mbailey/files/2010/04/Using-ASP.NET-MVC-2-with-Sharepoint-Publishing.pdf" rel="noreferrer">http://vspug.com/mbailey/files/2010/04/Using-ASP.NET-MVC-2-with-Sharepoint-Publishing.pdf</a></p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
70,842 |
<p>How should I run another program from within my <code>C</code> program? I need to be able to write data into <code>STDIN</code> of the launched program (and maybe read from it's <code>STDOUT</code>)</p>
<p>I am not sure if this is a standard C function. I need the solution that should work under Linux.</p>
|
[{'answer_id': 70848, 'author': 'freespace', 'author_id': 8297, 'author_profile': 'https://Stackoverflow.com/users/8297', 'pm_score': 5, 'selected': True, 'text': '<p>You want to use <code>popen</code>. It gives you a unidirectional pipe with which you can access stdin and stdout of the program.</p>\n\n<p>popen is standard on modern unix and unix-like OS, of which Linux is one :-)</p>\n\n<p>Type</p>\n\n<pre><code>man popen\n</code></pre>\n\n<p>in a terminal to read more about it.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Whether <code>popen</code> produces unidirectional or bidirectional pipes depends on the implementation. In <a href="https://manpages.debian.org/jessie/manpages-dev/popen.3.en.html" rel="nofollow noreferrer">Linux</a> and <a href="http://man.openbsd.org/OpenBSD-current/man3/popen.3" rel="nofollow noreferrer">OpenBSD</a>, <code>popen</code> produces unidirectional pipes, which are read-only or write-only. On <a href="https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/popen.3.html" rel="nofollow noreferrer">OS X</a>, <a href="https://www.freebsd.org/cgi/man.cgi?query=popen&apropos=0&sektion=0&manpath=FreeBSD+11.0-RELEASE+and+Ports&arch=default&format=html" rel="nofollow noreferrer">FreeBSD</a> and <a href="http://netbsd.gw.com/cgi-bin/man-cgi?popen++NetBSD-current" rel="nofollow noreferrer">NetBSD</a> <code>popen</code> produces bidirectional pipes.</p>\n'}, {'answer_id': 70857, 'author': 'Vhaerun', 'author_id': 11234, 'author_profile': 'https://Stackoverflow.com/users/11234', 'pm_score': 0, 'selected': False, 'text': '<p>I think you can use </p>\n\n<blockquote>\n <p><code>freopen</code></p>\n</blockquote>\n\n<p>for this .</p>\n'}, {'answer_id': 70858, 'author': 'Jorge Ferreira', 'author_id': 6508, 'author_profile': 'https://Stackoverflow.com/users/6508', 'pm_score': 3, 'selected': False, 'text': "<ol>\n<li>Create two pipes with <code>pipe(...)</code>, one for <code>stdin</code>, one for <code>stdout</code>. </li>\n<li><code>fork(...)</code> the process.</li>\n<li>In the child process (the one where <code>fork(...)</code> returns 0) <code>dup (...)</code> the pipes to <code>stdin</code>/<code>stdout</code>.</li>\n<li><code>exec[v][e]</code> the to be started programm file in the child process.</li>\n<li>In the parent process (the one where <code>fork</code>) returns the PID of the child) do a loop that reads from the child's <code>stdout</code> (<code>select(...)</code> or <code>poll(...)</code>, <code>read(...)</code> ) into a buffer, until the\nchild terminates (<code>waitpid(...)</code>). </li>\n<li>Eventually supply the child with input on <code>stdin</code> if it expects some.</li>\n<li>When done <code>close(...)</code> the pipes.</li>\n</ol>\n"}, {'answer_id': 70954, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>You can use the system call, read <a href="http://www.linuxmanpages.com/man3/system.3.php" rel="nofollow noreferrer">manpage for system(3)</a></p>\n'}, {'answer_id': 80866, 'author': 'Jonathan Leffler', 'author_id': 15168, 'author_profile': 'https://Stackoverflow.com/users/15168', 'pm_score': 3, 'selected': False, 'text': '<p>For simple unidirectional communication, popen() is a decent solution. It is no use for bi-directional communication, though.</p>\n<p>IMO, imjorge (Jorge Ferreira) gave most of the answer (80%?) for bi-directional communication - but omitted a few key details.</p>\n<ol>\n<li>It is crucial that the parent process close the read end of the pipe that is used to send messages to the child process.</li>\n<li>It is crucial that the child process close the write end of the pipe that is used to send messages to the child process.</li>\n<li>It is crucial that the parent process close the write end of the pipe that is used to send messages to the parent process.</li>\n<li>It is crucial that the child process close the read end of the pipe that is used to send messages to the parent process.</li>\n</ol>\n<p>If you do not close the unused ends of the pipes, you do not get sensible behaviour when one of the programs terminates; for example, the child might be reading from its standard input, but unless the write end of the pipe is closed in the child, it will never get EOF (zero bytes from read) because it still has the pipe open and the system thinks it might sometime get around to writing to that pipe, even though it is currently hung waiting for something to read from it.</p>\n<p>The writing processes should consider whether to handle the SIGPIPE signal that is given when you write on a pipe where there is no reading process.</p>\n<p>You have to be aware of pipe capacity (platform dependent, and might be as little as 4KB) and design the programs to avoid deadlock.</p>\n'}, {'answer_id': 83456, 'author': 'Steve Baker', 'author_id': 13566, 'author_profile': 'https://Stackoverflow.com/users/13566', 'pm_score': 4, 'selected': False, 'text': '<p>I wrote some example C code for someone else a while back that shows how to do this. Here it is for you:</p>\n\n<pre><code>#include <sys/types.h>\n#include <unistd.h>\n#include <stdio.h>\n\nvoid error(char *s);\nchar *data = "Some input data\\n";\n\nmain()\n{\n int in[2], out[2], n, pid;\n char buf[255];\n\n /* In a pipe, xx[0] is for reading, xx[1] is for writing */\n if (pipe(in) < 0) error("pipe in");\n if (pipe(out) < 0) error("pipe out");\n\n if ((pid=fork()) == 0) {\n /* This is the child process */\n\n /* Close stdin, stdout, stderr */\n close(0);\n close(1);\n close(2);\n /* make our pipes, our new stdin,stdout and stderr */\n dup2(in[0],0);\n dup2(out[1],1);\n dup2(out[1],2);\n\n /* Close the other ends of the pipes that the parent will use, because if\n * we leave these open in the child, the child/parent will not get an EOF\n * when the parent/child closes their end of the pipe.\n */\n close(in[1]);\n close(out[0]);\n\n /* Over-write the child process with the hexdump binary */\n execl("/usr/bin/hexdump", "hexdump", "-C", (char *)NULL);\n error("Could not exec hexdump");\n }\n\n printf("Spawned \'hexdump -C\' as a child process at pid %d\\n", pid);\n\n /* This is the parent process */\n /* Close the pipe ends that the child uses to read from / write to so\n * the when we close the others, an EOF will be transmitted properly.\n */\n close(in[0]);\n close(out[1]);\n\n printf("<- %s", data);\n /* Write some data to the childs input */\n write(in[1], data, strlen(data));\n\n /* Because of the small amount of data, the child may block unless we\n * close it\'s input stream. This sends an EOF to the child on it\'s\n * stdin.\n */\n close(in[1]);\n\n /* Read back any output */\n n = read(out[0], buf, 250);\n buf[n] = 0;\n printf("-> %s",buf);\n exit(0);\n}\n\nvoid error(char *s)\n{\n perror(s);\n exit(1);\n}\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6974/']
|
70,850 |
<p>What advantage, if any, is provided by formatting C code as follows:</p>
<pre><code>while(lock_file(lockdir)==0)
{
count++;
if(count==20)
{
fprintf(stderr,"Can't lock dir %s\n",lockdir);
exit(1);
}
sleep(3);
}
if(rmdir(serverdir)!=0)
{
switch(errno)
{
case EEXIST:
fprintf(stderr,"Server dir %s not empty\n",serverdir);
break;
default:
fprintf(stderr,"Can't delete dir %s\n",serverdir);
}
exit(1);
}
unlock_file(lockdir);
</code></pre>
<p>versus something more typical such as</p>
<pre><code>while(lock_file(lockdir)==0) {
count++;
if(count==20) {
fprintf(stderr,"Can't lock dir %s\n",lockdir);
exit(1);
}
sleep(3);
}
if(rmdir(serverdir)!=0) {
switch(errno) {
case EEXIST:
fprintf(stderr,"Server dir %s not empty\n",serverdir);
break;
default:
fprintf(stderr,"Can't delete dir %s\n",serverdir);
}
exit(1);
}
unlock_file(lockdir);
</code></pre>
<p>I just find the top version difficult to read and to get the indenting level correct for statements outside of a long block, especially for longs blocks containing several nested blocks.</p>
<p>Only advantage I can see is just to be different and leave your fingerprints on code that you've written.</p>
<p>I notice vim formatting would have to be hand-rolled to handle the top case.</p>
|
[{'answer_id': 70862, 'author': 'cruizer', 'author_id': 6441, 'author_profile': 'https://Stackoverflow.com/users/6441', 'pm_score': 3, 'selected': False, 'text': '<p>Nothing. Indentation and other coding standards are a matter of preference.</p>\n'}, {'answer_id': 70863, 'author': 'JamesSugrue', 'author_id': 1075, 'author_profile': 'https://Stackoverflow.com/users/1075', 'pm_score': 2, 'selected': False, 'text': '<p>Personal Preference I would have thought? I guess it has the code block in one vertical line so possibly easier to work out at a glance? Personally I prefer the brace to start directly under the previous line</p>\n'}, {'answer_id': 70865, 'author': 'Dark Shikari', 'author_id': 11206, 'author_profile': 'https://Stackoverflow.com/users/11206', 'pm_score': 1, 'selected': False, 'text': "<p>Its just another style--people code how they like to code, and that is one accepted style (though not my preferred). I don't think it has much of a disadvantage or advantage over the more common style in which brackets are not indented but the code within them is. Perhaps one could justify it by saying that it more clearly delimits code blocks.</p>\n"}, {'answer_id': 70867, 'author': 'prakash', 'author_id': 123, 'author_profile': 'https://Stackoverflow.com/users/123', 'pm_score': 2, 'selected': False, 'text': '<p>Code formatting is personal taste. As long as it is easy to read, it would pay for maintenance!</p>\n'}, {'answer_id': 70873, 'author': 'benefactual', 'author_id': 6445, 'author_profile': 'https://Stackoverflow.com/users/6445', 'pm_score': 1, 'selected': False, 'text': '<p>In order for this format to have "advantage", we really need some equivalent C code in another format to compare to!</p>\n\n<p>Where I work, this indentation scheme is used in order to facilitate a home-grown folding editor mechanism.</p>\n\n<p>Thus, I see nothing fundamentally wrong with this format - within certain rational limits, formatting is a matter of personal preference. </p>\n'}, {'answer_id': 70893, 'author': 'Andreas Bakurov', 'author_id': 7400, 'author_profile': 'https://Stackoverflow.com/users/7400', 'pm_score': 2, 'selected': False, 'text': "<p>By following some formatting and commenting standards, first of all you show your respect to other people that will read and edit code written by you. If you don't accept rules and write somehow esoteric code the most probable result is that you will not be able communicate with other people (programmers) effectively. Code format is personal choice if software is written only by you and for you and nobody is expected to read it, but how many modern software is written only by one person ?</p>\n"}, {'answer_id': 70923, 'author': 'Ben', 'author_id': 11522, 'author_profile': 'https://Stackoverflow.com/users/11522', 'pm_score': 2, 'selected': False, 'text': "<p>It looks pretty standard to me. The only personal change I'd make is aligning the curly-braces with the start of the previous line, rather than the start of the next line, but that's just a personal choice.</p>\n\n<p>Anyway, the style of formatting you're looking at there is a standard one for C and C++, and is used because it makes the code easier to read, and in particular by looking at the level of indentation you can tell where you are with nested loops, conditionals, etc. E.g.:</p>\n\n<pre><code>if (x == 0) \n{\n if (y == 2)\n {\n if (z == 3)\n {\n do_something (x);\n }\n }\n}\n</code></pre>\n\n<p>OK in that example it's pretty easy to see what's happening, but if you put a lot of code inside those if statements, it can sometimes be hard to tell where you are without consistent indentation.</p>\n\n<p>In your example, have a look at the position of the exit(1) statement -- if it weren't indented like that, it would be hard to tell where this was. As it is, you can tell it's at the end of that big if statement.</p>\n"}, {'answer_id': 271627, 'author': 'brian d foy', 'author_id': 2766176, 'author_profile': 'https://Stackoverflow.com/users/2766176', 'pm_score': 6, 'selected': True, 'text': '<p>The top example is know as "Whitesmiths style". <a href="http://en.wikipedia.org/wiki/Indent_style" rel="noreferrer">Wikipedia\'s entry on Indent Styles</a> explains several styles along with their advantages and disadvantages.</p>\n'}, {'answer_id': 272759, 'author': 'bendin', 'author_id': 33412, 'author_profile': 'https://Stackoverflow.com/users/33412', 'pm_score': 3, 'selected': False, 'text': '<p>The indentation you\'re seeing is <a href="http://en.wikipedia.org/wiki/Indent_style#Whitesmiths_style" rel="noreferrer">Whitesmiths style</a>. It\'s described in the first edition of <em>Code Complete</em> as "begin-end Block Boundaries". The basic argument for this style is that in languages like C (and Pascal) an <code>if</code> governs either a single statement or a block. Thus the whole block, not just its contents should be shown subordinate to the <code>if</code>-statement by being indented consistently.</p>\n\n<pre><code>XXXXXXXXXXXXXXX if (test)\n XXXXXXXXXXXX one_thing();\n\nXXXXXXXXXXXXXXX if (test)\n X {\n XXXXX one_thing();\n XXXXX another_thing();\n X }\n</code></pre>\n\n<p>Back when I first read this book (in the 90s) I found the argument for "begin-end Block Boundaries" to be convincing, though I didn\'t like it much when I put it into practice (in Pascal). I like it even less in C and find it confusing to read. I end up using what Steve McConnel calls "Emulating Pure Blocks" (<a href="http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html#15395" rel="noreferrer">Sun\'s Java Style</a>, which is almost <a href="http://en.wikipedia.org/wiki/Indent_style#K.26R_style" rel="noreferrer">K&R</a>).</p>\n\n<pre><code>XXXXXXXXXXXXXX X if (test) {\n XXXXXX one_thing();\n XXXXXX another_thing();\nX }\n</code></pre>\n\n<p>This is the most common style used to program in Java (which is what I do all day). It\'s also most similar to my <a href="http://www-old.oberon.ethz.ch/oreport.html" rel="noreferrer">previous language</a> which was a "pure block" language, requiring no "emulation". There are no single-statement bodies, blocks are inherent in the control structure syntax.</p>\n\n<pre><code>IF test THEN\n oneThing;\n anotherThing\nEND\n</code></pre>\n'}, {'answer_id': 58456821, 'author': 'foo', 'author_id': 448779, 'author_profile': 'https://Stackoverflow.com/users/448779', 'pm_score': 2, 'selected': False, 'text': '<p>The "advantage" of Whitesmiths style (as the top one in your example is called) is that it mirrors the actual logical structure of the code:</p>\n\n<ul>\n<li>indent if there is a logical dependency</li>\n<li>place corresponding brackets on the same column so they are easy to find</li>\n<li>opening and closing of a context (which may open/close a stack frame etc) are visible, not hidden</li>\n</ul>\n\n<p>So, less if/else errors, loops gone wrong, and catches at the wrong level, and overall logical consistency.</p>\n\n<p>But as benefactual wrote: within certain rational limits, formatting is a matter of personal preference. </p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2974/']
|
70,855 |
<p>Is there a realistic way of implementing a multi-threaded model in PHP whether truly, or just simulating it. Some time back it was suggested that you could force the operating system to load another instance of the PHP executable and handle other simultaneous processes.</p>
<p>The problem with this is that when the PHP code finished executing the PHP instance remains in memory because there is no way to kill it from within PHP. So if you are simulating several threads you can imagine whats going to happen. So I am still looking for a way multi-threading can be done or simulated effectively from within PHP. Any ideas?</p>
|
[{'answer_id': 71043, 'author': 'J.D. Fitz.Gerald', 'author_id': 11542, 'author_profile': 'https://Stackoverflow.com/users/11542', 'pm_score': 4, 'selected': False, 'text': '<p>While you can\'t thread, you do have some degree of process control in php. The two function sets that are useful here are:</p>\n\n<p>Process control functions\n<a href="http://www.php.net/manual/en/ref.pcntl.php" rel="noreferrer">http://www.php.net/manual/en/ref.pcntl.php</a></p>\n\n<p>POSIX functions\n<a href="http://www.php.net/manual/en/ref.posix.php" rel="noreferrer">http://www.php.net/manual/en/ref.posix.php</a></p>\n\n<p>You could fork your process with pcntl_fork - returning the PID of the child. Then you can use posix_kill to despose of that PID.</p>\n\n<p>That said, if you kill a parent process a signal should be sent to the child process telling it to die. If php itself isn\'t recognising this you could register a function to manage it and do a clean exit using pcntl_signal.</p>\n'}, {'answer_id': 72605, 'author': 'Adam Hopkinson', 'author_id': 12280, 'author_profile': 'https://Stackoverflow.com/users/12280', 'pm_score': 4, 'selected': False, 'text': '<p>You can use exec() to run a command line script (such as command line php), and if you pipe the output to a file then your script won\'t wait for the command to finish.</p>\n\n<p>I can\'t quite remember the php CLI syntax, but you\'d want something like:</p>\n\n<pre><code>exec("/path/to/php -f \'/path/to/file.php\' | \'/path/to/output.txt\'");\n</code></pre>\n\n<p>I think quite a few shared hosting servers have exec() disabled by default for security reasons, but might be worth a try.</p>\n'}, {'answer_id': 1079624, 'author': 'Ricardo', 'author_id': 132841, 'author_profile': 'https://Stackoverflow.com/users/132841', 'pm_score': 5, 'selected': False, 'text': '<p>Threading isn\'t available in stock PHP, but concurrent programming is possible by using HTTP requests as asynchronous calls.</p>\n\n<p>With the curl\'s timeout setting set to 1 and using the same session_id for the processes you want to be associated with each other, you can communicate with session variables as in my example below. With this method you can even close your browser and the concurrent process still exists on the server.</p>\n\n<p>Don\'t forget to verify the correct session ID like this:</p>\n\n<blockquote>\n <p><a href="http://localhost/test/verifysession.php?sessionid=[the" rel="noreferrer">http://localhost/test/verifysession.php?sessionid=[the</a> correct id]</p>\n</blockquote>\n\n<h3>startprocess.php</h3>\n\n<pre><code>$request = "http://localhost/test/process1.php?sessionid=".$_REQUEST["PHPSESSID"];\n$ch = curl_init();\ncurl_setopt($ch, CURLOPT_URL, $request);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_setopt($ch, CURLOPT_TIMEOUT, 1);\ncurl_exec($ch);\ncurl_close($ch);\necho $_REQUEST["PHPSESSID"];\n</code></pre>\n\n<h3>process1.php</h3>\n\n<pre><code>set_time_limit(0);\n\nif ($_REQUEST["sessionid"])\n session_id($_REQUEST["sessionid"]);\n\nfunction checkclose()\n{\n global $_SESSION;\n if ($_SESSION["closesession"])\n {\n unset($_SESSION["closesession"]);\n die();\n }\n}\n\nwhile(!$close)\n{\n session_start();\n $_SESSION["test"] = rand();\n checkclose();\n session_write_close();\n sleep(5);\n}\n</code></pre>\n\n<h3>verifysession.php</h3>\n\n<pre><code>if ($_REQUEST["sessionid"])\n session_id($_REQUEST["sessionid"]);\n\nsession_start();\nvar_dump($_SESSION);\n</code></pre>\n\n<h3>closeprocess.php</h3>\n\n<pre><code>if ($_REQUEST["sessionid"])\n session_id($_REQUEST["sessionid"]);\n\nsession_start();\n$_SESSION["closesession"] = true;\nvar_dump($_SESSION);\n</code></pre>\n'}, {'answer_id': 3579723, 'author': 'Pete', 'author_id': 432373, 'author_profile': 'https://Stackoverflow.com/users/432373', 'pm_score': 3, 'selected': False, 'text': "<p>You could simulate threading. PHP can run background processes via popen (or proc_open). Those processes can be communicated with via stdin and stdout. Of course those processes can themselves be a php program. That is probably as close as you'll get. </p>\n"}, {'answer_id': 4350418, 'author': 'masterb', 'author_id': 529958, 'author_profile': 'https://Stackoverflow.com/users/529958', 'pm_score': 6, 'selected': False, 'text': '<p>why don\'t you use <a href="https://secure.php.net/manual/en/function.popen.php" rel="noreferrer">popen</a>?</p>\n<pre><code>for ($i=0; $i<10; $i++) {\n // open ten processes\n for ($j = 0; $j < 10; $j++) {\n $pipe[$j] = popen(\'script2.php\', \'w\');\n }\n\n // wait for them to finish\n for ($j = 0; $j < 10; ++$j) {\n pclose($pipe[$j]);\n }\n}\n</code></pre>\n'}, {'answer_id': 4790074, 'author': 'Sheldmandu', 'author_id': 2641644, 'author_profile': 'https://Stackoverflow.com/users/2641644', 'pm_score': 3, 'selected': False, 'text': "<p>Depending on what you're trying to do you could also use curl_multi to achieve it.</p>\n"}, {'answer_id': 5946750, 'author': 'Manoj Donga', 'author_id': 746369, 'author_profile': 'https://Stackoverflow.com/users/746369', 'pm_score': 3, 'selected': False, 'text': '<p>You can have option of:</p>\n\n<ol>\n<li>multi_curl</li>\n<li>One can use system command for the same</li>\n<li>Ideal scenario is, create a threading function in C language and compile/configure in PHP. Now that function will be the function of PHP.</li>\n</ol>\n'}, {'answer_id': 8844548, 'author': 'Jarrod', 'author_id': 577306, 'author_profile': 'https://Stackoverflow.com/users/577306', 'pm_score': 3, 'selected': False, 'text': '<p>How about pcntl_fork?</p>\n\n<p>check our the manual page for examples: <a href="http://php.net/manual/en/function.pcntl-fork.php" rel="nofollow noreferrer">PHP pcntl_fork</a></p>\n\n<pre><code><?php\n\n $pid = pcntl_fork();\n if ($pid == -1) {\n die(\'could not fork\');\n } else if ($pid) {\n // we are the parent\n pcntl_wait($status); //Protect against Zombie children\n } else {\n // we are the child\n }\n\n?>\n</code></pre>\n'}, {'answer_id': 9107047, 'author': 'Stilero', 'author_id': 1180559, 'author_profile': 'https://Stackoverflow.com/users/1180559', 'pm_score': 2, 'selected': False, 'text': "<p><code>pcntl_fork</code> won't work in a web server environment if it has <em>safe mode</em> turned on. In this case, it will only work in the CLI version of PHP.</p>\n"}, {'answer_id': 12487840, 'author': 'JasonDavis', 'author_id': 143030, 'author_profile': 'https://Stackoverflow.com/users/143030', 'pm_score': 4, 'selected': False, 'text': '<p>I know this is an old question but for people searching, there is a PECL extension written in C that gives PHP multi-threading capability now, it\'s located here <a href="https://github.com/krakjoe/pthreads" rel="noreferrer">https://github.com/krakjoe/pthreads</a></p>\n'}, {'answer_id': 15501449, 'author': 'Baba', 'author_id': 1226894, 'author_profile': 'https://Stackoverflow.com/users/1226894', 'pm_score': 9, 'selected': False, 'text': '<h1>Multi-threading is possible in php</h1>\n\n<p>Yes you can do multi-threading in PHP with <a href="https://github.com/krakjoe/pthreads" rel="noreferrer">pthreads</a> </p>\n\n<p>From <a href="http://www.php.net/manual/en/intro.pthreads.php" rel="noreferrer">the PHP documentation</a>:</p>\n\n<blockquote>\n <p>pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.</p>\n \n <p><strong>Warning</strong>:\n The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only.</p>\n</blockquote>\n\n<p><strong>Simple Test</strong></p>\n\n<pre><code>#!/usr/bin/php\n<?php\nclass AsyncOperation extends Thread {\n\n public function __construct($arg) {\n $this->arg = $arg;\n }\n\n public function run() {\n if ($this->arg) {\n $sleep = mt_rand(1, 10);\n printf(\'%s: %s -start -sleeps %d\' . "\\n", date("g:i:sa"), $this->arg, $sleep);\n sleep($sleep);\n printf(\'%s: %s -finish\' . "\\n", date("g:i:sa"), $this->arg);\n }\n }\n}\n\n// Create a array\n$stack = array();\n\n//Initiate Multiple Thread\nforeach ( range("A", "D") as $i ) {\n $stack[] = new AsyncOperation($i);\n}\n\n// Start The Threads\nforeach ( $stack as $t ) {\n $t->start();\n}\n\n?>\n</code></pre>\n\n<p>First Run</p>\n\n<pre><code>12:00:06pm: A -start -sleeps 5\n12:00:06pm: B -start -sleeps 3\n12:00:06pm: C -start -sleeps 10\n12:00:06pm: D -start -sleeps 2\n12:00:08pm: D -finish\n12:00:09pm: B -finish\n12:00:11pm: A -finish\n12:00:16pm: C -finish\n</code></pre>\n\n<p>Second Run </p>\n\n<pre><code>12:01:36pm: A -start -sleeps 6\n12:01:36pm: B -start -sleeps 1\n12:01:36pm: C -start -sleeps 2\n12:01:36pm: D -start -sleeps 1\n12:01:37pm: B -finish\n12:01:37pm: D -finish\n12:01:38pm: C -finish\n12:01:42pm: A -finish\n</code></pre>\n\n<p><strong>Real World Example</strong></p>\n\n<pre><code>error_reporting(E_ALL);\nclass AsyncWebRequest extends Thread {\n public $url;\n public $data;\n\n public function __construct($url) {\n $this->url = $url;\n }\n\n public function run() {\n if (($url = $this->url)) {\n /*\n * If a large amount of data is being requested, you might want to\n * fsockopen and read using usleep in between reads\n */\n $this->data = file_get_contents($url);\n } else\n printf("Thread #%lu was not provided a URL\\n", $this->getThreadId());\n }\n}\n\n$t = microtime(true);\n$g = new AsyncWebRequest(sprintf("http://www.google.com/?q=%s", rand() * 10));\n/* starting synchronization */\nif ($g->start()) {\n printf("Request took %f seconds to start ", microtime(true) - $t);\n while ( $g->isRunning() ) {\n echo ".";\n usleep(100);\n }\n if ($g->join()) {\n printf(" and %f seconds to finish receiving %d bytes\\n", microtime(true) - $t, strlen($g->data));\n } else\n printf(" and %f seconds to finish, request failed\\n", microtime(true) - $t);\n}\n</code></pre>\n'}, {'answer_id': 19713701, 'author': 'pinkal vansia', 'author_id': 1606631, 'author_profile': 'https://Stackoverflow.com/users/1606631', 'pm_score': 4, 'selected': False, 'text': '<p>using threads is made possible by the pthreads PECL extension</p>\n\n<p><a href="http://www.php.net/manual/en/book.pthreads.php">http://www.php.net/manual/en/book.pthreads.php</a></p>\n'}, {'answer_id': 19789433, 'author': 'Pir Abdul', 'author_id': 665485, 'author_profile': 'https://Stackoverflow.com/users/665485', 'pm_score': -1, 'selected': False, 'text': '<p>Multithreading means performing multiple tasks or processes simultaneously, we can achieve this in php by using following code,although there is no direct way to achieve multithreading in php but we can achieve almost same results by following way.</p>\n\n<pre><code>chdir(dirname(__FILE__)); //if you want to run this file as cron job\n for ($i = 0; $i < 2; $i += 1){\n exec("php test_1.php $i > test.txt &");\n //this will execute test_1.php and will leave this process executing in the background and will go \n\n //to next iteration of the loop immediately without waiting the completion of the script in the \n\n //test_1.php , $i is passed as argument .\n</code></pre>\n\n<p>}</p>\n\n<p>Test_1.php</p>\n\n<pre><code>$conn=mysql_connect($host,$user,$pass);\n$db=mysql_select_db($db);\n$i = $argv[1]; //this is the argument passed from index.php file\nfor($j = 0;$j<5000; $j ++)\n{\nmysql_query("insert into test set\n\n id=\'$i\',\n\n comment=\'test\',\n\n datetime=NOW() ");\n\n}\n</code></pre>\n\n<p>This will execute test_1.php two times simultaneously and both process will run in the background simultaneously ,so in this way you can achieve multithreading in php.</p>\n\n<p>This guy done really good work <a href="https://github.com/krakjoe/pthreads" rel="nofollow">Multithreading in php</a></p>\n'}, {'answer_id': 52125027, 'author': 'Martin Vahi', 'author_id': 855783, 'author_profile': 'https://Stackoverflow.com/users/855783', 'pm_score': -1, 'selected': False, 'text': '<p>As of the writing of my current comment, I don\'t know about the PHP threads. I came to look for the answer here myself, but one workaround is that the PHP program that receives the request from the web server delegates the whole answer formulation to a console application that stores its output, the answer to the request, to a binary file and the PHP program that launched the console application returns that binary file byte-by-byte as the answer to the received request. The console application can be written in any programming language that runs on the server, including those that have proper threading support, including C++ programs that use OpenMP.</p>\n\n<p>One unreliable, dirty, trick is to use PHP for executing a console application, "uname",</p>\n\n<pre><code>uname -a\n</code></pre>\n\n<p>and print the output of that console command to the HTML output to find out the exact version of the server software. Then install the exact same version of the software to a VirtualBox instance, compile/assemble whatever fully self-contained, preferably static, binaries that one wants and then upload those to the server. From that point onwards the PHP application can use those binaries in the role of the console application that has proper multi-threading. It\'s a dirty, unreliable, workaround to a situation, when the server administrator has not installed all needed programming language implementations to the server. The thing to watch out for is that at every request that the PHP application receives the console application(s) terminates/exit/get_killed. </p>\n\n<p>As to what the hosting service administrators think of such server usage patterns, I guess it boils down to culture. In Northern Europe the service provider HAS TO DELIVER WHAT WAS ADVERTISED and if execution of console commands was allowed and uploading of non-malware files was allowed and the service provider has a right to kill any server process after a few minutes or even after 30 seconds, then the hosting service administrators lack any arguments for forming a proper complaint. In United States and Western Europe the situation/culture is very different and I believe that there\'s a great chance that in U.S. and/or Western Europe the hosting service provider will \n refuse to serve hosting service clients that use the above described trick. That\'s just my guess, given my personal experience with U.S. hosting services and given what I have heard from others about Western European hosting services. As of the writing of my current comment(2018_09_01) I do not know anything about the cultural norms of the Southern-European hosting service providers, Southern-European network administrators.</p>\n'}, {'answer_id': 61505176, 'author': 'Юрий Ярвинен', 'author_id': 10738019, 'author_profile': 'https://Stackoverflow.com/users/10738019', 'pm_score': 3, 'selected': False, 'text': '<p>If you are using a Linux server, you can use </p>\n\n<pre><code>exec("nohup $php_path path/script.php > /dev/null 2>/dev/null &")\n</code></pre>\n\n<p>If you need pass some args </p>\n\n<pre><code>exec("nohup $php_path path/script.php $args > /dev/null 2>/dev/null &")\n</code></pre>\n\n<p>In script.php</p>\n\n<pre><code>$args = $argv[1];\n</code></pre>\n\n<p>Or use Symfony\n<a href="https://symfony.com/doc/current/components/process.html" rel="noreferrer">https://symfony.com/doc/current/components/process.html</a></p>\n\n<pre><code>$process = Process::fromShellCommandline("php ".base_path(\'script.php\'));\n$process->setTimeout(0); \n$process->disableOutput(); \n$process->start();\n</code></pre>\n'}, {'answer_id': 71617864, 'author': 'Justin Jack', 'author_id': 1678210, 'author_profile': 'https://Stackoverflow.com/users/1678210', 'pm_score': 2, 'selected': False, 'text': '<p>I know this is an old question, but this will undoubtedly be useful to many: <a href="https://github.com/justincjack/phpthreads" rel="nofollow noreferrer">PHPThreads</a></p>\n<p>Code Example:</p>\n<pre><code>function threadproc($thread, $param) {\n \n echo "\\tI\'m a PHPThread. In this example, I was given only one parameter: \\"". print_r($param, true) ."\\" to work with, but I can accept as many as you\'d like!\\n";\n \n for ($i = 0; $i < 10; $i++) {\n usleep(1000000);\n echo "\\tPHPThread working, very busy...\\n";\n }\n \n return "I\'m a return value!";\n}\n \n\n$thread_id = phpthread_create($thread, array(), "threadproc", null, array("123456"));\n \necho "I\'m the main thread doing very important work!\\n";\n \nfor ($n = 0; $n < 5; $n++) {\n usleep(1000000);\n echo "Main thread...working!\\n";\n}\n \necho "\\nMain thread done working. Waiting on our PHPThread...\\n";\n \nphpthread_join($thread_id, $retval);\n \necho "\\n\\nOur PHPThread returned: " . print_r($retval, true) . "!\\n";\n</code></pre>\n<p>Requires PHP extensions:</p>\n<ul>\n<li>posix</li>\n<li>pcntl</li>\n<li>sockets</li>\n</ul>\n<p>I\'ve been using this library in production now for months. I put a LOT of effort into making it feel like using POSIX pthreads. If you\'re comfortable with pthreads, you can pick this up and use it very effectively in no time.</p>\n<p>Computationally, the inner workings are quite different, but practically, the functionality is nearly the same including semantics and syntax.</p>\n<p>I\'ve used it to write an extremely efficient WebSocket server that supports high throughput rates. Sorry, I\'m rambling. I\'m just excited that I finally got it released and I want to see who it will help!</p>\n'}, {'answer_id': 74086559, 'author': 'gzhegow', 'author_id': 2119205, 'author_profile': 'https://Stackoverflow.com/users/2119205', 'pm_score': 0, 'selected': False, 'text': '<p>popen()/proc_open() works parallel even in Windows.</p>\n<p>Most often pitfall is "fread/stream_get_contents" without while loop. Once you try to fread() from running process it will block output for processes that run after it (cause of fread() waits until at least one byte arrives)</p>\n<p>Add stream_select(). Closest analogy is "foreach with timeout but for streams", you pass few arrays to read and write and each call of stream_select() one or more streams will be selected. Function updates original arrays by reference, so dont forget to restore it to all streams before next call. Function gives them some time to read or write. If no content - control returns allowing us to retry cycle.</p>\n<pre class="lang-php prettyprint-override"><code>// sleep.php\nset_error_handler(function ($severity, $error, $file, $line) {\n throw new ErrorException($error, -1, $severity, $file, $line);\n});\n\n$sleep = $argv[ 1 ];\n\nsleep($sleep);\n\necho $sleep . PHP_EOL;\n\nexit(0);\n</code></pre>\n<pre class="lang-php prettyprint-override"><code>// run.php\n<?php\n\n$procs = [];\n$pipes = [];\n\n$cmd = \'php %cd%/sleep.php\';\n\n$desc = [\n 0 => [ \'pipe\', \'r\' ],\n 1 => [ \'pipe\', \'w\' ],\n 2 => [ \'pipe\', \'a\' ],\n];\n\nfor ( $i = 0; $i < 10; $i++ ) {\n $iCmd = $cmd . \' \' . ( 10 - $i ); // add SLEEP argument to each command 10, 9, ... etc.\n\n $proc = proc_open($iCmd, $desc, $pipes[ $i ], __DIR__);\n\n $procs[ $i ] = $proc;\n}\n\n$stdins = array_column($pipes, 0);\n$stdouts = array_column($pipes, 1);\n$stderrs = array_column($pipes, 2);\n\nwhile ( $procs ) {\n foreach ( $procs as $i => $proc ) {\n // @gzhegow > [OR] you can output while script is running (if child never finishes)\n $read = [ $stdins[ $i ] ];\n $write = [ $stdouts[ $i ], $stderrs[ $i ] ];\n $except = [];\n if (stream_select($read, $write, $except, $seconds = 0, $microseconds = 1000)) {\n foreach ( $write as $stream ) {\n echo stream_get_contents($stream);\n }\n }\n\n $status = proc_get_status($proc);\n\n if (false === $status[ \'running\' ]) {\n $status = proc_close($proc);\n unset($procs[ $i ]);\n\n echo \'STATUS: \' . $status . PHP_EOL;\n }\n\n // @gzhegow > [OR] you can output once command finishes\n // $status = proc_get_status($proc);\n //\n // if (false === $status[ \'running\' ]) {\n // if ($content = stream_get_contents($stderrs[ $i ])) {\n // echo \'[ERROR]\' . $content . PHP_EOL;\n // }\n //\n // echo stream_get_contents($stdouts[ $i ]) . PHP_EOL;\n //\n // $status = proc_close($proc);\n // unset($procs[ $i ]);\n //\n // echo \'STATUS: \' . $status . PHP_EOL;\n // }\n }\n\n usleep(1); // give your computer one tick to decide what thread should be used\n}\n\n// ensure you receive 1,2,3... but you\'ve just run it 10,9,8...\n\nexit(0);\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11190/']
|
70,880 |
<p>Say I have the following C++:</p>
<pre><code>char *p = new char[cb];
SOME_STRUCT *pSS = (SOME_STRUCT *) p;
delete pSS;
</code></pre>
<p>Is this safe according to the C++ standard? Do I need to cast back to a <code>char*</code> and then use <code>delete[]</code>? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?</p>
|
[{'answer_id': 70904, 'author': 'Daniel James', 'author_id': 2434, 'author_profile': 'https://Stackoverflow.com/users/2434', 'pm_score': 3, 'selected': False, 'text': '<p>No, it\'s undefined behaviour - a compiler could plausibly do something different, and as the C++ FAQ entry that <a href="https://stackoverflow.com/questions/70880/deleting-a-buffer-through-a-different-type-of-pointer#70905">thudbang</a> linked to says, <code>operator delete[]</code> might be overloaded to do something different to <code>operator delete</code>. You can sometimes get away with it, but it\'s also good practice to get into the habit of matching delete[] with new[] for the cases where you can\'t.</p>\n'}, {'answer_id': 70905, 'author': 'thudbang', 'author_id': 11661, 'author_profile': 'https://Stackoverflow.com/users/11661', 'pm_score': 4, 'selected': True, 'text': '<p>It\'s not guaranteed to be safe. Here\'s a relevant link in the C++ FAQ lite:</p>\n\n<p>[16.13] Can I drop the <code>[]</code> when deleting array of some built-in type (<code>char</code>, <code>int</code>, etc.)?</p>\n\n<p><a href="https://isocpp.org/wiki/faq/freestore-mgmt#delete-array-built-ins" rel="nofollow noreferrer">http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13</a></p>\n'}, {'answer_id': 70910, 'author': 'warren', 'author_id': 4418, 'author_profile': 'https://Stackoverflow.com/users/4418', 'pm_score': 0, 'selected': False, 'text': "<p>While this <em>should</em> work, I don't think you can guarantee it to be safe because the SOME_STRUCT is not a char* (unless it's merely a typedef).</p>\n\n<p>Additionally, since you're using different types of references, if you continue to use the *p access, and the memory has been deleted, you will get a runtime error.</p>\n"}, {'answer_id': 70941, 'author': 'Igor Semenov', 'author_id': 11401, 'author_profile': 'https://Stackoverflow.com/users/11401', 'pm_score': 2, 'selected': False, 'text': '<p>C++ Standard [5.3.5.2] declares:</p>\n\n<blockquote>\n <p>If the operand has a class type, the operand is converted to a pointer type by calling the above-mentioned conversion\n function, and the converted operand is used in place of the original operand for the remainder of this section. In either\n alternative, the value of the operand of delete may be a null pointer value. <strong>If it is not a null pointer value, in the first\n alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a\n subobject (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined. In the second\n alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous\n array new-expression.77) If not, the behavior is undefined. [ Note: this means that the syntax of the delete-expression\n must match the type of the object allocated by new, not the syntax of the new-expression. —end note ]</strong> [ Note: a pointer\n to a const type can be the operand of a delete-expression; it is not necessary to cast away the constness (5.2.11) of the\n pointer expression before it is used as the operand of the delete-expression. —end note ]</p>\n</blockquote>\n'}, {'answer_id': 70942, 'author': 'Zooba', 'author_id': 891, 'author_profile': 'https://Stackoverflow.com/users/891', 'pm_score': 2, 'selected': False, 'text': '<p>I highly doubt it.</p>\n\n<p>There are a lot of questionable ways of freeing memory, for example you can use <code>delete</code> on your <code>char</code> array (rather than <code>delete[]</code>) and it will likely work fine. I <a href="http://www.byteclub.net/blog/zooba/?p=77" rel="nofollow noreferrer">blogged</a> in detail about this (apologies for the self-link, but it\'s easier than rewriting it all).</p>\n\n<p>The compiler is not so much the issue as the platform. Most libraries will use the allocation methods of the underlying operating system, which means the same code could behave differently on Mac vs. Windows vs. Linux. I have seen examples of this and every single one was questionable code.</p>\n\n<p>The safest approach is to always allocate and free memory using the same data type. If you are allocating <code>char</code>s and returning them to other code, you may be better off providing specific allocate/deallocate methods:</p>\n\n<pre><code>SOME_STRUCT* Allocate()\n{\n size_t cb; // Initialised to something\n return (SOME_STRUCT*)(new char[cb]);\n}\n</code></pre>\n\n<p> </p>\n\n<pre><code>void Free(SOME_STRUCT* obj)\n{\n delete[] (char*)obj;\n}\n</code></pre>\n\n<p>(Overloading the <code>new</code> and <code>delete</code> operators may also be an option, but I have never liked doing this.)</p>\n'}, {'answer_id': 71090, 'author': '0124816', 'author_id': 11521, 'author_profile': 'https://Stackoverflow.com/users/11521', 'pm_score': 0, 'selected': False, 'text': "<p>This will work OK if the memory being pointed to <strong>and</strong> the pointer you are pointing with are both POD. In this case, no destructor would be called anyhow, and the memory allocator does not know or care about the type stored within the memory.</p>\n\n<p>The only case this is OK with non-POD types, is if the pointee is a subtype of the pointer, (e.g. You are pointing at a Car with a Vehicle*) and the pointer's destructor has been declared virtual.</p>\n"}, {'answer_id': 71442, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>This isn't safe, and non of the responses so far have emphasized enough the madness of doing this. Simply don't do it, if you consider yourself a real programmer, or ever want to work as a professional programmer in a team. You can only say that your struct contains non destructor <em>at the moment</em>, however you are laying a nasty possibly compiler and system specific trap for the future. Also, your code is unlikely to work as expected. The very best you can hope for is it doesn't crash. However I suspect you will slowly get a memory leak, as array allocations via new very often allocate extra memory in the bytes <em>prior</em> to the returned pointer. You won't be freeing the memory you think you are. A good memory allocation routine should pick up this mismatch, as would tools like Lint etc. </p>\n\n<p>Simply don't do that, and purge from your mind whatever thinking process led you to even consider such nonsense.</p>\n"}, {'answer_id': 72444, 'author': 'Roger Lipscombe', 'author_id': 8446, 'author_profile': 'https://Stackoverflow.com/users/8446', 'pm_score': 0, 'selected': False, 'text': "<p>I've changed the code to use malloc/free. While I know how MSVC implements new/delete for plain-old-data (and SOME_STRUCT in this case was a Win32 structure, so simple C), I just wanted to know if it was a portable technique.</p>\n\n<p>It's not, so I'll use something that is.</p>\n"}, {'answer_id': 78368, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 0, 'selected': False, 'text': "<p>If you use malloc/free instead of new/delete, malloc and free won't care about the type.</p>\n\n<p>So if you're using a C-like POD (plain old data, like a build-in type, or a struct), you can malloc some type, and free another. <strong>note that this is poor style even if it works</strong>.</p>\n"}, {'answer_id': 108579, 'author': 'CB Bailey', 'author_id': 19563, 'author_profile': 'https://Stackoverflow.com/users/19563', 'pm_score': 2, 'selected': False, 'text': '<p>This is a very similar question to the one that I answered here: <a href="https://stackoverflow.com/questions/73134/will-this-c-code-cause-a-memory-leak-casting-vector-new#108454">link text</a></p>\n\n<p>In short, no, it\'s not safe according to the C++ standard. If, for some reason, you need a SOME_STRUCT object allocated in an area of memory that has a size difference from <code>size_of(SOME_STRUCT)</code> (and it had better be bigger!), then you are better off using a raw allocation function like global <code>operator new</code> to perform the allocation and then creating the object instance in raw memory with a placement <code>new</code>. Placement <code>new</code> will be extremely cheap if the object type has no constructor.</p>\n\n<pre><code>void* p = ::operator new( cb );\nSOME_STRUCT* pSS = new (p) SOME_STRUCT;\n\n// ...\n\ndelete pSS;\n</code></pre>\n\n<p>This will work most of the time. It should always work if <code>SOME_STRUCT</code> is a POD-struct. It will also work in other cases if <code>SOME_STRUCT</code>\'s constructor does not throw and if <code>SOME_STRUCT</code> does not have a custom operator delete. This technique also removes the need for any casts.</p>\n\n<p><code>::operator new</code> and <code>::operator delete</code> are C++\'s closest equivalent to <code>malloc</code> and <code>free</code> and as these (in the absence of class overrides) are called as appropriate by <code>new</code> and <code>delete</code> expressions they can (with care!) be used in combination.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8446/']
|
70,890 |
<p>I am trying to write a web-app to manage references for my PhD thesis.</p>
<p>I used to manage this information inside a personal Confluence (fantastic tool! - <a href="http://www.atlassian.com/software/confluence/" rel="nofollow noreferrer">http://www.atlassian.com/software/confluence/</a>) instance however I'm fed-up with the opening of PDF's and cutting and pasting values into fields that I wish to record.</p>
<p>I have exposed a webservice that will return me images based on a PDF filename and a page number. The same webservice also exposes a method that will return the text inside of a provided rectangle (top left x-y coord, bottom right x-y coord).</p>
<p>I would like to be able to drag a rectangle over part of the PDF image and then call the webservice to give me the text (which I will then store on a EntityBean). I am looking at using the JBoss application stack (Application Server, Hibernate, Seam and Richfaces). Does anybody know how I could go about achieving this? I have seen the ability to draw custom images in other RIA toolkits (e.g. dojo), but I can't see a way of doing this inside of Richfaces.</p>
<p>Hopefully somebody out there could prove me wrong, or provide some idea about what I can do (as I am not a web developer - I'm mainly building this tool because the RIA frameworks available now have got me interested!)</p>
<p>I already have the code to extract the text, my problem is purely how can I get the user to draw a "selection rectangle" inside the web browser over the top of the image?</p>
<p>Many Thanks,</p>
<p>Aidos</p>
|
[{'answer_id': 71007, 'author': 'Andy MacGilvery', 'author_id': 5546, 'author_profile': 'https://Stackoverflow.com/users/5546', 'pm_score': 1, 'selected': False, 'text': '<p>Try using the <a href="http://livedemo.exadel.com/richfaces-demo/richfaces/paint2D.jsf?c=paint2d&tab=usage" rel="nofollow noreferrer">RichFaces Paint 2D</a> tag</p>\n\n<p>It exposes the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics2D.html" rel="nofollow noreferrer">Graphics2D</a> package to the user interface.</p>\n\n<p>Track user drag events on the image using javascript, then post the co-ordrdinates to the backing bean to re-render the image with a drawn on selection box.</p>\n'}, {'answer_id': 386521, 'author': 'anders.norgaard', 'author_id': 8805, 'author_profile': 'https://Stackoverflow.com/users/8805', 'pm_score': 0, 'selected': False, 'text': '<p>Have you considered <a href="http://www.mendeley.com/" rel="nofollow noreferrer">Mendeley</a> ? It will try to parse and extract bibliographic information from your pdfs.</p>\n'}, {'answer_id': 1310826, 'author': 'SomaSekhar', 'author_id': 92076, 'author_profile': 'https://Stackoverflow.com/users/92076', 'pm_score': 0, 'selected': False, 'text': '<p>you can do it with itext (<a href="http://www.lowagie.com/iText/" rel="nofollow noreferrer">http://www.lowagie.com/iText/</a>)</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
70,909 |
<p>With Hibernate, can you create a composite ID where one of the columns you are mapping to the ID can have null values?</p>
<p>This is to deal with a legacy table that has a unique key which can have null values but no primary key.</p>
<p>I realise that I could just add a new primary key column to the table, but I'm wondering if there's any way to avoid doing this.</p>
|
[{'answer_id': 70925, 'author': 'Manrico Corazzi', 'author_id': 4690, 'author_profile': 'https://Stackoverflow.com/users/4690', 'pm_score': -1, 'selected': False, 'text': "<p>Why would you want to do that? Your composite ID should map the primary key of your table, and it doesn't sound wise to put null values in a key, does it?</p>\n\n<p><strong>EDIT:</strong> Hibernate does not allow to do so; you might put the property outside the key and tweak the DAO a little to take the field into account wherever necessary</p>\n"}, {'answer_id': 70933, 'author': 'Andreas Bakurov', 'author_id': 7400, 'author_profile': 'https://Stackoverflow.com/users/7400', 'pm_score': 5, 'selected': True, 'text': '<p>No. Primary keys can not be null.</p>\n'}, {'answer_id': 70934, 'author': 'Paul Shannon', 'author_id': 11503, 'author_profile': 'https://Stackoverflow.com/users/11503', 'pm_score': 0, 'selected': False, 'text': '<p>This is not advisable. Could you use a view and map that instead? You could use COALESCE to supply a default if you are stuck with legacy data. We had lots of trouble with composite keys and I imagine null values will cause even more issues.</p>\n'}, {'answer_id': 70966, 'author': 'Andreas Bakurov', 'author_id': 7400, 'author_profile': 'https://Stackoverflow.com/users/7400', 'pm_score': 0, 'selected': False, 'text': '<p>For composite keys (assumed that database allows nulls in PKs) you can have maximum number_of_cols^2 - 1 entries containing nulls, (for example for composite key of 2 columns you can have 3 rows having in their primary key null, the fourth is the PK without nulls).</p>\n'}, {'answer_id': 36640391, 'author': 'Rakesh Patil', 'author_id': 1535849, 'author_profile': 'https://Stackoverflow.com/users/1535849', 'pm_score': 3, 'selected': False, 'text': '<p>You wont get error but Hibernate wont be able to map those rows with NULL value for composite column to your Entity. That means you get entity with NULL values in result.</p>\n'}, {'answer_id': 42247822, 'author': 'BlondCode', 'author_id': 4503189, 'author_profile': 'https://Stackoverflow.com/users/4503189', 'pm_score': 3, 'selected': False, 'text': '<p>Unfortunatly, no. I either had to use a workaround:</p>\n\n<p>I used composit Id for a view(! not table) where rows can be identified by 2 cols exactly (A, B). Although one of the cols (B) can have null values as well as positive integers.\nSo my workaround is that i created a new col in the view: "BKey" and my view is written as if B is null then value of BKey is -1 else BKey = B. (Only positive integers occour in B and null). I also changed my composit id implementation to use BKey instead of B.\nHope it helps for somebody..</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
70,947 |
<p>I have a workbook with 20 different pivot tables. Is there any easy way to find all the pivot tables and refresh them in VBA?</p>
|
[{'answer_id': 70976, 'author': 'GSerg', 'author_id': 11683, 'author_profile': 'https://Stackoverflow.com/users/11683', 'pm_score': 9, 'selected': True, 'text': '<p>Yes.</p>\n\n<pre><code>ThisWorkbook.RefreshAll\n</code></pre>\n\n<p>Or, if your Excel version is old enough,</p>\n\n<pre><code>Dim Sheet as WorkSheet, Pivot as PivotTable\nFor Each Sheet in ThisWorkbook.WorkSheets\n For Each Pivot in Sheet.PivotTables\n Pivot.RefreshTable\n Pivot.Update\n Next\nNext\n</code></pre>\n'}, {'answer_id': 71002, 'author': 'LohanJ', 'author_id': 11286, 'author_profile': 'https://Stackoverflow.com/users/11286', 'pm_score': 1, 'selected': False, 'text': "<p>You have a <em>PivotTables</em> collection on a the VB <em>Worksheet</em> object. So, a quick loop like this will work:</p>\n\n<pre><code>Sub RefreshPivotTables()\n Dim pivotTable As PivotTable\n For Each pivotTable In ActiveSheet.PivotTables\n pivotTable.RefreshTable\n Next\nEnd Sub\n</code></pre>\n\n<p>Notes from the trenches:</p>\n\n<ol>\n<li>Remember to unprotect any protected sheets before updating the PivotTable.</li>\n<li><strong>Save often</strong>.</li>\n<li>I'll think of more and update in due course... :)</li>\n</ol>\n\n<p>Good luck!</p>\n"}, {'answer_id': 71084, 'author': 'Robert Mearns', 'author_id': 5050, 'author_profile': 'https://Stackoverflow.com/users/5050', 'pm_score': 5, 'selected': False, 'text': "<p>This VBA code will refresh all pivot tables/charts in the workbook.</p>\n\n<pre><code>Sub RefreshAllPivotTables()\n\nDim PT As PivotTable\nDim WS As Worksheet\n\n For Each WS In ThisWorkbook.Worksheets\n\n For Each PT In WS.PivotTables\n PT.RefreshTable\n Next PT\n\n Next WS\n\nEnd Sub\n</code></pre>\n\n<p>Another non-programatic option is:</p>\n\n<ul>\n<li>Right click on each pivot table</li>\n<li>Select Table options</li>\n<li>Tick the <strong>'Refresh on open'</strong> option.</li>\n<li>Click on the OK button</li>\n</ul>\n\n<p>This will refresh the pivot table each time the workbook is opened.</p>\n"}, {'answer_id': 359227, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>There is a refresh all option in the Pivot Table tool bar. That is enough. Dont have to do anything else.</p>\n\n<p>Press ctrl+alt+F5</p>\n'}, {'answer_id': 8432023, 'author': 'Steve WahWah Weeks', 'author_id': 1087868, 'author_profile': 'https://Stackoverflow.com/users/1087868', 'pm_score': 3, 'selected': False, 'text': "<p>In certain circumstances you might want to differentiate between a PivotTable and its PivotCache. The Cache has it's own refresh method and its own collections. So we could have refreshed all the PivotCaches instead of the PivotTables.</p>\n\n<p>The difference? When you create a new Pivot Table you are asked if you want it based on a previous table. If you say no, this Pivot Table gets its own cache and doubles the size of the source data. If you say yes, you keep your WorkBook small, but you add to a collection of Pivot Tables that share a single cache. The entire collection gets refreshed when you refresh any single Pivot Table in that collection. You can imagine therefore what the difference might be between refreshing every cache in the WorkBook, compared to refreshing every Pivot Table in the WorkBook.</p>\n"}, {'answer_id': 10434668, 'author': 'Karuna', 'author_id': 1372934, 'author_profile': 'https://Stackoverflow.com/users/1372934', 'pm_score': -1, 'selected': False, 'text': '<p>If you are using MS Excel 2003 then go to view->Tool bar->Pivot Table From this tool bar we can do refresh by clicking ! this symbol.</p>\n'}, {'answer_id': 12478754, 'author': 'RBhandal', 'author_id': 1680524, 'author_profile': 'https://Stackoverflow.com/users/1680524', 'pm_score': -1, 'selected': False, 'text': '<p>I have use the command listed below in the recent past and it seems to work fine.</p>\n\n<pre><code>ActiveWorkbook.RefreshAll\n</code></pre>\n\n<p>Hope that helps.</p>\n'}, {'answer_id': 12592078, 'author': 'Kevin', 'author_id': 1698696, 'author_profile': 'https://Stackoverflow.com/users/1698696', 'pm_score': 5, 'selected': False, 'text': '<p><code>ActiveWorkbook.RefreshAll</code> refreshes everything, not only the pivot tables but also the ODBC queries. I have a couple of VBA queries that refer to Data connections and using this option crashes as the command runs the Data connections without the detail supplied from the VBA</p>\n\n<p>I recommend the option if you only want the pivots refreshed</p>\n\n<pre><code>Sub RefreshPivotTables() \n Dim pivotTable As PivotTable \n For Each pivotTable In ActiveSheet.PivotTables \n pivotTable.RefreshTable \n Next \nEnd Sub \n</code></pre>\n'}, {'answer_id': 29474211, 'author': 'user3564681', 'author_id': 3564681, 'author_profile': 'https://Stackoverflow.com/users/3564681', 'pm_score': 0, 'selected': False, 'text': '<p>The code </p>\n\n<pre><code>Private Sub Worksheet_Activate()\n Dim PvtTbl As PivotTable\n Cells.EntireColumn.AutoFit\n For Each PvtTbl In Worksheets("Sales Details").PivotTables\n PvtTbl.RefreshTable\n Next\nEnd Sub \n</code></pre>\n\n<p>works fine.</p>\n\n<p>The code is used in the activate sheet module, thus it displays a flicker/glitch when the sheet is activated.</p>\n'}, {'answer_id': 34544128, 'author': 'Rajiv Singh', 'author_id': 1527856, 'author_profile': 'https://Stackoverflow.com/users/1527856', 'pm_score': 0, 'selected': False, 'text': '<p>Even <strong>we can refresh particular connection</strong> and in turn it will refresh all the pivots linked to it.</p>\n\n<p><strong>For this code I have created slicer from table present in Excel</strong>:</p>\n\n<pre><code>Sub UpdateConnection()\n Dim ServerName As String\n Dim ServerNameRaw As String\n Dim CubeName As String\n Dim CubeNameRaw As String\n Dim ConnectionString As String\n\n ServerNameRaw = ActiveWorkbook.SlicerCaches("Slicer_ServerName").VisibleSlicerItemsList(1)\n ServerName = Replace(Split(ServerNameRaw, "[")(3), "]", "")\n\n CubeNameRaw = ActiveWorkbook.SlicerCaches("Slicer_CubeName").VisibleSlicerItemsList(1)\n CubeName = Replace(Split(CubeNameRaw, "[")(3), "]", "")\n\n If CubeName = "All" Or ServerName = "All" Then\n MsgBox "Please Select One Cube and Server Name", vbOKOnly, "Slicer Info"\n Else\n ConnectionString = GetConnectionString(ServerName, CubeName)\n UpdateAllQueryTableConnections ConnectionString, CubeName\n End If\n End Sub\n\n Function GetConnectionString(ServerName As String, CubeName As String)\n Dim result As String\n result = "OLEDB;Provider=MSOLAP.5;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=" & CubeName & ";Data Source=" & ServerName & ";MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error;Update Isolation Level=2"\n \'"OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=" & CubeName & ";Data Source=" & ServerName & ";Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False"\n GetConnectionString = result\n End Function\n\n Function GetConnectionString(ServerName As String, CubeName As String)\n Dim result As String\n result = "OLEDB;Provider=MSOLAP.5;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=" & CubeName & ";Data Source=" & ServerName & ";MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error;Update Isolation Level=2"\n GetConnectionString = result\nEnd Function\n\nSub UpdateAllQueryTableConnections(ConnectionString As String, CubeName As String)\n Dim cn As WorkbookConnection\n Dim oledbCn As OLEDBConnection\n Dim Count As Integer, i As Integer\n Dim DBName As String\n DBName = "Initial Catalog=" + CubeName\n\n Count = 0\n For Each cn In ThisWorkbook.Connections\n If cn.Name = "ThisWorkbookDataModel" Then\n Exit For\n End If\n\n oTmp = Split(cn.OLEDBConnection.Connection, ";")\n For i = 0 To UBound(oTmp) - 1\n If InStr(1, oTmp(i), DBName, vbTextCompare) = 1 Then\n Set oledbCn = cn.OLEDBConnection\n oledbCn.SavePassword = True\n oledbCn.Connection = ConnectionString\n oledbCn.Refresh\n Count = Count + 1\n End If\n Next\n Next\n\n If Count = 0 Then\n MsgBox "Nothing to update", vbOKOnly, "Update Connection"\n ElseIf Count > 0 Then\n MsgBox "Update & Refresh Connection Successfully", vbOKOnly, "Update Connection"\n End If\nEnd Sub\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8418/']
|
70,956 |
<p>Is there a good way to exclude certain pages from using a HTTP module?</p>
<p>I have an application that uses a custom HTTP module to validate a session. The HTTPModule is set up like this in web config:</p>
<pre><code><system.web>
<!-- ... -->
<httpModules>
<add name="SessionValidationModule"
type="SessionValidationModule, SomeNamespace" />
</httpModules>
</system.web>
</code></pre>
<p>To exclude the module from the page, I tried doing this (without success):</p>
<pre><code><location path="ToBeExcluded">
<system.web>
<!-- ... -->
<httpModules>
<remove name="SessionValidationModule" />
</httpModules>
</system.web>
</location>
</code></pre>
<p>Any thoughts?</p>
|
[{'answer_id': 71790, 'author': 'Crob', 'author_id': 2460, 'author_profile': 'https://Stackoverflow.com/users/2460', 'pm_score': 5, 'selected': True, 'text': '<p>You could use an HTTPHandler instead of an HTTPModule. Handlers let you specify a path when you declare them in Web.Config. </p>\n\n<pre><code><add verb="*" path="/validate/*.aspx" type="Handler,Assembly"/>\n</code></pre>\n\n<p>If you must use an HTTPModule, you could just check the path of the request and if it\'s one to be excluded, bypass the validation. </p>\n'}, {'answer_id': 72823, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>HttpModules attach to the ASP.NET request processing pipeline itself. The httpModule itself must take care of figuring out which requests it wants to act on and which requests it wants to ignore. </p>\n\n<p>This can, for example, be achieved by looking at the context.Request.Path property.</p>\n'}, {'answer_id': 18411217, 'author': 'Mr. Pumpkin', 'author_id': 524605, 'author_profile': 'https://Stackoverflow.com/users/524605', 'pm_score': 3, 'selected': False, 'text': '<p>Here is some simple example how to filter requests by extension... the example below exclude from the processing files with the specific extensions. Filtering by file name will look almost the same with some small changes...</p>\n\n<pre><code>public class AuthenticationModule : IHttpModule\n{\n private static readonly List<string> extensionsToSkip = AuthenticationConfig.ExtensionsToSkip.Split(\'|\').ToList();\n\n // In the Init function, register for HttpApplication \n // events by adding your handlers.\n public void Init(HttpApplication application)\n {\n application.BeginRequest += new EventHandler(this.Application_BeginRequest);\n application.EndRequest += new EventHandler(this.Application_EndRequest);\n }\n\n private void Application_BeginRequest(Object source, EventArgs e)\n {\n // we don\'t have to process all requests...\n if (extensionsToSkip.Contains(Path.GetExtension(HttpContext.Current.Request.Url.LocalPath)))\n return;\n\n Trace.WriteLine("Application_BeginRequest: " + HttpContext.Current.Request.Url.AbsoluteUri);\n }\n\n private void Application_EndRequest(Object source, EventArgs e)\n {\n // we don\'t have to process all requests...\n if (extensionsToSkip.Contains(Path.GetExtension(HttpContext.Current.Request.Url.LocalPath)))\n return;\n\n Trace.WriteLine("Application_BeginRequest: " + HttpContext.Current.Request.Url.AbsoluteUri);\n }\n}\n</code></pre>\n\n<p>General idea is to specify in config file what exactly should be processed (or excluded from the processing) and use that config parameter in the module.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6308/']
|
70,964 |
<p>Originally I am looking for a solution in Actionscript. The point of this question is the algorithm, which detects the exact Minute, when a clock has to switch the Daylight Saving Time. </p>
<p>So for example between the 25th and the 31th of October we have to check, if the actual date is a sunday, it is before or after 2 o'clock...</p>
|
[{'answer_id': 154765, 'author': 'Benno Richters', 'author_id': 3565, 'author_profile': 'https://Stackoverflow.com/users/3565', 'pm_score': 2, 'selected': False, 'text': '<p>There is no real algorithm for dealing with Daylight Saving Time. Basically every country can decide for themselves when -and if- DST starts and ends. The only thing we can do as developers is using some sort of table to look it up. Most computer languages integrate such a table in the language.</p>\n\n<p>In Java you could use the <code>inDaylightTime</code> method of the <a href="http://java.sun.com/javase/6/docs/api/java/util/TimeZone.html" rel="nofollow noreferrer">TimeZone</a> class. If you want to know the exact date and time when DST starts or ends in a certain year, I would recommend to use <a href="http://joda-time.sourceforge.net/" rel="nofollow noreferrer">Joda Time</a>. I can\'t see a clean way of finding this out using just the standard libraries.</p>\n\n<p>The following program is an example: (Note that it could give unexpected results if a certain time zone does not have DST for a certain year)</p>\n\n<pre><code>import org.joda.time.DateTime;\nimport org.joda.time.DateTimeZone;\n\npublic class App {\n public static void main(String[] args) {\n DateTimeZone dtz = DateTimeZone.forID("Europe/Amsterdam");\n\n System.out.println(startDST(dtz, 2008));\n System.out.println(endDST(dtz, 2008));\n }\n\n public static DateTime startDST(DateTimeZone zone, int year) {\n return new DateTime(zone.nextTransition(new DateTime(year, 1, 1, 0, 0, 0, 0, zone).getMillis()));\n }\n\n public static DateTime endDST(DateTimeZone zone, int year) {\n return new DateTime(zone.previousTransition(new DateTime(year + 1, 1, 1, 0, 0, 0, 0, zone).getMillis()));\n }\n}\n</code></pre>\n'}, {'answer_id': 50499119, 'author': 'Basil Bourque', 'author_id': 642706, 'author_profile': 'https://Stackoverflow.com/users/642706', 'pm_score': 1, 'selected': False, 'text': '<p>The <a href="https://stackoverflow.com/a/154765/642706">Answer by Richters</a> is correct and should be accepted.</p>\n\n<p>As Richters noted, there is no logic to <a href="https://en.wikipedia.org/wiki/Daylight_saving_time" rel="nofollow noreferrer">Daylight Saving Time (DST)</a> or other anomalies. Politicians arbitrarily redefine the <a href="https://en.wikipedia.org/wiki/UTC_offset" rel="nofollow noreferrer">offset-from-UTC</a> used in their <a href="https://en.wikipedia.org/wiki/Time_zone" rel="nofollow noreferrer">time zones</a>. They make these changes often with little forewarning, or even no warning at all as <a href="http://www.bbc.com/news/world-asia-44010705" rel="nofollow noreferrer">North Korea did</a> a few weeks ago.</p>\n\n<h1>java.time</h1>\n\n<p>Here are some further thoughts, and example code using the modern <em>java.time</em> classes that succeeded the Joda-Time classes shown in his Answer.</p>\n\n<p>These changes are tracked in a list maintained by <a href="https://en.wikipedia.org/wiki/ICANN" rel="nofollow noreferrer">ICANN</a>, known as <a href="https://en.wikipedia.org/wiki/Tz_database" rel="nofollow noreferrer"><em>tzdata</em></a>, formerly known as the Olson Database. Your Java implementation, host operating system, and database system likely all have their own copies of this data which must be replaced as needed when changes are mode to zones you care about. There is no logic to these changes, so there is no way to predict the changes programmatically. Your code must call upon a fresh copy of <em>tzdata</em>.</p>\n\n<blockquote>\n <p>So for example between the 25th and the 31th of October we have to check, if the actual date is a sunday, it is before or after 2 o\'clock...</p>\n</blockquote>\n\n<p>Actually, you need not determine the point of the cut-over. A good date-time library handles that for you automatically. </p>\n\n<p>Java has the best such library, the industry-leading <em>java.time</em> classes. When you ask for a time-of-day on a certain date in a certain region (time zone), if that time-of-day is no valid an adjustment is made automatically. Read the documentation for the <code>ZonedDateTime</code> to understand the algorithm used in that adjustment.</p>\n\n<pre><code>ZoneId z = ZoneId.of( "America/Montreal" );\nLocalDate ld = LocalDate.of( 2018 , Month.MARCH , 11 ); // 2018-03-11.\nLocalTime lt = LocalTime.of( 2 , 0 ); // 2 AM.\nZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );\n</code></pre>\n\n<p>Notice the result is 3 AM rather than the 2 AM requested. There was no 2 AM on that date in that zone. So java.time adjusted to 3 AM as the clock “Springs ahead” an hour.</p>\n\n<blockquote>\n <p>zdt.toString(): 2018-03-11T03:00-04:00[America/Montreal]</p>\n</blockquote>\n\n<p>If you feel the need to investigate the rules defined for a time zone, use the <a href="https://docs.oracle.com/javase/10/docs/api/java/time/zone/ZoneRules.html" rel="nofollow noreferrer"><code>ZoneRules</code></a> class.</p>\n\n<p>Get the amount of DST shift used in the present moment.</p>\n\n<pre><code>Duration d = z.getRules().getDaylightSavings\u200b( Instant.now() ) ;\n</code></pre>\n\n<p>Get the next planned change, represented as a <a href="https://docs.oracle.com/javase/10/docs/api/java/time/zone/ZoneOffsetTransition.html" rel="nofollow noreferrer"><code>ZoneOffsetTransition</code></a> object.</p>\n\n<pre><code>ZoneId z = ZoneId.of( "America/Montreal" );\nZoneOffsetTransition t = z.getRules().nextTransition( Instant.now() );\nString output = "For zone: " + z + ", on " + t.getDateTimeBefore() + " duration change: " + t.getDuration() + " to " + t.getDateTimeAfter();\n</code></pre>\n\n<blockquote>\n <p>For zone: America/Montreal, on 2018-11-04T02:00 duration change: PT-1H to 2018-11-04T01:00</p>\n</blockquote>\n\n<p>Specify a <a href="https://en.wikipedia.org/wiki/List_of_tz_zones_by_name" rel="nofollow noreferrer">proper time zone name</a> in the format of <code>continent/region</code>, such as <a href="https://en.wikipedia.org/wiki/America/Montreal" rel="nofollow noreferrer"><code>America/Montreal</code></a>, <a href="https://en.wikipedia.org/wiki/Africa/Casablanca" rel="nofollow noreferrer"><code>Africa/Casablanca</code></a>, or <code>Pacific/Auckland</code>. Never use the 3-4 letter abbreviation such as <code>EST</code> or <code>IST</code> as they are <em>not</em> true time zones, not standardized, and not even unique(!). </p>\n\n<hr>\n\n<h1>About <em>java.time</em></h1>\n\n<p>The <a href="http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html" rel="nofollow noreferrer"><em>java.time</em></a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href="https://en.wikipedia.org/wiki/Legacy_system" rel="nofollow noreferrer">legacy</a> date-time classes such as <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Date.html" rel="nofollow noreferrer"><code>java.util.Date</code></a>, <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html" rel="nofollow noreferrer"><code>Calendar</code></a>, & <a href="http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html" rel="nofollow noreferrer"><code>SimpleDateFormat</code></a>.</p>\n\n<p>The <a href="http://www.joda.org/joda-time/" rel="nofollow noreferrer"><em>Joda-Time</em></a> project, now in <a href="https://en.wikipedia.org/wiki/Maintenance_mode" rel="nofollow noreferrer">maintenance mode</a>, advises migration to the <a href="http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html" rel="nofollow noreferrer">java.time</a> classes.</p>\n\n<p>To learn more, see the <a href="http://docs.oracle.com/javase/tutorial/datetime/TOC.html" rel="nofollow noreferrer"><em>Oracle Tutorial</em></a>. And search Stack Overflow for many examples and explanations. Specification is <a href="https://jcp.org/en/jsr/detail?id=310" rel="nofollow noreferrer">JSR 310</a>.</p>\n\n<p>You may exchange <em>java.time</em> objects directly with your database. Use a <a href="https://en.wikipedia.org/wiki/JDBC_driver" rel="nofollow noreferrer">JDBC driver</a> compliant with <a href="http://openjdk.java.net/jeps/170" rel="nofollow noreferrer">JDBC 4.2</a> or later. No need for strings, no need for <code>java.sql.*</code> classes.</p>\n\n<p>Where to obtain the java.time classes? </p>\n\n<ul>\n<li><a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8" rel="nofollow noreferrer"><strong>Java SE 8</strong></a>, <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9" rel="nofollow noreferrer"><strong>Java SE 9</strong></a>, <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10" rel="nofollow noreferrer"><strong>Java SE 10</strong></a>, and later\n\n<ul>\n<li>Built-in. </li>\n<li>Part of the standard Java API with a bundled implementation.</li>\n<li>Java 9 adds some minor features and fixes.</li>\n</ul></li>\n<li><a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6" rel="nofollow noreferrer"><strong>Java SE 6</strong></a> and <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7" rel="nofollow noreferrer"><strong>Java SE 7</strong></a>\n\n<ul>\n<li>Much of the java.time functionality is back-ported to Java 6 & 7 in <a href="http://www.threeten.org/threetenbp/" rel="nofollow noreferrer"><strong><em>ThreeTen-Backport</em></strong></a>.</li>\n</ul></li>\n<li><a href="https://en.wikipedia.org/wiki/Android_(operating_system)" rel="nofollow noreferrer"><strong>Android</strong></a>\n\n<ul>\n<li>Later versions of Android bundle implementations of the java.time classes.</li>\n<li>For earlier Android (<26), the <a href="https://github.com/JakeWharton/ThreeTenABP" rel="nofollow noreferrer"><strong><em>ThreeTenABP</em></strong></a> project adapts <a href="http://www.threeten.org/threetenbp/" rel="nofollow noreferrer"><strong><em>ThreeTen-Backport</em></strong></a> (mentioned above). See <a href="http://stackoverflow.com/q/38922754/642706"><em>How to use ThreeTenABP…</em></a>.</li>\n</ul></li>\n</ul>\n\n<p>The <a href="http://www.threeten.org/threeten-extra/" rel="nofollow noreferrer"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html" rel="nofollow noreferrer"><code>Interval</code></a>, <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html" rel="nofollow noreferrer"><code>YearWeek</code></a>, <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html" rel="nofollow noreferrer"><code>YearQuarter</code></a>, and <a href="http://www.threeten.org/threeten-extra/apidocs/index.html" rel="nofollow noreferrer">more</a>.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70964', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
70,992 |
<p>Relating to my <a href="https://stackoverflow.com/questions/48733/javahibernate-jpa-designing-the-server-data-reload">earlier question</a>, I want to ensure all the child objects are loaded as I have a multiple threads that may need to access the data (and thus avoid lazy loading exceptions). I understand the way to do this is to use the "fetch" keyword in the query (EJB QL). Like this:</p>
<pre><code>select distinct o from Order o left join fetch o.orderLines
</code></pre>
<p>Assuming a model with an <code>Order</code> class which has a set of <code>OrderLines</code> in it.</p>
<p>My question is that the "distinct" keyword seems to be needed as otherwise I seem to get back an <code>Order</code> for each <code>OrderLine</code>. Am I doing the right thing?</p>
<p>Perhaps more importantly, is there a way to pull in all child objects, no matter how deep? We have around 10-15 classes and for the server we will need everything loaded... I was avoiding using <code>FetchType.EAGER</code> as that meant its always eager and in particular the web front end loads everything - but perhaps that is the way to go - is that what you do? I seem to remember us trying this before and then getting really slow webpages - but perhaps that means we should be using a second-level cache?</p>
|
[{'answer_id': 71172, 'author': 'Jeremy', 'author_id': 4419, 'author_profile': 'https://Stackoverflow.com/users/4419', 'pm_score': 3, 'selected': False, 'text': '<p>I\'m not sure about using the fetch keyword in your EJBQL, you might be getting it confused with the annotation...</p>\n\n<p>Have you tried adding the FetchType property to your relationship attribute?</p>\n\n<p>@OneToMany(fetch=FetchType.EAGER)?</p>\n\n<p>See: </p>\n\n<p><a href="http://java.sun.com/javaee/5/docs/api/javax/persistence/FetchType.html" rel="noreferrer">http://java.sun.com/javaee/5/docs/api/javax/persistence/FetchType.html</a>\n<a href="http://www.jroller.com/eyallupu/entry/hibernate_exception_simultaneously_fetch_multiple" rel="noreferrer">http://www.jroller.com/eyallupu/entry/hibernate_exception_simultaneously_fetch_multiple</a></p>\n'}, {'answer_id': 71316, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 0, 'selected': False, 'text': '<p>That would only work for ManyToOne relations and for them @ManyToOne(fetch=FetchType.EAGER) would probably appropriate.</p>\n\n<p>Fetching more than one OneToMany relation eagerly is discouraged and/or does not work as you can read in the link Jeremy posted. Just think about the SQL statement that would be needed to do such a fetch...</p>\n'}, {'answer_id': 71499, 'author': 'James Law', 'author_id': 11855, 'author_profile': 'https://Stackoverflow.com/users/11855', 'pm_score': 5, 'selected': True, 'text': "<p>Changing the annotation is a bad idea IMO. As it can't be changed to lazy at runtime. Better to make everything lazy, and fetch as needed.</p>\n\n<p>I'm not sure I understand your problem without mappings. Left join fetch should be all you need for the use case you describe. Of course you'll get back an order for every orderline if orderline has an order as its parent.</p>\n"}, {'answer_id': 73267, 'author': 'Chris Kimpton', 'author_id': 48310, 'author_profile': 'https://Stackoverflow.com/users/48310', 'pm_score': 0, 'selected': False, 'text': '<p>What I have done is to refactor the code to keep a map of objects to entity managers and each time I need to refresh, close the old entitymanager for the object and open a new one. I used the above query without the <strong>fetch</strong> as that is going too deep for my needs - just doing a plain join pulls in the OrderLines - the <strong>fetch</strong> makes it go even deeper. </p>\n\n<p>There are only a few objects that I need this for, around 20, so I think the resource overhead in having 20 open entitymanagers is not an issue - although the DBAs may have a different view when this goes live...</p>\n\n<p>I also re-worked things so that the db work is on the main thread and has the entity manager. </p>\n\n<p>Chris</p>\n'}, {'answer_id': 74284, 'author': 'ncgz', 'author_id': 12905, 'author_profile': 'https://Stackoverflow.com/users/12905', 'pm_score': -1, 'selected': False, 'text': '<p>If the problem is just LazyInitializationExceptions, you can avoid that by adding an OpenSessionInViewFilter.<br>\nThis will allow the objects to be loaded in the view, but will not help with the speed issue.</p>\n\n<pre><code> <filter>\n <filter-name>hibernateFilter</filter-name>\n <filter-class> org.springframework.orm.hibernate3.support.OpenSessionInViewFilter\n </filter-class>\n </filter>\n <filter-mapping>\n <filter-name>hibernateFilter</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n</code></pre>\n'}, {'answer_id': 75459, 'author': 'Mike Desjardins', 'author_id': 10466, 'author_profile': 'https://Stackoverflow.com/users/10466', 'pm_score': 2, 'selected': False, 'text': '<p>You might be able to do something like that using a (detached) criteria query, and setting the fetch mode. E.g.,</p>\n\n<pre><code>Session s = ((HibernateEntityManager) em).getSession().getSessionFactory().openSession();\nDetachedCriteria dc = DetachedCriteria.forClass(MyEntity.class).add(Expression.idEq(id));\ndc.setFetchMode("innerTable", FetchMode.JOIN);\nCriteria c = dc.getExecutableCriteria(s);\nMyEntity a = (MyEntity)c.uniqueResult();\n</code></pre>\n'}, {'answer_id': 227780, 'author': 'Miguel Ping', 'author_id': 22992, 'author_profile': 'https://Stackoverflow.com/users/22992', 'pm_score': 2, 'selected': False, 'text': '<p>Have you tried using a result transformer? If you use Criteria queries, you can apply a result transformer (although <a href="http://www.jroller.com/RickHigh/entry/hibernate_query_getting_rid_of" rel="nofollow noreferrer">there are some problems with pagination and result transformer</a>):</p>\n\n<pre><code>Criteria c = ((Session)em.getDelegate()).createCriteria(Order.class);\nc.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\nc.list();\n</code></pre>\n\n<p>the <code>em.getDelegate()</code> is a hack that only works if you are using hibernate.</p>\n\n<blockquote>\n <p>Perhaps more importantly, is there a\n way to pull in all child objects, no\n matter how deep? We have around 10-15\n classes and for the server we will\n need everything loaded... I was\n avoiding using FetchType.EAGER as that\n meant its always eager and in\n particular the web front end loads\n everything - but perhaps that is the\n way to go - is that what you do? I\n seem to remember us trying this before\n and then getting really slow webpages\n - but perhaps that means we should be using a second-level cache?</p>\n</blockquote>\n\n<p>If you are still interested, I responded a similar question in this thread <a href="https://stackoverflow.com/questions/182323/how-to-serialize-hibernate-collections-properly#182955">how to serialize hibernate collections</a>.</p>\n\n<p>Basically you use a utility called <a href="http://dozer.sf.net" rel="nofollow noreferrer">dozer</a> that maps beans onto another beans, and by doing this you trigger all your lazy loads. As you can imagine, this works better if all collections are eagerly fetched.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48310/']
|
70,993 |
<p>We all know the various ways of testing OO systems. However, it looks like I'll be going to do a project where I'll be dealing with PLC ladder logic (don't ask :/), and I was wondering if there's a good way of testing the validity of the system.</p>
<p>The only way I see so far is simply constructing a huge table with all known states of the system and which output states that generates. This would do for simple 'if input A is on, turn output B on' cases. I don't think this will work for more complicated constructions though.</p>
|
[{'answer_id': 71105, 'author': 'jbdavid', 'author_id': 6314, 'author_profile': 'https://Stackoverflow.com/users/6314', 'pm_score': 4, 'selected': True, 'text': '<p>The verification of "logical" systems in the IC design arena is known as "Design Verification", which is the process of ensuring that the system you design in hardware (RTL) implements the desired functionality. </p>\n\n<p>Ladder logic can be transformed to one of the modern HDL\'s like Verilog.. \ntransform each ladder </p>\n\n<pre><code>|---|R15|---+---|/R16|---------(R18)--------|\n| |\n|---|R12|---+\n</code></pre>\n\n<p>to an expression like </p>\n\n<pre><code>always @(*) R18 = !R16 && ( R15 | R12);\n</code></pre>\n\n<p>or you could use an assign statement</p>\n\n<pre><code>assign R18 = R16 && (R15 | R12); \n</code></pre>\n\n<p>a latching relay</p>\n\n<pre><code>assign R18 = (set condition) || R18 && !(break condition);\n</code></pre>\n\n<p>Then use a free verilog simulator like <a href="http://www.icarus.com/eda/verilog/" rel="nofollow noreferrer">Icarus</a> to develop a testbench and test your system. \nMake sure you\'re testcases give good CODE coverage of your logic! And If your ladder editing software gives you decent naming capabilities, use them, rather than Rnn. </p>\n\n<p>(Note: in Ladder Logic for PLC convention, Rnn is for internal relays, while, Xnn is an input and Ynn is an output, as can be quickly gleaned from one of the online tutorials.</p>\n\n<p>Verilog will be an easier language to develop your tests and testbenches in!</p>\n\n<p>It may be helpful to program in some unit delays.</p>\n\n<p>Sorry, I have never looked for ladder logic to/from verilog translators.. \nbut ladder logic in my day was only just being put into a computer for programming PLC\'s - most of the relay systems I used were REAL Relays, wired into the cabinets!!</p>\n\n<p>Good luck. \njbd</p>\n\n<p>There are a couple of ladder logic editors (with simultors) available for free.. \nhere is one that runs on windows supposedly:</p>\n\n<p><a href="http://cq.cx/ladder.pl" rel="nofollow noreferrer">http://cq.cx/ladder.pl</a></p>\n'}, {'answer_id': 693089, 'author': 'rlbond', 'author_id': 72631, 'author_profile': 'https://Stackoverflow.com/users/72631', 'pm_score': 0, 'selected': False, 'text': '<p>There is a program called LogixPro which has an IO simulator for ladder logic, you can try that.</p>\n'}, {'answer_id': 1365819, 'author': 'Ira Baxter', 'author_id': 120163, 'author_profile': 'https://Stackoverflow.com/users/120163', 'pm_score': 2, 'selected': False, 'text': '<p>We\'ve experimented with test coverage tools for Rockwell Control Logix controllers. Most procedural language test coverage tools do branch coverage or some such; because Relay Ladder Logic typically doesn\'t branch, this doesn\'t work very well. </p>\n\n<p>What we have prototyped is <a href="http://en.wikipedia.org/wiki/Modified_Condition/Decision_Coverage" rel="nofollow noreferrer">MC/DC</a> (modified/condition/decision coverage) for RLL code for Rockwell controllers.. This tells, for each condition in rung, whether that condition has been tested as TRUE, tested as FALSE, and more importantly, if there the condition controlled the output of the decision in the rung (well at least the action controlled by the decision) in both true and false directions under some test.</p>\n\n<p>This work is done using a general purpose program analysis and transformation tool called\n<a href="http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html" rel="nofollow noreferrer">DMS</a> used to instrument the RLL code with additional logic to collect the necessary data.</p>\n\n<p>You still have to code unit tests. The easiest way to do that is to get another PLC to act as a replacement for the mechanical hardware you intend to control, and simply write another RLL program to exercise the first one.</p>\n'}, {'answer_id': 7591379, 'author': 'daniel', 'author_id': 866502, 'author_profile': 'https://Stackoverflow.com/users/866502', 'pm_score': 0, 'selected': False, 'text': '<p>Sometimes on small PLC programs a test program (or subroutine, or ladder file) is written in the project, which is only run when the project is being emulated. The file has some simple logic that says when an output is energised, turn on the input associated with the feedback. You can then control your PLC through whatever HMI is wired up to it and see that the code behaves as expected. Its very important to disable or delete the test program when the software is downloaded to a real site as it can do very strange things in the real world.</p>\n\n<p>On larger projects each device has a simulation mode that does something slightly similar. <a href="http://www.batchcontrol.com/s88/01_tutorial/06-modules.shtml" rel="nofollow">http://www.batchcontrol.com/s88/01_tutorial/06-modules.shtml</a> </p>\n\n<p>This is nothing like using test frameworks for OO languages, but I haven\'t really seen any test driven development for PLCs, or even much automated testing.</p>\n'}, {'answer_id': 56534301, 'author': 'Chris Johnson', 'author_id': 6228010, 'author_profile': 'https://Stackoverflow.com/users/6228010', 'pm_score': 0, 'selected': False, 'text': '<p>My boss on a constant basis tells me that the testing is built in the logic itself . PLC’s are in fact deterministic so you should practically be able to follow logic and not need to simulate testing. However we’re not perfect. Having framework would really only allow us to step through what we already know, ladder logic really just takes practice to understand how PLCS work.</p>\n\n<p>That being said I did have some good success with a program I made that essentially flipped on and off IO , it could even simulate the counts of an encoder to test what happens when an object gets to a position. Their were assert statements that could get tripped and inform me where my logic faulted. It did catch a few bugs, and that implementation went very well for a system I’ve never touched. It itself was very beneficial and I do think that it could be useful but I’ve gotten a lot better so I find myself not needing it because of my experience.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/70993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/909/']
|
71,000 |
<p>I'm trying to create a Zip file from .Net that can be read from Java code.</p>
<p>I've used SharpZipLib to create the Zip file but also if the file generated is valid according to the CheckZip function of the #ZipLib library and can be successfully uncompressed via WinZip or WinRar I always get an error when trying to uncompress it using the Java.Utils.Zip class in Java.</p>
<p>Problem seems to be in the wrong header written by SharpZipLib, I've also posted a question on the SharpDevelop forum but with no results (see <a href="http://community.sharpdevelop.net/forums/t/8272.aspx" rel="nofollow noreferrer">http://community.sharpdevelop.net/forums/t/8272.aspx</a> for info) but with no result.</p>
<p>Has someone a code sample of compressing a Zip file with .Net and de-compressing it with the Java.Utils.Zip class?</p>
<p>Regards
Massimo</p>
|
[{'answer_id': 71060, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 2, 'selected': False, 'text': '<p>Can\'t help with SharpZipLib, but you can try to create zip file using <a href="http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx" rel="nofollow noreferrer">ZipPackage</a> class <a href="http://msdn.microsoft.com/en-us/library/system.io.packaging.aspx" rel="nofollow noreferrer">System.IO.Packaging</a> without using 3rd part libraries (requires .NET 3+).</p>\n'}, {'answer_id': 71072, 'author': 'Panos', 'author_id': 8049, 'author_profile': 'https://Stackoverflow.com/users/8049', 'pm_score': 4, 'selected': True, 'text': '<p>I have used <a href="http://www.codeplex.com/DotNetZip" rel="noreferrer">DotNetZip library</a> and it seems to work properly. Typical code:</p>\n\n<pre><code>using (ZipFile zipFile = new ZipFile())\n{\n zipFile.AddDirectory(sourceFolderPath);\n zipFile.Save(archiveFolderName);\n}\n</code></pre>\n'}, {'answer_id': 71890, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 1, 'selected': False, 'text': '<p>To judge whether it\'s really a conformant ZIP file, see PKZIP\'s <a href="http://www.pkware.com/documents/casestudies/APPNOTE.TXT" rel="nofollow noreferrer">.ZIP File Format Specification</a>.</p>\n\n<p>For what it\'s worth I have had no trouble using SharpZipLib to create ZIPs on a Windows Mobile device and open them with WinZip or Windows XP\'s built-in Compressed Folders feature, and also no trouble producing ZIPs on the desktop with SharpZipLib and processing them with my own ZIP extraction utility (basically a wrapper around zlib) on the mobile device.</p>\n'}, {'answer_id': 410383, 'author': 'Cheeso', 'author_id': 48082, 'author_profile': 'https://Stackoverflow.com/users/48082', 'pm_score': 1, 'selected': False, 'text': '<p>You don\'t wanna use the ZipPackage class in .NET - it isn\'t quite a standard zip model. Well it is, but it presumes a particular structure in the file, with a manifest with a well-known name, and so on. ZipPackage seems to have been optimized for Office docs and XPS docs. </p>\n\n<p>A third-party library, like <a href="http://www.codeplex.com/DotNetZip" rel="nofollow noreferrer">http://www.codeplex.com/DotNetZip</a>, is probably a better bet if you are doing general-purpose ZIP files and want good interoperability. </p>\n\n<p>DotNetZip builds files that are very interoperable with just about everything, including Java\'s java.utils.zip. But be careful using features that Java does not support, like ZIP64 or Unicode. ZIP64 is useful only for very large archives, which Java does not support well at this time, I think. Java supports Unicode in a particular way, so if you produce a Unicode-based ZIP file with DotNetZip, you just have to follow a few rules and it will work fine. </p>\n'}, {'answer_id': 487038, 'author': 'Igor Brejc', 'author_id': 55408, 'author_profile': 'https://Stackoverflow.com/users/55408', 'pm_score': 1, 'selected': False, 'text': '<p>I had a similar problem with unzipping SharpZipLib-zipped files on Linux. I think I solved it (well I works on Linux and Mac now, I tested it), check out my blog post: <a href="http://igorbrejc.net/development/c/sharpziplib-making-it-work-for-linuxmac" rel="nofollow noreferrer">http://igorbrejc.net/development/c/sharpziplib-making-it-work-for-linuxmac</a></p>\n'}, {'answer_id': 659397, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I had the same problem creating zips with SharpZipLib (latest version) and extracting with java.utils.zip.</p>\n\n<p>Here is what fixed the problem for me. I had to force the exclusion of the zip64 usage:</p>\n\n<pre><code>ZipOutputStream s = new ZipOutputStream(File.Create(someZipFileName))\n\ns.UseZip64 = UseZip64.Off;\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11673/']
|
71,022 |
<p>How do you return 1 value per row of the max of several columns:</p>
<p><strong>TableName</strong></p>
<pre><code>[Number, Date1, Date2, Date3, Cost]
</code></pre>
<p>I need to return something like this:</p>
<pre><code>[Number, Most_Recent_Date, Cost]
</code></pre>
<p>Query?</p>
|
[{'answer_id': 71045, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 9, 'selected': True, 'text': '<p>This is an old answer and broken in many way.</p>\n<p>See <a href="https://stackoverflow.com/a/6871572/194653">https://stackoverflow.com/a/6871572/194653</a> which has way more upvotes and works with sql server 2008+ and handles nulls, etc.</p>\n<p><strong>Original but problematic answer</strong>:</p>\n<p>Well, you can use the CASE statement:</p>\n<pre><code>SELECT\n CASE\n WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1\n WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2\n WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3\n ELSE Date1\n END AS MostRecentDate\n</code></pre>\n'}, {'answer_id': 71147, 'author': 'databyss', 'author_id': 9094, 'author_profile': 'https://Stackoverflow.com/users/9094', 'pm_score': 4, 'selected': False, 'text': '<p>Either of the two samples below will work:</p>\n\n<pre><code>SELECT MAX(date_columns) AS max_date\nFROM ( (SELECT date1 AS date_columns\n FROM data_table )\n UNION\n ( SELECT date2 AS date_columns\n FROM data_table\n )\n UNION\n ( SELECT date3 AS date_columns\n FROM data_table\n )\n ) AS date_query\n</code></pre>\n\n<p>The second is an add-on to <a href="https://stackoverflow.com/users/267/lassevk">lassevk\'s</a> answer.</p>\n\n<pre><code>SELECT MAX(MostRecentDate)\nFROM ( SELECT CASE WHEN date1 >= date2\n AND date1 >= date3 THEN date1\n WHEN date2 >= date1\n AND date2 >= date3 THEN date2\n WHEN date3 >= date1\n AND date3 >= date2 THEN date3\n ELSE date1\n END AS MostRecentDate\n FROM data_table\n ) AS date_query \n</code></pre>\n'}, {'answer_id': 331873, 'author': 'bajafresh4life', 'author_id': 21339, 'author_profile': 'https://Stackoverflow.com/users/21339', 'pm_score': 8, 'selected': False, 'text': "<p>If you're using MySQL or PostgreSQL or Oracle or BigQuery, you can use</p>\n<pre><code>SELECT GREATEST(col1, col2 ...) FROM table\n</code></pre>\n"}, {'answer_id': 331933, 'author': 'Lance Fisher', 'author_id': 571, 'author_profile': 'https://Stackoverflow.com/users/571', 'pm_score': 2, 'selected': False, 'text': "<p>If you are using SQL Server 2005, you can use the UNPIVOT feature. Here is a complete example:</p>\n\n<pre><code>create table dates \n(\n number int,\n date1 datetime,\n date2 datetime,\n date3 datetime \n)\n\ninsert into dates values (1, '1/1/2008', '2/4/2008', '3/1/2008')\ninsert into dates values (1, '1/2/2008', '2/3/2008', '3/3/2008')\ninsert into dates values (1, '1/3/2008', '2/2/2008', '3/2/2008')\ninsert into dates values (1, '1/4/2008', '2/1/2008', '3/4/2008')\n\nselect max(dateMaxes)\nfrom (\n select \n (select max(date1) from dates) date1max, \n (select max(date2) from dates) date2max,\n (select max(date3) from dates) date3max\n) myTable\nunpivot (dateMaxes For fieldName In (date1max, date2max, date3max)) as tblPivot\n\ndrop table dates\n</code></pre>\n"}, {'answer_id': 1398019, 'author': 'Niikola', 'author_id': 130904, 'author_profile': 'https://Stackoverflow.com/users/130904', 'pm_score': 6, 'selected': False, 'text': "<p>There are 3 more methods where <code>UNPIVOT</code> (1) is the fastest by far, followed by Simulated Unpivot (3) which is much slower than (1) but still faster than (2)</p>\n\n<pre><code>CREATE TABLE dates\n (\n number INT PRIMARY KEY ,\n date1 DATETIME ,\n date2 DATETIME ,\n date3 DATETIME ,\n cost INT\n )\n\nINSERT INTO dates\nVALUES ( 1, '1/1/2008', '2/4/2008', '3/1/2008', 10 )\nINSERT INTO dates\nVALUES ( 2, '1/2/2008', '2/3/2008', '3/3/2008', 20 )\nINSERT INTO dates\nVALUES ( 3, '1/3/2008', '2/2/2008', '3/2/2008', 30 )\nINSERT INTO dates\nVALUES ( 4, '1/4/2008', '2/1/2008', '3/4/2008', 40 )\nGO\n</code></pre>\n\n<h2>Solution 1 (<code>UNPIVOT</code>)</h2>\n\n<pre><code>SELECT number ,\n MAX(dDate) maxDate ,\n cost\nFROM dates UNPIVOT ( dDate FOR nDate IN ( Date1, Date2,\n Date3 ) ) as u\nGROUP BY number ,\n cost \nGO\n</code></pre>\n\n<h2>Solution 2 (Sub query per row)</h2>\n\n<pre><code>SELECT number ,\n ( SELECT MAX(dDate) maxDate\n FROM ( SELECT d.date1 AS dDate\n UNION\n SELECT d.date2\n UNION\n SELECT d.date3\n ) a\n ) MaxDate ,\n Cost\nFROM dates d\nGO\n</code></pre>\n\n<h2>Solution 3 (Simulated <code>UNPIVOT</code>)</h2>\n\n<pre><code>;WITH maxD\n AS ( SELECT number ,\n MAX(CASE rn\n WHEN 1 THEN Date1\n WHEN 2 THEN date2\n ELSE date3\n END) AS maxDate\n FROM dates a\n CROSS JOIN ( SELECT 1 AS rn\n UNION\n SELECT 2\n UNION\n SELECT 3\n ) b\n GROUP BY Number\n )\n SELECT dates.number ,\n maxD.maxDate ,\n dates.cost\n FROM dates\n INNER JOIN MaxD ON dates.number = maxD.number\nGO\n\nDROP TABLE dates\nGO\n</code></pre>\n"}, {'answer_id': 4308539, 'author': 'Nat', 'author_id': 13813, 'author_profile': 'https://Stackoverflow.com/users/13813', 'pm_score': 3, 'selected': False, 'text': '<pre><code>SELECT \n CASE \n WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1 \n WHEN Date2 >= Date3 THEN Date2 \n ELSE Date3\n END AS MostRecentDate \n</code></pre>\n\n<p>This is slightly easier to write out and skips evaluation steps as the case statement is evaluated in order.</p>\n'}, {'answer_id': 4308905, 'author': 'Martin Smith', 'author_id': 73226, 'author_profile': 'https://Stackoverflow.com/users/73226', 'pm_score': 3, 'selected': False, 'text': "<pre><code>DECLARE @TableName TABLE (Number INT, Date1 DATETIME, Date2 DATETIME, Date3 DATETIME, Cost MONEY)\n\nINSERT INTO @TableName \nSELECT 1, '20000101', '20010101','20020101',100 UNION ALL\nSELECT 2, '20000101', '19900101','19980101',99 \n\nSELECT Number,\n Cost ,\n (SELECT MAX([Date])\n FROM (SELECT Date1 AS [Date]\n UNION ALL\n SELECT Date2\n UNION ALL\n SELECT Date3\n )\n D\n )\n [Most Recent Date]\nFROM @TableName\n</code></pre>\n"}, {'answer_id': 4695172, 'author': 'DrYodo', 'author_id': 576121, 'author_profile': 'https://Stackoverflow.com/users/576121', 'pm_score': 0, 'selected': False, 'text': "<p>You could create a function where you pass the dates and then add the function to the select statement like below.\nselect Number, dbo.fxMost_Recent_Date(Date1,Date2,Date3), Cost</p>\n\n<pre><code>create FUNCTION fxMost_Recent_Date \n</code></pre>\n\n<p>(\n @Date1 smalldatetime, \n @Date2 smalldatetime,\n @Date3 smalldatetime\n)\nRETURNS smalldatetime\nAS\nBEGIN\n DECLARE @Result smalldatetime</p>\n\n<pre><code>declare @MostRecent smalldatetime\n\nset @MostRecent='1/1/1900'\n\nif @Date1>@MostRecent begin set @MostRecent=@Date1 end\nif @Date2>@MostRecent begin set @MostRecent=@Date2 end\nif @Date3>@MostRecent begin set @MostRecent=@Date3 end\nRETURN @MostRecent\n</code></pre>\n\n<p>END</p>\n"}, {'answer_id': 4922103, 'author': 'MartinC', 'author_id': 606510, 'author_profile': 'https://Stackoverflow.com/users/606510', 'pm_score': 4, 'selected': False, 'text': '<p>Scalar Function cause all sorts of performance issues, so its better to wrap the logic into an Inline Table Valued Function if possible. This is the function I used to replace some User Defined Functions which selected the Min/Max dates from a list of upto ten dates. When tested on my dataset of 1 Million rows the Scalar Function took over 15 minutes before I killed the query the Inline TVF took 1 minute which is the same amount of time as selecting the resultset into a temporary table. To use this call the function from either a subquery in the the SELECT or a CROSS APPLY.</p>\n\n<pre><code>CREATE FUNCTION dbo.Get_Min_Max_Date\n(\n @Date1 datetime,\n @Date2 datetime,\n @Date3 datetime,\n @Date4 datetime,\n @Date5 datetime,\n @Date6 datetime,\n @Date7 datetime,\n @Date8 datetime,\n @Date9 datetime,\n @Date10 datetime\n)\nRETURNS TABLE\nAS\nRETURN\n(\n SELECT Max(DateValue) Max_Date,\n Min(DateValue) Min_Date\n FROM (\n VALUES (@Date1),\n (@Date2),\n (@Date3),\n (@Date4),\n (@Date5),\n (@Date6),\n (@Date7),\n (@Date8),\n (@Date9),\n (@Date10)\n ) AS Dates(DateValue)\n)\n</code></pre>\n'}, {'answer_id': 6650238, 'author': 'Michael Freidgeim', 'author_id': 52277, 'author_profile': 'https://Stackoverflow.com/users/52277', 'pm_score': 1, 'selected': False, 'text': '<p>Based on the <a href="http://www.experts-exchange.com/M_664986.html" rel="nofollow noreferrer">ScottPletcher</a>\'s solution from <a href="http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/Q_24204894.html" rel="nofollow noreferrer">http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/Q_24204894.html</a>\nI’ve created a set of functions (e.g. GetMaxOfDates3 , GetMaxOfDates13 )to find max of up to 13 Date values using UNION ALL.\nSee <a href="https://mfreidge.wordpress.com/2011/07/11/t-sql-function-to-get-maximum-of-values-from-the-same-row/" rel="nofollow noreferrer">T-SQL function to Get Maximum of values from the same row</a>\nHowever I haven\'t considered UNPIVOT solution at the time of writing these functions</p>\n<pre><code>CREATE FUNCTION GetMaxOfDates13 (\n@value01 DateTime = NULL, \n@value02 DateTime = NULL,\n@value03 DateTime = NULL,\n@value04 DateTime = NULL,\n@value05 DateTime = NULL,\n@value06 DateTime = NULL,\n@value07 DateTime = NULL,\n@value08 DateTime = NULL,\n@value09 DateTime = NULL,\n@value10 DateTime = NULL,\n@value11 DateTime = NULL,\n@value12 DateTime = NULL,\n@value13 DateTime = NULL\n)\nRETURNS DateTime\nAS\nBEGIN\nRETURN (\nSELECT TOP 1 value\nFROM (\nSELECT @value01 AS value UNION ALL\nSELECT @value02 UNION ALL\nSELECT @value03 UNION ALL\nSELECT @value04 UNION ALL\nSELECT @value05 UNION ALL\nSELECT @value06 UNION ALL\nSELECT @value07 UNION ALL\nSELECT @value08 UNION ALL\nSELECT @value09 UNION ALL\nSELECT @value10 UNION ALL\nSELECT @value11 UNION ALL\nSELECT @value12 UNION ALL\nSELECT @value13\n) AS [values]\nORDER BY value DESC \n)\nEND –FUNCTION\nGO\nCREATE FUNCTION GetMaxOfDates3 (\n@value01 DateTime = NULL, \n@value02 DateTime = NULL,\n@value03 DateTime = NULL\n)\nRETURNS DateTime\nAS\nBEGIN\nRETURN dbo.GetMaxOfDates13(@value01,@value02,@value03,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)\nEND –FUNCTION\n</code></pre>\n'}, {'answer_id': 6871572, 'author': 'Sven', 'author_id': 442204, 'author_profile': 'https://Stackoverflow.com/users/442204', 'pm_score': 10, 'selected': False, 'text': '<p>Here is another nice solution for the <code>Max</code> functionality using T-SQL and SQL Server</p>\n<pre><code>SELECT [Other Fields],\n (SELECT Max(v) \n FROM (VALUES (date1), (date2), (date3),...) AS value(v)) as [MaxDate]\nFROM [YourTableName]\n</code></pre>\n<p>Values is the <a href="https://learn.microsoft.com/en-us/sql/t-sql/queries/table-value-constructor-transact-sql?view=sql-server-ver15" rel="noreferrer">Table Value Constructor</a>.</p>\n<p>"Specifies a set of row value expressions to be constructed into a table. The Transact-SQL table value constructor allows multiple rows of data to be specified in a single DML statement. The table value constructor can be specified either as the VALUES clause of an INSERT ... VALUES statement, or as a derived table in either the USING clause of the MERGE statement or the FROM clause."</p>\n'}, {'answer_id': 8971789, 'author': 'Disillusioned', 'author_id': 224704, 'author_profile': 'https://Stackoverflow.com/users/224704', 'pm_score': 3, 'selected': False, 'text': '<p>Unfortunately <a href="https://stackoverflow.com/a/71045/224704">Lasse\'s answer</a>, though seemingly obvious, has a crucial flaw. It cannot handle NULL values. Any single NULL value results in Date1 being returned. Unfortunately any attempt to fix that problem tends to get extremely messy and doesn\'t scale to 4 or more values very nicely.</p>\n\n<p><a href="https://stackoverflow.com/a/71147/224704">databyss\'s first answer</a> looked (and is) good. However, it wasn\'t clear whether the answer would easily extrapolate to 3 values from a multi-table join instead of the simpler 3 values from a single table. I wanted to avoid turning such a query into a sub-query just to get the max of 3 columns, also I was pretty sure databyss\'s excellent idea could be cleaned up a bit.</p>\n\n<p>So without further ado, here\'s my solution (derived from databyss\'s idea).<br>\nIt uses cross-joins selecting constants to simulate the effect of a multi-table join. The important thing to note is that all the necessary aliases carry through correctly (which is not always the case) and this keeps the pattern quite simple and fairly scalable through additional columns.</p>\n\n<pre><code>DECLARE @v1 INT ,\n @v2 INT ,\n @v3 INT\n--SET @v1 = 1 --Comment out SET statements to experiment with \n --various combinations of NULL values\nSET @v2 = 2\nSET @v3 = 3\n\nSELECT ( SELECT MAX(Vals)\n FROM ( SELECT v1 AS Vals\n UNION\n SELECT v2\n UNION\n SELECT v3\n ) tmp\n WHERE Vals IS NOT NULL -- This eliminates NULL warning\n\n ) AS MaxVal\nFROM ( SELECT @v1 AS v1\n ) t1\n CROSS JOIN ( SELECT @v2 AS v2\n ) t2\n CROSS JOIN ( SELECT @v3 AS v3\n ) t3\n</code></pre>\n'}, {'answer_id': 10831815, 'author': 'Luis Miguel Rosa', 'author_id': 1428154, 'author_profile': 'https://Stackoverflow.com/users/1428154', 'pm_score': 2, 'selected': False, 'text': '<p>Problem: choose the minimum rate value given to an entity\nRequirements: Agency rates can be null</p>\n\n<pre><code>[MinRateValue] = \nCASE \n WHEN ISNULL(FitchRating.RatingValue, 100) < = ISNULL(MoodyRating.RatingValue, 99) \n AND ISNULL(FitchRating.RatingValue, 100) < = ISNULL(StandardPoorsRating.RatingValue, 99) \n THEN FitchgAgency.RatingAgencyName\n\n WHEN ISNULL(MoodyRating.RatingValue, 100) < = ISNULL(StandardPoorsRating.RatingValue , 99)\n THEN MoodyAgency.RatingAgencyName\n\n ELSE ISNULL(StandardPoorsRating.RatingValue, \'N/A\') \nEND \n</code></pre>\n\n<p>Inspired by <a href="https://stackoverflow.com/a/4308539">this answer</a> from <a href="https://stackoverflow.com/users/13813/nat">Nat</a></p>\n'}, {'answer_id': 23864329, 'author': 'TechDo', 'author_id': 1367256, 'author_profile': 'https://Stackoverflow.com/users/1367256', 'pm_score': 1, 'selected': False, 'text': '<p>Please try using <code>UNPIVOT</code>:</p>\n\n<pre><code>SELECT MAX(MaxDt) MaxDt\n FROM tbl \nUNPIVOT\n (MaxDt FOR E IN \n (Date1, Date2, Date3)\n)AS unpvt;\n</code></pre>\n'}, {'answer_id': 23888942, 'author': 'EarlOfEnnui', 'author_id': 3442468, 'author_profile': 'https://Stackoverflow.com/users/3442468', 'pm_score': 2, 'selected': False, 'text': '<p>Using CROSS APPLY (for 2005+) ....</p>\n\n<pre><code>SELECT MostRecentDate \nFROM SourceTable\n CROSS APPLY (SELECT MAX(d) MostRecentDate FROM (VALUES (Date1), (Date2), (Date3)) AS a(d)) md\n</code></pre>\n'}, {'answer_id': 24527258, 'author': 'abdulbasit', 'author_id': 3678700, 'author_profile': 'https://Stackoverflow.com/users/3678700', 'pm_score': 2, 'selected': False, 'text': '<p>From SQL Server 2012 we can use <a href="http://msdn.microsoft.com/en-us/library/hh213574%28v=sql.110%29.aspx" rel="nofollow">IIF</a>.</p>\n\n<pre><code> DECLARE @Date1 DATE=\'2014-07-03\';\n DECLARE @Date2 DATE=\'2014-07-04\';\n DECLARE @Date3 DATE=\'2014-07-05\';\n\n SELECT IIF(@Date1>@Date2,\n IIF(@Date1>@Date3,@Date1,@Date3),\n IIF(@Date2>@Date3,@Date2,@Date3)) AS MostRecentDate\n</code></pre>\n'}, {'answer_id': 29385881, 'author': 'jjaskulowski', 'author_id': 2053494, 'author_profile': 'https://Stackoverflow.com/users/2053494', 'pm_score': 4, 'selected': False, 'text': '<p>For T-SQL (MSSQL 2008+)</p>\n\n<pre><code>SELECT\n (SELECT\n MAX(MyMaxName) \n FROM ( VALUES \n (MAX(Field1)), \n (MAX(Field2)) \n ) MyAlias(MyMaxName)\n ) \nFROM MyTable1\n</code></pre>\n'}, {'answer_id': 31914496, 'author': 'danvasiloiu', 'author_id': 4424087, 'author_profile': 'https://Stackoverflow.com/users/4424087', 'pm_score': -1, 'selected': False, 'text': '<p>here is a good solution:</p>\n\n<pre><code>CREATE function [dbo].[inLineMax] (@v1 float,@v2 float,@v3 float,@v4 float)\nreturns float\nas\nbegin\ndeclare @val float\nset @val = 0 \ndeclare @TableVal table\n(value float )\ninsert into @TableVal select @v1\ninsert into @TableVal select @v2\ninsert into @TableVal select @v3\ninsert into @TableVal select @v4\n\nselect @val= max(value) from @TableVal\n\nreturn @val\nend \n</code></pre>\n'}, {'answer_id': 37784473, 'author': 'claudio', 'author_id': 6458642, 'author_profile': 'https://Stackoverflow.com/users/6458642', 'pm_score': -1, 'selected': False, 'text': '<p>I do not know if it is on SQL, etc... on M$ACCESS help there is a function called <code>MAXA(Value1;Value2;...)</code> that is supposed to do such.</p>\n\n<p>Hope can help someone.</p>\n\n<p>P.D.: Values can be columns or calculated ones, etc.</p>\n'}, {'answer_id': 49515362, 'author': 'M.A.Bell', 'author_id': 8889436, 'author_profile': 'https://Stackoverflow.com/users/8889436', 'pm_score': 0, 'selected': False, 'text': '<p>Another way to use <strong>CASE WHEN</strong> </p>\n\n<pre><code>SELECT CASE true \n WHEN max(row1) >= max(row2) THEN CASE true WHEN max(row1) >= max(row3) THEN max(row1) ELSE max(row3) end ELSE\n CASE true WHEN max(row2) >= max(row3) THEN max(row2) ELSE max(row3) END END\nFROM yourTable\n</code></pre>\n'}, {'answer_id': 54612018, 'author': 'Robert Lujo', 'author_id': 565525, 'author_profile': 'https://Stackoverflow.com/users/565525', 'pm_score': 1, 'selected': False, 'text': "<p>I prefer solutions based on case-when, my assumption is that it should have the least impact on possible performance drop compared to other possible solutions like those with cross-apply, values(), custom functions etc.</p>\n\n<p>Here is the case-when version that handles null values with most of possible test cases:</p>\n\n<pre><code>SELECT\n CASE \n WHEN Date1 > coalesce(Date2,'0001-01-01') AND Date1 > coalesce(Date3,'0001-01-01') THEN Date1 \n WHEN Date2 > coalesce(Date3,'0001-01-01') THEN Date2 \n ELSE Date3\n END AS MostRecentDate\n , *\nfrom \n(values\n ( 1, cast('2001-01-01' as Date), cast('2002-01-01' as Date), cast('2003-01-01' as Date))\n ,( 2, cast('2001-01-01' as Date), cast('2003-01-01' as Date), cast('2002-01-01' as Date))\n ,( 3, cast('2002-01-01' as Date), cast('2001-01-01' as Date), cast('2003-01-01' as Date))\n ,( 4, cast('2002-01-01' as Date), cast('2003-01-01' as Date), cast('2001-01-01' as Date))\n ,( 5, cast('2003-01-01' as Date), cast('2001-01-01' as Date), cast('2002-01-01' as Date))\n ,( 6, cast('2003-01-01' as Date), cast('2002-01-01' as Date), cast('2001-01-01' as Date))\n ,( 11, cast(NULL as Date), cast('2002-01-01' as Date), cast('2003-01-01' as Date))\n ,( 12, cast(NULL as Date), cast('2003-01-01' as Date), cast('2002-01-01' as Date))\n ,( 13, cast('2003-01-01' as Date), cast(NULL as Date), cast('2002-01-01' as Date))\n ,( 14, cast('2002-01-01' as Date), cast(NULL as Date), cast('2003-01-01' as Date))\n ,( 15, cast('2003-01-01' as Date), cast('2002-01-01' as Date), cast(NULL as Date))\n ,( 16, cast('2002-01-01' as Date), cast('2003-01-01' as Date), cast(NULL as Date))\n ,( 21, cast('2003-01-01' as Date), cast(NULL as Date), cast(NULL as Date))\n ,( 22, cast(NULL as Date), cast('2003-01-01' as Date), cast(NULL as Date))\n ,( 23, cast(NULL as Date), cast(NULL as Date), cast('2003-01-01' as Date))\n ,( 31, cast(NULL as Date), cast(NULL as Date), cast(NULL as Date))\n\n) as demoValues(id, Date1,Date2,Date3)\norder by id\n;\n</code></pre>\n\n<p>and the result is:</p>\n\n<pre><code>MostRecent id Date1 Date2 Date3\n2003-01-01 1 2001-01-01 2002-01-01 2003-01-01\n2003-01-01 2 2001-01-01 2003-01-01 2002-01-01\n2003-01-01 3 2002-01-01 2001-01-01 2002-01-01\n2003-01-01 4 2002-01-01 2003-01-01 2001-01-01\n2003-01-01 5 2003-01-01 2001-01-01 2002-01-01\n2003-01-01 6 2003-01-01 2002-01-01 2001-01-01\n2003-01-01 11 NULL 2002-01-01 2003-01-01\n2003-01-01 12 NULL 2003-01-01 2002-01-01\n2003-01-01 13 2003-01-01 NULL 2002-01-01\n2003-01-01 14 2002-01-01 NULL 2003-01-01\n2003-01-01 15 2003-01-01 2002-01-01 NULL\n2003-01-01 16 2002-01-01 2003-01-01 NULL\n2003-01-01 21 2003-01-01 NULL NULL\n2003-01-01 22 NULL 2003-01-01 NULL\n2003-01-01 23 NULL NULL 2003-01-01\nNULL 31 NULL NULL NULL\n</code></pre>\n"}, {'answer_id': 60684209, 'author': 'Brijesh Ray', 'author_id': 5284448, 'author_profile': 'https://Stackoverflow.com/users/5284448', 'pm_score': -1, 'selected': False, 'text': '<p><a href="https://i.stack.imgur.com/peyNn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/peyNn.png" alt="enter image description here"></a>Above table is an employee salary table with salary1,salary2,salary3,salary4 as columns.Query below will return the max value out of four columns</p>\n\n<pre><code>select \n (select Max(salval) from( values (max(salary1)),(max(salary2)),(max(salary3)),(max(Salary4)))alias(salval)) as largest_val\n from EmployeeSalary\n</code></pre>\n\n<p>Running above query will give output as largest_val(10001)</p>\n\n<p>Logic of above query is as below:</p>\n\n<pre><code>select Max(salvalue) from(values (10001),(5098),(6070),(7500))alias(salvalue)\n</code></pre>\n\n<p>output will be 10001</p>\n'}, {'answer_id': 66815967, 'author': 'Hemendr', 'author_id': 5139020, 'author_profile': 'https://Stackoverflow.com/users/5139020', 'pm_score': 0, 'selected': False, 'text': '<p>My solution can handle null value comparison as well. It can be simplified by writing as one single query but for an explanation, I am using CTE. The idea is to reduce the comparison from 3 number to 2 number in step 1 and then from 2 number to 1 number in step 2.</p>\n<pre><code>with x1 as\n(\n select 1 as N1, null as N2, 3 as N3\n union\n select 1 as N1, null as N2, null as N3\n union\n select null as N1, null as N2, null as N3\n)\n,x2 as\n(\nselect \nN1,N2,N3,\nIIF(Isnull(N1,0)>=Isnull(N2,0),N1,N2) as max1,\nIIF(Isnull(N2,0)>=Isnull(N3,0),N2,N3) as max2\nfrom x1\n)\n,x3 as\n(\n select N1,N2,N3,max1,max2,\n IIF(IsNull(max1,0)>=IsNull(max2,0),max1,max2) as MaxNo\n from x2\n)\nselect * from x3\n</code></pre>\n<p>Output:</p>\n<p><a href="https://i.stack.imgur.com/XcI1W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XcI1W.png" alt="enter image description here" /></a></p>\n'}, {'answer_id': 72403229, 'author': 'gotqn', 'author_id': 1080354, 'author_profile': 'https://Stackoverflow.com/users/1080354', 'pm_score': 1, 'selected': False, 'text': '<p>Finally, for the following:</p>\n<ul>\n<li>SQL Server 2022 (16.x) Preview</li>\n<li>Azure SQL Database</li>\n<li>Azure SQL Managed Instance</li>\n</ul>\n<p>we can use <a href="https://learn.microsoft.com/en-us/sql/t-sql/functions/logical-functions-greatest-transact-sql?view=azure-sqldw-latest" rel="nofollow noreferrer">GREATEST</a>, too. Similar to other T-SQL functions, here are few important notes:</p>\n<ul>\n<li>if all arguments have the same data type and\u202fthe type is\u202fsupported\u202ffor comparison,\u202fGREATEST will return that type;</li>\n<li>otherwise,\u202fthe function\u202fwill implicitly convert all arguments to the data type of the\u202fhighest precedence\u202fbefore comparison and use\u202fthis\u202ftype\u202fas the return type;</li>\n<li>if one or more arguments are not NULL, then NULL arguments will be ignored during comparison; if all arguments are NULL, then GREATEST will return NULL;</li>\n</ul>\n<p>The following types are not supported for comparison in GREATEST: varchar(max), varbinary(max) or nvarchar(max) exceeding 8,000 bytes, cursor, geometry, geography, image, non-byte-ordered user-defined types, ntext, table, text, and xml.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11703/']
|
71,030 |
<p>I'm aware I can add maven repositories for fetching dependencies in ~/.m2/settings.xml. But is it possible to add a repository using command line, something like:</p>
<pre><code>mvn install -Dmaven.repository=http://example.com/maven2
</code></pre>
<p>The reason I want to do this is because I'm using a continuous integration tool where I have full control over the command line options it uses to call maven, but managing the settings.xml for the user that runs the integration tool is a bit of a hassle.</p>
|
[{'answer_id': 71132, 'author': 'Jorge Ferreira', 'author_id': 6508, 'author_profile': 'https://Stackoverflow.com/users/6508', 'pm_score': 3, 'selected': False, 'text': '<p>I am not sure if you can do it using the command line. You can on the other hand add repositories in the <strong>pom.xml</strong> as in the following example. Using this approach you do not need to change the <strong>~/.m2/settings.xml</strong> file.</p>\n\n<pre><code> <?xml version="1.0" encoding="UTF-8"?>\n <project xmlns="http://maven.apache.org/POM/4.0.0"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">\n ...\n <repositories>\n <repository>\n <id>MavenCentral</id>\n <name>Maven repository</name>\n <url>http://repo1.maven.org/maven2</url>\n <releases>\n <enabled>true</enabled>\n </releases>\n <snapshots>\n <enabled>false</enabled>\n </snapshots>\n </repository>\n...\n <repository>\n <id>Codehaus Snapshots</id>\n <url>http://snapshots.repository.codehaus.org/</url>\n <snapshots>\n <enabled>true</enabled>\n </snapshots>\n <releases>\n <enabled>false</enabled>\n </releases>\n </repository>\n </repositories>\n\n ...\n\n <pluginRepositories>\n <pluginRepository>\n <id>apache.snapshots</id>\n <name>Apache Snapshot Repository</name>\n <url>\n http://people.apache.org/repo/m2-snapshot-repository\n </url>\n <releases>\n <enabled>false</enabled>\n </releases>\n </pluginRepository>\n <pluginRepository>\n <id>Codehaus Snapshots</id>\n <url>http://snapshots.repository.codehaus.org/</url>\n <snapshots>\n <enabled>true</enabled>\n </snapshots>\n <releases>\n <enabled>false</enabled>\n </releases>\n </pluginRepository>\n </pluginRepositories>\n\n ...\n\n </project>\n</code></pre>\n'}, {'answer_id': 71179, 'author': 'Henry B', 'author_id': 6414, 'author_profile': 'https://Stackoverflow.com/users/6414', 'pm_score': 2, 'selected': False, 'text': '<p>I haven\'t really used maven 2 before, our system is still working on maven 1.x because of some issues with maven 2.</p>\n\n<p>However, looking at the documentation for maven 2 it seems that there aren\'t any specific System properties like that. However, you could probably build one into your poms/settings using the System properties. See System properties part of this <a href="http://maven.apache.org/settings.html" rel="nofollow noreferrer">http://maven.apache.org/settings.html</a></p>\n\n<p>So you\'d have ${maven.repository} in your settings file and then use the -Dmaven.repository like you do above.</p>\n\n<p>I am unsure as to if this would work, but with some tweaking I am sure you can come up with something.</p>\n'}, {'answer_id': 95559, 'author': 'Eduard Wirch', 'author_id': 17428, 'author_profile': 'https://Stackoverflow.com/users/17428', 'pm_score': 2, 'selected': False, 'text': '<p>As\n@Jorge Ferreira\nalready said put your repository definitions in the pom.xml. Use <a href="http://maven.apache.org/pom.html#Profiles" rel="nofollow noreferrer">profiles</a> adittionally to select the repository to use via command line:</p>\n\n<pre><code>mvn deploy -P MyRepo2\n\nmvn deploy -P MyRepo1\n</code></pre>\n'}, {'answer_id': 95711, 'author': 'Steve Moyer', 'author_id': 17008, 'author_profile': 'https://Stackoverflow.com/users/17008', 'pm_score': 1, 'selected': False, 'text': '<p>Create a POM that has the repository settings that you want and then use a parent element in your project POMs to inherit the additional repositories. The use of an "organization" POM has several other benefits when a group of projects belong to one team.</p>\n'}, {'answer_id': 96765, 'author': 'ddimitrov', 'author_id': 18187, 'author_profile': 'https://Stackoverflow.com/users/18187', 'pm_score': 3, 'selected': False, 'text': "<p>One of the goals for Maven't Project Object Model (POM) is to capture all information needed to reliably reproduce an artifact, thus passing settings impacting the artifact creation is strongly discouraged.</p>\n\n<p>To achieve your goal, you can check in your user-level settings.xml file with each project and use the -s (or --settings) option to pass it to the build. </p>\n"}, {'answer_id': 1193664, 'author': 'Rich Seller', 'author_id': 123582, 'author_profile': 'https://Stackoverflow.com/users/123582', 'pm_score': 7, 'selected': True, 'text': '<p>You can do this but you\'re probably better off doing it in the POM as others have said.</p>\n\n<p>On the command line you can specify a property for the local repository, and another repository for the remote repositories. The remote repository will have all default settings though</p>\n\n<p>The example below specifies two remote repositories and a custom local repository.</p>\n\n<pre><code>mvn package -Dmaven.repo.remote=http://www.ibiblio.org/maven/,http://myrepo \n -Dmaven.repo.local="c:\\test\\repo"\n</code></pre>\n'}, {'answer_id': 2031913, 'author': 'Kevin Wright', 'author_id': 165009, 'author_profile': 'https://Stackoverflow.com/users/165009', 'pm_score': 2, 'selected': False, 'text': "<p>I'll assume here that you're asking this because you occasionally want to add a new 3rd-party repository to your builds. I may be wrong of course... :)</p>\n\n<p>Your best bet in this case is to use a managed proxy such as artifactory or nexus. Then make a one-time change in settings.xml to set this up as a mirror for the world.</p>\n\n<p>Any 3rd party repos that you need to add from that point on can be handled via the proxy.</p>\n"}, {'answer_id': 73148984, 'author': 'YGXXII', 'author_id': 6102698, 'author_profile': 'https://Stackoverflow.com/users/6102698', 'pm_score': 0, 'selected': False, 'text': '<p>I am using <code>xmlstarlet</code> to achieve this. Tested for Maven 3 on CentOS 7, Maven 2 was not tested yet.</p>\n<pre class="lang-bash prettyprint-override"><code>XML_FULLPATH="$HOME/.m2/settings.xml"\nMIRROR_ID=\'example\'\nMIRROR_MIRROROF=\'*\'\nMIRROR_NAME=\'Example Mirror\'\nMIRROR_URL=\'http://example.com/maven2\'\n\n\n## Preview settings without comment:\nxmlstarlet ed -d \'//comment()\' "$XML_FULLPATH"\n\n\n## Add Mirror settings:\nxmlstarlet ed -L \\\n --subnode "/_:settings/_:mirrors" --type elem --name "mirrorTMP" --value "" \\\n --subnode "/_:settings/_:mirrors/mirrorTMP" --type elem --name "id" --value "$MIRROR_ID" \\\n --subnode "/_:settings/_:mirrors/mirrorTMP" --type elem --name "mirrorOf" --value "$MIRROR_MIRROROF" \\\n --subnode "/_:settings/_:mirrors/mirrorTMP" --type elem --name "name" --value "$MIRROR_NAME" \\\n --subnode "/_:settings/_:mirrors/mirrorTMP" --type elem --name "url" --value "$MIRROR_URL" \\\n --rename "/_:settings/_:mirrors/mirrorTMP" --value "mirror" \\\n "$XML_FULLPATH"\n\n\n## Remove Mirror settings by id:\nxmlstarlet ed -L \\\n --delete "/_:settings/_:mirrors/_:mirror[_:id=\\"$MIRROR_ID\\"]" \\\n "$XML_FULLPATH"\n</code></pre>\n<p>The idea is from: <a href="https://stackoverflow.com/a/9172796/6102698">How to insert a new element under another with xmlstarlet?</a>.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1113/']
|
71,031 |
<p>I have an application that imports large volumes of data daily, several 100 thousands records.<br>
Data comes from different sources. The data is read using C#, then bulk inserted into the database.
<br>
<br>
This data is then processed:</p>
<ul>
<li>different tables are linked</li>
<li>new tables are generated</li>
<li>data is corrected using complicated algorithmns (totals of certain tables have to total zero)</li>
</ul>
<p>Most of this processing is done in stored procedures.
<br>
Although some of the complex processing would be simpler in C#, the extraction of the data into a dataset and its reinjection would slow things down considerably.
<br>
You may ask why I do not process the data before inserting it into the database, but I do not think it practical to manipulate 100,000s of records in memory, and the SQLs set based commands help when creating lots of records.
<br>
<br>
This will probably spark up the age old question of using stored procedures and their pros and cons.
(eg. How do you unit test stored procedures?)
<br>
<br>
What I would like in response, is your experience with large volumes of data and how you tackled the problem.</p>
|
[{'answer_id': 71070, 'author': 'Sklivvz', 'author_id': 7028, 'author_profile': 'https://Stackoverflow.com/users/7028', 'pm_score': 1, 'selected': False, 'text': '<p>I would use SSIS or DTS (assuming you are talking about MSSQL). They are made for that purpose and work with SPs if you need them.</p>\n\n<p>Another option is to preprocess the data using Perl. Even though it sounds like a wierd suggestion, Perl is actually extremely fast in these scenarios. I\'ve used it in the past to process billions of records in reasonable time (i.e. days instead of weeks).</p>\n\n<p>Regarding "How do you Unit Test store procedures", you unit test them with MBUnit like anything else. Only bit of advice: the setup and rollback of the data can be tricky, you can either use a DTS transaction or explicit SQL statements.</p>\n'}, {'answer_id': 71190, 'author': 'Josh', 'author_id': 11702, 'author_profile': 'https://Stackoverflow.com/users/11702', 'pm_score': 1, 'selected': False, 'text': '<p>I would generally have to agree with Skliwz when it comes to doing things in MSSQL. SSIS and DTS are the way to go, but if you are unfamiliar with those technologies they can be cumbersome to work with. However, there is an alternative that would allow you to do the processing in C#, and still keep your data inside of SQL Server.</p>\n\n<p>If you really think the processing would be simpler in C# then you may want to look into using a <a href="http://msdn.microsoft.com/en-us/library/c8dbfz8s(VS.80).aspx" rel="nofollow noreferrer">SQL Server Project</a> to create <a href="http://msdn.microsoft.com/en-us/library/k2e1fb36(VS.80).aspx" rel="nofollow noreferrer">database objects using C#</a>. There are a lot of really powerful things you can do with CLR objects inside of SQL Server, and this would allow you to write and unit test the code before it ever touches the database. You can unit test your CLR code inside of VS using any of the standard unit testing frameworks (NUnit, MSTest), and you don\'t have to write a bunch of set up and tear down scripts that can be difficult to manage.</p>\n\n<p>As far as testing your stored procedures I would honestly look into <a href="http://benilovj.github.com/dbfit" rel="nofollow noreferrer">DBFit</a> for that. Your database doesn\'t have to be a black hole of untested functionality any more :)</p>\n'}, {'answer_id': 71680, 'author': 'Ovid', 'author_id': 8003, 'author_profile': 'https://Stackoverflow.com/users/8003', 'pm_score': 0, 'selected': False, 'text': '<p>Where you process data depends greatly on what you\'re doing. If you need, for example, to discard data which you don\'t want in your database, then you would process that in your C# code. However, data to process in the database should generally be data which should be "implementation agnostic". So if someone else wants to insert data from a Java client, the database should be able to reject bad data. If you put that logic into your C# code, the Java code won\'t know about it.</p>\n\n<p>Some people object and say "but I\'ll never use another language for the database!" Even if that\'s true, you\'ll still have DBAs or developers working with the database and they\'ll make mistakes if the logic isn\'t there. Or your new C# developer will try to shove in data and not know about (or just ignore) data pre-processors written in C#.</p>\n\n<p>In short, the logic you put in your database should be enough to guarantee that the data is correct without relying on external software.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7050/']
|
71,036 |
<p>What do you do if members of your team are not cooperative during scrum meetings?
They either provide a very high level definition of what they are currently working on, ("working on feature x"), or go into extremely irrelevant details, <strong>in spite of being well educated in SCRUM methodology</strong>.
This causes the scrum meeting to be ineffective and boring.</p>
<p>As a scrum master, what are your techniques to getting the best out of people during the meeting?</p>
<p>Edited to add:</p>
<p><strong>What technique do you use to stop someone who is talking too much, without being offensive?</strong></p>
<p><strong>What technique do you use to encourage someone to provide a more detailed answer?</strong></p>
<p><strong>How do you react when you find yourself being the only one who listens, while other team members just sit there and maybe even fall asleep?</strong></p>
|
[{'answer_id': 71061, 'author': 'Niyaz', 'author_id': 184, 'author_profile': 'https://Stackoverflow.com/users/184', 'pm_score': 0, 'selected': False, 'text': "<p>Ask for the specific details you need. People won't be aware of stuff you are interested in.</p>\n\n<p>Also try to put forth some guidelines for better and effective presentation before the meeting.</p>\n"}, {'answer_id': 71121, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 3, 'selected': False, 'text': "<p>If time management is your problem. Get a timer and have someone buzz when you run out of time. Make sure tasks are broken down to an adequate level of granularity - any task should be anywhere between 4 hours to 2 days.. max 3 days. Anything above that break it down further before people signup to do it.</p>\n\n<p>I think the three questions are:</p>\n\n<ul>\n<li>What did you do yesterday? </li>\n<li>What are you going to do today? </li>\n<li>What obstacles do you see in your path?</li>\n</ul>\n\n<p>Granular tasks (post iteration planning) should cater to bullets 1 and 2. The third actually depends on environmental conditions. The timer should over time subsconsciously jolt the members into thinking about their problems and framing short sentences. Focus on concrete obstacles instead of explaining why or preconditions or whatever. If you are talking to a single person for over 5 mins about something that only is of relevance to both of you.. stop, make a note (have a talk later at their desk) and move on.</p>\n\n<p><em>Update: Also make sure everyone understands that 'rehearsing' before the Scrum meeting would save everyone's time. <strong>Think</strong> about what you would like to convey instead of just walking into the stand-up.</em></p>\n"}, {'answer_id': 71123, 'author': 'Loofer', 'author_id': 5552, 'author_profile': 'https://Stackoverflow.com/users/5552', 'pm_score': 3, 'selected': False, 'text': '<p>They should be saying what they achieved not what they worked on, and if they achieved nothing then what stopped them achieving.</p>\n\n<p>The questions that are asked could be phrased differently</p>\n\n<ol>\n<li>What have I completed since the last meeting? </li>\n<li>What will I complete before the next meeting? </li>\n<li>What is in my way (impediments)?</li>\n</ol>\n\n<p>also it is important that the meeting is not the team reporting to the scrum master, but the team keeping in check with each other. \nIf people are talking straight at you the scrum master there are techniques to move the focus. Make sure you don\'t look at the speaker, or even move back so the sight line changes and they are forced to look at team mates as they talk. Do it subtle though :)</p>\n\n<p>EDIT:</p>\n\n<p>I cribbed that from \n<a href="http://www.implementingscrum.com/2007/04/02/work-naked/" rel="nofollow noreferrer">http://www.implementingscrum.com/2007/04/02/work-naked/</a></p>\n'}, {'answer_id': 71138, 'author': 'Erwin', 'author_id': 7236, 'author_profile': 'https://Stackoverflow.com/users/7236', 'pm_score': 0, 'selected': False, 'text': '<p>Talk to them outside the scrum meeting and tell them how others may perceive their way of presenting what they are currently working on. I assume they are not deliberately non cooperative, but just not accustomed to the exact level of detail scrum meetings should have. </p>\n\n<p>You may also ask them how much information they expect from others during the meeting.</p>\n'}, {'answer_id': 71462, 'author': 'Thomas Owens', 'author_id': 572, 'author_profile': 'https://Stackoverflow.com/users/572', 'pm_score': 0, 'selected': False, 'text': '<p>By "scrum meeting", are you referring to the daily "stand up" meeting? If so, I believe those are usually timeboxed at about 15-20 minutes. So divide that time equally among everyone, and once someone uses up all their time, they can\'t talk. It might be harsh, but I believe that\'s how it\'s supposed to go down.</p>\n'}, {'answer_id': 71485, 'author': 'Kief', 'author_id': 5432, 'author_profile': 'https://Stackoverflow.com/users/5432', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n <p>How do you react when you find yourself being the only one who listenes, while other team members just <strong>sit</strong> there and maybe even fall asleep?</p>\n</blockquote>\n\n<p>Hmm, are you actually having stand-up meetings? It may sound hokey, but aside from making it harder for people to fall asleep, it also helps foster the feeling of a quick huddle to rather than a leisurelymeeting.</p>\n'}, {'answer_id': 72294, 'author': 'Ilja Preuß', 'author_id': 11765, 'author_profile': 'https://Stackoverflow.com/users/11765', 'pm_score': 2, 'selected': False, 'text': '<p>One thing that I have seen lead to an improvement is the use of a "talking stick" (we actually use a soft ball). It provides some additional focus on who is currently speaking, and makes the transition to another person more obvious.</p>\n'}, {'answer_id': 72373, 'author': 'roo', 'author_id': 716, 'author_profile': 'https://Stackoverflow.com/users/716', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n <p>How do you react when you find yourself being the only one who listenes, while other team members just sit there and maybe even fall asleep?</p>\n</blockquote>\n\n<p>If I have already heard what the others have said I would ask a question of someone who is not paying attention about how it this might affect what they are working on. Very school teacher like, however it is enough so that they respond and engage with the meeting again.</p>\n\n<p>I also agree with <a href="https://stackoverflow.com/questions/71036/scrum-non-cooperative-team-members#71485">Kief</a></p>\n'}, {'answer_id': 89068, 'author': 'steve_mtl', 'author_id': 178, 'author_profile': 'https://Stackoverflow.com/users/178', 'pm_score': 1, 'selected': False, 'text': '<p>The Scrum is a standup meeting, and the concept of a talking stick is an excellent point. </p>\n\n<p>The key here is not that you have one or a few uncooperative team members, but is IMO, a more fundamental problem: the scrum team is supposed to be self managed, and the scrum meeting is to keep the <strong>team</strong> informed. If the other team members are not asking for clarifications and calling out the uncooperative members, then a re-education on scrum needs to happen.</p>\n\n<p>Remember, the scrum master is not being reported to, s/he is just the person who removes blockages to the process. This does include facilitating the scrum meeting, but the team does have a responsibility to understand and demand clarification independent of the scrum master.</p>\n'}, {'answer_id': 90825, 'author': 'Asgeir S. Nilsen', 'author_id': 16023, 'author_profile': 'https://Stackoverflow.com/users/16023', 'pm_score': 0, 'selected': False, 'text': '<p>Scrum is a bottom up process, so in principle every team member should support the process.</p>\n\n<p>How is the team put together? By organizational tradition or because of a common goal?</p>\n\n<p>Not everybody buy into the Scrum idea, and we should respect that. Perhaps the best for all is that these members are not part of the Scrum team?</p>\n'}, {'answer_id': 91675, 'author': 'Xetius', 'author_id': 274, 'author_profile': 'https://Stackoverflow.com/users/274', 'pm_score': 0, 'selected': False, 'text': '<p>Some people just don\'t understand what is required. You can try to guide the conversation by using some key phrases.</p>\n\n<p>If someone is giving too much detail then you can try to cut them off with a "What else". This will hint that they are done on that point. Or you can try the "OK, can we discuss that offline" type direction.</p>\n\n<p>For people who don\'t buy into it, ask them questions about what they did and what they are going to do.</p>\n'}, {'answer_id': 214558, 'author': 'Adrian Wible', 'author_id': 23105, 'author_profile': 'https://Stackoverflow.com/users/23105', 'pm_score': 5, 'selected': True, 'text': '<p>First of all... make sure folks are standing up... and not even leaning on the wall or a desk.</p>\n\n<p>At a high level, I would say that, whenever you face issues on the team, the best response is to <em>ask the team</em> for solutions. However, here are some of the techniques I\'ve used for the issues you\'re facing.</p>\n\n<p><strong>Talks too much</strong> </p>\n\n<ul>\n<li>have him/her stand on one leg</li>\n<li>have him/her hold the scrum "speaking" token in an outstretched hand while they speak.</li>\n<li>Add a flip chart to the scrum to list tabled issues... when someone gets longwinded on a topic that is not scrum-meeting-worthy, interrupt and say "Hey - great point. I\'m not sure everyone needs to discuss this, how \'bout if we park this for a follow-up discussion?" A key to making this successful is to actually follow-up afterwards and get the side conversation scheduled. Alternatively, the speaker may just say "Not necessary... I\'ll be working with Joe this afternoon on this" or something like that, which accomplishes the goal of reducing the windedness without the need to schedule the follow-up.</li>\n</ul>\n\n<p><strong>Need more detail</strong>. Is this for the scrum master\'s benefit or the team\'s? </p>\n\n<ul>\n<li>wait until afterwards to ask the individual more detailed questions. If you think the team also needs to know them, coach the team member by conveying (in your after-scrum questioning) that "this is the sort of thing that I think Joe Smith would be helped in hearing from you, what do you think?"</li>\n</ul>\n\n<p><strong>Team doesn\'t listen</strong>. </p>\n\n<ul>\n<li>Ask them on an individual basis. "Sally, I noticed that you don\'t seem to be getting much out of the Scrum. How can we adjust it to make it valuable for you?".</li>\n<li>Post questions to others during the scrum. Like if Sally says "I integrated with Bob\'s code yesterday", ask Bob "how\'d that go?" (I\'d use this sparingly... to guard against scrums taking too long).</li>\n<li>I\'ve found that sometimes team members tend towards old habits by looking at the scrum master or project manager when they speak. When this happens alot, I alter my gaze to look away, which almost forces the speaker to gain eye contact with other members of the team, which may help the other members of the team to pay attention.</li>\n</ul>\n'}, {'answer_id': 779061, 'author': 'Dustin Getz', 'author_id': 20003, 'author_profile': 'https://Stackoverflow.com/users/20003', 'pm_score': 2, 'selected': False, 'text': '<p>for your team to participate they have to see value in it, not just do it because you told them to.</p>\n'}, {'answer_id': 1549536, 'author': 'JeffO', 'author_id': 61339, 'author_profile': 'https://Stackoverflow.com/users/61339', 'pm_score': 0, 'selected': False, 'text': "<p>For the sake of arguement, let's say someone really has something they need to tell the team and it is going to take some time. Do you have an appropriate place, time or method (email, other type of meeting, lunch time) to do this? Just interupt the person and let them know the stand up meeting isn't the place.</p>\n\n<p>Also, what problems during development does this create? If there is an error because of lack of communication, people need to be confronted on why they don't mention these things during the standup.</p>\n"}, {'answer_id': 24178322, 'author': 'paul', 'author_id': 854207, 'author_profile': 'https://Stackoverflow.com/users/854207', 'pm_score': 0, 'selected': False, 'text': "<ul>\n<li>You can plan a maximum average time to explain what you did and what you gonna do. </li>\n<li>About the people that are not willing to speak too much, I guess is responsibility of the scrum master to encourage that people to be a little bit more clear about his tasks.</li>\n<li>If still people dont share what they´re doing a radical solution is use a canvas board where there people of the team have to move the task that they´re doing to his respective area(In development, ready to validation, in code review). Then you can know for sure in which task is he working.</li>\n<li>After every daily meeting remember to ask for impediments or whatever kind of issue, sometimes people don't remember to say in his time or don't want share their issues.</li>\n</ul>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11710/']
|
71,057 |
<p>Does anyone know of a good code obsfucator for Perl? I'm being ask to look into the option of obsfucating code before releasing it to a client. I know obsfucated code can still be reverse engineered, but that's not our main concern. </p>
<p>Some clients are making small changes to the source code that we give them and it's giving us nightmares when something goes wrong and we have to fix it, or when we release a patch that doesn't work with what they've changed. So the intention is just to make it so that it's difficult for them to make their own changes to the code(they're not supposed to be doing that anyway).</p>
|
[{'answer_id': 71078, 'author': 'Dave Cross', 'author_id': 7231, 'author_profile': 'https://Stackoverflow.com/users/7231', 'pm_score': 3, 'selected': False, 'text': '<p>Please don\'t do that. If you don\'t want people to alter your Perl code then put it under an appropriate licence and enforce that licence. If people change your code when you licence says that they shouldn\'t do that, then it\'s not your problem when your updates not longer work with their installation.</p>\n\n<p>See <a href="http://perldoc.perl.org/perlfaq3.html#How-can-I-hide-the-source-for-my-Perl-program%3f" rel="nofollow noreferrer">perlfaq3\'s answer to "How Can I hide the source for my Perl programs?</a> for more details.</p>\n'}, {'answer_id': 71097, 'author': 'rjray', 'author_id': 6421, 'author_profile': 'https://Stackoverflow.com/users/6421', 'pm_score': 4, 'selected': False, 'text': "<p>Don't. Just don't.</p>\n\n<p>Write it into the contract (or revise the contract if you have to), that you are not responsible for changes they make to the software. If they're f-ing up your code and then expecting you to fix it, <em>you have client problems that aren't going to be solved by obfuscating the code</em>. And if you obfuscate it and they encounter an actual problem, good luck in getting them to accurately report line number, etc., in the bug report.</p>\n"}, {'answer_id': 71116, 'author': 'Ovid', 'author_id': 8003, 'author_profile': 'https://Stackoverflow.com/users/8003', 'pm_score': 6, 'selected': True, 'text': '<p>I\'ve been down this road before and it\'s an absolute nightmare when you have to work on "obfuscated" code because it drives up costs tremendously trying to debug a problem on the client\'s server when you, the developer, can\'t read the code. You wind up with "deobfuscators", copying the "real code" to the client\'s server or any of a number of other issues which just become a real hassle to maintain.</p>\n\n<p>I understand where you\'re coming from, but it sounds like management has a problem and they\'re looking to you to implement a chosen solution rather than figuring out what the correct solution is.</p>\n\n<p>In this case, it sounds like it\'s really a licensing or contractual issue. Let \'em have the code open source, but make it a part of the license that any changes they submit have to come back to you and be approved. When you push out patches, check the md5 sums of all code and if it doesn\'t match what\'s expected, they\'re in license violation and will be charged accordingly (and it should be a far, far higher rate). (I remember one company which let us have the code open source, but made it clear that if we changed anything, we\'ve "bought" the code for $25,000 and they were no longer responsible for any bug fixes or upgrades unless we bought a new license).</p>\n'}, {'answer_id': 71133, 'author': 'freespace', 'author_id': 8297, 'author_profile': 'https://Stackoverflow.com/users/8297', 'pm_score': 3, 'selected': False, 'text': "<p>It would seem your main issue is clients modifying code which then makes it difficult for you to support it. I would suggest you ask for checksums (md5,sha, etc) of their files when they come to you for support, and similarly check files' checksums when patching. For example, you can ask the client to provide the output of a provided program which goes through their install and checksums all the files.</p>\n\n<p>Ultimately they have the code, so they can do whatever they want to it. The best you can do is enforce your licenses and to make sure you only support unmodified code.</p>\n"}, {'answer_id': 71135, 'author': 'EvdB', 'author_id': 5349, 'author_profile': 'https://Stackoverflow.com/users/5349', 'pm_score': 2, 'selected': False, 'text': '<p>In this case obfuscating is the wrong approach.</p>\n\n<p>When you release the code to the client you should keep a copy of the code you send them (either on disk or preferably in your version control as a tag/branch).</p>\n\n<p>Then if your client makes changes you can compare the code they have to the code you sent them and easily spot the changes. After all if they feel the need to make changes there is a problem somewhere and you should fix it in the master codebase.</p>\n'}, {'answer_id': 71294, 'author': 'David Webb', 'author_id': 3171, 'author_profile': 'https://Stackoverflow.com/users/3171', 'pm_score': 2, 'selected': False, 'text': '<p>An alternative to obfuscation is converting your script to a binary using something like <a href="http://www.activestate.com/Products/perl_dev_kit/index.mhtml" rel="nofollow noreferrer">ActiveState\'s Perl Dev Kit</a>. </p>\n'}, {'answer_id': 71403, 'author': 'cressie176', 'author_id': 11786, 'author_profile': 'https://Stackoverflow.com/users/11786', 'pm_score': 2, 'selected': False, 'text': '<p>This isn\'t a serious suggestion, however take a look at <a href="http://search.cpan.org/dist/Acme-Buffy" rel="nofollow noreferrer">Acme::Buffy</a>.</p>\n\n<p>It will at least brighten your day!</p>\n'}, {'answer_id': 71425, 'author': 'xdg', 'author_id': 11800, 'author_profile': 'https://Stackoverflow.com/users/11800', 'pm_score': 2, 'selected': False, 'text': '<p>Another alternative for converting your program into a binary is the free <a href="http://search.cpan.org/dist/PAR-Packer/" rel="nofollow noreferrer">PAR-Packer</a> tool on <a href="http://search.cpan.org" rel="nofollow noreferrer">CPAN</a>. There are even filters for code obfuscation, though as others have said, that\'s possibly more trouble than it\'s worth.</p>\n'}, {'answer_id': 71747, 'author': 'Penfold', 'author_id': 11952, 'author_profile': 'https://Stackoverflow.com/users/11952', 'pm_score': 2, 'selected': False, 'text': '<p>As several folks have already said: don\'t.</p>\n\n<p>It\'s pretty much implicit, given the nature of the Perl interpreter, that anything you do to obfuscate the Perl must be undoable before Perl gets its hands on it, which means you need to leave the de-obfuscation script/binary lying around where the interpreter (and thus your customer) can find it :)</p>\n\n<p>Fix the real problem: checksums and/or a suitably worded license. And support staff trained to say \'you changed it? we\'re invoking clause 34b of our license, and that\'ll be $X,000 before we touch it\'....</p>\n\n<p>Also, read <a href="https://stackoverflow.com/questions/31882/why-should-i-use-obfuscation">why-should-i-use-obfuscation</a> for a more general answer.</p>\n'}, {'answer_id': 73457, 'author': 'piCookie', 'author_id': 8763, 'author_profile': 'https://Stackoverflow.com/users/8763', 'pm_score': 2, 'selected': False, 'text': '<p>I am running a Windows O/S and use perl2exe from IndigoSTAR. The resulting .EXE file will be unlikely to be changed on-site.</p>\n\n<p>As others have said, "how do I obfuscate it" is the wrong question. "How do I stop the customer from changing the code" is the right one.</p>\n'}, {'answer_id': 73898, 'author': 'Cosimo', 'author_id': 11303, 'author_profile': 'https://Stackoverflow.com/users/11303', 'pm_score': 2, 'selected': False, 'text': '<p>I agree with the previous suggestions.</p>\n\n<p>However if you really want to, you can look into <a href="http://search.cpan.org/dist/PAR" rel="nofollow noreferrer">PAR</a> and/or <a href="http://search.cpan.org/dist/Filter-Crypto" rel="nofollow noreferrer">Filter::Crypto</a> CPAN modules. You can also use them together.</p>\n\n<p>I used the latter (Filter::Crypto) as a really lightweight form of "protection" when we were shipping our product on optical media. It doesn\'t "protect" you, but it will stop 90% of the people that want to modify your source files.</p>\n'}, {'answer_id': 79973, 'author': 'Eric Wilhelm', 'author_id': 11580, 'author_profile': 'https://Stackoverflow.com/users/11580', 'pm_score': 2, 'selected': False, 'text': '<p>The checksum and contract ideas are good for preventing the "problems" you describe, but if the cost to you is the difficulty of rolling-out upgrades and bug-fixes, how are your clients making changes that don\'t pass the <b>comprehensive test suite</b>? If they are capable of making these changes (or at least, making a change which expresses what they want the code to do), why not simply make it easy/automated for them to open a support ticket and upload the patch? The customer is always right <em>about what the customer wants</em> (they might not have a clue how to do it "the right way", but that\'s why they are paying you.)</p>\n\n<p>A better reason to want an obfuscator would be for mass-market desktop deployment where you don\'t have every customer on a standing contract. In that case, something <em>like</em> PAR -- anything which packs the encryption/obfuscation logic into a compiled binary is the way to go.</p>\n'}, {'answer_id': 83878, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>I would just invite them into my SVN tree on their own branch so they can provide changes and I can see them and integrate their changes into my development tree. </p>\n\n<p>Don't fight it, embrace it. </p>\n"}, {'answer_id': 109565, 'author': 'brian d foy', 'author_id': 2766176, 'author_profile': 'https://Stackoverflow.com/users/2766176', 'pm_score': 1, 'selected': False, 'text': '<p>As Ovid says, it\'s a contractual, social problem. If they change the code, they invalidate the warranty. Charge them a lot to fix that, but at the same time, give them a channel where they can suggest changes. Also, look at what they want to change and make that part of the configuration if you can. They have something they want to do, and until you satisfy that, they are going to keep trying to get around you.</p>\n\n<p>In <A href="http://oreilly.com/catalog/9780596527242/" rel="nofollow noreferrer">Mastering Perl</a>, I talk a bit about defeating obfucators. Even if you do things like making nonsense variables names and the like, modules such as <a href="http://search.cpan.org/dist/B-Deparse" rel="nofollow noreferrer">B::Deparse</a> and <a href="http://search.cpan.org/dist/B-Deobfuscate" rel="nofollow noreferrer">B::Deobfuscate</a>, along with Perl tools such as <a href="http://search.cpan.org/dist/Perl-Tidy" rel="nofollow noreferrer">Perl::Tidy</a>, make it pretty easy for the knowledgable and motivated person to get your source. You don\'t have to worry about the unknowledgable and unmotivated so much because they don\'t know what to do with the code anyway. </p>\n\n<p>When I talk to managers about this, we go through the normal cost benefit analysis. There is all sorts of stuff you <i>could</i> do, but not much of it costs less than the benefit you get.</p>\n\n<p>Good luck,</p>\n'}, {'answer_id': 23672411, 'author': 'pau4o', 'author_id': 1353117, 'author_profile': 'https://Stackoverflow.com/users/1353117', 'pm_score': 0, 'selected': False, 'text': '<p>Another not serious suggestion is to use <a href="https://metacpan.org/pod/Acme%3a%3aBleach" rel="nofollow">Acme::Bleach</a>, it will make your code very clean ;-)</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11708/']
|
71,065 |
<p>We have a collection of commercial MFC/C++ applications which we sell using <a href="http://www.roguewave.com/products/stingray.php" rel="nofollow noreferrer">Stingray Objective Toolkit</a>, we have source code license and have ported it in the past to Solaris/IRIX/HP-UX/AIX using <a href="http://en.wikipedia.org/wiki/Bristol_Technology_Inc." rel="nofollow noreferrer">Bristol Technologies WindU</a> (Windows API on UNIX, including MFC). </p>
<p>Any long story short recently about 18 months ago we ported Stingray to Win64, but a long a tedious task, during this time I did some research on commercial and open source alternative MFC extension libraries things like <a href="http://www.codeproject.com/KB/MFC/UltimateToolbox.aspx" rel="nofollow noreferrer">Ultimate Toolbox</a> and <a href="http://www.prof-uis.com/" rel="nofollow noreferrer">Prof-UIS</a>.</p>
<ul>
<li>Has anyone else used Stingray and moved to an alternative? </li>
<li>If so which one would you suggest? </li>
<li>What were the main perils of the move?</li>
</ul>
|
[{'answer_id': 71350, 'author': 'Roel', 'author_id': 11449, 'author_profile': 'https://Stackoverflow.com/users/11449', 'pm_score': 3, 'selected': True, 'text': '<p>Yes, we haved moved away from Stingray. It depends on what Stingray components you are using. For the grid control, you can use the free MFC gridcontrol from www.codeproject.com or the commercial one from <a href="http://www.bcgsoft.com/" rel="nofollow noreferrer">http://www.bcgsoft.com/</a>. The free one is OK but development has stalled, so no modern UI rendering etc.</p>\n\n<p>The \'layout editor\' Stingray component can be replaced by the one from bcgsoft.com, but I don\'t have experience with that - we rewrote the functionality we needed from that on our own (it was only a subset of what Stingray provided).</p>\n\n<p>As for alternative MFC toolboxes, I suggest bcgsoft because part of their toolbox is in the Visual Studio Feature Pack so it\'s free and fits very well with VS. I have looked at Ultimate Toolbox (stay away from it, stale code that isn\'t updated anymore) and Prof-UIs (OK but I found it not so easy to integrate).</p>\n\n<p>Now that BCG is part of the \'official\' MFC I don\'t see a reason to choose something else than BCG (except for maybe the cost, if you need a free alternative you can look at codeproject).</p>\n'}, {'answer_id': 91432, 'author': 'Gautam Jain', 'author_id': 15065, 'author_profile': 'https://Stackoverflow.com/users/15065', 'pm_score': 1, 'selected': False, 'text': '<p>I have limited experience with Stingray.</p>\n\n<p>However, I want to suggest trying CodeJock\'s Xtreme Toolkit Pro (<a href="http://www.codejock.com" rel="nofollow noreferrer">http://www.codejock.com</a>). Its GUI is very good and its supported very well.</p>\n'}, {'answer_id': 143258, 'author': 'SmacL', 'author_id': 22564, 'author_profile': 'https://Stackoverflow.com/users/22564', 'pm_score': 0, 'selected': False, 'text': '<p>I have been using Stingray for last eight years or so, and have looked at moving off it a couple of times. So far, I\'ve decided against, principally because I have ported a version to Windows CE & Mobile and don\'t see much else giving the same solution on this platform. While Stingray isn\'t perfect, they have now got a 64bit version, and it\'s a pretty stable product.</p>\n\n<p>What I am doing, is replacing the very weak areas of Stingray, such as the XML support, with alternatives. In this case I went with <a href="http://expat.sourceforge.net/" rel="nofollow noreferrer">Expat</a> for performance reasons. </p>\n\n<p>The perils of moving? You could go from something stable but old fashioned to pretty but flakey ;) In my case, I would also kill a fair number of my automated test scripts that work at GUI level.</p>\n\n<p><strong>Edit:</strong> Just to add a bit to the above, I moved from VS2003 to VS2008 this week and at the same time Objective Studio 2006 v2 to Objective Studio 10.1. The transition was pretty seamless, with one minor glitch that was promptly handled by RogueWave tech support. Even this would have gone unnoticed if we didn\'t have a very extensive GUI regression test suite. IMO, Stingray is a very mature, well supported, feature rich and most importantly stable product. I for won\'t be moving of it any time soon without very good reason.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2387/']
|
71,069 |
<p>Maven spews out far too many lines of output to my taste (I like the Unix way: no news is good news).</p>
<p>I want to get rid of all <code>[INFO]</code> lines, but I couldn't find any mention of an argument or config settings that controls the verbosity of Maven.</p>
<p>Is there no LOG4J-like way to set the log level?</p>
|
[{'answer_id': 71086, 'author': 'Jorge Ferreira', 'author_id': 6508, 'author_profile': 'https://Stackoverflow.com/users/6508', 'pm_score': 8, 'selected': True, 'text': '<p>You can try the <a href="http://maven.apache.org/ref/current/maven-embedder/cli.html" rel="noreferrer"><code>-q</code> switch</a>.</p>\n<blockquote>\n<p><code>-q</code>,<code>--quiet</code> Quiet output - only show errors</p>\n</blockquote>\n'}, {'answer_id': 71091, 'author': 'Sietse', 'author_id': 6400, 'author_profile': 'https://Stackoverflow.com/users/6400', 'pm_score': 3, 'selected': False, 'text': '<p>Use the -q or --quiet command-line options</p>\n'}, {'answer_id': 40535065, 'author': 'Stanislav', 'author_id': 2213164, 'author_profile': 'https://Stackoverflow.com/users/2213164', 'pm_score': 5, 'selected': False, 'text': '<p><code>-q</code> as said above is what you need. An alternative could be:</p>\n<blockquote>\n<p><code>-B</code>,<code>--batch-mode</code>\nRun in non-interactive (batch) mode\nBatch mode is essential if you need to run Maven in a non-interactive, continuous integration environment. When running in non-interactive mode, Maven will never stop to accept input from the user. Instead, it will use sensible default values when it requires input.</p>\n</blockquote>\n<p>And will also reduce the output messages more or less to the essentials.</p>\n'}, {'answer_id': 41002277, 'author': 'ankon', 'author_id': 196315, 'author_profile': 'https://Stackoverflow.com/users/196315', 'pm_score': 1, 'selected': False, 'text': '<p>Maven 3.1.x uses SLF4j for logging, you can find instructions how to configure it at <a href="https://maven.apache.org/maven-logging.html" rel="nofollow noreferrer">https://maven.apache.org/maven-logging.html</a></p>\n\n<p>In short: Either modify <code>${MAVEN_HOME}/conf/logging/simplelogger.properties</code>, or set the same properties via the <code>MAVEN_OPTS</code> environment variable.</p>\n\n<p>For example: setting <code>MAVEN_OPTS</code> to <code>-Dorg.slf4j.simpleLogger.log.org.apache.maven.cl\u200c\u200bi.transfer.Slf4jMave\u200c\u200bnTransferListener=wa\u200c\u200brn</code> configures the logging of the batch mode transfer listener, and <code>-Dorg.slf4j.simpleLogger.defaultLogLevel=warn</code> sets the default log level.</p>\n'}, {'answer_id': 45345022, 'author': 'jgrtalk', 'author_id': 8374743, 'author_profile': 'https://Stackoverflow.com/users/8374743', 'pm_score': 5, 'selected': False, 'text': '<p>Official link :\n<a href="https://maven.apache.org/maven-logging.html" rel="noreferrer">https://maven.apache.org/maven-logging.html</a></p>\n\n<p>You can add in the <strong>JVM</strong> parameters :</p>\n\n<pre><code>-Dorg.slf4j.simpleLogger.defaultLogLevel=WARN\n</code></pre>\n\n<p>Beware of UPPERCASE.</p>\n'}, {'answer_id': 48989076, 'author': 'm13r', 'author_id': 2249798, 'author_profile': 'https://Stackoverflow.com/users/2249798', 'pm_score': 2, 'selected': False, 'text': '\n\n<p>If you only want to get rid of the <code>[INFO]</code> messages you also could do:</p>\n\n<pre class="lang-none prettyprint-override"><code>mvn ... | fgrep -v "[INFO]"\n</code></pre>\n\n<p>To suppress <strong>all</strong> outputs (except errors) you could redirect <code>stdout</code> to <code>/dev/null</code> with:</p>\n\n<pre class="lang-none prettyprint-override"><code>mvn ... 1>/dev/null\n</code></pre>\n\n<p>(This only works if you use <code>bash</code> (or similar shells) to run the Maven commands.)</p>\n'}, {'answer_id': 55963149, 'author': 'errant.info', 'author_id': 496663, 'author_profile': 'https://Stackoverflow.com/users/496663', 'pm_score': 1, 'selected': False, 'text': '<p>The existing answer help you filter based on the log-level using <code>--quiet</code>. I found that many INFO messages are useful for debugging, however the downloading artifact log messages such as the following were noisy and not helpful. </p>\n\n<pre><code>Downloading: http://nexus:8081/nexus/content/groups/public/org/apache/maven/plugins/maven-compiler-plugin/maven-metadata.xml\n</code></pre>\n\n<p>I found this solution:</p>\n\n<p><a href="https://blogs.itemis.com/en/in-a-nutshell-removing-artifact-messages-from-maven-log-output" rel="nofollow noreferrer">https://blogs.itemis.com/en/in-a-nutshell-removing-artifact-messages-from-maven-log-output</a></p>\n\n<pre><code>mvn clean install -B -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn\n</code></pre>\n'}, {'answer_id': 56118170, 'author': 'VonC', 'author_id': 6309, 'author_profile': 'https://Stackoverflow.com/users/6309', 'pm_score': 5, 'selected': False, 'text': '<blockquote>\n <p>My problem is that -q is too quiet. I\'m running maven under CI</p>\n</blockquote>\n\n<p>With <a href="https://maven.apache.org/docs/3.6.1/release-notes.html" rel="noreferrer">Maven 3.6.1 (April 2019)</a>, you now have an <strong>option to suppress the transfer progress when downloading/uploading in interactive mode</strong>.</p>\n\n<pre><code>mvn --no-transfer-progress ....\n</code></pre>\n\n<blockquote>\n <p>or in short:</p>\n</blockquote>\n\n<pre><code>mvn -ntp ... ....\n</code></pre>\n\n<p>That is what <a href="https://stackoverflow.com/users/279640/ray">Ray</a> proposed <a href="https://stackoverflow.com/questions/71069/can-maven-be-made-less-verbose/40535065#comment97499320_71086">in the comments</a> with <a href="https://issues.apache.org/jira/browse/MNG-6605" rel="noreferrer">MNG-6605</a> and <a href="https://github.com/apache/maven/pull/239" rel="noreferrer">PR 239</a>.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71069', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7483/']
|
71,074 |
<p>I can make Firefox not display the ugly dotted focus outlines on <b>links</b> with this:</p>
<pre class="lang-css prettyprint-override"><code>a:focus {
outline: none;
}
</code></pre>
<p>But how can I do this for <code><button></code> tags as well? When I do this:</p>
<pre class="lang-css prettyprint-override"><code>button:focus {
outline: none;
}
</code></pre>
<p>the buttons still have the dotted focus outline when I click on them.</p>
<p>(and yes, I know this is a usability issue, but I would like to provide my own focus hints which are appropriate to the design instead of ugly grey dots)</p>
|
[{'answer_id': 71251, 'author': 'Vitaly Sharovatov', 'author_id': 6647, 'author_profile': 'https://Stackoverflow.com/users/6647', 'pm_score': 3, 'selected': False, 'text': '<p>There\'s no way to remove these dotted focus in Firefox using CSS.</p>\n\n<p>If you have access to the computers where your webapplication works, go to about:config in Firefox and set <code>browser.display.focus_ring_width</code> to 0. Then Firefox won\'t show any dotted borders at all.</p>\n\n<p>The following bug explains the topic: <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=74225" rel="nofollow noreferrer">https://bugzilla.mozilla.org/show_bug.cgi?id=74225</a></p>\n'}, {'answer_id': 71260, 'author': 'AlexWilson', 'author_id': 2240, 'author_profile': 'https://Stackoverflow.com/users/2240', 'pm_score': 2, 'selected': False, 'text': '<p>It looks like the only way to achieve this is by setting</p>\n\n<pre><code>browser.display.focus_ring_width = 0\n</code></pre>\n\n<p>in about:config on a per browser basis.</p>\n'}, {'answer_id': 199319, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 11, 'selected': True, 'text': '<pre class="lang-css prettyprint-override"><code>button::-moz-focus-inner {\n border: 0;\n}\n</code></pre>\n'}, {'answer_id': 857360, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>You might want to intensify the focus rather than get rid of it.</p>\n\n<pre><code>button::-moz-focus-inner {border: 2px solid transparent;}\n\nbutton:focus::-moz-focus-inner {border-color: blue} \n</code></pre>\n'}, {'answer_id': 1095624, 'author': 'Flatline', 'author_id': 134628, 'author_profile': 'https://Stackoverflow.com/users/134628', 'pm_score': 2, 'selected': False, 'text': "<p>I think you should really know what you're doing by removing the focus outline, because it can mess it up for keyboard navigation and accessibility.</p>\n\n<p>If you need to take it out because of a design issue, add a <code>:focus</code> state to the button that replaces this with some other visual cue, like, changing the border to a brighter color or something like that.</p>\n\n<p>Sometimes I feel the need to take that annoying outline out, but I always prepare an alternate focus visual cue.</p>\n\n<p>And <strong>never</strong> use the <code>blur()</code> js function. Use the <code>::-moz-focus-inner</code> pseudo class.</p>\n"}, {'answer_id': 1622384, 'author': 'chinkchink', 'author_id': 196344, 'author_profile': 'https://Stackoverflow.com/users/196344', 'pm_score': 6, 'selected': False, 'text': '<p>If you prefer to use CSS to get rid of the dotted outline:</p>\n\n<pre class="lang-css prettyprint-override"><code>/*for FireFox*/\n input[type="submit"]::-moz-focus-inner, input[type="button"]::-moz-focus-inner\n { \n border : 0;\n } \n/*for IE8 and below */\n input[type="submit"]:focus, input[type="button"]:focus\n { \n outline : none; \n }\n</code></pre>\n'}, {'answer_id': 1750468, 'author': 'wavded', 'author_id': 47158, 'author_profile': 'https://Stackoverflow.com/users/47158', 'pm_score': 2, 'selected': False, 'text': '<pre><code>button::-moz-focus-inner { border: 0; }\n</code></pre>\n\n<p>Where <code>button</code> can be whatever CSS selector for which you want to disable the behavior.</p>\n'}, {'answer_id': 2021783, 'author': 'usual', 'author_id': 245688, 'author_profile': 'https://Stackoverflow.com/users/245688', 'pm_score': 0, 'selected': False, 'text': '<p>You can try <code>button::-moz-focus-inner {border: 0px solid transparent;}</code> in your CSS.</p>\n'}, {'answer_id': 3129247, 'author': 'blizzyx', 'author_id': 377621, 'author_profile': 'https://Stackoverflow.com/users/377621', 'pm_score': 5, 'selected': False, 'text': '<pre class="lang-css prettyprint-override"><code>:focus, :active {\n outline: 0;\n border: 0;\n}\n</code></pre>\n'}, {'answer_id': 3844452, 'author': 'Anderson Custódio', 'author_id': 464428, 'author_profile': 'https://Stackoverflow.com/users/464428', 'pm_score': 8, 'selected': False, 'text': '<p>No need to define a selector.</p>\n\n<pre class="lang-css prettyprint-override"><code>:focus {outline:none;}\n::-moz-focus-inner {border:0;}\n</code></pre>\n\n<p>However, this violates accessibility best practices from the W3C. The outline is there to help those navigating with keyboards.</p>\n\n<p><a href="https://www.w3.org/TR/WCAG20-TECHS/F78.html#F78-examples" rel="noreferrer">https://www.w3.org/TR/WCAG20-TECHS/F78.html#F78-examples</a></p>\n'}, {'answer_id': 6635075, 'author': 'Dave Everitt', 'author_id': 123033, 'author_profile': 'https://Stackoverflow.com/users/123033', 'pm_score': 2, 'selected': False, 'text': '<p>If you have a border on a button and want to hide the dotted outline in Firefox <em>without</em> removing the border (and hence it\'s extra width on the button) you can use:</p>\n\n<pre class="lang-css prettyprint-override"><code>.button::-moz-focus-inner {\n border-color: transparent;\n}\n</code></pre>\n'}, {'answer_id': 7628310, 'author': 'foxybagga', 'author_id': 95350, 'author_profile': 'https://Stackoverflow.com/users/95350', 'pm_score': 5, 'selected': False, 'text': '<p>The below worked for me in case of LINKS, thought of sharing - in case someone is interested. </p>\n\n<pre class="lang-css prettyprint-override"><code>a, a:visited, a:focus, a:active, a:hover{\n outline:0 none !important;\n}\n</code></pre>\n\n<p>Cheers!</p>\n'}, {'answer_id': 15608143, 'author': 'Shannon Hochkins', 'author_id': 1683943, 'author_profile': 'https://Stackoverflow.com/users/1683943', 'pm_score': 3, 'selected': False, 'text': '<p>There is many solutions found on the web for this, many of which work, but to force this, so that absolutely nothing can highlight/focus once a use the following:</p>\n\n<pre class="lang-css prettyprint-override"><code>::-moz-focus-inner, :active, :focus {\n outline:none;\n border:0;\n -moz-outline-style: none;\n}\n</code></pre>\n\n<p>This just adds that little bit extra security & seals the deal!</p>\n'}, {'answer_id': 18993053, 'author': 'Renato Carvalho', 'author_id': 925560, 'author_profile': 'https://Stackoverflow.com/users/925560', 'pm_score': 3, 'selected': False, 'text': '<p>[Update] This solution doesn\'t work anymore. The solution that worked for me is this one <a href="https://stackoverflow.com/a/3844452/925560">https://stackoverflow.com/a/3844452/925560</a></p>\n\n<p><strong>The answer marked as correct didn\'t work with Firefox 24.0.</strong></p>\n\n<p>To remove Firefox\'s dotted outline on buttons and anchor tags I added the code below:</p>\n\n<pre class="lang-css prettyprint-override"><code>a:focus, a:active, \nbutton::-moz-focus-inner,\ninput[type="reset"]::-moz-focus-inner,\ninput[type="button"]::-moz-focus-inner,\ninput[type="submit"]::-moz-focus-inner,\nselect::-moz-focus-inner,\ninput[type="file"] > input[type="button"]::-moz-focus-inner {\n border: 0;\n outline : 0;\n}\n</code></pre>\n\n<p>I found the solution here: <a href="http://aghoshb.com/articles/css-how-to-remove-firefoxs-dotted-outline-on-buttons-and-anchor-tags.html" rel="nofollow noreferrer">http://aghoshb.com/articles/css-how-to-remove-firefoxs-dotted-outline-on-buttons-and-anchor-tags.html</a></p>\n'}, {'answer_id': 20731378, 'author': 'Fizer Khan', 'author_id': 1154350, 'author_profile': 'https://Stackoverflow.com/users/1154350', 'pm_score': 2, 'selected': False, 'text': '<p>Remove dotted outline from links, button and input element.</p>\n\n<pre><code>a:focus, a:active,\nbutton::-moz-focus-inner,\ninput[type="reset"]::-moz-focus-inner,\ninput[type="button"]::-moz-focus-inner,\ninput[type="submit"]::-moz-focus-inner {\n border: 0;\n outline : 0;\n}\n</code></pre>\n'}, {'answer_id': 20833484, 'author': 'DPP', 'author_id': 1766855, 'author_profile': 'https://Stackoverflow.com/users/1766855', 'pm_score': 1, 'selected': False, 'text': '<p>This works on firefox v-27.0</p>\n\n<pre><code> .buttonClassName:focus {\n outline:none;\n}\n</code></pre>\n'}, {'answer_id': 24791473, 'author': 'Vartox', 'author_id': 2366511, 'author_profile': 'https://Stackoverflow.com/users/2366511', 'pm_score': 3, 'selected': False, 'text': '<p>Tried most of the answers here, but none of them worked for me. When I realized that I have to get rid of the blue outline on buttons on Chrome too, I found another solution. <a href="https://stackoverflow.com/questions/20340138/remove-blue-border-from-css-custom-styled-button-in-chrome">Remove blue border from css custom-styled button in Chrome</a></p>\n\n<p>This code worked for me on Firefox version 30 on Windows 7. Perhaps it might help somebody else out there :)</p>\n\n<pre class="lang-css prettyprint-override"><code>button:focus {outline:0 !important;}\n</code></pre>\n'}, {'answer_id': 31893576, 'author': 'herci', 'author_id': 3294466, 'author_profile': 'https://Stackoverflow.com/users/3294466', 'pm_score': 2, 'selected': False, 'text': "<p>In most cases without adding the <strong><code>!important</code></strong> to the CSS code, it won't work.</p>\n\n<h2>So, do not forget to add <code>!important</code></h2>\n\n<pre><code>a, a:active, a:focus{\n outline: none !important; /* Works in Firefox, Chrome, IE8 and above */\n}\n</code></pre>\n\n<p><br>\nOr any other code:</p>\n\n<pre><code>button::-moz-focus-inner {\n border: 0 !important;\n}\n</code></pre>\n"}, {'answer_id': 36897437, 'author': 'Madan Sapkota', 'author_id': 782535, 'author_profile': 'https://Stackoverflow.com/users/782535', 'pm_score': 3, 'selected': False, 'text': '<p>Tested on Firefox 46 and Chrome 49 using this code.</p>\n<pre><code>input:focus, textarea:focus, button:focus {\n outline: none !important;\n}\n</code></pre>\n<p><strong>Before</strong> (white dots are visible )</p>\n<p><a href="https://i.stack.imgur.com/1hP1m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1hP1m.png" alt="input with white dots" /></a></p>\n<p><strong>After</strong> ( White dots are invisible )\n<a href="https://i.stack.imgur.com/62tZV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/62tZV.png" alt="enter image description here" /></a></p>\n<p>If you want to apply only on few input fields, buttons etc. Use the more specific code.</p>\n<pre><code>input[type=text] {\n outline: none !important;\n}\n</code></pre>\n'}, {'answer_id': 37482092, 'author': 'Syed Waqas Bukhary', 'author_id': 3633267, 'author_profile': 'https://Stackoverflow.com/users/3633267', 'pm_score': 1, 'selected': False, 'text': '<p>After trying many options from the above only the following worked for me.</p>\n\n<pre><code>*:focus, *:visited, *:active, *:hover { outline:0 !important;}\n*::-moz-focus-inner {border:0;}\n</code></pre>\n'}, {'answer_id': 37717454, 'author': 'Ehsan88', 'author_id': 2571422, 'author_profile': 'https://Stackoverflow.com/users/2571422', 'pm_score': 1, 'selected': False, 'text': '<p>Along with Bootstrap 3 I used this code. The second set of rules just <em>undo</em> what bootstrap does for focus/active buttons:</p>\n\n<pre><code>button::-moz-focus-inner {\n border: 0; /*removes dotted lines around buttons*/\n}\n\n.btn.active.focus, .btn.active:focus, .btn.focus, .btn.focus:active, .btn:active:focus, .btn:focus{\n outline:0;\n}\n</code></pre>\n\n<p><strong>NOTE that your custom css file should come after Bootstrap css file in your html code to override it.</strong></p>\n'}, {'answer_id': 38766296, 'author': 'kurumkan', 'author_id': 5714544, 'author_profile': 'https://Stackoverflow.com/users/5714544', 'pm_score': 2, 'selected': False, 'text': '<p>The CSS code below works to remove this:</p>\n\n<pre><code>a:focus, a:active, \nbutton::-moz-focus-inner,\ninput[type="reset"]::-moz-focus-inner,\ninput[type="button"]::-moz-focus-inner,\ninput[type="submit"]::-moz-focus-inner,\nselect::-moz-focus-inner,\ninput[type="file"] > input[type="button"]::-moz-focus-inner {\n border: 0;\n outline : 0;\n}\n</code></pre>\n'}, {'answer_id': 41631535, 'author': 'Abhay Singh', 'author_id': 2063930, 'author_profile': 'https://Stackoverflow.com/users/2063930', 'pm_score': 3, 'selected': False, 'text': '<p>Simply add this css for select box </p>\n\n<pre><code>select:-moz-focusring {\n color: transparent;\n text-shadow: 0 0 0 #000;\n}\n</code></pre>\n\n<p>This is working fine for me.</p>\n'}, {'answer_id': 47195132, 'author': 'bob', 'author_id': 1088866, 'author_profile': 'https://Stackoverflow.com/users/1088866', 'pm_score': 3, 'selected': False, 'text': '<p>This will get the range control:</p>\n\n<pre><code>:focus {\n outline:none;\n}\n::-moz-focus-inner {\n border:0;\n}\ninput[type=range]::-moz-focus-outer {\n border: 0;\n}\n</code></pre>\n\n<p>From: <a href="https://stackoverflow.com/questions/18794026/remove-dotted-outline-from-range-input-element-in-firefox">Remove dotted outline from range input element in Firefox</a></p>\n'}, {'answer_id': 55434025, 'author': 'Riwaj Chalise', 'author_id': 10003098, 'author_profile': 'https://Stackoverflow.com/users/10003098', 'pm_score': 1, 'selected': False, 'text': '<p>Yep don\'t miss <strong>!important</strong></p>\n\n<pre class="lang-css prettyprint-override"><code>button::-moz-focus-inner {\n border: 0 !important;\n}\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4639/']
|
71,077 |
<p>I want to compress some files (into the <a href="http://en.wikipedia.org/wiki/ZIP_%28file_format%29" rel="nofollow noreferrer">ZIP</a> format) and encrypt them if possible using C#. Is there some way to do this?</p>
<p>Can encryption be done as a part of the compression itself?</p>
|
[{'answer_id': 71099, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 5, 'selected': True, 'text': '<p>For compression, look at the <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.aspx" rel="nofollow noreferrer"><code>System.IO.Compression</code></a> namespace and for encryption look at <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx" rel="nofollow noreferrer"><code>System.Security.Cryptography</code></a>.</p>\n'}, {'answer_id': 71101, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': -1, 'selected': False, 'text': '<p>Here is a useful topic:</p>\n\n<p><a href="https://stackoverflow.com/questions/71000/help-in-creating-zip-files-from-net-and-reading-them-from-java">Help in creating Zip files from .Net and reading them from Java</a></p>\n\n<p>System.IO.Packaging namespace gives you useful classes to compress data in zip format and <a href="http://msdn.microsoft.com/en-us/library/ms580548.aspx" rel="nofollow noreferrer">support</a> rights management.</p>\n'}, {'answer_id': 71102, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 1, 'selected': False, 'text': '<p>The <a href="http://blogs.msdn.com/bclteam/archive/2005/06/15/429542.aspx" rel="nofollow noreferrer">GZipStream</a> class is a native way to handle compression.</p>\n\n<p>As for encryption, there are <a href="http://www.codeproject.com/KB/security/SimpleEncryption.aspx" rel="nofollow noreferrer">many</a> <a href="http://www.codeproject.com/KB/security/encryption_decryption.aspx" rel="nofollow noreferrer">ways</a> to do it, most of them in the System.Security namespace. They can be done chained (encrypt a compressed stream or compress an encrypted stream).</p>\n'}, {'answer_id': 71103, 'author': 'Mark Ingram', 'author_id': 986, 'author_profile': 'https://Stackoverflow.com/users/986', 'pm_score': -1, 'selected': False, 'text': '<p>There isn\'t anything you can use directly in C#, however you can use some libraries from J# to do it for you:</p>\n\n<p><a href="http://msdn.microsoft.com/en-us/magazine/cc164129.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/cc164129.aspx</a></p>\n\n<p>Should do just what you want?</p>\n\n<p>With regards to the encryption, have a look at these links:</p>\n\n<p><a href="http://www.codeproject.com/KB/security/fileencryptdecrypt.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/security/fileencryptdecrypt.aspx</a></p>\n\n<p><a href="http://www.obviex.com/samples/EncryptionWithSalt.aspx" rel="nofollow noreferrer">http://www.obviex.com/samples/EncryptionWithSalt.aspx</a></p>\n'}, {'answer_id': 71109, 'author': 'Hank Gay', 'author_id': 4203, 'author_profile': 'https://Stackoverflow.com/users/4203', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m not sure if the steps can be combined, but .NET has good support for basic crypto. Here\'s an <a href="http://www.ondotnet.com/pub/a/dotnet/2003/02/10/dotnetcryto.html" rel="nofollow noreferrer">article on it</a>.</p>\n'}, {'answer_id': 71155, 'author': 'prakash', 'author_id': 123, 'author_profile': 'https://Stackoverflow.com/users/123', 'pm_score': 3, 'selected': False, 'text': '<p>For Zip Compression, have you seen <a href="http://www.icsharpcode.net/OpenSource/SharpZipLib/" rel="nofollow noreferrer">http://www.icsharpcode.net/OpenSource/SharpZipLib/</a></p>\n'}, {'answer_id': 71292, 'author': 'Rik', 'author_id': 5409, 'author_profile': 'https://Stackoverflow.com/users/5409', 'pm_score': 0, 'selected': False, 'text': '<p>If they cannot be combined, do compression first and then encryption. Compressing an already encrypted file will lead to poor compression ratios, because a lot of redundancy is removed.</p>\n'}, {'answer_id': 71831, 'author': 'Ian Nelson', 'author_id': 2084, 'author_profile': 'https://Stackoverflow.com/users/2084', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.chilkatsoft.com/" rel="nofollow noreferrer">Chilkat</a> provides .NET libraries for compression and encryption.</p>\n'}, {'answer_id': 123411, 'author': 'Martin Plante', 'author_id': 4898, 'author_profile': 'https://Stackoverflow.com/users/4898', 'pm_score': 3, 'selected': False, 'text': '<p>I know the question is already old, but I must add my two cents.</p>\n\n<p>First, some definitions:</p>\n\n<ul>\n<li><strong>Zip</strong>: Archive format for regrouping files and folders into a single file, and optionally encrypting data.</li>\n<li><strong>Deflate</strong>: One of the compression algorithms used within a Zip file to compress the data. The most popular one.</li>\n<li><strong>GZip</strong>: A single file compressed with deflate, with a small header and footer.</li>\n</ul>\n\n<p>Now, System.IO.Compression does <strong>not</strong> do Zip archiving. It does <strong>deflate</strong> and <strong>gzip</strong> compression, thus will compress a single blob of data into another single blob of data.</p>\n\n<p>So, if you\'re looking for an archive format that can group many files and folders, you need Zip libraries like:</p>\n\n<ul>\n<li><a href="http://xceed.com" rel="noreferrer">Xceed Zip</a> (it does support strong encryption)</li>\n<li><a href="http://www.icsharpcode.net/OpenSource/SharpZipLib/" rel="noreferrer">SharpZipLib</a></li>\n</ul>\n\n<p>If you only need to compress and encrypt a single blob of data, then look under <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.aspx" rel="noreferrer">System.IO.Compression</a> and <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx" rel="noreferrer">System.Security.Cryptography</a>.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71077', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184/']
|
71,092 |
<p>What is the difference, what is the official terms, are any terms obsolete in ASP.NET 3.5?</p>
|
[{'answer_id': 71194, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 7, 'selected': True, 'text': '<p><strong>UserControl</strong>: A custom control, ending in .ascx, that is composed of other web controls. Its almost like a small version of an aspx webpage. It consists of a UI (the ascx) and codebehind. Cannot be reused in other projects by referencing a DLL.</p>\n\n<p><strong>WebControl</strong>: A control hosted on a webpage or in a UserControl. It consists of one or more classes, working in tandem, and is hosted on an aspx page or in a UserControl. WebControls don\'t have a UI "page" and must render their content directly. They can be reused in other applications by referencing their DLLs.</p>\n\n<p><strong>RenderedControl</strong>: Does not exist. May be synonymous to WebControl. Might indicate the control is written directly to the HttpResponse rather than rendered to an aspx page.</p>\n\n<p><strong><a href="http://msdn.microsoft.com/en-us/library/aa479016.aspx" rel="noreferrer">CompositeControl</a></strong>: Inbetween UserControls and WebControls. They code like UserControls, as they are composed of other controls. There is not any graphical UI for control compositing, and support for UI editing of CompositeControls must be coded by the control designer. Compositing is done in the codebehind. CompositeControls can be reused in other projects like WebControls. </p>\n'}, {'answer_id': 71231, 'author': 'JRoppert', 'author_id': 6777, 'author_profile': 'https://Stackoverflow.com/users/6777', 'pm_score': 3, 'selected': False, 'text': '<p>You\'ve forgotten the ServerControl.</p>\n\n<p>In my understanding it is like that:</p>\n\n<ul>\n<li>There are only two different kind of controls: UserControl and ServerControl</li>\n<li>CompositeControls are kind of "advanced" UserControls. Find some more info on <a href="http://weblogs.asp.net/scottgu/archive/2006/01/29/436854.aspx" rel="noreferrer">Scott Guthries Blog</a>.</li>\n<li>All of them are WebControls (because they are all derived from System.Web.UI.Control)</li>\n<li>They are all rendered in any way so i would like to see them all as rendered controls.</li>\n</ul>\n\n<p>From MSDN:</p>\n\n<blockquote>\n <p><strong>User Control</strong></p>\n \n <p>In ASP.NET: A server\n control that is authored declaratively\n using the same syntax as an ASP.NET\n page and is saved as a text file with\n an .ascx extension. User controls\n allow page functionality to be\n partitioned and reused. Upon first\n request, the page framework parses a\n user control into a class that derives\n from System.Web.UI.UserControl and\n compiles that class into an assembly,\n which it reuses on subsequent\n requests. User controls are easy to\n develop due to their page-style\n authoring and deployment without prior\n compilation.</p>\n \n <p><strong>Server control</strong> </p>\n \n <p>A server-side component\n that encapsulates user interface and\n related functionality. An ASP.NET\n server control derives directly or\n indirectly from the\n System.Web.UI.Control class. The\n superset of ASP.NET server controls\n includes Web server controls, HTML\n server controls, and ASP.NET mobile\n controls. The page syntax for an\n ASP.NET server control includes a\n runat="server" attribute on the\n control\'s tag. See also: HTML server\n control, validation server controls,\n Web server control.</p>\n</blockquote>\n'}, {'answer_id': 971878, 'author': 'Don', 'author_id': 101007, 'author_profile': 'https://Stackoverflow.com/users/101007', 'pm_score': 0, 'selected': False, 'text': '<p>Since I don\'t have enough reputation yet to comment, I\'ll add this as an answer, but it refers to Will\'s answer above.</p>\n\n<p>From the <a href="http://msdn.microsoft.com/en-us/library/aa479016.aspx" rel="nofollow noreferrer">link</a> you included:</p>\n\n<blockquote>\n <p>Composite controls are the right tool to architect complex components in which multiple child controls are aggregated and interact among themselves and with the outside world. Rendered controls are just right for read-only aggregation of controls in which the output doesn\'t include interactive elements such as drop-down or text boxes.</p>\n</blockquote>\n\n<p>I believe the documentation is refering to UserControls that have been created by overriding the Render method as Rendered Controls. Thus, it is not a separate type as the question implies, but a way of implementing a UserControl; a pattern.</p>\n'}, {'answer_id': 4995617, 'author': 'Govardhan', 'author_id': 616626, 'author_profile': 'https://Stackoverflow.com/users/616626', 'pm_score': 2, 'selected': False, 'text': '<p>Like Web Forms, user controls can be created in the visual designer or they can be written with code separate from the HTML. They can also support execution events. However, since Web user controls are compiled dynamically at run time they cannot be added to the Toolbox and they are represented by a simple placeholder when added to a page.</p>\n\n<p>This makes Web user controls harder to use if you are accustomed to full Visual Studio .NET design-time support, including the Properties window and Design view previews. Also the only way to share the user control between applications is to put a separate copy in each application, which takes more maintenance if you make changes to the control.</p>\n\n<p>Web custom controls are compiled code, which makes them easier to use but more difficult to create. Web custom controls must be authored in code. Once you have created the control you can add it to the Toolbox and display it in a visual designer with full Properties window support and all the other design-time features of ASP.NET server controls. In addition you can install a single copy of the Web custom control in the global assembly cache and share it between applications, which make maintenance easier.</p>\n'}, {'answer_id': 8143442, 'author': 'Guillaume CR', 'author_id': 922202, 'author_profile': 'https://Stackoverflow.com/users/922202', 'pm_score': 2, 'selected': False, 'text': '<p>Contrary to Will\'s response, it is possible to reuse UserControls in other projects by <a href="http://readcommit.blogspot.com/2008/01/share-aspnet-user-controls-between.html" rel="nofollow">referencing a web deployment project</a>.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8547/']
|
71,100 |
<p>Can you suggest a tool for testing accessibility and section 508/ADA compliance of a Website with MS Share Point and .Net 2.0 as the underlying platform?</p>
|
[{'answer_id': 71148, 'author': 'Galwegian', 'author_id': 3201, 'author_profile': 'https://Stackoverflow.com/users/3201', 'pm_score': 2, 'selected': False, 'text': '<p>In my experience, testing Sharepoint for accessibility is not worth it. Even if you\'ve used the Accessibility Toolkit for Sharepoint (AKS) with Sharepoint 2007, the end result is far from accessible.</p>\n\n<p>The trouble is that accessibility was not, and still is not a big consideration for MS when they made Sharepoint. Everything depends on table layout, and screenreaders are given a nightmare to deal with.</p>\n\n<p>There are a few online tools - some will help validate your output, others pretend to test you for accessibility (<a href="http://www.tawdis.net" rel="nofollow noreferrer">TAW</a>). </p>\n\n<p>The problem is that many of the guidelines under WCAG are just too arbitrary, and will never be testable by an automated tool. This may change with WCAG 2.</p>\n\n<p>Anyway, wish you the best trying to make Sharepoint accessible.</p>\n\n<p><strong>EDIT:</strong> As a side not, I can highly recommend the following tools/resources for anyone interested in accessible development:</p>\n\n<ul>\n<li>Chris Pederick\'s <a href="http://chrispederick.com/work/web-developer/" rel="nofollow noreferrer">Web Accessibility\nToolbar</a></li>\n<li><a href="http://www.accessit.nda.ie/" rel="nofollow noreferrer">NDA\'s Web Accessibility IT\nGuidelines</a></li>\n</ul>\n'}, {'answer_id': 10845066, 'author': 'paul', 'author_id': 431876, 'author_profile': 'https://Stackoverflow.com/users/431876', 'pm_score': 0, 'selected': False, 'text': '<p>You can try FireEyes(http://www.deque.com/products/worldspace-fireeyes/download-worldspace-fireeyes) . You can run it in firebug and can set up your own set of rules through a dedicated server.</p>\n\n<p>FireEyes is an unprecedented, nextgen web accessibility tool that ensures both static and dynamic content within a web portfolio are compliant with standards such as Section 508, WCAG 1.0, and WCAG 2.0. You can use another tool, but it won’t be fully JavaScript aware or handle event-based page content, like FireEyes. Does your site: \nUse AJAX, JavaScript, Flash, PDFs, or dynamic content?\nPersonalize multiple user roles?\nDisplay pages based on user-entered data?\nUse a content management system, with or without templates?\nNeed to be accessible, secure, and private?</p>\n'}, {'answer_id': 11924895, 'author': 'paul', 'author_id': 431876, 'author_profile': 'https://Stackoverflow.com/users/431876', 'pm_score': 2, 'selected': False, 'text': '<p>This is the list of web accessibility tools currently available:\n1. <a href="http://www.deque.com/worldspace%E2%84%A2-first-software-product-to-fully-support-new-wcag-2-0-standard" rel="nofollow">Worldspace</a> (price varies by number of pages): Though this tool is not free, it is the most comprehensive web accessibility tool out there. It’s highly customizable and can check AJAX applications and WCAG 2.0, along with Canadian Common Look and Feel, UK DDA and Japanese Industrial Standard</p>\n\n<ol start="2">\n<li><p><a href="https://addons.mozilla.org/en-US/firefox/addon/accessibility-evaluation-toolb/" rel="nofollow">Firefox Accessibility Extension</a> (free): The Firefox Accessibility Extension brings an array of accessibility tools together in one extension. It stands out for its ability to validate dynamic content through Web 2.0 applications. In addition to integrating with other accessibility tools, it also supports the Accessible Rich Internet Applications (ARIA) standard and includes tools for creating accessible scripts</p></li>\n<li><p><a href="http://webinsight.cs.washington.edu/wa/content.php" rel="nofollow">WebAnywhere</a> (free): When checking web accessibility, automated tools are never enough. WebAnywhere is a web application that simulates how a typical screen-reading program such as Window-eyes or Jaws would interact with a web page. It has some of the same commands used by screen-reader users to browse websites, so as a web designer, you can experience your site as a screen reader user would.</p></li>\n<li><p><a href="http://www.fujitsu.com/global/accessibility/assistance/wi/" rel="nofollow">Web Accessibility Inspector</a> (free): This is a desktop application that checks accessibility based on WCAG 1.0. Though not as up to date as the Firefox Accessibility Extension, this tool is easier to use, as it offers visual cues that point out where accessibility problems exist.</p></li>\n<li><p><a href="http://sipt07.si.ehu.es/evalaccess2/" rel="nofollow">EvalAccess</a> (free): This tool, developed by the University of the Basque Country in Spain, is one of the only free tools that lets you evaluate an entire website for compliance with the WCAG version 1.0. Results are displayed in an easy-to-read report. The tool gives you a brief description of each error detected, along with the line numbers in the source where it can be found. It’s not the most user friendly access tool, but it works well enough to help most designers and developers clean up their sites.</p></li>\n<li><p><a href="http://www.vischeck.com/vischeck/" rel="nofollow">Vischeck</a> (free): Vischeck is a visual simulator that can simulate how a web page looks to someone with either of three types of color blindness. There are millions of color blind people around the world who find it difficult to distinguish between certain colors. Vischeck is a quick way for you to tell if your images, navigation buttons or color selections may be confusing to these people. You can either upload a picture or have Vischeck analyze a specific web page.</p></li>\n<li><p><a href="http://juicystudio.com/services.php" rel="nofollow">Juicy Studio</a> (free): Juicy Studio, created by Jez Lemon in the UK, has several specialized accessibility tools. Primary among these is a color contrast analyzer Firefox extension that can analyze the contrast of the foreground and background colors of text nodes in a document. This helps you find areas with low contrast that could make your site difficult to read by color blind individuals as well as those with visual impairments. Juicy Studio also includes a table analyzer, readability analyzer and more.</p></li>\n<li><p><a href="http://ncam.wgbh.org/invent_build/web_multimedia/tools-guidelines/magpie" rel="nofollow">Media Access Generator</a> (free): MAGpie, the Media Access Generator, is a tool that creates captions and audio descriptions for various video formats. As Flash has now become more or less universal around the web, it is more important than ever that deaf and blind people alike are able to get the most from Flash videos and websites. Not only are captions helpful for translating the audio track of a video into other languages, they enable those who are deaf or hard of hearing to receive the same content as is heard on the audio track. Audio descriptions allow blind people to follow the action of a video by overlaying an audio track describing the action. MAGpie can create audio description and caption files for the major video formats including: Windows Media Player, Real Player, Quicktime and Flash.</p></li>\n<li><p><a href="http://wave.webaim.org/" rel="nofollow">WAVE</a> (free): WAVE, the Web Accessibility Evaluation Tool, is a simple, free tool that can quickly check the Section 508 and/or WCAG 1.0 accessibility of an URL. It can’t crawl, so it’s not practical to use for checking an entire site, but if you want to quickly check an URL, a file or a code snippet, WAVE is a quick and comprehensive option. You can also download a WAVE toolbar for Firefox that lets you locally analyze web pages. This is particularly helpful if you have sensitive pages you don’t want to transmit over an unencrypted connection or you have a small, local site you need to analyze.</p></li>\n<li><p><a href="http://www.paciellogroup.com/resources/wat-ie-about.html" rel="nofollow">Web Accessibility Toolbar</a> (free): The Web Accessibility Toolbar offers a suite of tools to manually check all types of possible accessibility problems, from low contrast areas to incorrect scripting. The toolbar works in both Internet Explorer and Opera. It doesn’t seem to have been updated recently, but its tools are still very useful for low-vision accessibility testing as well as to validate HTML for typical accessibility errors.</p></li>\n<li><p><a href="https://chrome.google.com/webstore/detail/colora11y/icfneoldcbdmgaiocnnobpbbjncdfbfb?hl=en" rel="nofollow">ColorA11y</a> (free): Chrome Developer Tools extension to test color contrast.</p></li>\n</ol>\n'}, {'answer_id': 44341420, 'author': 'jigar gala', 'author_id': 7504303, 'author_profile': 'https://Stackoverflow.com/users/7504303', 'pm_score': 0, 'selected': False, 'text': '<p>There are many tools available to test web accessibility. I would suggest below.</p>\n\n<ol>\n<li>voiceover in iOS, macOS. (in built).</li>\n<li>JAWS in windows (Need to purchase).</li>\n<li>web extensions like chromevox.</li>\n</ol>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71100', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
71,108 |
<p>Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in <code>Foo **</code>) in C++?</p>
|
[{'answer_id': 71143, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 3, 'selected': False, 'text': '<p>IMO most common usage is to pass reference to pointer variable</p>\n\n<pre><code>void test(int ** var)\n{\n ...\n}\n\nint *foo = ...\ntest(&foo);\n</code></pre>\n\n<p>You can create multidimensional jagged array using double pointers: </p>\n\n<pre><code>int ** array = new *int[2];\narray[0] = new int[2];\narray[1] = new int[3];\n</code></pre>\n'}, {'answer_id': 71154, 'author': 'Carl Seleborg', 'author_id': 2095, 'author_profile': 'https://Stackoverflow.com/users/2095', 'pm_score': 2, 'selected': False, 'text': '<p>If you pass a pointer in as output parameter, you might want to pass it as <code>Foo**</code> and set its value as <code>*ppFoo = pSomeOtherFoo</code>.</p>\n\n<p>And from the algorithms-and-data-structures department, you can use that double indirection to update pointers, which can be faster than for instance swapping actual objects.</p>\n'}, {'answer_id': 71160, 'author': 'dudico', 'author_id': 11089, 'author_profile': 'https://Stackoverflow.com/users/11089', 'pm_score': 1, 'selected': False, 'text': "<p>A simple example would be using <code>int** foo_mat</code> as a 2d array of integers.\nOr you may also use pointers to pointers - lets say that you have a pointer <code>void* foo</code> and you have 2 different objects that have a reference to it with the following members: <code>void** foo_pointer1</code> and <code>void** foo_pointer2</code>, by having a pointer to a pointer you can actually check whether <code>*foo_pointer1 == NULL</code> which indicates that foo is NULL. You wouldn't be able to check whether foo is NULL if foo_pointer1 was a regular pointer.\nI hope that my explanation wasn't too messy :)</p>\n"}, {'answer_id': 71164, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 1, 'selected': False, 'text': '<p>Usually when you pass a pointer to a function as a return value:</p>\n\n<pre><code>ErrorCode AllocateObject (void **object);\n</code></pre>\n\n<p>where the function returns a success/failure error code and fills in the object parameter with a pointer to the new object:</p>\n\n<pre><code>*object = new Object;\n</code></pre>\n\n<p>This is used a lot in COM programming in Win32.</p>\n\n<p>This is more of a C thing to do, in C++ you can often wrap this type of system into a class to make the code more readable.</p>\n'}, {'answer_id': 71175, 'author': '0124816', 'author_id': 11521, 'author_profile': 'https://Stackoverflow.com/users/11521', 'pm_score': 1, 'selected': False, 'text': '<p>Carl: Your example should be:</p>\n\n<pre><code>*p = x;\n</code></pre>\n\n<p>(You have two stars.) :-)</p>\n'}, {'answer_id': 71250, 'author': 'John B', 'author_id': 11773, 'author_profile': 'https://Stackoverflow.com/users/11773', 'pm_score': 3, 'selected': False, 'text': "<p>One common scenario is where you need to pass a <strong>null</strong> pointer to a function, and have it initialized within that function, and used outside the function. Without multplie indirection, the calling function would never have access to the initialized object.</p>\n\n<p>Consider the following function:</p>\n\n<pre><code>initialize(foo* my_foo)\n{\n my_foo = new Foo();\n}\n</code></pre>\n\n<p>Any function that calls 'initialize(foo*)' will not have access to the initialized instance of <strong>Foo</strong>, beacuse the pointer that's passed to this function is a copy. (The pointer is just an integer after all, and integers are passed by value.)</p>\n\n<p>However, if the function was defined like this:</p>\n\n<pre><code>initialize(foo** my_foo)\n{\n *my_foo = new Foo();\n}\n</code></pre>\n\n<p>...and it was called like this...</p>\n\n<pre><code>Foo* my_foo;\n\ninitialize(&my_foo);\n</code></pre>\n\n<p>...then the caller would have access to the initialized instance, via 'my_foo' - because it's the <em>address</em> of the pointer that was passed to 'initialize'. </p>\n\n<p>Of course, in my simplified example, the 'initialize' function could simply return the newly created instance via the return keyword, but that does not always suit - maybe the function needs to return something else.</p>\n"}, {'answer_id': 71298, 'author': 'Jorge Ferreira', 'author_id': 6508, 'author_profile': 'https://Stackoverflow.com/users/6508', 'pm_score': 5, 'selected': True, 'text': '<p>Most common usage as @aku pointed out is to allow a change to a pointer parameter to be visible after the function returns.</p>\n\n<pre><code>#include <iostream>\n\nusing namespace std;\n\nstruct Foo {\n int a;\n};\n\nvoid CreateFoo(Foo** p) {\n *p = new Foo();\n (*p)->a = 12;\n}\n\nint main(int argc, char* argv[])\n{\n Foo* p = NULL;\n CreateFoo(&p);\n cout << p->a << endl;\n delete p;\n return 0;\n}\n</code></pre>\n\n<p>This will print</p>\n\n<pre><code>12\n</code></pre>\n\n<p>But there are several other useful usages as in the following example to iterate an array of strings and print them to the standard output.</p>\n\n<pre><code>#include <iostream>\n\nusing namespace std;\n\nint main(int argc, char* argv[])\n{\n const char* words[] = { "first", "second", NULL };\n for (const char** p = words; *p != NULL; ++p) {\n cout << *p << endl;\n }\n\n return 0;\n}\n</code></pre>\n'}, {'answer_id': 73382, 'author': 'mlbrock', 'author_id': 9966, 'author_profile': 'https://Stackoverflow.com/users/9966', 'pm_score': 1, 'selected': False, 'text': '<p>In C, the idiom is absolutely required. Consider the problem in which you want a function to add a string (pure C, so a char *) to an array of pointers to char *. The function prototype requires three levels of indirection:</p>\n\n<pre><code>int AddStringToList(unsigned int *count_ptr, char ***list_ptr, const char *string_to_add);\n</code></pre>\n\n<p>We call it as follows:</p>\n\n<pre><code>unsigned int the_count = 0;\nchar **the_list = NULL;\n\nAddStringToList(&the_count, &the_list, "The string I\'m adding");\n</code></pre>\n\n<p>In C++ we have the option of using references instead, which would yield a different signature. But we still need the two levels of indirection you asked about in your original question:</p>\n\n<pre><code>int AddStringToList(unsigned int &count_ptr, char **&list_ptr, const char *string_to_add);\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11575/']
|
71,118 |
<p>I have developed a simple page using JQuery. It works fine in almost all browsers (i.e. Firefox, IE, Chrome) but whenever the page is opened in IE, it prompts Javascript error like,</p>
<pre><code>'guid' is null or not an object on line 1834
</code></pre>
<p>Do you have any idea ?</p>
|
[{'answer_id': 71269, 'author': 'Wouter Lievens', 'author_id': 7927, 'author_profile': 'https://Stackoverflow.com/users/7927', 'pm_score': 0, 'selected': False, 'text': "<p>Maybe you're using the parentNode or parentElement property? There are some issues with that in IE vs other browsers.</p>\n"}, {'answer_id': 71477, 'author': 'jatanp', 'author_id': 959, 'author_profile': 'https://Stackoverflow.com/users/959', 'pm_score': 2, 'selected': False, 'text': '<p>Thanks guys for your messages.</p>\n\n<p>The error was on my part. For hover event, I was not passing function for "out". Therefore the handler was passed as undefined in jQuery.event function and that causing error for statement ,</p>\n\n<p>if ( !handler.guid )</p>\n\n<p>written at 1834 line of jquery-1.2.6.js file.</p>\n\n<p>While using I thought that out handler is not mandatory to specify, but I guess I am wrong.</p>\n\n<p>Strangely, FF / Chrome does not prompt error but IE does :) which is bit different than what it used to be.</p>\n\n<p>Regards,\nJatan</p>\n'}, {'answer_id': 71511, 'author': 'jatanp', 'author_id': 959, 'author_profile': 'https://Stackoverflow.com/users/959', 'pm_score': 0, 'selected': False, 'text': '<p>Sorry, FF / Chrome both report this error but in very silent way. You need to go to Firefox 3.0 Javascript errors dialog to see if is there any error and for Chrome you need to go to Javascript console.</p>\n\n<p>In my view, there should be at least some UI indications (like icon would turn RED), for such errors in FF 3.0 as well as Chrome. In FF 2.0, I guess the icon was turning to RED CROSS if any error is there but it does not happen in FF 3.0 !</p>\n'}, {'answer_id': 71675, 'author': 'Neall', 'author_id': 619, 'author_profile': 'https://Stackoverflow.com/users/619', 'pm_score': 2, 'selected': False, 'text': '<p>Firefox removed the javascript error indication by default because there are a lot of pages that throw javascript errors. To an average user, the error messages aren\'t useful - only confusing. If you are a web developer, you should definitely install <a href="http://getfirebug.com/" rel="nofollow noreferrer">Firebug</a>.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/959/']
|
71,144 |
<p>For a typical Web client -to- Servlet/WS -to- Business Tier (Spring or EJB) app, what are the trade-offs of approaches like remote RPC or messaging for Web (Servlet) tier to remote Business tier, aside from the basic sync/async aspects?</p>
|
[{'answer_id': 71945, 'author': 'Chris Kimpton', 'author_id': 48310, 'author_profile': 'https://Stackoverflow.com/users/48310', 'pm_score': 1, 'selected': False, 'text': '<p>We use RMI via Spring and find it very easy to use, fairly robust and fast. Although our requirements were for a fairly responsive link and there was no real need to add a messaging component.</p>\n'}, {'answer_id': 72833, 'author': 'James Strachan', 'author_id': 2068211, 'author_profile': 'https://Stackoverflow.com/users/2068211', 'pm_score': 3, 'selected': True, 'text': '<p>By web client do you mean web browser? If so looking at stuff like DWR or JAX-RS are my recommendations. RMI or JMS only really work when both sides are Java code.</p>\n\n<p>With any remoting technology the biggest issue using them tends to be how intrusive the technology becomes on your business objects. e.g. using RMI interface/exceptions everywhere or using the JMS APIs inside your business code.</p>\n\n<p>My recommendation is to use POJOs everywhere in Java then use a technology like <a href="http://static.springframework.org/spring/docs/2.5.x/reference/remoting.html" rel="nofollow noreferrer">Spring Remoting</a> to layer on your middleware whether its RMI or JMS or whatever - but totally de-couple the middleware code from your business logic so you can switch between technologies at any time (and keep your business logic code simpler and focussed on your business problem).</p>\n\n<p>For example see the <a href="http://activemq.apache.org/camel/spring-remoting.html" rel="nofollow noreferrer">Camel implementation of Spring Remoting</a> which then allows you to use <a href="http://activemq.apache.org/camel/components.html" rel="nofollow noreferrer">any of these transports and protocols</a> such as RMI, JMS or even plain HTTP, email, files or XMPP - then switch between them trivially using a simple URI string change.</p>\n'}, {'answer_id': 2849885, 'author': 'Joe', 'author_id': 343143, 'author_profile': 'https://Stackoverflow.com/users/343143', 'pm_score': 0, 'selected': False, 'text': "<p>SUN RMI broke for us. </p>\n\n<p>The settings and garbage collection for a very long running application with continuous meassaging. We are patching to make it work continuously. JMS applications we run don't get the out of memory errors or gc problems that RMI does. Anything that needs to call System.gc() periodically and doesn't work with incremental collection to recover resources is coded wrong. </p>\n\n<p>RMI reliability improves with the JDK 6 and the correct property settings, but JHC, it's a bodgey framework. RMI would be vastly improved by using channels in nio and fixing the sun nio uses of system.gc(). </p>\n\n<p>The correct answer - seperate communication (mechanism) from the domain code. RPC is tightly coupled, and the protocol and application can interfere with each other. JMS seperates the protocol from the application, a much better paradigm. </p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11645/']
|
71,146 |
<p>What's the best value for money c# code protection? Some just use obfuscation, others add win32 wrapping, some cost a fortune. So far I've come up with <a href="http://www.eziriz.com/" rel="nofollow noreferrer">http://www.eziriz.com/</a> who's Intellilock looks promising. Any other suggestions? Any reasons why this is not a good idea?</p>
<p>I know its impossible to completely protect but I'd prefer the ability to protect my code so that it would require a lot of effort in order to recover it. I do hope to sell my products eventually, while also releasing some for free.</p>
|
[{'answer_id': 71212, 'author': 'Silver Dragon', 'author_id': 9440, 'author_profile': 'https://Stackoverflow.com/users/9440', 'pm_score': 2, 'selected': False, 'text': '<p>First of all, no matter what kind of protection you\'ll employ,a truly dedicated cracker will, eventually, get through all of the protective barriers. It might simply not worth it employing high-level code obfuscation; rather focus that time into making a better application.</p>\n\n<p>One way to look at this problem, is that people pirating your software are not your target audience; focus on paying customers instead.</p>\n\n<p>With that said, Visual Studio includes the community edition of <a href="http://www.preemptive.com/dotfuscator.html" rel="nofollow noreferrer">Dotfuscator</a>, which is fairly decent (for it\'s value); I would look into that, if needed.</p>\n'}, {'answer_id': 73346, 'author': 'Roger Ween', 'author_id': 6143, 'author_profile': 'https://Stackoverflow.com/users/6143', 'pm_score': 2, 'selected': False, 'text': '<p>The Dotfuscator community edition does nothing more than renaming your methods (to my knowledge). That is far away from a reasonable protection.</p>\n\n<p>If you want a free obfuscator you may try <a href="http://www.foss.kharkov.ua/g1/projects/eazfuscator/dotnet/Default.aspx" rel="nofollow noreferrer">this one</a></p>\n\n<p>Other than that, Intelliclock looks like a good decision if price matters.</p>\n'}, {'answer_id': 1769047, 'author': 'logicnp', 'author_id': 51919, 'author_profile': 'https://Stackoverflow.com/users/51919', 'pm_score': 1, 'selected': False, 'text': '<p>Our <a href="http://www.ssware.com/cryptoobfuscator/obfuscator-net.htm" rel="nofollow noreferrer">Crypto Obfuscator</a> product is affordable - license does not cost thousands of dollars - and provides strong obfuscation to your assemblies.</p>\n'}, {'answer_id': 2647292, 'author': 'Daniel Dolz', 'author_id': 307280, 'author_profile': 'https://Stackoverflow.com/users/307280', 'pm_score': 1, 'selected': False, 'text': '<p>I have tried many, and I think <a href="http://www.bithelmet.com" rel="nofollow noreferrer">BitHelmet obfuscator</a> is the best choice nowadays.</p>\n'}, {'answer_id': 2647341, 'author': 'MadBoy', 'author_id': 218540, 'author_profile': 'https://Stackoverflow.com/users/218540', 'pm_score': 3, 'selected': True, 'text': '<p><a href="http://www.smartassembly.com/product/editions.aspx" rel="nofollow noreferrer">Smartassembly</a> does very decent job. It\'s very very good, and easy to use. It even makes it harder to look at obfuscated file since it even makes it harder to decompile.</p>\n\n<blockquote>\n <p>Why choose {smartassembly}?</p>\n \n <p>{smartassembly} is a first-rate .NET Obfuscator, and will thus protect your .NET Intellectual Property.\n But, beyond that, {smartassembly} additionally offers you, and every .NET developer, the most efficient and easiest way to:\n Further secure your .NET application (Strings Encoding, Anti-disassembler & Anti-decompiler options, Strong Name signature...)\n Deploy your .NET application in one file (Dependencies Merging, Compression and Embedding)\n Remove all non-useful code and metadata (Pruning)\n Perform other code optimizations (Memory Management, Automatic Sealing of Classes...)\n And debug your obfuscated and deployed assembly (automatic unhandled exception reporting via 24x7x365 managed Web Service).</p>\n \n <p>This comprehensive feature-set to efficiently produce better software, protected, optimized, and improved, definitely distinguishes {smartassembly} of all other .NET "protection and/or optimization solutions" available on the market.</p>\n \n <p>And its user-friendliness, which allows every .NET developer, whatever his level of competence or expertise, to easily take advantage of all these capabilities, advantageously completes this uniqueness, to your benefit.</p>\n \n <p>By efficiently enabling every .NET developer to deliver a smart version of his .NET application, in no time, and with unmatched ease, {smartassembly} definitely takes the Improvement and Protection of .NET software forward!</p>\n \n <p>With {smartassembly}, you’ll take your valued .NET application to the next level! </p>\n</blockquote>\n\n<p>Price range is also affordable:</p>\n\n<p>Product Name Product ID Price in Euros Price in US$</p>\n\n<p>{smartassembly} Standard Edition – Single User #300056706 € 349.00 $ 499.00</p>\n\n<p>{smartassembly} Professional Edition – Single User #300056708 € 499.00 $ 699.00</p>\n\n<p>{smartassembly} Enterprise Edition – Single User #300072534 € 649.00 $ 899.0</p>\n'}, {'answer_id': 3037799, 'author': 'Marcel', 'author_id': 366378, 'author_profile': 'https://Stackoverflow.com/users/366378', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.eziriz.com/" rel="nofollow noreferrer">http://www.eziriz.com/</a> application work reasonble. But the SUPPORT S*CKS. They NEVER reply. So I would advice you to look for something else.</p>\n'}, {'answer_id': 5381613, 'author': 'Timwi', 'author_id': 33225, 'author_profile': 'https://Stackoverflow.com/users/33225', 'pm_score': 2, 'selected': False, 'text': '<p><strong><a href="http://www.aldaray.com/Rummage" rel="nofollow">Rummage</a></strong> offers reasonable professional-grade obfuscation for a very modest price. (Disclosure: I work for the company, Aldaray Ltd.)</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10957/']
|
71,149 |
<p>Using .NET 2.0 with WinForms, I'd like to create a custom, multi-columned menu (similiar to the word 2007 look&feel, but without the ribbon).</p>
<p>My approach was creating a control, and using a left/right docked toolstrip, I have constructed a similar look&feel of a menu. However, there are a few shortcomings of this solution, such as</p>
<ul>
<li>the control can only be placed, and displayed within the form; </li>
<li>if the form is too small, some area of the control won't be displayed;</li>
<li>the control also have to be manually shown/hidden.</li>
</ul>
<p>Thus, I'm looking for a way to display this control outside of the boundaries of the application. Creating a new form would result in title-bar deactivating on display, so that's also out. Alternatively, any other approach to create a customized menu would be very welcomed.</p>
<p>Edit: I don't want to use any commercial products for this; and since it's about a simple menu customization, it's not related to Microsoft's ribbon "research" in any way.</p>
|
[{'answer_id': 71243, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 2, 'selected': False, 'text': '<ul>\n<li>unless you are in the business of providing .net components, you should be looking to buy it off the shelf. Its a lot of work getting such a control right - There are already vendors providing this kind of UI. e.g. <a href="http://www.componentone.com/SuperProducts/RibbonWinForms/" rel="nofollow noreferrer">ComponentOne</a></li>\n<li>if you are trying to build this component as a product, you should look at the link below. Apparently Microsoft has a \'royalty-free\' license around the Office UI to protect their R&D investments. As of now you need to tell them that you are using something similar to the Office UI. <a href="http://msdn.microsoft.com/en-us/office/aa973809.aspx" rel="nofollow noreferrer">More of that here</a></li>\n</ul>\n'}, {'answer_id': 89510, 'author': 'Hans Passant', 'author_id': 17034, 'author_profile': 'https://Stackoverflow.com/users/17034', 'pm_score': 2, 'selected': True, 'text': "<p>The MenuStrip class has a Renderer property. You can assign your own ToolStripRenderer derived class to customize the painting. It's a fair amount of work.</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9440/']
|
71,151 |
<p>Using the Python Documentation I found the <a href="http://docs.python.org/lib/module-HTMLParser.html" rel="noreferrer">HTML parser</a> but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).</p>
|
[{'answer_id': 71161, 'author': '1077', 'author_id': 10776, 'author_profile': 'https://Stackoverflow.com/users/10776', 'pm_score': 5, 'selected': True, 'text': '<p>Try:</p>\n\n<pre><code>import HTMLParser\n</code></pre>\n\n<p>In Python 3.0, the HTMLParser module has been renamed to html.parser\nyou can check about this <a href="http://docs.python.org/library/htmlparser.html" rel="noreferrer">here</a></p>\n\n<p>Python 3.0</p>\n\n<pre><code>import html.parser\n</code></pre>\n\n<p>Python 2.2 and above</p>\n\n<pre><code>import HTMLParser\n</code></pre>\n'}, {'answer_id': 71168, 'author': 'Vytautas Šaltenis', 'author_id': 6763, 'author_profile': 'https://Stackoverflow.com/users/6763', 'pm_score': 1, 'selected': False, 'text': '<p>There\'s a link to an example on the bottom of (<a href="http://docs.python.org/2/library/htmlparser.html" rel="nofollow noreferrer">http://docs.python.org/2/library/htmlparser.html</a>) , it just doesn\'t work with the original python or python3. It has to be python2 as it says on the top.</p>\n'}, {'answer_id': 71174, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 5, 'selected': False, 'text': '<p>You probably really want <a href="https://stackoverflow.com/questions/55391/python-regular-expression-for-html-parsing-beautifulsoup#55424">BeautifulSoup</a>, check the link for an example. </p>\n\n<p>But in any case</p>\n\n<pre><code>>>> import HTMLParser\n>>> h = HTMLParser.HTMLParser()\n>>> h.feed(\'<html></html>\')\n>>> h.get_starttag_text()\n\'<html>\'\n>>> h.close()\n</code></pre>\n'}, {'answer_id': 71176, 'author': 'Swaroop C H', 'author_id': 4869, 'author_profile': 'https://Stackoverflow.com/users/4869', 'pm_score': 2, 'selected': False, 'text': '<p>I would recommend using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow noreferrer">Beautiful Soup</a> module instead and it has <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html" rel="nofollow noreferrer">good documentation</a>.</p>\n'}, {'answer_id': 71186, 'author': 'Antti Rasinen', 'author_id': 8570, 'author_profile': 'https://Stackoverflow.com/users/8570', 'pm_score': 1, 'selected': False, 'text': '<p>For real world HTML processing I\'d recommend <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow noreferrer">BeautifulSoup</a>. It is great and takes away much of the pain. Installation is easy.</p>\n'}, {'answer_id': 71614, 'author': 'Alexey Feldgendler', 'author_id': 10682, 'author_profile': 'https://Stackoverflow.com/users/10682', 'pm_score': 2, 'selected': False, 'text': '<p>You should also look at <a href="http://code.google.com/p/html5lib/" rel="nofollow noreferrer">html5lib</a> for Python as it tries to parse HTML in a way that very much resembles what web browsers do, especially when dealing with invalid HTML (which is more than 90% of today\'s web).</p>\n'}, {'answer_id': 72100, 'author': '1077', 'author_id': 10776, 'author_profile': 'https://Stackoverflow.com/users/10776', 'pm_score': 2, 'selected': False, 'text': "<p>I don't recommend BeautifulSoup if you want speed. lxml is much, much faster, and you can fall back in lxml's BS soupparser if the default parser doesn't work.</p>\n"}, {'answer_id': 82117, 'author': 'Paweł Hajdan', 'author_id': 9403, 'author_profile': 'https://Stackoverflow.com/users/9403', 'pm_score': 2, 'selected': False, 'text': '<p>You may be interested in <a href="http://codespeak.net/lxml/" rel="nofollow noreferrer">lxml</a>. It is a separate package and has C components, but is the fastest. It has also very nice API, allowing you to easily list links in HTML documents, or list forms, sanitize HTML, and more. It also has capabilities to parse not well-formed HTML (it\'s configurable).</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1384652/']
|
71,157 |
<p>I may have this completely wrong, but my understanding is that the --standalone compiler option tells the compiler to include the F# core and other dependencies in the exe, so that you can run it on another machine without installing any 'runtime'.</p>
<p>However, I can't get this to work in the CTP - it doesn't even seem to change the size of the output file (docs I've read say about 1M extra).</p>
<p>"Google may know, but if it does, it ain't telling, or I'm not looking in the right place"</p>
<p><strong>UPDATE:</strong></p>
<p>It seems to work with latest CTP <a href="http://www.microsoft.com/downloads/details.aspx?familyid=61ad6924-93ad-48dc-8c67-60f7e7803d3c&displaylang=en" rel="nofollow noreferrer">update 1.9.6.2</a></p>
<p><strong>UPDATE2:</strong></p>
<p>I have since experienced another error: </p>
<pre><code>FSC(0,0): error FS0191: could not resolve assembly Microsoft.Build.Utilities.
</code></pre>
<p>If you get errors like this when trying to compile --standalone, you need to explicitly include them as references in your project.</p>
|
[{'answer_id': 71200, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 1, 'selected': False, 'text': '<p>F# manual: <a href="http://research.microsoft.com/fsharp/manual/compiler.aspx#Standalone" rel="nofollow noreferrer">Statically linking the F# library using "--standalone"</a></p>\n\n<p>Did you try to run peverify.exe utility?</p>\n'}, {'answer_id': 71938, 'author': 'Benjol', 'author_id': 11410, 'author_profile': 'https://Stackoverflow.com/users/11410', 'pm_score': 3, 'selected': True, 'text': "<p>Answer from MS:</p>\n\n<p><em>There is a CTP update 1.9.6.2 that fixed some --standalone bugs.</em></p>\n\n<p>I'm reinstalling now...</p>\n\n<p>UPDATE:\nWorks for me - so the my accepted answer is <strong>download CTP update 1.9.6.2</strong>.</p>\n"}, {'answer_id': 901597, 'author': 'J D', 'author_id': 13924, 'author_profile': 'https://Stackoverflow.com/users/13924', 'pm_score': 1, 'selected': False, 'text': '<p>This has been a pet hatred of mine for a long time (it has been broken in every CTP release ever including the latest 1.9.6.16 May 2009 release). The "solution" is essentially to write your own build system that is not broken.</p>\n\n<p>This is a real problem for me because I have accumulated hundreds of great F# programs that I would like to put on our site but it takes hours to build each one into a standalone executable.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11410/']
|
71,163 |
<p>Are there any systems out there where one can check in changes for a website and have that automatically update the website. </p>
<p>The website effetively runs off the latest stable build the whole time without the need to ftp the files to the server.</p>
|
[{'answer_id': 71171, 'author': 'Sklivvz', 'author_id': 7028, 'author_profile': 'https://Stackoverflow.com/users/7028', 'pm_score': 2, 'selected': False, 'text': '<p>You might want to use a combination of CruiseControl (or CruiseControl.NET) and Ant (or NAnt). That does the job extremely well for us.</p>\n'}, {'answer_id': 71178, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 3, 'selected': False, 'text': '<p>I would look into using a <a href="http://svnbook.red-bean.com/en/1.4/svn.ref.reposhooks.post-commit.html" rel="nofollow noreferrer">post-commit hook</a> to update the site when changes are made. This could be something as simple as using "svn export" to export the current state of the repository to the live website location. Of course, this has performance considerations if your site has lots of content, so you may want to do something more sophisticated and only push updates for content that was changed in the commit.</p>\n'}, {'answer_id': 71188, 'author': 'David Precious', 'author_id': 4040, 'author_profile': 'https://Stackoverflow.com/users/4040', 'pm_score': 0, 'selected': False, 'text': '<p>SVN\'s post_commit hook is ideal for things like this.</p>\n\n<p><a href="http://amiworks.co.in/talk/ads-automatic-deployment-script/" rel="nofollow noreferrer">ADS (automatic deployment script</a> looks like a solution to this, but I\'ve never tried it - just found it with a few seconds of Googling.</p>\n'}, {'answer_id': 71210, 'author': 'mdxi', 'author_id': 11164, 'author_profile': 'https://Stackoverflow.com/users/11164', 'pm_score': 1, 'selected': False, 'text': "<p>Yes, post_commit hook is what you want.</p>\n\n<p>What to hook <em>to</em>? I'd recommend rsync (if your site instance isn't a svn working copy) or ssh with key auth calling a script which does 'cd WEBDIR && svn up' (if it is).</p>\n"}, {'answer_id': 72262, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Effectively what needs to happen is that changes I have marked as live or stable needs to be merged with the Live website. This effectively means I don't have to worry about accidently copying over files and if something goes wrong it could be reverted to the previous version again. </p>\n\n<p>I'll investigate post_commit hook but I'll have to find a way to do a backup first so that a problem with subversiondoesn't kill the site.</p>\n"}, {'answer_id': 72366, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>You may want to take a look at <a href="http://www.cis.upenn.edu/~bcpierce/unison/" rel="nofollow noreferrer">Unison</a>. I was fairly happy with it as a publishing mechanism for a site where I wanted, effectively, a smart two-way rsync. You could probably tie it to SVN without much difficulty.</p>\n'}, {'answer_id': 512765, 'author': 'gavinandresen', 'author_id': 58359, 'author_profile': 'https://Stackoverflow.com/users/58359', 'pm_score': 0, 'selected': False, 'text': '<p>svn2web, installed as a post-commit hook, will ftp or scp files from a subversion repository to one or more web servers on every commit. See the <a href="http://svn2web.sourceforge.net/" rel="nofollow noreferrer">SourceForge</a> project for details.</p>\n'}, {'answer_id': 1224211, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.assembla.com/catalog/37-Web-Designers-Package?affiliate" rel="nofollow noreferrer">Assembla</a> got it, with their FTP and Subversion tools.</p>\n'}, {'answer_id': 3399433, 'author': 'Joemama88', 'author_id': 355853, 'author_profile': 'https://Stackoverflow.com/users/355853', 'pm_score': 2, 'selected': False, 'text': '<p>Beanstalk is a solution that integrates ftp with subversion.</p>\n\n<p><a href="http://beanstalkapp.com/" rel="nofollow noreferrer">http://beanstalkapp.com/</a></p>\n'}, {'answer_id': 4471666, 'author': 'Graham', 'author_id': 546204, 'author_profile': 'https://Stackoverflow.com/users/546204', 'pm_score': 0, 'selected': False, 'text': '<p><a href="http://svn2ftp.com" rel="nofollow">http://svn2ftp.com</a> > SVN2FTP allows users to Push SVN / Subversion Commits Directly to an FTP or SFTP Server</p>\n'}, {'answer_id': 14539806, 'author': 'coderex', 'author_id': 110976, 'author_profile': 'https://Stackoverflow.com/users/110976', 'pm_score': 0, 'selected': False, 'text': '<p>I think this will help you </p>\n\n<p><a href="https://github.com/midhundevasia/deploy" rel="nofollow">https://github.com/midhundevasia/deploy</a></p>\n\n<p>its works well in Windows.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
71,180 |
<p>How can I find the last row that contains data in a specific column and on a specific sheet?</p>
|
[{'answer_id': 71197, 'author': 'Galwegian', 'author_id': 3201, 'author_profile': 'https://Stackoverflow.com/users/3201', 'pm_score': -1, 'selected': False, 'text': '<pre><code>Function LastRow(rng As Range) As Long\n Dim iRowN As Long\n Dim iRowI As Long\n Dim iColN As Integer\n Dim iColI As Integer\n iRowN = 0\n iColN = rng.Columns.count\n For iColI = 1 To iColN\n iRowI = rng.Columns(iColI).Offset(65536 - rng.Row, 0).End(xlUp).Row\n If iRowI > iRowN Then iRowN = iRowI\n Next\n LastRow = iRowN\nEnd Function \n</code></pre>\n'}, {'answer_id': 71296, 'author': 'GSerg', 'author_id': 11683, 'author_profile': 'https://Stackoverflow.com/users/11683', 'pm_score': 3, 'selected': False, 'text': '<pre><code>function LastRowIndex(byval w as worksheet, byval col as variant) as long\n dim r as range\n\n set r = application.intersect(w.usedrange, w.columns(col))\n if not r is nothing then\n set r = r.cells(r.cells.count)\n\n if isempty(r.value) then\n LastRowIndex = r.end(xlup).row\n else\n LastRowIndex = r.row\n end if\n end if\nend function\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>? LastRowIndex(ActiveSheet, 5)\n? LastRowIndex(ActiveSheet, "AI")\n</code></pre>\n'}, {'answer_id': 71310, 'author': 'Fionnuala', 'author_id': 2548, 'author_profile': 'https://Stackoverflow.com/users/2548', 'pm_score': 7, 'selected': True, 'text': '<p>How about:</p>\n\n<pre><code>Function GetLastRow(strSheet, strColumn) As Long\n Dim MyRange As Range\n\n Set MyRange = Worksheets(strSheet).Range(strColumn & "1")\n GetLastRow = Cells(Rows.Count, MyRange.Column).End(xlUp).Row\nEnd Function\n</code></pre>\n\n<p>Regarding a comment, this will return the row number of the last cell even when only a single cell in the last row has data:</p>\n\n<pre><code>Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row\n</code></pre>\n'}, {'answer_id': 71349, 'author': 'databyss', 'author_id': 9094, 'author_profile': 'https://Stackoverflow.com/users/9094', 'pm_score': -1, 'selected': False, 'text': '<p>The first line moves the cursor to the last non-empty row in the column. The second line prints that columns row.</p>\n\n<pre><code>Selection.End(xlDown).Select\nMsgBox(ActiveCell.Row)\n</code></pre>\n'}, {'answer_id': 73489, 'author': 'Jon Fournier', 'author_id': 5106, 'author_profile': 'https://Stackoverflow.com/users/5106', 'pm_score': 4, 'selected': False, 'text': '<p>You should use the <code>.End(xlup)</code> but instead of using 65536 you might want to use:</p>\n\n<pre><code>sheetvar.Rows.Count\n</code></pre>\n\n<p>That way it works for Excel 2007 which I believe has more than 65536 rows</p>\n'}, {'answer_id': 74282, 'author': 'Dick Kusleika', 'author_id': 4280, 'author_profile': 'https://Stackoverflow.com/users/4280', 'pm_score': 2, 'selected': False, 'text': '<pre><code>Public Function LastData(rCol As Range) As Range \n Set LastData = rCol.Find("*", rCol.Cells(1), , , , xlPrevious) \nEnd Function\n</code></pre>\n\n<p>Usage: <code>?lastdata(activecell.EntireColumn).Address</code></p>\n'}, {'answer_id': 962530, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s a solution for finding the last row, last column, or last cell. It addresses the A1 R1C1 Reference Style dilemma for the column it finds. Wish I could give credit, but can\'t find/remember where I got it from, so "Thanks!" to whoever it was that posted the original code somewhere out there.</p>\n\n<pre><code>Sub Macro1\n Sheets("Sheet1").Select\n MsgBox "The last row found is: " & Last(1, ActiveSheet.Cells)\n MsgBox "The last column (R1C1) found is: " & Last(2, ActiveSheet.Cells)\n MsgBox "The last cell found is: " & Last(3, ActiveSheet.Cells)\n MsgBox "The last column (A1) found is: " & Last(4, ActiveSheet.Cells)\nEnd Sub\n\nFunction Last(choice As Integer, rng As Range)\n\' 1 = last row\n\' 2 = last column (R1C1)\n\' 3 = last cell\n\' 4 = last column (A1)\n Dim lrw As Long\n Dim lcol As Integer\n\n Select Case choice\n Case 1:\n On Error Resume Next\n Last = rng.Find(What:="*", _\n After:=rng.Cells(1), _\n LookAt:=xlPart, _\n LookIn:=xlFormulas, _\n SearchOrder:=xlByRows, _\n SearchDirection:=xlPrevious, _\n MatchCase:=False).Row\n On Error GoTo 0\n\n Case 2:\n On Error Resume Next\n Last = rng.Find(What:="*", _\n After:=rng.Cells(1), _\n LookAt:=xlPart, _\n LookIn:=xlFormulas, _\n SearchOrder:=xlByColumns, _\n SearchDirection:=xlPrevious, _\n MatchCase:=False).Column\n On Error GoTo 0\n\n Case 3:\n On Error Resume Next\n lrw = rng.Find(What:="*", _\n After:=rng.Cells(1), _\n LookAt:=xlPart, _\n LookIn:=xlFormulas, _\n SearchOrder:=xlByRows, _\n SearchDirection:=xlPrevious, _\n MatchCase:=False).Row\n lcol = rng.Find(What:="*", _\n After:=rng.Cells(1), _\n LookAt:=xlPart, _\n LookIn:=xlFormulas, _\n SearchOrder:=xlByColumns, _\n SearchDirection:=xlPrevious, _\n MatchCase:=False).Column\n Last = Cells(lrw, lcol).Address(False, False)\n If Err.Number > 0 Then\n Last = rng.Cells(1).Address(False, False)\n Err.Clear\n End If\n On Error GoTo 0\n Case 4:\n On Error Resume Next\n Last = rng.Find(What:="*", _\n After:=rng.Cells(1), _\n LookAt:=xlPart, _\n LookIn:=xlFormulas, _\n SearchOrder:=xlByColumns, _\n SearchDirection:=xlPrevious, _\n MatchCase:=False).Column\n On Error GoTo 0\n Last = R1C1converter("R1C" & Last, 1)\n For i = 1 To Len(Last)\n s = Mid(Last, i, 1)\n If Not s Like "#" Then s1 = s1 & s\n Next i\n Last = s1\n\n End Select\n\nEnd Function\n\nFunction R1C1converter(Address As String, Optional R1C1_output As Integer, Optional RefCell As Range) As String\n \'Converts input address to either A1 or R1C1 style reference relative to RefCell\n \'If R1C1_output is xlR1C1, then result is R1C1 style reference.\n \'If R1C1_output is xlA1 (or missing), then return A1 style reference.\n \'If RefCell is missing, then the address is relative to the active cell\n \'If there is an error in conversion, the function returns the input Address string\n Dim x As Variant\n If RefCell Is Nothing Then Set RefCell = ActiveCell\n If R1C1_output = xlR1C1 Then\n x = Application.ConvertFormula(Address, xlA1, xlR1C1, , RefCell) \'Convert A1 to R1C1\n Else\n x = Application.ConvertFormula(Address, xlR1C1, xlA1, , RefCell) \'Convert R1C1 to A1\n End If\n If IsError(x) Then\n R1C1converter = Address\n Else\n \'If input address is A1 reference and A1 is requested output, then Application.ConvertFormula\n \'surrounds the address in single quotes.\n If Right(x, 1) = "\'" Then\n R1C1converter = Mid(x, 2, Len(x) - 2)\n Else\n x = Application.Substitute(x, "$", "")\n R1C1converter = x\n End If\n End If\nEnd Function\n</code></pre>\n'}, {'answer_id': 25509398, 'author': 'user2988717', 'author_id': 2988717, 'author_profile': 'https://Stackoverflow.com/users/2988717', 'pm_score': 3, 'selected': False, 'text': '<p>Simple and quick:</p>\n\n<pre><code>Dim lastRow as long\nRange("A1").select\nlastRow = Cells.Find("*",SearchOrder:=xlByRows,SearchDirection:=xlPrevious).Row\n</code></pre>\n\n<p>Example use:</p>\n\n<pre><code>cells(lastRow,1)="Ultima Linha, Last Row. Youpi!!!!"\n\n\'or \n\nRange("A" & lastRow).Value = "FIM, THE END"\n</code></pre>\n'}, {'answer_id': 33434570, 'author': 'Ashwith Ullal', 'author_id': 1534035, 'author_profile': 'https://Stackoverflow.com/users/1534035', 'pm_score': -1, 'selected': False, 'text': '<pre><code>Sub test()\n MsgBox Worksheets("sheet_name").Range("A65536").End(xlUp).Row\nEnd Sub\n</code></pre>\n\n<p>This is looking for a value in column <code>A</code> because of <code>"A65536"</code>.</p>\n'}, {'answer_id': 35975280, 'author': 'Stupid_Intern', 'author_id': 5398127, 'author_profile': 'https://Stackoverflow.com/users/5398127', 'pm_score': 0, 'selected': False, 'text': '<p>I would like to add one more reliable way using <code>UsedRange</code> to find the last used row:</p>\n\n<pre><code>lastRow = Sheet1.UsedRange.Row + Sheet1.UsedRange.Rows.Count - 1\n</code></pre>\n\n<p>Similarly to find the last used column you can <a href="https://stackoverflow.com/questions/11926972/excel-vba-finding-the-last-column-with-data/35945397#35945397">see this</a></p>\n\n<p><a href="https://i.stack.imgur.com/46aa0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/46aa0.jpg" alt="enter image description here"></a></p>\n\n<p>Result in Immediate Window:</p>\n\n<pre><code>?Sheet1.UsedRange.Row+Sheet1.UsedRange.Rows.Count-1\n 21 \n</code></pre>\n'}, {'answer_id': 46419169, 'author': 'Phaithoon Jariyanantakul', 'author_id': 8674380, 'author_profile': 'https://Stackoverflow.com/users/8674380', 'pm_score': 0, 'selected': False, 'text': "<pre><code>Public Function GetLastRow(ByVal SheetName As String) As Integer\n Dim sht As Worksheet\n Dim FirstUsedRow As Integer 'the first row of UsedRange\n Dim UsedRows As Integer ' number of rows used\n\n Set sht = Sheets(SheetName)\n ''UsedRange.Rows.Count for the empty sheet is 1\n UsedRows = sht.UsedRange.Rows.Count\n FirstUsedRow = sht.UsedRange.Row\n GetLastRow = FirstUsedRow + UsedRows - 1\n\n Set sht = Nothing\nEnd Function\n</code></pre>\n\n<p>sheet.UsedRange.Rows.Count: retrurn number of rows used, not include empty row above the first row used</p>\n\n<p>if row 1 is empty, and the last used row is 10, UsedRange.Rows.Count will return 9, not 10.</p>\n\n<p>This function calculate the first row number of UsedRange plus number of UsedRange rows.</p>\n"}, {'answer_id': 49971492, 'author': 'Nickolay', 'author_id': 1026, 'author_profile': 'https://Stackoverflow.com/users/1026', 'pm_score': 2, 'selected': False, 'text': '<p>All the solutions relying on built-in behaviors (like <code>.Find</code> and <code>.End</code>) have limitations that are not well-documented (see <a href="https://stackoverflow.com/a/49971540/1026">my other answer</a> for details).</p>\n\n<p>I needed something that:</p>\n\n<ul>\n<li>Finds the last <strong>non-empty</strong> cell (i.e. that has <em>any formula or value</em>, even if it\'s an empty string) in a <strong>specific column</strong></li>\n<li>Relies on primitives with well-defined behavior</li>\n<li>Works reliably with autofilters and user modifications</li>\n<li>Runs as fast as possible on 10,000 rows (to be run in a <code>Worksheet_Change</code> handler without feeling sluggish)</li>\n<li>...with performance not falling off a cliff with accidental data or formatting put at the very end of the sheet (at ~1M rows)</li>\n</ul>\n\n<p>The solution below:</p>\n\n<ul>\n<li>Uses <code>UsedRange</code> to find the upper bound for the row number (to make the search for the true "last row" fast in the common case where it\'s close to the end of the used range);</li>\n<li>Goes backwards to find the row with data in the given column;</li>\n<li>...using VBA arrays to avoid accessing each row individually (in case there are many rows in the <code>UsedRange</code> we need to skip)</li>\n</ul>\n\n<p>(No tests, sorry)</p>\n\n<pre><code>\' Returns the 1-based row number of the last row having a non-empty value in the given column (0 if the whole column is empty)\nPrivate Function getLastNonblankRowInColumn(ws As Worksheet, colNo As Integer) As Long\n \' Force Excel to recalculate the "last cell" (the one you land on after CTRL+END) / "used range"\n \' and get the index of the row containing the "last cell". This is reasonably fast (~1 ms/10000 rows of a used range)\n Dim lastRow As Long: lastRow = ws.UsedRange.Rows(ws.UsedRange.Rows.Count).Row - 1 \' 0-based\n\n \' Since the "last cell" is not necessarily the one we\'re looking for (it may be in a different column, have some\n \' formatting applied but no value, etc), we loop backward from the last row towards the top of the sheet).\n Dim wholeRng As Range: Set wholeRng = ws.Columns(colNo)\n\n \' Since accessing cells one by one is slower than reading a block of cells into a VBA array and looping through the array,\n \' we process in chunks of increasing size, starting with 1 cell and doubling the size on each iteration, until MAX_CHUNK_SIZE is reached.\n \' In pathological cases where Excel thinks all the ~1M rows are in the used range, this will take around 100ms.\n \' Yet in a normal case where one of the few last rows contains the cell we\'re looking for, we don\'t read too many cells.\n Const MAX_CHUNK_SIZE = 2 ^ 10 \' (using large chunks gives no performance advantage, but uses more memory)\n Dim chunkSize As Long: chunkSize = 1\n Dim startOffset As Long: startOffset = lastRow + 1 \' 0-based\n Do \' Loop invariant: startOffset>=0 and all rows after startOffset are blank (i.e. wholeRng.Rows(i+1) for i>=startOffset)\n startOffset = IIf(startOffset - chunkSize >= 0, startOffset - chunkSize, 0)\n \' Fill `vals(1 To chunkSize, 1 To 1)` with column\'s rows indexed `[startOffset+1 .. startOffset+chunkSize]` (1-based, inclusive)\n Dim chunkRng As Range: Set chunkRng = wholeRng.Resize(chunkSize).Offset(startOffset)\n Dim vals() As Variant\n If chunkSize > 1 Then\n vals = chunkRng.Value2\n Else \' reading a 1-cell range requires special handling <http://www.cpearson.com/excel/ArraysAndRanges.aspx>\n ReDim vals(1 To 1, 1 To 1)\n vals(1, 1) = chunkRng.Value2\n End If\n\n Dim i As Long\n For i = UBound(vals, 1) To LBound(vals, 1) Step -1\n If Not IsEmpty(vals(i, 1)) Then\n getLastNonblankRowInColumn = startOffset + i\n Exit Function\n End If\n Next i\n\n If chunkSize < MAX_CHUNK_SIZE Then chunkSize = chunkSize * 2\n Loop While startOffset > 0\n\n getLastNonblankRowInColumn = 0\nEnd Function\n</code></pre>\n'}, {'answer_id': 55383256, 'author': 'Sumit Pokhrel', 'author_id': 2690723, 'author_profile': 'https://Stackoverflow.com/users/2690723', 'pm_score': 0, 'selected': False, 'text': '<pre><code>Last_Row = Range("A1").End(xlDown).Row\n</code></pre>\n\n<p>Just to verify, let\'s say you want to print the row number of the last row with the data in cell C1. </p>\n\n<pre><code>Range("C1").Select\nLast_Row = Range("A1").End(xlDown).Row\nActiveCell.FormulaR1C1 = Last_Row\n</code></pre>\n'}, {'answer_id': 71204877, 'author': 'Potocpe1', 'author_id': 8867339, 'author_profile': 'https://Stackoverflow.com/users/8867339', 'pm_score': 0, 'selected': False, 'text': '<p>get last non-empty row using <i>binary search</i></p>\n<ul>\n<li>returns correct value event though there are hidden values</li>\n<li>may returns incorrect value if there are empty cells before last non-empty cells (e.g. row 5 is empty, but row 10 is last non-empty row)</li>\n</ul>\n<pre><code>Function getLastRow(col As String, ws As Worksheet) As Long\n Dim lastNonEmptyRow As Long\n lastNonEmptyRow = 1\n Dim lastEmptyRow As Long\n\n lastEmptyRow = ws.Rows.Count + 1\n Dim nextTestedRow As Long\n \n Do While (lastEmptyRow - lastNonEmptyRow > 1)\n nextTestedRow = Application.WorksheetFunction.Ceiling _\n (lastNonEmptyRow + (lastEmptyRow - lastNonEmptyRow) / 2, 1)\n If (IsEmpty(ws.Range(col & nextTestedRow))) Then\n lastEmptyRow = nextTestedRow\n Else\n lastNonEmptyRow = nextTestedRow\n End If\n Loop\n \n getLastRow = lastNonEmptyRow\n \n\nEnd Function\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8418/']
|
71,195 |
<p>I was thinking about obfuscating a commercial .Net application. But is it really worth the effort to select, buy and use such a tool? Are the obfuscated binaries really safe from reverse engineering?</p>
|
[{'answer_id': 71209, 'author': 'kemiller2002', 'author_id': 1942, 'author_profile': 'https://Stackoverflow.com/users/1942', 'pm_score': 2, 'selected': False, 'text': '<p>No, obfuscation has been proven that it does not prevent someone from being able to decipher the compiled code. It makes it more difficult to do so but not impossible. </p>\n'}, {'answer_id': 71232, 'author': 'Blair Conrad', 'author_id': 1199, 'author_profile': 'https://Stackoverflow.com/users/1199', 'pm_score': 6, 'selected': True, 'text': '<p>You may not have to buy a tool - Visual Studio.NET comes with a community version of Dotfuscator. Other free obfuscation tools <a href="http://twit88.com/blog/2007/09/15/free-net-obfuscation-tools/" rel="noreferrer">are listed here</a>, and they may meet your needs.</p>\n\n<p>It\'s possible that the obfuscated binaries aren\'t safe from reverse engineering, just like it\'s possible that your bike lock might be breakable/pickable. However, it\'s often the case that a small inconvenience is enough to deter would be code/bicycle thieves.</p>\n\n<p>Also, if ever it comes time to assert your rights to a piece of code in court, having been seen to make an effort to protect it (by obfuscating it) may give you extra points. :-)</p>\n\n<p>You do have to consider the downsides, though - it can be more difficult to use reflection with obfuscated code, and if you\'re using something like log4net to generate parts of log lines based on the name of the class involved, these messages can become much more difficult to interpret.</p>\n'}, {'answer_id': 71247, 'author': 'Martin', 'author_id': 11481, 'author_profile': 'https://Stackoverflow.com/users/11481', 'pm_score': 1, 'selected': False, 'text': '<p>It\'s quite simple to reverse engineer a .net app using <a href="http://www.red-gate.com/products/reflector/" rel="nofollow noreferrer">.net reflector</a> - since the app will generate VB, VC and C# code straight from the MSIL, and it\'s possible to pull out all kinds of useful gems.</p>\n\n<p>Code obfuscators hide code quite well from most reverse engineering hacks, and would be a good idea to use on proprietary and competitive code that adds value to your app.</p>\n\n<p><a href="https://web.archive.org/web/20210802164229/https://aspnet.4guysfromrolla.com/demos/printPage.aspx?path=/articles/080404-1.aspx" rel="nofollow noreferrer">There\'s a pretty good article on obfuscation and it\'s workings here</a></p>\n'}, {'answer_id': 71274, 'author': 'Magnus Johansson', 'author_id': 3584, 'author_profile': 'https://Stackoverflow.com/users/3584', 'pm_score': 2, 'selected': False, 'text': '<blockquote>\n <p>...snip... \n these messages can become much more\n difficult to interpret</p>\n</blockquote>\n\n<p>Yes, but the free community edition that comes with Visual Studio has a map functionality.\nWith that you can back track the obfuscated method names to the original names.</p>\n'}, {'answer_id': 71276, 'author': 'harriyott', 'author_id': 5744, 'author_profile': 'https://Stackoverflow.com/users/5744', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve had success putting the output from one free obfuscator <a href="http://harriyott.com/2008/09/obfuscations-what-you-need-if-you-want.aspx" rel="nofollow noreferrer">into a different obfuscator</a>. In Dotfuscator CE, only some of the obfuscation tricks are included, so using a second obfuscator that has different tricks makes it more obfuscated.</p>\n'}, {'answer_id': 71280, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 3, 'selected': False, 'text': '<p>The fact that you actually can reverse engineer it does not make obfuscation useless. It does raise the bar significantly. </p>\n\n<p>An unobfuscated .NET assembly will show you all the source, highlighted and all just by downloading the <a href="http://en.wikipedia.org/wiki/.NET_Reflector" rel="noreferrer">.NET Reflector</a>. Add obfuscation to that and you\'ll reduce very significatively the amount of people who\'ll be able to modify the code.</p>\n\n<p>It depends on you are you protecting yourself from. If you\'ll ship it unobfuscated, you might as well open source the application and benefit from marketing. Shipping it obfuscated will only allow people to relatively easily generate modified binaries through patches instead of being able to steal your code and create a direct competitor. Getting the actual source from obfuscated code is very hard, depending on the obfuscator, of course.</p>\n'}, {'answer_id': 71317, 'author': 'RickL', 'author_id': 7261, 'author_profile': 'https://Stackoverflow.com/users/7261', 'pm_score': 4, 'selected': False, 'text': '<p>At our company we evaluated several different obfuscation technologies, but they all had problems. The biggest problem was that we rely a lot on reflection, e.g. to dynamically create grids based upon property names.</p>\n\n<p>So all of the obfuscators rename things, you can disable it of course, but then you lose a lot of the benefit of obfuscation.</p>\n\n<p>Also, in our code we have a lot of NUnit tests which rely on a lot more of the methods and properties being public, this prevented some of the obfuscators from being able to obfuscate those classes.</p>\n\n<p>In the end we settled on a product called <a href="http://www.eziriz.com/" rel="noreferrer">.NET Reactor</a></p>\n\n<p>It works very well, and we don\'t have any of the problems associated with the other products.</p>\n\n<p>"In contrast to obfuscators .NET Reactor completely stops any decompiling by mixing any pure .NET assembly (written in C#, VB.NET, Delphi.NET, J#, MSIL...) with native machine code. In detail, .NET Reactor builds a native wall between potential hackers and your .NET code. The result is a standard Windows based, not MSIL compatible, file. The original .NET code remains intact, well protected by native code and invisible for prying eyes. The original .NET code is not copied on harddisk at any time. There is no tool which is able to decompile .NET Reactor protected assemblies."</p>\n'}, {'answer_id': 72102, 'author': 'Doron Yaacoby', 'author_id': 3389, 'author_profile': 'https://Stackoverflow.com/users/3389', 'pm_score': 2, 'selected': False, 'text': "<p>I think that it depends on the type of your product. If it is directed to be used by developers - obfuscation will hurt your customers. We've been using the ArcGIS products at work, and all the DLLs are obfuscated. It's making our job a lot harder, since we can't use Reflector to decipher weird behaviors. And we're buying customers who paid thousands of dollars for the product.</p>\n\n<p>So please, don't obfuscate unless you really have to.</p>\n"}, {'answer_id': 72135, 'author': 'Leigh Caldwell', 'author_id': 3267, 'author_profile': 'https://Stackoverflow.com/users/3267', 'pm_score': 1, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/31882/why-should-i-use-obfuscation#31902">This post</a> and the surrounding question have some discussion which might be of value. It isn\'t a yes-or-no issue.</p>\n'}, {'answer_id': 72177, 'author': 'Jay Bazuzi', 'author_id': 5314, 'author_profile': 'https://Stackoverflow.com/users/5314', 'pm_score': 5, 'selected': False, 'text': "<p>Remember that obfuscation is only a barrier to the casual examiner of your code. If someone is serious about figuring out what you wrote, you will have a very hard time stopping them.</p>\n\n<p>If you have secrets in your code (like passwords), you're doing it wrong.</p>\n\n<p>If you worried someone might produce your own software with your ideas, you'll have more luck in the marketplace by providing new versions that your customers want, with technical support, and by being a partner to them. Good business wins.</p>\n"}, {'answer_id': 1600687, 'author': 'Mandrake', 'author_id': 192561, 'author_profile': 'https://Stackoverflow.com/users/192561', 'pm_score': 2, 'selected': False, 'text': '<p>I am very confortable reading x86 assembly code, what about people that is working with assembly for more than 20 years ?</p>\n\n<p>You will always find someone that only need a minute to see what your c# or c code is doing...</p>\n'}, {'answer_id': 2138406, 'author': 'Nick M', 'author_id': 259097, 'author_profile': 'https://Stackoverflow.com/users/259097', 'pm_score': 2, 'selected': False, 'text': "<p>Just a note to anyone else reading this years later - I just skimmed through the Dotfuscator Community Edition (that comes with VS2008) license a few hours ago, and I believe that you cannot use this version to distribute a commercial product, or to obfuscate code from a project that involves any developers other than yourself. So for commercial app developers, it's really just a trial version.</p>\n"}, {'answer_id': 2585240, 'author': 'Daniel Dolz', 'author_id': 307280, 'author_profile': 'https://Stackoverflow.com/users/307280', 'pm_score': 0, 'selected': False, 'text': "<p>Yes, we do. We use BitHelmet obfuscator. It's new, but it works really well.</p>\n"}, {'answer_id': 2706291, 'author': 'ileon', 'author_id': 269595, 'author_profile': 'https://Stackoverflow.com/users/269595', 'pm_score': 1, 'selected': False, 'text': '<p>Yes you definitely should. Not to protect it from a determined person, but to get some profit and have customers. By the way, if you reach a point here someone tries to crack your software, that means you sell a popular software.</p>\n\n<p>The problem is what tool to choose for the job. Check out my experience with commercial obfuscators: <a href="https://stackoverflow.com/questions/337134/what-is-the-best-net-obfuscator-on-the-market/2356575#2356575">https://stackoverflow.com/questions/337134/what-is-the-best-net-obfuscator-on-the-market/2356575#2356575</a></p>\n'}, {'answer_id': 2706329, 'author': 'ChrisW', 'author_id': 49942, 'author_profile': 'https://Stackoverflow.com/users/49942', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n <p>But is it really worth the effort to select, buy and use such a tool?</p>\n</blockquote>\n\n<p>I found Eazfuscator cheap (free), and easy to use: took about a day.\nI already had extensive automated tests (good coverage), so I reckon I could find any bugs that are/were introduced by obfuscation.</p>\n'}, {'answer_id': 23164511, 'author': 'Axel', 'author_id': 3550434, 'author_profile': 'https://Stackoverflow.com/users/3550434', 'pm_score': 2, 'selected': False, 'text': '<p>Things you should take into account:</p>\n\n<ul>\n<li><strong>Obfuscation does not protect your code or logic.</strong> It just makes it harder to read and understand. </li>\n<li><strong>Obfuscation does no one stop from reverse engineering.</strong> It just slows the process down.</li>\n<li><strong>Your intellectual property is protected by law in most countries.</strong> So if an competitor uses your code or specific implementation, you can sue him.</li>\n</ul>\n\n<p><strong>The one and only problem obfuscation can solve is that someone creates a 1:1 (or close to 1:1) copy of your specific implementation.</strong></p>\n\n<p>Also in an ideal world reverse engineering of an obfuscated application is economical unattractive.</p>\n\n<p>But back to reality:</p>\n\n<ul>\n<li><strong>There exists no tool on this planet that stops someone from copying user interfaces, behaviors or results any application provide or produce.</strong> Obfuscation is in this situations 100% useless</li>\n<li><strong>The best obfuscator on the market cannot stop one from using some kind of disassembler or hex editor</strong> and for some geeks this is pretty good to look into the heart of an application. It\'s just harder than on an unobfuscated code.</li>\n</ul>\n\n<p>So the reality is that you can make it harder and more time consuming to look into your application but you won\'t really get any reliable protection. Regardless if you use a free or an commercial product.</p>\n\n<p>Advanced technologies like control flow obfuscation or code virtualization may help to make understanding of logic sometimes really hard but they can also cause a lot of funny and hard to debug or solve problems. So they are sometimes more like an additional problem than a solution.</p>\n\n<p><strong>From my point of view obfuscation is not worth the money some companies charge for their products.</strong> If you want to nag casual developers, open source obfuscators are good enough. If you want to make it as hard as possible to look into the heart of your applications, you need to use cryptographic containers with virtual execution environments and virtual filesystems but they also provide attack vectors and may also be a source for a bag full of problems.</p>\n\n<p><strong>Your intellectual property and your products are in most countries protected by law.</strong> So if there\'s one competitor analyzing and copying your code, you can sue him. If a bad guy or and hacker or cracker takes your application you are pranked - but an obfuscator does not make a difference.</p>\n\n<p>So you should first think about your targets, your market and what you want to achieve with an obfuscator. <strong>As you can read here (and at other places) obfuscation does not really solve the problem of reverse engineering. It only makes it harder and more time consuming.</strong> But if this is what you want, you may have a look to open source obfuscators like e.g. sharpObfuscator or obfuscar which may be good enough to nag casual coders (a List can be found here: <a href="http://en.wikipedia.org/wiki/List_of_obfuscators_for_.NET" rel="nofollow noreferrer">List of .NET Obfuscators on Wikipedia</a>).</p>\n\n<p><strong>If it is possible in your scenario you might also be interested in SaaS-Concepts.</strong> This means that you provide access to your software but not the software itself. So the customer normally has no access to your assemblies. <strong>But depending on service level, security and user base it can be expensive, complex and difficult to realize a reliable, confident and performant SaaS-Service.</strong></p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9602/']
|
71,198 |
<p>I have a problem (and have been having it for some time now) -- the new sound mixer stack in Vista features new cool things, but also re-invents the wheel. Many applications that used to use Volume Mixer on a Windows system to mix different voiced outputs into one input (for example Wave-out + Line-in --> Stereo Mix) have since stopped working. The prime example of this behavior is the Shoutcast DSP plugin (could be useful for solution testing).</p>
<p>How Can I re-enable XP-mixer controls, or maybe emulate this behavior somehow, so that the program (SC DSP) can properly manage Microphone/Line-In playback volume along with Wave-out playback volume?</p>
<p>My thinking would be to emulate a program hooked-in into the Vista Mixer for Wave-Out and Line-out (or Mic speaker volume -- all playback, shown as separate adjustable "programs" so that the Vista Mixer could refer to it) and 'hook' it into the system under some emulation representing itself as the old volume mixer control interface for the program, but I frankly have no idea how to do that.</p>
<p>To clarify: this is not my PC (it is a HP Pavilion laptop). The problem seems to exist mostly due to the fact that Vista mixer controls separate programs, not separate inputs/outputs. The hardware is fully capable of doing what is needed when using Windows XP. I am well aware of the fact that this is a driver issue, but the driver is simply prepared for what Vista presents to the programmer through interfaces. The mixer device - as seen in the operating system, however it might look in software - is based on the mixer APIs for Windows Audio control.</p>
<p>Search using Google on Vista and line-in playback volume control for more info on the problem (and the sheer amount of users affected by it). Of course, a re-write of the Shoutcast Source DSP plug-in for WinAMP would do the trick, but that is not likely to happen...</p>
|
[{'answer_id': 71392, 'author': 'CL.', 'author_id': 11654, 'author_profile': 'https://Stackoverflow.com/users/11654', 'pm_score': 2, 'selected': False, 'text': "<p>The audio driver controls which mixer controls are available, and this will depend largely on the capabilities of the hardware.</p>\n\n<p>If the Vista driver doesn't have certain controls, then it's likely to be a shortcoming of that driver and not of Vista.</p>\n\n<p>(Please tell us which sound card/device you are using.)</p>\n\n<p>It would be possible to write a program to create your own mixer controls (this would be a software-only driver for a virtual sound card), but this program wouldn't be able to affect the audio routing inside the device if the actual driver doesn't have some mixer control for this.</p>\n"}, {'answer_id': 139736, 'author': 'Nick Haddad', 'author_id': 2813, 'author_profile': 'https://Stackoverflow.com/users/2813', 'pm_score': 3, 'selected': True, 'text': '<p>Controlling the volume levels of a soundcards indivudual input/output levels in Windows Vista mixer is possible using the audio <a href="http://msdn.microsoft.com/en-us/library/ms679162(VS.85).aspx" rel="nofollow noreferrer">EndPoint API</a></p>\n\n<p>This should allow you to adjust the main volume, and the volume of and <strong>connected</strong> audio inputs. One wrinkle about this that when you enumerate the end points, if there isn\'t a microphone plugged into your soundcard, then nothing will be enumerated. This means you\'ll need to change your application to respond to "microphone plugged in" events, and notify the user appropriately. </p>\n\n<p>Another option is to dip below the Microsoft Core Audio and access the <a href="http://www.microsoft.com/whdc/device/audio/wavertport.mspx" rel="nofollow noreferrer">WaveRT</a> driver directly. This is a lot more work than using the WASAPI/Endpoint APIs, but will give you the most control over access to the inputs/outputs of the soundcard. </p>\n'}, {'answer_id': 1185768, 'author': 'Larry Osterman', 'author_id': 761503, 'author_profile': 'https://Stackoverflow.com/users/761503', 'pm_score': 2, 'selected': False, 'text': '<p>If you mark your app as running in Windows XP compatibility, then all the old controls and behaviors will come back.</p>\n'}, {'answer_id': 1297432, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<blockquote>\n <p>If you mark your app as running in Windows XP compatibility, then all the old controls and behaviors will come back.</p>\n</blockquote>\n\n<p>This is true, but as of Vista SP1 patch KB957388, included in SP2, and with some soundcard drivers, the old mixer API (winmm.dll) functions can hang when the app is in XP compatibility mode. In particular, mixerGetNumDevs and less often mixerOpen will not return on some computers.</p>\n\n<p>I've got reports from 5 Vista users out of around 200 Vista users in total where my app hangs when starting up, and I have tracked it down to these functions hanging.</p>\n\n<p>I would like to report this to Microsoft but cannot find anywhere to do so.</p>\n\n<p>All I can do now is release my software without compatibility mode enabled, but this loses functionality in my app, and the software cannot control the line-in or microphone mixers.</p>\n\n<p>I don't have time to work with low level API functions directly. I rely on high level components, and I cannot find any for the new audio API's for my development system (Delphi).</p>\n\n<p>I would be interested in paying someone to write a DLL for me!!!\ne mail ross att stationplaylist dott com</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71198', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/456146/']
|
71,201 |
<p>I'm developing a web service whose methods will be called from a "dynamic banner" that will show a sort of queue of messages read from a sql server table.</p>
<p>The banner will have a heavy pressure in the home pages of high traffic sites; every time the banner will be loaded, it will call my web service, in order to obtain the new queue of messages.</p>
<p>Now: I don't want that all this traffic drives queries to the database every time the banner is loaded, so I'm thinking to use the asp.net cache (i.e. HttpRuntime.Cache[cacheKey]) to limit database accesses; I will try to have a cache refresh every minute or so.</p>
<p>Obviously I'll try have the messages as little as possible, to limit traffic.</p>
<p>But maybe there are other ways to deal with such a scenario; for example I could write the last version of the queue on the file system, and have the web service access that file; or something mixing the two approaches...</p>
<p>The solution is c# web service, asp.net 3.5, sql server 2000. </p>
<p>Any hint? Other approaches? </p>
<p>Thanks</p>
<p>Andrea</p>
|
[{'answer_id': 71237, 'author': 'Mike Becatti', 'author_id': 6617, 'author_profile': 'https://Stackoverflow.com/users/6617', 'pm_score': 2, 'selected': False, 'text': '<p>I think caching is a reasonable approach and you can take it a step further and add a SQL Dependency to it. </p>\n\n<p><a href="http://www.c-sharpcorner.com/UploadFile/mosessaur/sqlcachedependency01292006135138PM/sqlcachedependency.aspx?ArticleID=3caa7d32-dce0-44dc-8769-77f8448e76bc" rel="nofollow noreferrer">ASP.NET Caching: SQL Cache Dependency With SQL Server 2000</a></p>\n'}, {'answer_id': 71421, 'author': 'user11826', 'author_id': 11826, 'author_profile': 'https://Stackoverflow.com/users/11826', 'pm_score': 1, 'selected': False, 'text': '<p>Writing a file is a better solution IMHO - its served by IIS kernel code, w/o the huge asp.net overhead and you can copy the file to CDNs later.</p>\n\n<p>AFAIK dependency cashing is not very efficient with SQL Server 2000.</p>\n'}, {'answer_id': 71445, 'author': 'Mike Becatti', 'author_id': 6617, 'author_profile': 'https://Stackoverflow.com/users/6617', 'pm_score': 1, 'selected': False, 'text': '<p>If you go the file route, keep this in mind.</p>\n\n<p><a href="http://petesbloggerama.blogspot.com/2008/02/aspnet-writing-files-vs-application.html" rel="nofollow noreferrer">http://petesbloggerama.blogspot.com/2008/02/aspnet-writing-files-vs-application.html</a></p>\n'}, {'answer_id': 71596, 'author': 'Sklivvz', 'author_id': 7028, 'author_profile': 'https://Stackoverflow.com/users/7028', 'pm_score': 3, 'selected': True, 'text': '<p>It depends on a lot of things:</p>\n\n<ul>\n<li>If there is little change in the data (think backend with "publish" button or daily batches), then I would definitely use static files (updated via push from the backend). We used this solution on a couple of large sites and worked really well.</li>\n<li>If the data is small enough, memory caching (i.e. Http Cache) is viable, but beware of locking issues and also beware that Http Cache <strong>will not</strong> work that well under heavy memory load, because items can be expired early if the framework needs memory. I have been bitten by it before! With the above caveats, Http Cache works quite well.</li>\n</ul>\n'}, {'answer_id': 77530, 'author': 'Mitchel Sellers', 'author_id': 13279, 'author_profile': 'https://Stackoverflow.com/users/13279', 'pm_score': 0, 'selected': False, 'text': "<p>Also, one way to get around the memory limitation mentioned by Skliwz is that if you are using this service outside of the normal application you can isolate it in it's own app pool. I have seen this done before which helps as well.</p>\n"}, {'answer_id': 81198, 'author': 'ila', 'author_id': 1178, 'author_profile': 'https://Stackoverflow.com/users/1178', 'pm_score': 0, 'selected': False, 'text': "<p>Thanks all, as the data are little in size, but the underlying tables will change, I think that I'll go the HttpCache way: I need actually a way to reduce db access, even if the data are changing (so that's the reason to not using a direct Sql dependency as suggested by @Bloodhound).</p>\n\n<p>I'll make some stress test before going public, I think.</p>\n\n<p>Thanks again all.</p>\n"}, {'answer_id': 404798, 'author': 'Sklivvz', 'author_id': 7028, 'author_profile': 'https://Stackoverflow.com/users/7028', 'pm_score': 0, 'selected': False, 'text': '<p>Of course you could (should) also use the caching features in the <a href="http://code.google.com/p/sixpack-library/" rel="nofollow noreferrer">SixPack library</a> .</p>\n\n<ul>\n<li>Forward (normal) cache, based on HttpCache, which works by putting attributes on your class. Simplest to use, but in some cases you have to wait for the content to be actually be fetched from database.</li>\n<li>Pre-fetch cache, from scratch, which, after the first call will start refreshing the cache behind the scenes, and you are guaranteed to have content without wait in some cases.</li>\n</ul>\n\n<p>More info on the <a href="http://code.google.com/p/sixpack-library/" rel="nofollow noreferrer">SixPack library homepage</a>. Note that the code (especially the forward cache) is load tested.</p>\n\n<p>Here\'s an example of simple caching:</p>\n\n<pre><code> [Cached]\n public class MyTime : ContextBoundObject\n {\n [CachedMethod(1)]\n public DateTime Get()\n {\n Console.WriteLine("Get invoked.");\n return DateTime.Now;\n }\n }\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1178/']
|
71,203 |
<p>Our installer is written with Inno Setup and we are actually quite happy with it. Yet some customers keep asking for an MSI installer which they could more easily distribute via Active Directory. We have already gone to some lengths to make the installer deal really well with automated and unattended installations by extending Inno Setup's <code>/LOADINF</code>-mechanism with our own options.</p>
<p>In order to satisfy the customers asking for MSI, I had been thinking about simply wrapping our regular installer inside an MSI, possibly created using WIX. The question is: can I maintain the high configurability which our current installer offers that way? How would I go about exposing the Inno Setup installer's options through the outer MSI in the unattended/mass installation scenario?</p>
<p>Note that I haven't really gotten to the point of actually digging into MSI-creation and WIX myself yet. Right now I'm only interested in whether people who do know what they're talking about think this would be a feasible/sensible approach to invest our energy in in the first place...</p>
<p>[EDIT:]
Initially I thought I could do with the temp extraction and execution approach, i.e. the MSI would simply serve as a vessel for delivering the Inno installer to the target PC and executing it there in <code>/VERYSILENT</code>-mode. But I guess the customers who ask for the MSI also want to be able to uninstall or even modify the install from a central location and I guess that won't be possible in that scenario, would it?</p>
<p>P.S.: We do have an old copy of WISE for MSI here as well but that experience was actually the reason why we started using Inno instead to begin with...</p>
|
[{'answer_id': 71283, 'author': 'Roel', 'author_id': 11449, 'author_profile': 'https://Stackoverflow.com/users/11449', 'pm_score': 5, 'selected': True, 'text': "<p>No, there's no way to do that while still keeping the functionality your customers are 'implicitly' asking for. The only 'wrapping' in MSI you can do is to extract it on installation and start your InnoSetup installer from the temporary location where you extracted to. MSI is a fundamentally different way of working: InnoSetup (& NSIS & most other installers) take a code-centric approach: you 'program' the 'steps' to install your data. MSI is a database and takes a 'data-centric' approach: you indicate what files should be installed and the MSI 'runtime' does the rest. This gives you versioning and exact control of what goes where.</p>\n\n<p>In short, to give your customers what they want (i.e., the ease of deployment that MSI brings with AD), you'll need 'proper' MSI's. Good luck with that, it's a major pain IMHO. But it does give good results once you master MSI & WiX.</p>\n"}, {'answer_id': 71700, 'author': 'Vytautas Šaltenis', 'author_id': 6763, 'author_profile': 'https://Stackoverflow.com/users/6763', 'pm_score': 1, 'selected': False, 'text': "<p>Doing so would be pretty much equivalent to delivering a ZIP file and calling unzip by the end of installation.</p>\n\n<p>With such approach AD and Windows Installer would be fooled as if dealing with proper MSI installation, but as it is not the case, they'd backfire on you on the very first occasion.</p>\n\n<p>Don't go this way.</p>\n\n<p>And WiX is superior toolset to InnoSetup, anyway, so the time you'll spend on learning and porting will pay off by better support of collaboration.</p>\n"}, {'answer_id': 72664, 'author': 'Roel', 'author_id': 11449, 'author_profile': 'https://Stackoverflow.com/users/11449', 'pm_score': 2, 'selected': False, 'text': "<p>In response to your edit: yes, what you describe will prevent doing upgrades (other than delete/reinstall) and remote configuration, since the MSI database won't know anything about the contents of your installer.</p>\n\n<p>Many installer packages started MSI 'support' in this way, though: InstallShield did, for example. That's the main reason I dumped them, because installers made in that way are useless for MSI purposes. I don't know if recent versions of InstallShield are better, last time I checked was 5 years ago.</p>\n"}, {'answer_id': 201131, 'author': 'Tom', 'author_id': 20979, 'author_profile': 'https://Stackoverflow.com/users/20979', 'pm_score': 2, 'selected': False, 'text': '<p>Its pretty easy to make a wrapper kit that automatically installs INNOSETUPper from MSI. For basic functionality (install/uninstall) this is enough. Most setuppers do not implement repair anyway.</p>\n\n<ol>\n<li><p>create silent.inf script for INNO Setup (optional)</p></li>\n<li><p>create install.bat that calls</p>\n\n<p>myinnosetup.exe /silent /NOCANCEL /norestart /Components="xxx"</p>\n\n<p>you can use /verysilent<br>\n you can load settings from silent.inf with /LOADINF="silent.inf"</p></li>\n<li><p>create MSI setup file that calls install.bat ( with parameters if necessary)</p></li>\n<li><p>deliver all 4 files to your customer and they can deploy your Inno setupper with SMS or ActiveDirectory and everyone is happy :)</p></li>\n</ol>\n'}, {'answer_id': 232183, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>although the last comment is feasible and workable, moving to MSI is the best way to handle this. </p>\n\n<p>almost all large organisations stipulate MSI only, there are multitudes of reasons why. </p>\n\n<p>1) first is ease of deployment\n2) more important to some is application sociability \n3) self healing</p>\n\n<p>inno setup and other such tools not implementing Windows Installer simply cannot offer application sociability in the same ways as windows installer. </p>\n\n<p>you have to understand Inno setup is software designed to deploy a single application. </p>\n\n<p>Windows Installer is an entire framework to deal with sociability, user impersonation, user elevation, self healing, user profile fix up. </p>\n\n<p>They two are not even remotely close in functionality, inno setup in my mind is completely and utterly way off course in terms of comparing with windows installer. </p>\n\n<p>Can it create successful installers ? yes \nIs it easy to use ? yes \nDoes it create good single installers ? yes \nIs it the best choice for enterprise ? no</p>\n\n<p>The earliest tools developed by microsoft "SMS Installer" was innosetup 10 years ago. Things have changed drastically in the install world and inno setup simply hasnt kept up with the pace of that change. </p>\n'}, {'answer_id': 509120, 'author': 'Rob Hunter', 'author_id': 1145, 'author_profile': 'https://Stackoverflow.com/users/1145', 'pm_score': 2, 'selected': False, 'text': '<p>I would argue that it is possible to do all that you would like with an MSI wrapped Inno Setup, but it is far from trivial, and using WiX might make this particular task more difficult. In short I would not really recommend it.</p>\n\n<p>But if you really would like to...</p>\n\n<p>MSI files are simply database files with additional script instructions and often embed the .cab file that contains the stuff you actually want to install.</p>\n\n<p>If you use Wise, you will generate default scripts that you can then add Windows Installer conditions to and control the events to a finer degree (Install, repair, modify, uninstall) so that they call equivalent actions on your Inno Setup install script which would need to be installed into and kept in a temporary folder.</p>\n'}, {'answer_id': 858292, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>I need to input a custome value on the silent.inf (not a stablished inno setup setting value) dosent look like LOADINF allows for that.</p>\n\n<p>Note:If you use makemsi you do not have to include a bat as you can use $WrapInstall.</p>\n'}, {'answer_id': 1244926, 'author': 'coding Bott', 'author_id': 44462, 'author_profile': 'https://Stackoverflow.com/users/44462', 'pm_score': 2, 'selected': False, 'text': '<p>It makes no sense mixing install technologies.</p>\n\n<p>If you are mixing you getting the first problem with the uninstall stuff.\nwithout changes you get 2 uninstallers of your program. </p>\n\n<p>there are some articles starting with windows installer in the "entwickler magazine"</p>\n\n<ul>\n<li>Entwickler Magazin (Ausgabe: 03.09/15.04.2009) Artikel: MSI-Pakete mit Open-Souce-Software erzeugen Teil\n4</li>\n<li>Entwickler Magazin (Ausgabe: 02.09/12.02.2009) Artikel: MSI-Pakete mit Open-Souce-Software erzeugen Teil\n3</li>\n<li>Entwickler Magazin (Ausgabe: 01.09/10.12.2008) Artikel: MSI-Pakete mit Open-Souce-Software erzeugen Teil\n2</li>\n<li>Entwickler Magazin (Ausgabe: 06.08/15.10.2008) Artikel: MSI-Pakete mit Open-Souce-Software erzeugen</li>\n</ul>\n\n<p><a href="http://entwickler-magazin.de/" rel="nofollow noreferrer">http://entwickler-magazin.de/</a></p>\n\n<p>windows installer should be the only technology for your installations.\nits future proof and its stable!</p>\n'}, {'answer_id': 12080164, 'author': 'Jacob', 'author_id': 1617989, 'author_profile': 'https://Stackoverflow.com/users/1617989', 'pm_score': 4, 'selected': False, 'text': '<p>I have had this problem many times myself. Therefore, I created a standard way to approach this problem and it resulted in a wizard that will guide you through the steps. The tool will support the following:</p>\n\n<ol>\n<li>Wrap the exe in an MSI.</li>\n<li>Support Uninstall.</li>\n<li>Only show one program in "Add or Remove programs".</li>\n<li>Allow you to pass command line arguments such as /SILENT to the embedded setup when you run the MSI package with MSIEXEC.EXE.</li>\n</ol>\n\n<p>You can get it at <a href="http://www.exemsi.com">http://www.exemsi.com</a> (the basic version is free)</p>\n\n<p>Use my contact form and let me know what you think :-)</p>\n'}, {'answer_id': 14925200, 'author': 'J. Rasmussen', 'author_id': 2081153, 'author_profile': 'https://Stackoverflow.com/users/2081153', 'pm_score': 2, 'selected': False, 'text': '<p>Wrapping an Inno Setup in an MSI package is not a trivial task. However, it is possible. There are lots of free tools out there that can be used to do this. You should choose one that also supports uninstall(s) and upgrades. </p>\n\n<p>I have found only one free tool that supports upgrades and uninstall. Check out <a href="http://www.exemsi.com/inno-setup-and-msi" rel="nofollow">http://www.exemsi.com/inno-setup-and-msi</a></p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9784/']
|
71,204 |
<p>Why can I not see an <strong>option</strong> for copying database objects when I <code>right click > tasks</code> on my database? </p>
|
[{'answer_id': 71408, 'author': 'dpollock', 'author_id': 7884, 'author_profile': 'https://Stackoverflow.com/users/7884', 'pm_score': 3, 'selected': True, 'text': '<p>MS Sql Server Express doesn\'t come with SSIS which is what you will need to import/export objects out of your database.</p>\n\n<p>You can also manually script this process. One way is to use BCP (<a href="http://msdn.microsoft.com/en-us/library/ms162802.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms162802.aspx</a>)</p>\n'}, {'answer_id': 71942, 'author': 'Portman', 'author_id': 1690, 'author_profile': 'https://Stackoverflow.com/users/1690', 'pm_score': 0, 'selected': False, 'text': '<p>Have a look at Red Gate <a href="http://www.red-gate.com/products/SQL_Compare/index.htm" rel="nofollow noreferrer">SQL Compare</a> and <a href="http://www.red-gate.com/products/SQL_Data_Compare/index.htm" rel="nofollow noreferrer">SQL Data Compare</a>.</p>\n\n<p>You can download the trial and use them to build a script that will dump your objects to a .sql file.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11757/']
|
71,223 |
<p>I'm currently writing a TYPO3 extension which is configured with a list of <code>tt_content</code> UID's.
These point to content elements of type "text" and i want to render them by my extension.</p>
<p>Because of TYPO3s special way of transforming the text you enter in the rich text editing when it enters the database, and again transforming it when it is rendered to the frontend, i can not just output the database contents of the <code>bodytext</code> field.</p>
<p>I want to render these texts as they would usually get rendered by TYPO3.
How do I do that? </p>
|
[{'answer_id': 71272, 'author': 'Jan Hančič', 'author_id': 185527, 'author_profile': 'https://Stackoverflow.com/users/185527', 'pm_score': 4, 'selected': True, 'text': "<p>I had the same problem a couple of months ago. Now I must say that I am no typo3 developer, so I don't know if this is the right solution.</p>\n\n<p>But I used something like this:</p>\n\n<p><code>$output .= $this->pi_RTEcssText( $contentFromDb );</code></p>\n\n<p>in my extension and it works.</p>\n"}, {'answer_id': 2592788, 'author': 'cweiske', 'author_id': 282601, 'author_profile': 'https://Stackoverflow.com/users/282601', 'pm_score': 3, 'selected': False, 'text': '<h2>PHP</h2>\n\n<p>That works for me; it renders any content element with the given ID:</p>\n\n<pre><code>function getCE($id)\n{\n $conf[\'tables\'] = \'tt_content\';\n $conf[\'source\'] = $id;\n $conf[\'dontCheckPid\'] = 1;\n return $GLOBALS[\'TSFE\']->cObj->cObjGetSingle(\'RECORDS\', $conf);\n}\n</code></pre>\n\n<p>See <a href="http://lists.typo3.org/pipermail/typo3-dev/2007-May/023467.html" rel="nofollow noreferrer">http://lists.typo3.org/pipermail/typo3-dev/2007-May/023467.html</a></p>\n\n<p>This does work for non-cached plugins, too. You will get a string like <code><!--INT_SCRIPT.0f1c1787dc3f62e40f944b93a2ad6a81--></code>, but TYPO3 will replace that on the next INT rendering pass with the real content.</p>\n\n<h2>Fluid</h2>\n\n<p>If you\'re in a fluid template, the <a href="https://fluidtypo3.org/viewhelpers/vhs/master/Content/RenderViewHelper.html" rel="nofollow noreferrer">VHS <code>content.render</code> view helper</a> is useful:</p>\n\n<pre><code><v:content.render contentUids="{0: textelementid}"/>\n</code></pre>\n\n<p>If your fluidcontent element has a grid itself, you can render the elements with flux\' own <code>content.get</code> or <code>content.render</code> view helper:</p>\n\n<pre><code><f:section name="Configuration>\n ... <flux:grid.column name="teaser"/> ...\n</f:section>\n<f:section name="Main>\n <flux:content.render area="teaser"/>\n<f:section>\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4186/']
|
71,226 |
<p>I am using a .NET Windows Forms DataGridView and I need to edit a DataBound column (that binds on a boolean DataTable column). For this I specify the cell template like this:</p>
<p>DataGridViewColumn column = new DataGridViewColumn(new DataGridViewCheckBoxCell());</p>
<p>You see that I need a CheckBox cell template.</p>
<p>The problem I face is that this column is constantly readonly/disabled, as if it would be of TextBox type. It doesn't show a checkbox at all.</p>
<p>Any thoughts on how to work with editable checkbox columns for DataGridView?</p>
<p>Update: For windows forms, please.</p>
<p>Thanks.</p>
|
[{'answer_id': 71252, 'author': 'Biri', 'author_id': 968, 'author_profile': 'https://Stackoverflow.com/users/968', 'pm_score': 0, 'selected': False, 'text': '<p>Create a TemplateField and bound the id to it, something like this:</p>\n\n<pre><code><asp:TemplateField HeaderText="Whatever" SortExpression="fieldname" ItemStyle-HorizontalAlign="Center">\n <ItemTemplate>\n <asp:CheckBox runat="server" ID="rowCheck" key=\'<%# Eval("id") %>\' />\n </ItemTemplate>\n</asp:TemplateField>\n</code></pre>\n'}, {'answer_id': 74298, 'author': 'Phillip Wells', 'author_id': 3012, 'author_profile': 'https://Stackoverflow.com/users/3012', 'pm_score': 1, 'selected': False, 'text': '<p>Instead of trying to create the column in code, click on the tiny arrow in a box at the top right of the DataGridView control, and select "Edit Columns..." from the menu that appears. In the dialog box, click the Add button, then choose the "Databound column" option and pick the boolean column you\'re binding to.</p>\n'}, {'answer_id': 81252, 'author': 'Vasile Tomoiaga', 'author_id': 2130892, 'author_profile': 'https://Stackoverflow.com/users/2130892', 'pm_score': 3, 'selected': False, 'text': '<p>Well, after more than 4 hours of debugging, I have found that the DataGridView row height was too small for the checkbox to be painted, so it was not displayed at all. I have found this after an accidental row height resizing.</p>\n\n<p>As a solution, you can set the AutoSizeRowsMode to AllCells.</p>\n\n<p><code>richDataGrid.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;</code></p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2130892/']
|
71,239 |
<p>It looks like <a href="http://brew.qualcomm.com/brew/" rel="nofollow noreferrer">BREW</a> 4.0 will have Lua included. But is it possible to use Lua on older BREW 3.0 (or even BREW 2.0)?</p>
|
[{'answer_id': 73522, 'author': 'realsugar', 'author_id': 6885, 'author_profile': 'https://Stackoverflow.com/users/6885', 'pm_score': 2, 'selected': False, 'text': '<p>It is possible, but you will have to link lua interpreter source code to your application source code and wrap BREW API functions in order to use them from lua scripts.</p>\n\n<p>Check out <a href="http://luaforge.net/projects/luabrew" rel="nofollow noreferrer">LuaBREW</a> project as an example of approach I briefly explained above.</p>\n'}, {'answer_id': 133156, 'author': 'Airsource Ltd', 'author_id': 18017, 'author_profile': 'https://Stackoverflow.com/users/18017', 'pm_score': 2, 'selected': False, 'text': "<p>We did this. I ported Lua to BREW turning it into a uiOne actor. Worked well, took about 3 days to get it working properly, mostly on the actor side. As far as I recall there was nothing in there that wouldn't have worked on BREW 2.1.</p>\n"}, {'answer_id': 162670, 'author': 'Ringoman', 'author_id': 24509, 'author_profile': 'https://Stackoverflow.com/users/24509', 'pm_score': 1, 'selected': False, 'text': "<p>We don't wait BREW 4.0. We are writing our LuaBREW implementation right now.</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11587/']
|
71,248 |
<p>I would like to debug an embedded system containing gdb remotely using some kind of gui (ie like ddd). The embedded system does not have the sources or build symbols. However my local x windows box has. However the execution must happen on the embedded system. How can I from my development box drive gdb remotely with some gui ? </p>
<p>leds and jtag are not an option. </p>
|
[{'answer_id': 71268, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': True, 'text': '<p>I think, gdbserver could help you.</p>\n'}, {'answer_id': 4675868, 'author': 'FractalSpace', 'author_id': 175169, 'author_profile': 'https://Stackoverflow.com/users/175169', 'pm_score': 2, 'selected': False, 'text': '<p>On Remote target:</p>\n\n<pre><code>target> gdbserver localhost:1234 <application>\n</code></pre>\n\n<p>On Host (build machine):</p>\n\n<pre><code>host> gdb <application>\n</code></pre>\n\n<p>Note that the on target may be stripped off from the symbols. But host may have all the symbols.</p>\n\n<pre><code>gdb> set <path-to-libs-search>\ngdb> target remote <target-ip>:1234\ngdb> break main\ngdb> cont\n</code></pre>\n\n<p>If this works, get some GDB gui on the host machine and try to replicate the same settings. (I have used SlickEdit and eclipse for this purpose).</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
71,254 |
<p>When viewing someone else's webpage containing an applet, how can I force Internet Explorer 6.0 to use a a particular JRE when I have several installed?</p>
|
[{'answer_id': 71329, 'author': 'BrezzaP', 'author_id': 11766, 'author_profile': 'https://Stackoverflow.com/users/11766', 'pm_score': 2, 'selected': False, 'text': '<p>For the server-side solution (which your question was originally ambiguous about), <a href="http://java.sun.com/j2se/1.5.0/docs/guide/plugin/developer_guide/using_tags.html" rel="nofollow noreferrer">this page at sun</a> lists one way to specify a JRE. Specifically, </p>\n\n<pre><code><OBJECT \n classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"\n width="200" height="200">\n <PARAM name="code" value="Applet1.class">\n</OBJECT>\n</code></pre>\n\n<blockquote>\n <p>The classid attribute identifies which\n version of Java Plug-in to use.</p>\n \n <p>Following is an alternative form of\n the classid attribute:</p>\n\n<pre><code>classid="clsid:CAFEEFAC-xxxx-yyyy-zzzz-ABCDEFFEDCBA"\n</code></pre>\n \n <p>In this form, "xxxx", "yyyy", and\n "zzzz" are four-digit numbers that\n identify the specific version of Java\n Plug-in to be used. </p>\n \n <p>For example, to use Java Plug-in\n version 1.5.0, you specify:</p>\n\n<pre><code>classid="clsid:CAFEEFAC-0015-0000-0000-ABCDEFFEDCBA"\n</code></pre>\n</blockquote>\n'}, {'answer_id': 71657, 'author': 'Stephen Denne', 'author_id': 11721, 'author_profile': 'https://Stackoverflow.com/users/11721', 'pm_score': 0, 'selected': False, 'text': '<p>Use the <a href="http://java.sun.com/javase/downloads/ea/6u10/deploymentToolkit.jsp" rel="nofollow noreferrer">deployment Toolkit</a>\'s <a href="http://java.com/js/deployJava.js" rel="nofollow noreferrer">deployJava.js</a> (though this ensures a minimum version, rather than a specific version)</p>\n'}, {'answer_id': 71717, 'author': 'Stephen Denne', 'author_id': 11721, 'author_profile': 'https://Stackoverflow.com/users/11721', 'pm_score': -1, 'selected': True, 'text': '<p>If you mean when you are not the person writing the web page, then you could disable the add ons you do not wish to use with the <a href="http://windowsxp.mvps.org/addons.htm" rel="nofollow noreferrer">Manage Add-Ons</a> IE Options screen added in Win XP SP2</p>\n'}, {'answer_id': 277661, 'author': 'Daniel Cassidy', 'author_id': 31662, 'author_profile': 'https://Stackoverflow.com/users/31662', 'pm_score': 6, 'selected': False, 'text': "<p>First, disable the currently installed version of Java. To do this, go to <strong>Control Panel > Java > Advanced > Default Java for Browsers</strong> and uncheck <strong>Microsoft Internet Explorer</strong>.</p>\n\n<p>Next, enable the version of Java you want to use instead. To do this, go to (for example) <strong>C:\\Program Files\\Java\\<i>jre1.5.0_15</i>\\bin</strong> (where <strong>jre1.5.0_15</strong> is the version of Java you want to use), and run <strong>javacpl.exe</strong>. Go to <strong>Advanced > Default Java for Browsers</strong> and check <strong>Microsoft Internet Explorer</strong>.</p>\n\n<p>To get your old version of Java back you need to reverse these steps.</p>\n\n<p>Note that in older versions of Java, <strong>Default Java for Browsers</strong> is called <strong><APPLET> Tag Support</strong> (but the effect is the same).</p>\n\n<p>The good thing about this method is that it doesn't affect other browsers, and doesn't affect the default system JRE.</p>\n"}, {'answer_id': 277693, 'author': 'Jack Leow', 'author_id': 31506, 'author_profile': 'https://Stackoverflow.com/users/31506', 'pm_score': 1, 'selected': False, 'text': "<p>I'd give all the responses here a try first. But I wanted to just throw in what I do, just in case these do not work for you.</p>\n\n<p>I've tried to solve the same problem you're having before, and in the end, what I decided on doing is to have only one JRE installed on my system at a given time. I do have about 10 different JDKs (1.3 through 1.6, and from various vendors - Sun, Oracle, IBM), since I do need it for development, but only one standalone JRE.</p>\n\n<p>This has worked for me on my Windows 2000 + IE 6 computer at home, as well as my Windows XP + Multiple IE computer at work.</p>\n"}, {'answer_id': 3090351, 'author': 'Kayhadrin', 'author_id': 104598, 'author_profile': 'https://Stackoverflow.com/users/104598', 'pm_score': 5, 'selected': False, 'text': '<p>I have the same issue today and I concur with Jack Leow.\nBasically, on Windows XP, I had to go to Control Panel > Java and then:</p>\n\n<ol>\n<li>Java tab</li>\n<li>Click on "View" button</li>\n<li>Enable only the JRE I want (i.e. JRE 1.5.x and keep 1.6.x disabled)</li>\n<li>Restart IE</li>\n<li>Load applet page in IE </li>\n<li>Et voila, it\'s loading the correct JRE version!</li>\n</ol>\n'}, {'answer_id': 3853297, 'author': 'Scott Bennett-McLeish', 'author_id': 1915, 'author_profile': 'https://Stackoverflow.com/users/1915', 'pm_score': 1, 'selected': False, 'text': "<p>As has been mentioned here for JRE6 and JRE5, I will update for JRE1.4:</p>\n\n<p>You will need to run the <strong>jpicpl32.exe</strong> application in the jre/bin directory of your java installation (e.g. <strong>c:\\java\\jdk1.4.2_07\\jre\\bin\\jpicpl32.exe</strong>).</p>\n\n<p>This is an earlier version of the application mentioned in Daniel Cassidy's post.</p>\n"}, {'answer_id': 26525940, 'author': 'Srujan Bangaru', 'author_id': 1683903, 'author_profile': 'https://Stackoverflow.com/users/1683903', 'pm_score': 0, 'selected': False, 'text': '<p>You can specify the family of JRE to be used.\n<a href="http://www.oracle.com/technetwork/java/javase/family-clsid-140615.html" rel="nofollow">http://www.oracle.com/technetwork/java/javase/family-clsid-140615.html</a></p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
71,257 |
<p>How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#.</p>
<p>I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it.</p>
|
[{'answer_id': 71290, 'author': 'Dave Moore', 'author_id': 6996, 'author_profile': 'https://Stackoverflow.com/users/6996', 'pm_score': 1, 'selected': False, 'text': '<p>See this CodeProject article for the win32 basics : <a href="http://www.codeproject.com/KB/threads/pausep.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/threads/pausep.aspx</a>. This sample code makes use of the ToolHelp32 library from the SDK, so I would recommend turning this sample code into an unmanaged C++/CLI library with a simple interface like "SuspendProcess(uint processID).</p>\n\n<p>Process.Start will return you a Process object, from which you can get the process id, and then pass this to your new library based on the above.</p>\n\n<p>Dave</p>\n'}, {'answer_id': 71457, 'author': 'Magnus Johansson', 'author_id': 3584, 'author_profile': 'https://Stackoverflow.com/users/3584', 'pm_score': 6, 'selected': True, 'text': '<p>Here\'s my suggestion:</p>\n\n<pre><code> [Flags]\n public enum ThreadAccess : int\n {\n TERMINATE = (0x0001),\n SUSPEND_RESUME = (0x0002),\n GET_CONTEXT = (0x0008),\n SET_CONTEXT = (0x0010),\n SET_INFORMATION = (0x0020),\n QUERY_INFORMATION = (0x0040),\n SET_THREAD_TOKEN = (0x0080),\n IMPERSONATE = (0x0100),\n DIRECT_IMPERSONATION = (0x0200)\n }\n\n [DllImport("kernel32.dll")]\n static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);\n [DllImport("kernel32.dll")]\n static extern uint SuspendThread(IntPtr hThread);\n [DllImport("kernel32.dll")]\n static extern int ResumeThread(IntPtr hThread);\n [DllImport("kernel32", CharSet = CharSet.Auto,SetLastError = true)]\n static extern bool CloseHandle(IntPtr handle);\n\n\nprivate static void SuspendProcess(int pid)\n{\n var process = Process.GetProcessById(pid); // throws exception if process does not exist\n\n foreach (ProcessThread pT in process.Threads)\n {\n IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);\n\n if (pOpenThread == IntPtr.Zero)\n {\n continue;\n }\n\n SuspendThread(pOpenThread);\n\n CloseHandle(pOpenThread);\n }\n}\n\npublic static void ResumeProcess(int pid)\n{\n var process = Process.GetProcessById(pid);\n\n if (process.ProcessName == string.Empty)\n return;\n\n foreach (ProcessThread pT in process.Threads)\n {\n IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);\n\n if (pOpenThread == IntPtr.Zero)\n {\n continue;\n }\n\n var suspendCount = 0;\n do\n {\n suspendCount = ResumeThread(pOpenThread);\n } while (suspendCount > 0);\n\n CloseHandle(pOpenThread);\n }\n}\n</code></pre>\n'}, {'answer_id': 1073037, 'author': 'RandomNickName42', 'author_id': 67819, 'author_profile': 'https://Stackoverflow.com/users/67819', 'pm_score': 2, 'selected': False, 'text': '<p>So really, what the other answer\'s are showing is suspending thread\'s in the process, there is no way to really suspend the process (i.e. in one call).... </p>\n\n<p>A bit of a different solution would be to actually debug the target process which you are starting, see <a href="http://blogs.msdn.com/jmstall/archive/2006/07/03/managed-Vs-native-apis.aspx" rel="nofollow noreferrer">Mike Stall\'s blog</a> for some advice how to implement this from a managed context. </p>\n\n<p>If you implement a debugger, you will be able to scan memory or what other snap-shotting you would like.</p>\n\n<p>However, I would like to point out, that technically, there is now way to really do this. Even if you do debugbreak a target debuggee process, another process on your system may inject a thread and will be given some ability to execute code regardless of the state of the target process (even let\'s say if it\'s hit a breakpoint due to an access violation), if you have all thread\'s suspended up to a super high suspend count, are currently at a break point in the main process thread and any other such presumed-frozen status, it is still possible for the system to inject another thread into that process and execute some instructions. You could also go through the trouble of modifying or replacing all of the entry point\'s the <a href="http://www.nynaeve.net/?p=205" rel="nofollow noreferrer">kernel usually calls</a> and so on, but you\'ve now entered the viscous arm\'s race of MALWARE ;)...</p>\n\n<p>In any case, using the managed interfaces for debugging seems\' a fair amount easier than p/invoke\'ng a lot of native API call\'s which will do a poor job of emulating what you probably really want to be doing... using debug api\'s ;)</p>\n'}, {'answer_id': 13109774, 'author': 'Sarath', 'author_id': 353241, 'author_profile': 'https://Stackoverflow.com/users/353241', 'pm_score': 4, 'selected': False, 'text': '<p>Thanks to Magnus</p>\n\n<p>After including the Flags, I modified the code a bit to be an extension method in my project. I could now use</p>\n\n<pre><code>var process = Process.GetProcessById(param.PId);\nprocess.Suspend();\n</code></pre>\n\n<p>Here is the code for those who might be interested.</p>\n\n<pre><code>public static class ProcessExtension\n{\n [DllImport("kernel32.dll")]\n static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);\n [DllImport("kernel32.dll")]\n static extern uint SuspendThread(IntPtr hThread);\n [DllImport("kernel32.dll")]\n static extern int ResumeThread(IntPtr hThread);\n\n public static void Suspend(this Process process)\n {\n foreach (ProcessThread thread in process.Threads)\n {\n var pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)thread.Id);\n if (pOpenThread == IntPtr.Zero)\n {\n break;\n }\n SuspendThread(pOpenThread);\n }\n }\n public static void Resume(this Process process)\n {\n foreach (ProcessThread thread in process.Threads)\n {\n var pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)thread.Id);\n if (pOpenThread == IntPtr.Zero)\n {\n break;\n }\n ResumeThread(pOpenThread);\n }\n }\n}\n</code></pre>\n\n<p>I have a utility done which I use to generally suspend/kill/list a process. Full source is <a href="https://github.com/SarathR/ProcessUtil.git" rel="noreferrer">on Git</a></p>\n'}, {'answer_id': 61282905, 'author': 'gerrard', 'author_id': 13148843, 'author_profile': 'https://Stackoverflow.com/users/13148843', 'pm_score': 1, 'selected': False, 'text': '<pre><code>[DllImport("ntdll.dll", PreserveSig = false)]\n public static extern void NtSuspendProcess(IntPtr processHandle);\n static IntPtr handle;\n\n string p = "";\n foreach (Process item in Process.GetProcesses())\n {\n if (item.ProcessName == "GammaVPN")\n {\n p = item.ProcessName;\n handle = item.Handle;\n NtSuspendProcess(handle);\n }\n }\n Console.WriteLine(p);\n Console.WriteLine("done");\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9632/']
|
71,273 |
<p>Working with software day-to-day usually means you have to juggle project work, meetings, calls and other interrupts.</p>
<p>What single technique, trick, or tool do you find most useful in managing your time?</p>
<p>How do you stay focused?</p>
<p>What is your single biggest distraction from your work?</p>
|
[{'answer_id': 71289, 'author': 'harriyott', 'author_id': 5744, 'author_profile': 'https://Stackoverflow.com/users/5744', 'pm_score': 2, 'selected': False, 'text': "<p>I find email the most distracting, so I've really cracked down on receiving certain types of email. I've unsubscribed from many mailing lists, job alerts etc. Shutting down email for a period of the day is quite useful too.</p>\n"}, {'answer_id': 71302, 'author': 'Epaga', 'author_id': 6583, 'author_profile': 'https://Stackoverflow.com/users/6583', 'pm_score': 0, 'selected': False, 'text': '<p>Single most useful? <a href="http://www.nowdothis.com" rel="nofollow noreferrer">http://www.nowdothis.com</a> is AWESOME for focusing on what currrently needs to get done, and has raised my productivity by tons. (Bonus tip: Use Google Chrome to make it its own application and then make the app always be on top of other windows)</p>\n\n<p>Biggest distraction? Google Reader.</p>\n'}, {'answer_id': 71307, 'author': 'Galwegian', 'author_id': 3201, 'author_profile': 'https://Stackoverflow.com/users/3201', 'pm_score': 4, 'selected': False, 'text': '<p>I read this rule somewhere, and I use it every day...</p>\n\n<ul>\n<li>If someone asks you to do something - if it takes less than 2 minutes, do it immediately. If it takes longer, put it on your list and come back to it.</li>\n</ul>\n\n<p>This really works for me.</p>\n'}, {'answer_id': 71312, 'author': 'Silver Dragon', 'author_id': 9440, 'author_profile': 'https://Stackoverflow.com/users/9440', 'pm_score': 1, 'selected': False, 'text': '<p>A single answer to all of the listed questions is David Ellen\'s Getting Things Done (GTD) ( "The Art of Stress-Free Productivity" )</p>\n\n<p>A 45-minute presentation of the process <a href="http://www.youtube.com/watch?v=Qo7vUdKTlhk" rel="nofollow noreferrer">can be found on youtube</a>, and you can get the book on <a href="https://rads.stackoverflow.com/amzn/click/com/0142000280" rel="nofollow noreferrer" rel="nofollow noreferrer">Amazon</a></p>\n'}, {'answer_id': 71321, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>Also you could think about the kind of things which make you want to browse the net, check your email, etc. For example, if a build I'm working on is taking too long my mind will wander. </p>\n\n<p>So it actually pays off to make the build process as quick and efficient as you can make it, so you can make changes and test quickly. </p>\n\n<p>I also find it helps to get enough sleep (tiredness is bad for concentration) and not to drink too much caffeine (seriously. I feel so much better after cutting down the amount of caffeine I drink. Try naturally caffeine free teas!)</p>\n\n<p>(I seem to have wandered slightly off-topic into concentration there... still, I find the better I can concentrate the better I will use time!)</p>\n"}, {'answer_id': 71327, 'author': 'Eugene Katz', 'author_id': 1533, 'author_profile': 'https://Stackoverflow.com/users/1533', 'pm_score': 4, 'selected': False, 'text': '<p>The trick the <a href="http://www.davidco.com/" rel="noreferrer">Getting Things Done</a> system teaches is to have a trusted system you can put action items into. That way you don\'t have to keep "juggling". To keep with the metaphor, you can put the other balls down and have confidence that they will not be forgotten. Then you can concentrate on a single ball at a time. There are many, many other excellent tricks GTD teaches. Well worth <a href="https://rads.stackoverflow.com/amzn/click/com/0142000280" rel="noreferrer" rel="nofollow noreferrer">getting the book</a>.</p>\n'}, {'answer_id': 71344, 'author': 'Matthias Winkelmann', 'author_id': 4494, 'author_profile': 'https://Stackoverflow.com/users/4494', 'pm_score': 1, 'selected': False, 'text': '<p>If you want to improve something, you first have to measure it.</p>\n\n<p>I like <a href="http://rescuetime.com" rel="nofollow noreferrer">Rescuetime</a>. It logs all applications and websites you visit and how much time you spend there. You can tag applications/websites, i. e. with "work", "waste", "news" and get nice charts, productivity measures etc.</p>\n'}, {'answer_id': 71347, 'author': 'Brian Phillips', 'author_id': 7230, 'author_profile': 'https://Stackoverflow.com/users/7230', 'pm_score': 3, 'selected': False, 'text': '<p>To manage the general mayhem of the job, I try to use a toned down version of <a href="http://en.wikipedia.org/wiki/Getting_Things_Done" rel="nofollow noreferrer">GTD</a> focusing mainly on trying to maintain <a href="http://www.43folders.com/izero" rel="nofollow noreferrer">Inbox Zero</a> and pushing tasks into a todo list (I use <a href="http://rmilk.com" rel="nofollow noreferrer">Remember the Milk</a> for task list management).</p>\n\n<p>As for maintaining flow in spite of interruptions, leaving a TDD project in a state where tests are failing tends to give you a place to jump right back in when you come back from a meeting or other interruption. Leaving a batch of uncommitted changes might serve a similar purpose -- to get your mind instantly back into the flow of the project without having to go look around to remind yourself what state things are in. Beyond that, using a fairly detailed task list for the projects at hand can help keep you on task and moving forward.</p>\n\n<p>Often times, I\'ve found my manager\'s manager to be the biggest distraction! :-) He likes to feel plugged in to the day-to-day work of his dev teams and frequently comes around on "walk-abouts" to see how things are going.</p>\n'}, {'answer_id': 71351, 'author': 'Matthias Winkelmann', 'author_id': 4494, 'author_profile': 'https://Stackoverflow.com/users/4494', 'pm_score': 2, 'selected': False, 'text': '<p>I enjoy going to the library. The quiet but busy, concentrated atmosphere basically forces you to work. The change of venue also seems to shut out some of the busyness and maybe worries you have in day-to-day life. </p>\n'}, {'answer_id': 71363, 'author': 'Eugene Katz', 'author_id': 1533, 'author_profile': 'https://Stackoverflow.com/users/1533', 'pm_score': 0, 'selected': False, 'text': '<p>(Slightly off-topic)</p>\n<p>They says there is no such thing as time management. You can\'t manage an hour and get extra 20 mins out of it. Well, I recently discovered that you can. It you\'re listening to podcasts or watching recoded web casts, you can speed up the play speed. I found that it also helps me stay focused on the content rather than drifting off and starting check my email during the natural pauses. Then I saw <a href="https://blog.stackoverflow.com/2008/06/listen-to-podcasts-in-less-time/">Jeff\'s post on the same topic</a>.</p>\n'}, {'answer_id': 71376, 'author': 'Miroslav Zadravec', 'author_id': 8239, 'author_profile': 'https://Stackoverflow.com/users/8239', 'pm_score': 0, 'selected': False, 'text': '<p>Email, IM, Skype... all those can distract. But biggest distraction is when my fellow colleague ask me why I wrote some year old algorithm this way and not that way. It brings my work to halt even if I know the answer.</p>\n\n<p>To stop this interruptions, we have a 5-minute break every hour outside the office where we can talk about such problems.</p>\n'}, {'answer_id': 71378, 'author': 'Rollo Tomazzi', 'author_id': 11477, 'author_profile': 'https://Stackoverflow.com/users/11477', 'pm_score': 0, 'selected': False, 'text': '<p>There are a lot of things to do and I\'m not sure you\'ll find any single technique to get organized and stay focused.</p>\n\n<p>But...</p>\n\n<ul>\n<li>Do list the things you have to do. Several short lists will be needed (today, later, inbox == to be sorted out, etc...). Review these lists once in the morning, and then in the evening. These related posts are worth a read: <a href="http://www.randsinrepose.com/archives/2008/07/22/the_taste_of_the_day.html" rel="nofollow noreferrer">The Taste of the Day</a> and <a href="http://www.randsinrepose.com/archives/2008/08/18/the_trickle_list.html" rel="nofollow noreferrer">The Trickle List</a></li>\n<li>Timeboxing: allocate time in your calendar to get the tasks done</li>\n<li>As suggested by harriyott, switching off email is kind of essential too!</li>\n</ul>\n'}, {'answer_id': 71383, 'author': 'Tomo', 'author_id': 9622, 'author_profile': 'https://Stackoverflow.com/users/9622', 'pm_score': 2, 'selected': False, 'text': '<p>I use most of ZTD (<a href="http://zenhabits.net/2007/11/zen-to-done-the-simple-productivity-e-book/" rel="nofollow noreferrer">http://zenhabits.net/2007/11/zen-to-done-the-simple-productivity-e-book/</a>). GTD is too sophisticated and to big for me.</p>\n\n<p>Basically, I make lists of tasks. Every morning I select three which I really need to do that day. I work on them until they\'re done. I struggle not to get dragged to other things. </p>\n\n<p>In an office, I sometimes book a conference room and work there, distraction free. I emerge from the lair when I\'m finished with the three most important tasks.</p>\n'}, {'answer_id': 71443, 'author': 'Johan', 'author_id': 11347, 'author_profile': 'https://Stackoverflow.com/users/11347', 'pm_score': 2, 'selected': False, 'text': '<p>My single biggest distraction is myself - I tend to go all hare-brained, chasing emails and internet links much of the time. Therefore, I\'m using a simple trick to discipline myself into staying focused and on-task for larger parts of the day. The principle is to stay accountable for the use of my time:</p>\n\n<p>1) Have a scheduled job in your operating system, that pops up a small messagebox every 15 minutes (in Windows, it should run the command <code>C:\\windows\\system32\\cmd.exe /C "start /B msg jpretori /W /V "15-minute check""</code>)</p>\n\n<p>2) Have IDailyDiary running in your system tray (a text file will work fine, too). Every time the box pops up, fill in what you\'ve been up to the last 15 minutes. </p>\n\n<p>I\'ve caught myself with an ugly day filled with procrastination before... It\'s quite a good motivation to stay on-task.</p>\n'}, {'answer_id': 71458, 'author': 'Marcin Gil', 'author_id': 5731, 'author_profile': 'https://Stackoverflow.com/users/5731', 'pm_score': 0, 'selected': False, 'text': '<p>This question has already been asked, so you might search for it.</p>\n\n<p>I personally use <a href="http://zenhabits.net" rel="nofollow noreferrer">Zen to done</a> which is a simplified version of "Get Things Done". For the <strong>trusted system</strong> I host <a href="http://www.rousette.org.uk/projects/" rel="nofollow noreferrer">Tracks</a> application for myself.</p>\n'}, {'answer_id': 71482, 'author': 'Tim Booker', 'author_id': 10046, 'author_profile': 'https://Stackoverflow.com/users/10046', 'pm_score': 0, 'selected': False, 'text': "<p>The best way to get through a big chunk of work while staying focused is to list your priorities on paper before you start. Trying to keep a big list in your head is a sure path to procrastination. Plus, it's a great feeling to tick off items as you finish them. Put on some music, close down your email, and get busy.</p>\n\n<p>But then you have people trying to get your attention. Make sure your colleagues and clients know that you prefer to receive their queries in email rather than in person or by phone. Bugs go directly into the tracking system, without anyone having to tap you on the shoulder for each one. Sounds obvious, but stopping your work to discuss something for 5 minutes can sometimes cost you 30 minutes productivity by the time you are focused again.</p>\n"}, {'answer_id': 71501, 'author': 'ugasoft', 'author_id': 10120, 'author_profile': 'https://Stackoverflow.com/users/10120', 'pm_score': 0, 'selected': False, 'text': '<p>You can find a great document about time management in <a href="http://strlen.com/" rel="nofollow noreferrer">Wouter van Oortmerssen</a> (aka Aardappel, the developer of famouses Open Source games like <a href="http://www.cubeengine.com/" rel="nofollow noreferrer">cube</a> and <a href="http://sauerbraten.org/" rel="nofollow noreferrer">http://sauerbraten.org/</a> )</p>\n\n<p>The article I\'m talking about is <a href="http://strlen.com/rants/timemanagementetc.html" rel="nofollow noreferrer">this</a></p>\n'}, {'answer_id': 71523, 'author': 'Loofer', 'author_id': 5552, 'author_profile': 'https://Stackoverflow.com/users/5552', 'pm_score': 1, 'selected': False, 'text': '<p>I find that <a href="http://www.rescuetime.com/" rel="nofollow noreferrer">http://www.rescuetime.com/</a> lets me know what I was actually doing all day, rather than what I THINK I was doing!</p>\n\n<p>It also lets you put a "productive" level on each process/website you run or do so you can see how productive you are being.</p>\n'}, {'answer_id': 71528, 'author': 'Garry Shutler', 'author_id': 6369, 'author_profile': 'https://Stackoverflow.com/users/6369', 'pm_score': 2, 'selected': False, 'text': '<p>Encourage people to push their correspondence with you down the distraction chain:</p>\n\n<ol>\n<li>Phone / Face-to-face </li>\n<li>Instant messaging </li>\n<li>Email</li>\n</ol>\n\n<p>You can do this by deffering them: "I\'m really busy right now, can you send me it in an email?"</p>\n\n<p>This should reduce the amount of interruptions you receive allowing you to stay "in the zone" for longer periods of time, increasing your productivity.</p>\n\n<p>Finally, allot time for processing emails at set times of the day. I, for example, have my email set to send and receive once every two hours. This bulking of activities allows you to get more done in the day without impacting customer relations.</p>\n'}, {'answer_id': 71650, 'author': 'Odd', 'author_id': 11908, 'author_profile': 'https://Stackoverflow.com/users/11908', 'pm_score': 0, 'selected': False, 'text': "<p>I guess you're after something practical. What I do is keep my action items away from my work environment, it helps keep me focussed. I keep a pad next to my desk, I write down each action item for the day at the top and half way down start keeping notes. When I've finished a task I tick it off, anything not ticked can be carried over to the next day (if it's still relevant). Been using it for about 3 years, I find it keeps me productive and helps me remember things. I've tried all kinds of software solutions, nothing works better for me.</p>\n"}, {'answer_id': 71693, 'author': 'Johnno Nolan', 'author_id': 1116, 'author_profile': 'https://Stackoverflow.com/users/1116', 'pm_score': 0, 'selected': False, 'text': "<p>I have an old laptop that I remove the wireless card from and sit on a completely quiet room away from distractions. Whatever I can't get done without the internet is just leave until later. My biggest problem is that I gooel to find a solution and end up doing 30 minutes research on something a blogger has mentioned in passing. I still find it takes me a good hour before i get into the flow of not distracting myself.</p>\n"}, {'answer_id': 71719, 'author': 'Chris Burgess', 'author_id': 6624, 'author_profile': 'https://Stackoverflow.com/users/6624', 'pm_score': 0, 'selected': False, 'text': '<p>On the \'how to stay focused\', I think once you decide to close your email and put your phone on send, the next things to control are the sounds around you that might derail your thoughts. People talking, phones ringing, etc.</p>\n\n<p>I have started putting the headphones on and surfing to <a href="http://www.simplynoise.com/" rel="nofollow noreferrer">http://www.simplynoise.com/</a>. This is a noise generator that gives you the option of white, pink, or brown/red noise. It drowns out most of the audio distractions that often poke at my concentration.</p>\n'}, {'answer_id': 71757, 'author': 'user11334', 'author_id': 11334, 'author_profile': 'https://Stackoverflow.com/users/11334', 'pm_score': 0, 'selected': False, 'text': "<p>Stay productive: When I'm working on a boring project and notice I don't do anything useful but reading news, I set a timer.\nSimple enough, set your mobile on a 1-2 hour timer. Work during that period. When the timer rings, take a break and feel good about yourself :)</p>\n\n<p>For some reason, this works (for me and a couple of other people I know)!</p>\n"}, {'answer_id': 71793, 'author': 'David Heggie', 'author_id': 4309, 'author_profile': 'https://Stackoverflow.com/users/4309', 'pm_score': 1, 'selected': False, 'text': '<p>The single most useful piece of time-management advice I could give is just get on and do it. If something is going to take less than 5 minutes to do, do it now.</p>\n'}, {'answer_id': 71937, 'author': 'brodie', 'author_id': 2231, 'author_profile': 'https://Stackoverflow.com/users/2231', 'pm_score': 2, 'selected': False, 'text': '<p>Recently I\'ve started using a great little free windows app called <strong>NextAction</strong> which you can get from <a href="http://www.timesnapper.com/NextAction/" rel="nofollow noreferrer">here</a>.</p>\n\n<p>It\'s greatness comes from it\'s simplicity and it really helps to refocus and stay on track when dealing with all the days distractions ... email, co-workers, scrums, rss feeds, twitter, lunch, coffee breaks, etc. Having a list of what I\'m working on always there on the desktop makes it very easy focus after any context switch.</p>\n\n<p>Much better than pencil and paper, check it out for yourself.</p>\n\n<p>NOTE: There is a more comprehensive web based \'NextAction\' at <a href="http://code.google.com/p/trimpath/wiki/NextAction" rel="nofollow noreferrer">code.google</a> ... not so good for me, but maybe for others.</p>\n'}, {'answer_id': 71946, 'author': 'Alan', 'author_id': 2958, 'author_profile': 'https://Stackoverflow.com/users/2958', 'pm_score': 0, 'selected': False, 'text': '<p>The single most valuable tool that I can recommend is a <strong>"todo" list</strong>. </p>\n\n<p>This may take the form of a specialised <a href="http://www.codeplex.com/todo" rel="nofollow noreferrer">app</a>, <a href="http://www.google.com/ig/directory?q=todo&hl=en&root=%2Fig&dpos=top&url=www.google.com/ig/modules/todo.xml" rel="nofollow noreferrer">gadget</a> or pen and paper, however the most important thing to remember is that new tasks should be added to the <em>bottom</em> of the list and tasks to be started must be taken from the <em>top</em> - ie. <strong>don\'t cherry pick your tasks</strong>, as this will leave you with a task list full of time-consuming (and often boring) jobs that will begin to drag you down.</p>\n'}, {'answer_id': 72146, 'author': 'J.T. Grimes', 'author_id': 1676, 'author_profile': 'https://Stackoverflow.com/users/1676', 'pm_score': 0, 'selected': False, 'text': '<p>Possibly better for programmers than GTD is <a href="https://rads.stackoverflow.com/amzn/click/com/0596007833" rel="nofollow noreferrer" rel="nofollow noreferrer">Time Management for System Administrators</a>. Same basic principles (reduce interruptions, keep a list) but with a nerdier bent.</p>\n'}, {'answer_id': 72499, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I close email and listen to soothing music. Of course, this tactic really is all about minimizing distractions.</p>\n'}, {'answer_id': 611686, 'author': 'fmsf', 'author_id': 26004, 'author_profile': 'https://Stackoverflow.com/users/26004', 'pm_score': 3, 'selected': False, 'text': '<p>You should see this:</p>\n<h1><a href="http://www.youtube.com/watch?v=oTugjssqOT0" rel="noreferrer">Randy Pausch Lecture: Time Management</a></h1>\n<p>It\'s a teacher from Carnegie Mellon who is near dying, giving his final lecture about time management. It\'s the best tips and tricks you can find.</p>\n'}, {'answer_id': 882127, 'author': 'robert.berger', 'author_id': 108743, 'author_profile': 'https://Stackoverflow.com/users/108743', 'pm_score': 0, 'selected': False, 'text': "<p>The lecture of Randy is great, especially since he knows that he does not have much time left in this world.</p>\n\n<p>Meetings are the biggest time wasters. Try to avoid them wherever you can. </p>\n\n<p>I don't believe in those tools popping up every so often asking me what I'm currently doing. That's very distracting as well. </p>\n\n<p>It might be good to make a time-log for for a couple of weeks, but just to understand where you are spending your time so you may be able to improve things.</p>\n\n<p>I like the time management stuff by Steven Covey.</p>\n\n<p>... and by the way I'm lecturer for time management for IEEE for Europe/Middle East and Africa. </p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11613/']
|
71,277 |
<p>Is it possible to have one application binary build for multiple mobile devices (on <a href="http://brew.qualcomm.com/brew/" rel="nofollow noreferrer">BREW</a> platform), rather than making a separate build for each device using build script with conditional compilation.</p>
<p>In particular is is possible to use single BREW application build for multiple screen resolutions?</p>
<p>Note that the goal is to have a single <em>binary</em> build. If it would be just to have a single codebase, than conditional compilation and smart build script would do the trick.</p>
|
[{'answer_id': 75166, 'author': 'Shane Breatnach', 'author_id': 10264, 'author_profile': 'https://Stackoverflow.com/users/10264', 'pm_score': 3, 'selected': True, 'text': "<p>Yes, it is possible, we were able to do this at my previous place of work. What's required is tricky though:</p>\n\n<ol>\n<li>Compile for the lowest common denominator BREW version. Version 1.1 is the base for all current handsets out there.</li>\n<li>Your code must be able to handle multiple resolutions. The methods for detecting screen width and height are accurate for all handsets in my experience.</li>\n<li>All your resources must load on all devices. This would require making your own custom image loader to work around certain device issues. For sound, I know simple MIDI type 0 works on all but QCP should also work (no experience of it myself).</li>\n<li>Use bitmap fonts. There are too many device issues with fonts to make it worthwhile using the system fonts.</li>\n<li>Design your code structure as a finite state machine. I cannot emphasise this enough - do this and many, many problems never materialise.</li>\n<li>Have workarounds for every single device issue. This is the hard part! It's possible but this rabbit hole is incredibly deep...</li>\n</ol>\n\n<p>In the end, the more complex and advanced the application, the less likely you can go this route. Some device properties simply cannot be detected reliably at runtime (such as platform ID) and so multiple builds are then required.</p>\n"}, {'answer_id': 111911, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Another idea might be to have the handsets divided into 2 to 4 categories based on say screen dimensions and create builds for them. It is a much faster route too as you will be able to support all the handsets you want to support with much lesser complexity.</p>\n\n<p>Another thing to see is the BREW versions on the handsets you want to launch on. If say BREW 1.1 is on one handset and that is owned by a small percentage in your target market, it doesnt make sense to work to support it.</p>\n'}, {'answer_id': 184105, 'author': 'nharding', 'author_id': 26228, 'author_profile': 'https://Stackoverflow.com/users/26228', 'pm_score': 1, 'selected': False, 'text': "<p>I wrote a J2ME to Brew conversion that is used at Javaground. It is quite possible to write multiple resolution, single binary code. We have a database of device bugs so that it can detect via platform id the device and then generate a series of flags which mark which bugs are tagged. For example most (if not all) of the Motorola Brew phones have a bug where an incoming call does not interrupt the application until you answer the call, so I use TAPI to monitor for an incoming call and generate a hideNotify event (since we are emulating Java, although the generated code is pure C++). I do some checks at runtime for Brew version, and disable certain APIs if it is Brew 2 rather than Brew 3.</p>\n\n<p>3D type games are easier to make resolution independent since you are scaling in software.</p>\n\n<p>Also there are 2 separate APIs for sound, IMEDIA and ISOUNDPLAYER, ISOUNDPLAYER is the older API and is supported on all devices but doesn't have as many facilities (you can only do multichannel audio using IMEDIA). I create an IMEDIA object, and it will fall back to create an ISOUNDPLAYER object if it can't get the IMEDIA object.</p>\n\n<p>The problem with a totally universal build is that there is a big difference in capability, so it can be worth having a few builds, the older devices only have under 1MB of heap (and a small screen size), and then you get a lot with 6MB+ (176x204 to larger).</p>\n\n<p>With Brew you do have a fairly consistent set of key values (unlike Java), although some of the new devices are touch screen (and you have to handle pointer input) and rotating screens.</p>\n\n<p>There are also some old Nokia phones that use big endian mode which mean the files are not the same as the normal mod files (UNLESS you want to write some REALLY cool assembly language prefix header that decodes the file)</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11587/']
|
71,293 |
<p>I want to develop some educational content, which I want to distribute to children using Adobe AIR. The content will contain videos. Now, from what I see, AIR will put the content onto the local file system, for anyone to see. I want to prevent this. Is there a way out?</p>
|
[{'answer_id': 71338, 'author': 'Stu Thompson', 'author_id': 2961, 'author_profile': 'https://Stackoverflow.com/users/2961', 'pm_score': 2, 'selected': False, 'text': '<p>Possibly, but you must embrace The Dark Side -- aka DRM (Digital Rights Management). Go read up <a href="http://www.flashcomguru.com/index.cfm/2007/10/23/Flash-Video-DRM-Roundup" rel="nofollow noreferrer">Flash Video DRM</a>. It is awfully painful stuff to do correctly, and users tend to hate it. Ask yourself if your content is <em>really</em> so valuable and hot that you need to go down this route.</p>\n'}, {'answer_id': 75835, 'author': 'mikechambers', 'author_id': 10232, 'author_profile': 'https://Stackoverflow.com/users/10232', 'pm_score': 3, 'selected': True, 'text': '<p>One solution is to use DRM in conjunction with Flash Media Server (as mentioned by Stu).</p>\n\n<p>Another option would be to stream the content at runtime, and not cache to the file system. </p>\n\n<p>Finally, it might also be possible to store the bits for the FLV in the encrypted local data store or SQLite database (which adds encryption support in AIR 1.5), however, this probably wouldnt work well for large videos (performance issues), and you may still need to write it out to the file system first before playing (although temporarily).</p>\n\n<p>mike chambers</p>\n'}, {'answer_id': 474253, 'author': 'Vinayak', 'author_id': 22009, 'author_profile': 'https://Stackoverflow.com/users/22009', 'pm_score': 2, 'selected': False, 'text': "<p>I would suggest you carry out the following steps:</p>\n\n<ol>\n<li>Using a key to encrypt the files that you are storing</li>\n<li>At run-time create a copy of the files in a temp folder and decrypt the files that the user needs using the embedded key in the AIR program</li>\n<li>At exit, delete the decrypted files</li>\n</ol>\n\n<p>This way the files are available for a short period of time, in which they are being used. Then also it is difficult to locate them as you can decrypt them in any obscure folder. </p>\n\n<p>This would protect your files from 99% of the population. And you cannot ever stop the rest 1%. So don't even try.</p>\n\n<p>All the best.</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11783/']
|
71,306 |
<p>The single timing column in the weblog naturally includes client transmission timing. For anamoly analysis, I want to differentiate pages that took excessive construction time from requests that simply had a slow client.</p>
<p>For buffered pages, I've looked at the ASP.NET page lifecycle model and do not see where I can tap in and codewise measure just the page-processing time before the page is flushed to the client.</p>
<p>I probably should have mentioned that my goal is production monitoring (not test or dev). In addition, the intent is to annotate the weblogs with this measurement for later analysis. Current we liberally annotate the weblogs with Response.AppendToLog(). I believe the desire to use Response.AppendToLog() somewhat limits my potential logpoints as for instance, the response-object is not viable in Application_EndRequest.</p>
<p>Any insight would be appreciated.</p>
|
[{'answer_id': 71569, 'author': 'Bob Dizzle', 'author_id': 9581, 'author_profile': 'https://Stackoverflow.com/users/9581', 'pm_score': 0, 'selected': False, 'text': '<p>the easist way would probably be to use the follow events in the global.asax file:</p>\n\n<p>protected void Application_BeginRequest(Object sender, EventArgs e)<br>\nprotected void Application_EndRequest(Object sender, EventArgs e)</p>\n\n<p>You could also implement a custom httpmodule</p>\n'}, {'answer_id': 71593, 'author': 'Kimoz', 'author_id': 7753, 'author_profile': 'https://Stackoverflow.com/users/7753', 'pm_score': 0, 'selected': False, 'text': '<p>This depends on the feature set of the performance tools you have. But if you just need to log the processing time then you could follow this approach.</p>\n\n<ol>\n<li>Log the starting time in the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpapplication.beginrequest.aspx" rel="nofollow noreferrer">HttpApplication.BeginRequest</a> event.</li>\n<li>Log the elapsed time in the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpapplication.presendrequestcontent.aspx" rel="nofollow noreferrer">HttpApplication.PreSendRequestContent</a> event.</li>\n</ol>\n\n<p>If you just want a specific page then you could check for this in the BeginRequest event.\nThe application events can be attached in Global.asax.</p>\n'}, {'answer_id': 71603, 'author': 'thomasb', 'author_id': 6776, 'author_profile': 'https://Stackoverflow.com/users/6776', 'pm_score': 0, 'selected': False, 'text': '<p>If you want to log on a specific page, I believe asp.net pages\' lifecycle begin with PreInit and end with Disposed, so you can log anything you want in those events.</p>\n\n<p>Or, if you want to log on every page, as Bob Dizzle pointed out, you can use the Global.asax file, which has a thousand events to choose from : <a href="http://msdn.microsoft.com/en-us/library/2027ewzw.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/2027ewzw.aspx</a></p>\n'}, {'answer_id': 71632, 'author': 'Timothy Khouri', 'author_id': 11917, 'author_profile': 'https://Stackoverflow.com/users/11917', 'pm_score': 2, 'selected': False, 'text': '<p>You could use a Stopwatch in the BeginRequest and the PreSendRequestContent as mentioned in the other two answers, or you could just use the request\'s Timestamp in the PreSendRequestContent.</p>\n\n<p>For example, on <a href="http://www.singingeels.com/" rel="nofollow noreferrer">SingingEels</a>, I added this to the bottom of my Master Page (yes, it\'s a hack) : <code><%=DateTime.Now.Subtract(HttpContext.Current.Timestamp).TotalSeconds %></code></p>\n\n<p>That way I can see how long any page took to actually execute on the server, including hitting the database, etc.</p>\n'}, {'answer_id': 72099, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 0, 'selected': False, 'text': '<p>You could also do your testing right there on the web server. Then ClientTransmission time becomes effectively 0.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11791/']
|
71,309 |
<p>for example this code</p>
<pre><code>var html = "<p>This text is <a href=#> good</a></p>";
var newNode = Builder.node('div',{className: 'test'},[html]);
$('placeholder').update(newNode);
</code></pre>
<p>casues the p and a tags to be shown, how do I prevent them from being escaped?</p>
|
[{'answer_id': 71371, 'author': 'Leo Lännenmäki', 'author_id': 2451, 'author_profile': 'https://Stackoverflow.com/users/2451', 'pm_score': 3, 'selected': True, 'text': '<p>The last parameter to Builder.node is "Array, List of other nodes to be appended as children" according to the <a href="http://github.com/madrobby/scriptaculous/wikis/builder" rel="nofollow noreferrer">Wiki</a>. So when you pass it a string it is treated like text.</p>\n\n<p>You could use:</p>\n\n<pre><code>var a = Builder.node(\'div\').update("<a href=\'#\'>foo</a>")\n</code></pre>\n\n<p>Where the link is text or:</p>\n\n<pre><code>var a = Builder.node(\'div\', {\'class\':\'cool\'}, \n [Builder.node(\'div\', {\'class\': \'another_div\'})]\n );\n</code></pre>\n\n<p>And you could use just Prototypes <a href="http://www.prototypejs.org/api/element" rel="nofollow noreferrer">new Element()</a> (Available as of version 1.6).</p>\n\n<pre><code>var a = new Element(\'div\').insert(\n new Element(\'div\', {\'class\': \'inner_div\'}).update("Text in the inner div")\n );\n</code></pre>\n'}, {'answer_id': 1360798, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>You can use this solution: <a href="http://sviudes.blogspot.com/2009/08/como-usar-etiquetas-html-con.html" rel="nofollow noreferrer">http://sviudes.blogspot.com/2009/08/como-usar-etiquetas-html-con.html</a></p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6892/']
|
71,315 |
<p>I am using git on a project, that generates lots of data-files (simulation-results).
I am "forced" to version and track all those results in the same repository. (This is a hard requirement and can not be changed)</p>
<p>However I don't need them. We have about 50 MB for the project and 5 GB results in the repository.</p>
<p>Is it feasible for me to create a branch, delete all the results, check this branch out and only work on that branch?</p>
<p>How hard would it be (what would I have to do), to push my local changes back into the fat branch?</p>
<p>Is there a better solution to get rid of those 5 GB for my work?</p>
|
[{'answer_id': 71348, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 3, 'selected': True, 'text': '<p>If you were to make a branch and delete the result files from the branch, then merging your branch back into master would also try to delete the results from master. A file delete is a change just like any other.</p>\n\n<p>Perhaps you could use the git submodule support to manage your code changes as a submodule of the fat repository. In this way, the fat repository would appear to contain everything, but you could work on just the small code bits independently. This may take some fiddling around to work smoothly.</p>\n'}, {'answer_id': 75975, 'author': 'SpoonMeiser', 'author_id': 1577190, 'author_profile': 'https://Stackoverflow.com/users/1577190', 'pm_score': 2, 'selected': False, 'text': '<p>If you create a branch, and delete the unwanted files in one commit, you should be able to cherry-pick any subsequent commits back into your main branch without merging the commit that deletes the data files.</p>\n\n<p>See the <a href="http://www.kernel.org/pub/software/scm/git/docs/git-cherry-pick.html" rel="nofollow noreferrer">manual for git cherry-pick</a>.</p>\n'}, {'answer_id': 711312, 'author': 'skiphoppy', 'author_id': 18103, 'author_profile': 'https://Stackoverflow.com/users/18103', 'pm_score': 0, 'selected': False, 'text': '<p>Besides git cherry-pick, another alternative is to run git-revert on the file delete change just before merging.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1870/']
|
71,323 |
<p>I'm trying to replace each <code>,</code> in the current file by a new line:</p>
<pre><code>:%s/,/\n/g
</code></pre>
<p>But it inserts what looks like a <code>^@</code> instead of an actual newline. The file is not in DOS mode or anything.</p>
<p>What should I do?</p>
<p>If you are curious, like me, check the question <em><a href="https://stackoverflow.com/questions/71417/why-is-r-a-newline-for-vim">Why is \r a newline for Vim?</a></em> as well.</p>
|
[{'answer_id': 71334, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 13, 'selected': True, 'text': '<h2>Use <code>\\r</code> instead of <code>\\n</code>.</h2>\n<p>Substituting by <code>\\n</code> inserts a null character into the text. To get a newline, use <code>\\r</code>. When <em>searching</em> for a newline, you’d still use <code>\\n</code>, however. This asymmetry is due to the fact that <code>\\n</code> and <code>\\r</code> <a href="http://vim.wikia.com/wiki/Search_and_replace" rel="noreferrer">do slightly different things</a>:</p>\n<p><code>\\n</code> matches an end of line (newline), whereas <code>\\r</code> matches a carriage return. On the other hand, in substitutions <code>\\n</code> inserts a null character whereas <code>\\r</code> inserts a newline (more precisely, it’s treated as the input <kbd>CR</kbd>). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it). <code>xxd</code> shows a hexdump of the resulting file.</p>\n<pre><code>echo bar > test\n(echo \'Before:\'; xxd test) > output.txt\nvim test \'+s/b/\\n/\' \'+s/a/\\r/\' +wq\n(echo \'After:\'; xxd test) >> output.txt\nmore output.txt\n</code></pre>\n\n<pre><code>Before:\n0000000: 6261 720a bar.\nAfter:\n0000000: 000a 720a ..r.\n</code></pre>\n<p>In other words, <code>\\n</code> has inserted the byte 0x00 into the text; <code>\\r</code> has inserted the byte 0x0a.</p>\n'}, {'answer_id': 71342, 'author': 'Lasar', 'author_id': 9438, 'author_profile': 'https://Stackoverflow.com/users/9438', 'pm_score': 5, 'selected': False, 'text': '<p><code>\\r</code> can do the work here for you. </p>\n'}, {'answer_id': 71388, 'author': 'dogbane', 'author_id': 7412, 'author_profile': 'https://Stackoverflow.com/users/7412', 'pm_score': 6, 'selected': False, 'text': '<p>You need to use:</p>\n\n<pre><code>:%s/,/^M/g\n</code></pre>\n\n<p>To get the <code>^M</code> character, press <kbd>Ctrl</kbd> + <kbd>v</kbd> followed by <kbd>Enter</kbd>.</p>\n'}, {'answer_id': 71474, 'author': 'grantc', 'author_id': 11845, 'author_profile': 'https://Stackoverflow.com/users/11845', 'pm_score': 5, 'selected': False, 'text': '<p>With Vim on Windows, use <kbd>Ctrl</kbd> + <kbd>Q</kbd> in place of <kbd>Ctrl</kbd> + <kbd>V</kbd>.</p>\n'}, {'answer_id': 136915, 'author': 'Logan', 'author_id': 1127433, 'author_profile': 'https://Stackoverflow.com/users/1127433', 'pm_score': 8, 'selected': False, 'text': "<p>Here's the trick:</p>\n<p>First, set your Vi(m) session to allow pattern matching with special characters (i.e.: newline). It's probably worth putting this line in your .vimrc or .exrc file:</p>\n<pre><code>:set magic\n</code></pre>\n<p>Next, do:</p>\n<pre><code>:s/,/,^M/g\n</code></pre>\n<p>To get the <code>^M</code> character, type <kbd>Ctrl</kbd> + <kbd>V</kbd> and hit <kbd>Enter</kbd>. Under Windows, do <kbd>Ctrl</kbd> + <kbd>Q</kbd>, <kbd>Enter</kbd>. The only way I can remember these is by remembering how little sense they make:</p>\n<blockquote>\n<p>A: <em>What would be the worst control-character to use to represent a newline?</em></p>\n<p>B: <em>Either <code>q</code> (because it usually means "Quit") or <code>v</code> because it would be so easy to type <kbd>Ctrl</kbd> + <kbd>C</kbd> by mistake and kill the editor.</em></p>\n<p>A: <em>Make it so.</em></p>\n</blockquote>\n"}, {'answer_id': 7324063, 'author': 'rickfoosusa', 'author_id': 931265, 'author_profile': 'https://Stackoverflow.com/users/931265', 'pm_score': 4, 'selected': False, 'text': '<p>From <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="nofollow noreferrer">Eclipse</a>, the <code>^M</code> characters can be embedded in a line, and you want to convert them to newlines.</p>\n\n<pre><code>:s/\\r/\\r/g\n</code></pre>\n'}, {'answer_id': 9134411, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s the answer that worked for me. From this guy:</p>\n\n<p>----quoting <em><a href="http://jaysonlorenzen.wordpress.com/2009/04/28/use-vi-editor-to-insert-newline-char-in-replace/" rel="nofollow noreferrer">Use the vi editor to insert a newline char in replace</a></em></p>\n\n<hr>\n\n<p>Something else I have to do and cannot remember and then have to look up.</p>\n\n<p>In vi, to insert a newline character in a search and replace, do the following:</p>\n\n<pre><code>:%s/look_for/replace_with^M/g\n</code></pre>\n\n<p>The command above would replace all instances of “look_for” with “replace_with\\n” (with \\n meaning newline).</p>\n\n<p>To get the “^M”, enter the key combination <kbd>Ctrl</kbd> + <kbd>V</kbd>, and then after that (release all keys) press the <kbd>Enter</kbd> key.</p>\n\n<hr>\n'}, {'answer_id': 9172870, 'author': 'Kiran K Telukunta', 'author_id': 888574, 'author_profile': 'https://Stackoverflow.com/users/888574', 'pm_score': 3, 'selected': False, 'text': '<p>But if one has to substitute, then the following thing works:</p>\n\n<pre><code>:%s/\\n/\\r\\|\\-\\r/g\n</code></pre>\n\n<p>In the above, every next line is substituted with next line, and then <code>|-</code> and again a new line. This is used in wiki tables.</p>\n\n<p>If the text is as follows:</p>\n\n<pre><code>line1\nline2\nline3\n</code></pre>\n\n<p>It is changed to</p>\n\n<pre><code>line1\n|-\nline2\n|-\nline3\n</code></pre>\n'}, {'answer_id': 9220288, 'author': 'Evan Donovan', 'author_id': 263877, 'author_profile': 'https://Stackoverflow.com/users/263877', 'pm_score': 3, 'selected': False, 'text': "<p>If you need to do it for a whole file, it was also suggested to me that you could try from the command line:</p>\n\n<pre><code>sed 's/\\\\n/\\n/g' file > newfile\n</code></pre>\n"}, {'answer_id': 18961239, 'author': 'sjas', 'author_id': 805284, 'author_profile': 'https://Stackoverflow.com/users/805284', 'pm_score': 7, 'selected': False, 'text': '<p>In the syntax <code>s/foo/bar</code>, <code>\\r</code> and <code>\\n</code> have different meanings, depending on context.</p>\n<hr />\n<h2>Short:</h2>\n<p>For <code>foo</code>:<br/></p>\n<p><code>\\r</code> == "carriage return" (<code>CR</code> / <code>^M</code>)<br/>\n<code>\\n</code> == matches "line feed" (<code>LF</code>) on Linux/Mac, and <code>CRLF</code> on Windows<br/></p>\n<p>For <code>bar</code>:<br/></p>\n<p><code>\\r</code> == produces <code>LF</code> on Linux/Mac, <code>CRLF</code> on Windows<br/>\n<code>\\n</code> == "null byte" (<code>NUL</code> / <code>^@</code>)<br/></p>\n<p>When editing files in linux (i.e. on a webserver) that were initially created in a windows environment and uploaded (i.e. FTP/SFTP) - all the <code>^M</code>\'s you see in vim, are the <code>CR</code>\'s which linux does not translate as it uses only <code>LF</code>\'s to depict a line break.</p>\n<hr />\n<h2>Longer (with ASCII numbers):</h2>\n<p>\n<code>NUL</code> == 0x00 == 0 == <kbd>Ctrl</kbd> + <kbd>@</kbd> == <code>^@</code> shown in vim<br/>\n<code>LF</code> == 0x0A == 10 == <kbd>Ctrl</kbd> + <kbd>J</kbd><br/>\n<code>CR</code> == 0x0D == 13 == <kbd>Ctrl</kbd> + <kbd>M</kbd> == <code>^M</code> shown in vim</p>\n<p>Here is a list of the <a href="http://www.cs.tut.fi/%7Ejkorpela/chars/c0.html" rel="noreferrer">ASCII control characters</a>. Insert them in Vim via <kbd>Ctrl</kbd> + <kbd>V</kbd>,<kbd>Ctrl</kbd> + <kbd>---key---</kbd>.</p>\n<p>In Bash or the other Unix/Linux shells, just type <kbd>Ctrl</kbd> + <kbd>---key---</kbd>.</p>\n<p>Try <kbd>Ctrl</kbd> + <kbd>M</kbd> in Bash. It\'s the same as hitting <kbd>Enter</kbd>, as the shell realizes what is meant, even though Linux systems use line feeds for line delimiting.</p>\n<p>To insert literal\'s in bash, prepending them with <kbd>Ctrl</kbd> + <kbd>V</kbd> will also work.</p>\n<p>Try in Bash:</p>\n<pre><code>echo ^[[33;1mcolored.^[[0mnot colored.\n</code></pre>\n<p>This uses <a href="http://en.wikipedia.org/wiki/ANSI_escape_code" rel="noreferrer">ANSI escape sequences</a>. Insert the two <code>^[</code>\'s via <kbd>Ctrl</kbd> + <kbd>V</kbd>, <kbd>Esc</kbd>.</p>\n<p>You might also try <kbd>Ctrl</kbd> + <kbd>V</kbd>,<kbd>Ctrl</kbd> + <kbd>M</kbd>, <kbd>Enter</kbd>, which will give you this:</p>\n<pre><code>bash: $\'\\r\': command not found\n</code></pre>\n<p>Remember the <code>\\r</code> from above? :></p>\n<p>This <a href="http://www.cs.tut.fi/%7Ejkorpela/chars/c0.html" rel="noreferrer">ASCII control characters</a> list is different from a complete <a href="http://ascii-code.com/" rel="noreferrer">ASCII symbol table</a>, in that the control characters, which are inserted into a console/pseudoterminal/Vim via the <kbd>Ctrl</kbd> key (haha), can be found there.</p>\n<p>Whereas in C and most other languages, you usually use the octal codes to represent these \'characters\'.</p>\n<p>If you really want to know where all this comes from: <em><a href="http://www.linusakesson.net/programming/tty/" rel="noreferrer">The TTY demystified</a></em>. This is the best link you will come across about this topic, but beware: There be dragons.</p>\n<hr />\n<p><em>TL;DR</em></p>\n<p>Usually <code>foo</code> = <code>\\n</code>, and <code>bar</code> = <code>\\r</code>.</p>\n'}, {'answer_id': 29514339, 'author': 'codeshot', 'author_id': 962394, 'author_profile': 'https://Stackoverflow.com/users/962394', 'pm_score': 4, 'selected': False, 'text': '<p>This is the best answer for the way I think, but it would have been nicer in a table:</p>\n\n<p><em><a href="https://stackoverflow.com/questions/71417/why-is-r-a-newline-for-vim/12389839#12389839">Why is \\r a newline for Vim?</a></em></p>\n\n<p>So, rewording:</p>\n\n<p>You need to use <code>\\r</code> to use a line feed (ASCII <code>0x0A</code>, the Unix newline) in a regex replacement, but that is peculiar to the replacement - you should normally continue to expect to use <code>\\n</code> for line feed and <code>\\r</code> for carriage return.</p>\n\n<p>This is because Vim used <code>\\n</code> in a replacement to mean the NIL character (ASCII <code>0x00</code>). You might have expected NIL to have been <code>\\0</code> instead, freeing <code>\\n</code> for its usual use for line feed, but <code>\\0</code> already has a meaning in regex replacements, so it was shifted to <code>\\n</code>. Hence then going further to also shift the newline from <code>\\n</code> to <code>\\r</code> (which in a regex pattern is the carriage return character, ASCII <code>0x0D</code>).</p>\n\n<pre>\nCharacter | ASCII code | C representation | Regex match | Regex replacement\n-------------------------+------------+------------------+-------------+------------------------\nnil | 0x00 | \\0 | \\0 | \\n\nline feed (Unix newline) | 0x0a | \\n | \\n | \\r\ncarriage return | 0x0d | \\r | \\r | <unknown>\n</pre>\n\n<p>NB: <code>^M</code> (<kbd>Ctrl</kbd> + <kbd>V</kbd> <kbd>Ctrl</kbd> + <kbd>M</kbd> on Linux) inserts a newline when used in a regex replacement rather than a carriage return as others have advised (I just tried it).</p>\n\n<p>Also note that Vim will translate the line feed character when it saves to file based on its file format settings and that might confuse matters.</p>\n'}, {'answer_id': 73473053, 'author': 'Rajashekhar Meesala', 'author_id': 3888182, 'author_profile': 'https://Stackoverflow.com/users/3888182', 'pm_score': 1, 'selected': False, 'text': '<p>in vim editor the following command successfully replaced \\n with new line</p>\n<pre><code>:%s/\\\\n/\\r/g\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5190/']
|
71,328 |
<p>I have PHP configured so that magic quotes are on and register globals are off.</p>
<p>I do my best to always call htmlentities() for anything I am outputing that is derived from user input.</p>
<p>I also occasionally seach my database for common things used in xss attached such as...</p>
<pre><code><script
</code></pre>
<p>What else should I be doing and how can I make sure that the things I am trying to do are <strong>always</strong> done.</p>
|
[{'answer_id': 71358, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 2, 'selected': False, 'text': "<p>Escaping all user input is enough for most sites. Also make sure that session IDs don't end up in the URL so they can't be stolen from the <code>Referer</code> link to another site. Additionally, if you allow your users to submit links, make sure no <code>javascript:</code> protocol links are allowed; these would execute a script as soon as the user clicks on the link.</p>\n"}, {'answer_id': 71431, 'author': 'Christian Studer', 'author_id': 6260, 'author_profile': 'https://Stackoverflow.com/users/6260', 'pm_score': 4, 'selected': False, 'text': '<p>There are a lot of ways to do XSS (See <a href="http://ha.ckers.org/xss.html" rel="noreferrer">http://ha.ckers.org/xss.html</a>) and it\'s very hard to catch.</p>\n\n<p>I personally delegate this to the current framework I\'m using (Code Igniter for example). While not perfect, it might catch more than my hand made routines ever do.</p>\n'}, {'answer_id': 71439, 'author': 'Niyaz', 'author_id': 184, 'author_profile': 'https://Stackoverflow.com/users/184', 'pm_score': 2, 'selected': False, 'text': '<p>If you are concerned about XSS attacks, encoding your output strings to HTML is the solution. If you remember to encode every single output character to HTML format, there is no way to execute a successful XSS attack.</p>\n\n<p>Read more:\n<a href="http://www.diovo.com/2008/09/sanitizing-user-data-how-and-where-to-do-it/" rel="nofollow noreferrer">Sanitizing user data: How and where to do it</a></p>\n'}, {'answer_id': 71444, 'author': 'Michał Niedźwiedzki', 'author_id': 2169, 'author_profile': 'https://Stackoverflow.com/users/2169', 'pm_score': 7, 'selected': True, 'text': "<p>Escaping input is not the best you can do for successful XSS prevention. Also output must be escaped. If you use Smarty template engine, you may use <code>|escape:'htmlall'</code> modifier to convert all sensitive characters to HTML entities (I use own <code>|e</code> modifier which is alias to the above).</p>\n\n<p>My approach to input/output security is:</p>\n\n<ul>\n<li>store user input not modified (no HTML escaping on input, only DB-aware escaping done via PDO prepared statements)</li>\n<li>escape on output, depending on what output format you use (e.g. HTML and JSON need different escaping rules)</li>\n</ul>\n"}, {'answer_id': 71541, 'author': 'Alexey Feldgendler', 'author_id': 10682, 'author_profile': 'https://Stackoverflow.com/users/10682', 'pm_score': 2, 'selected': False, 'text': "<p>“Magic quotes” is a palliative remedy for some of the worst XSS flaws which works by escaping everything on input, something that's wrong by design. The only case where one would want to use it is when you absolutely must use an existing PHP application known to be written carelessly with regard to XSS. (In this case you're in a serious trouble even with “magic quotes”.) When developing your own application, you should disable “magic quotes” and follow XSS-safe practices instead.</p>\n\n<p>XSS, a cross-site scripting vulnerability, occurs when an application includes strings from external sources (user input, fetched from other websites, etc) in its [X]HTML, CSS, ECMAscript or other browser-parsed output without proper escaping, hoping that special characters like less-than (in [X]HTML), single or double quotes (ECMAscript) will never appear. The proper solution to it is to always escape strings according to the rules of the output language: using entities in [X]HTML, backslashes in ECMAscript etc.</p>\n\n<p>Because it can be hard to keep track of what is untrusted and has to be escaped, it's a good idea to always escape everything that is a “text string” as opposed to “text with markup” in a language like HTML. Some programming environments make it easier by introducing several incompatible string types: “string” (normal text), “HTML string” (HTML markup) and so on. That way, a direct implicit conversion from “string” to “HTML string” would be impossible, and the only way a string could become HTML markup is by passing it through an escaping function.</p>\n\n<p>“Register globals”, though disabling it is definitely a good idea, deals with a problem entirely different from XSS.</p>\n"}, {'answer_id': 71568, 'author': 'dbr', 'author_id': 745, 'author_profile': 'https://Stackoverflow.com/users/745', 'pm_score': 0, 'selected': False, 'text': '<p>Use an existing user-input sanitization library to clean <em>all</em> user-input. Unless you put a <em>lot</em> of effort into it, implementing it yourself will never work as well.</p>\n'}, {'answer_id': 71612, 'author': 'Matt Farina', 'author_id': 11910, 'author_profile': 'https://Stackoverflow.com/users/11910', 'pm_score': 3, 'selected': False, 'text': '<p>This is a great question.</p>\n\n<p>First, don\'t escape text on input except to make it safe for storage (such as being put into a database). The reason for this is you want to keep what was input so you can contextually present it in different ways and places. Making changes here can compromise your later presentation.</p>\n\n<p>When you go to present your data filter out what shouldn\'t be there. For example, if there isn\'t a reason for javascript to be there search for it and remove it. An easy way to do that is to use the <a href="http://us.php.net/strip_tags" rel="noreferrer">strip_tags</a> function and only present the html tags you are allowing.</p>\n\n<p>Next, take what you have and pass it thought htmlentities or htmlspecialchars to change what\'s there to ascii characters. Do this based on context and what you want to get out.</p>\n\n<p>I\'d, also, suggest turning off Magic Quotes. It is has been removed from PHP 6 and is considered bad practice to use it. Details at <a href="http://us3.php.net/magic_quotes" rel="noreferrer">http://us3.php.net/magic_quotes</a></p>\n\n<p>For more details check out <a href="http://ha.ckers.org/xss.html" rel="noreferrer">http://ha.ckers.org/xss.html</a></p>\n\n<p>This isn\'t a complete answer but, hopefully enough to help you get started.</p>\n'}, {'answer_id': 71635, 'author': 'basszero', 'author_id': 287, 'author_profile': 'https://Stackoverflow.com/users/287', 'pm_score': 1, 'selected': False, 'text': "<p>Make you any session cookies (or all cookies) you use HttpOnly. Most browsers will hide the cookie value from JavaScript in that case. User could still manually copy cookies, but this helps prevent direct script access. StackOverflow had this problem durning beta. </p>\n\n<p>This isn't a solution, just another brick in the wall </p>\n"}, {'answer_id': 75839, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Personally, I would disable magic_quotes. In PHP5+ it is disabled by default and it is better to code as if it is not there at all as it does not escape everything and it will be removed from PHP6.</p>\n\n<p>Next, depending on what type of user data you are filtering will dictate what to do next e.g. if it is just text e.g. a name, then <code>strip_tags(trim(stripslashes()));</code> it or to check for ranges use regular expressions.</p>\n\n<p>If you expect a certain range of values, create an array of the valid values and only allow those values through (<code>in_array($userData, array(...))</code>).</p>\n\n<p>If you are checking numbers use is_numeric to enforce whole numbers or cast to a specific type, that should prevent people trying to send strings in stead.</p>\n\n<p>If you have PHP5.2+ then consider looking at <a href="http://ca.php.net/filter" rel="nofollow noreferrer">filter()</a> and making use of that extension which can filter various data types including email addresses. Documentation is not particularly good, but is improving.</p>\n\n<p>If you have to handle HTML then you should consider something like <a href="http://cyberai.users.phpclasses.org/browse/package/2189.html" rel="nofollow noreferrer">PHP Input Filter</a> or <a href="http://htmlpurifier.org/" rel="nofollow noreferrer">HTML Purifier</a>. HTML Purifier will also validate HTML for conformance. I am not sure if Input Filter is still being developed. Both will allow you to define a set of tags that can be used and what attributes are allowed.</p>\n\n<p>Whatever you decide upon, always remember, never ever trust anything coming into your PHP script from a user (including yourself!).</p>\n'}, {'answer_id': 75879, 'author': 'Mason', 'author_id': 8973, 'author_profile': 'https://Stackoverflow.com/users/8973', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n<p>rikh Writes:</p>\n<blockquote>\n<p>I do my best to always call htmlentities() for anything I am outputing that is derived from user input.</p>\n</blockquote>\n</blockquote>\n<p>See Joel\'s essay on <a href="http://www.joelonsoftware.com/articles/Wrong.html" rel="nofollow noreferrer">Making Code Look Wrong</a> for help with this</p>\n'}, {'answer_id': 77290, 'author': 'Daniel Papasian', 'author_id': 7548, 'author_profile': 'https://Stackoverflow.com/users/7548', 'pm_score': 2, 'selected': False, 'text': "<p>All of these answers are great, but fundamentally, the solution to XSS will be to stop generating HTML documents by string manipulation.</p>\n\n<p>Filtering input is always a good idea for any application.</p>\n\n<p>Escaping your output using htmlentities() and friends should work as long as it's used properly, but this is the HTML equivalent of creating a SQL query by concatenating strings with mysql_real_escape_string($var) - it should work, but fewer things can validate your work, so to speak, compared to an approach like using parameterized queries.</p>\n\n<p>The long-term solution should be for applications to construct the page internally, perhaps using a standard interface like the DOM, and then to use a library (like libxml) to handle the serialization to XHTML/HTML/etc. Of course, we're a long ways away from that being popular and fast enough, but in the meantime we have to build our HTML documents via string operations, and that's inherently more risky.</p>\n"}, {'answer_id': 77320, 'author': 'Rob', 'author_id': 3542, 'author_profile': 'https://Stackoverflow.com/users/3542', 'pm_score': 1, 'selected': False, 'text': "<ul>\n<li>Don't trust user input</li>\n<li>Escape all free-text output</li>\n<li>Don't use magic_quotes; see if there's a DBMS-specfic variant, or use PDO</li>\n<li>Consider using HTTP-only cookies where possible to avoid any malicious script being able to hijack a session</li>\n</ul>\n"}, {'answer_id': 77349, 'author': 'Jilles', 'author_id': 13864, 'author_profile': 'https://Stackoverflow.com/users/13864', 'pm_score': 4, 'selected': False, 'text': '<p>I\'m of the opinion that one shouldn\'t escape anything during input, only on output. Since (most of the time) you can not assume that you know where that data is going. Example, if you have form that takes data that later on appears in an email that you send out, you need different escaping (otherwise a malicious user could rewrite your email-headers). </p>\n\n<p>In other words, you can only escape at the very last moment the data is "leaving" your application:</p>\n\n<ul>\n<li>List item</li>\n<li>Write to XML file, escape for XML</li>\n<li>Write to DB, escape (for that particular DBMS)</li>\n<li>Write email, escape for emails</li>\n<li>etc</li>\n</ul>\n\n<p>To go short:</p>\n\n<ol>\n<li>You don\'t know where your data is going</li>\n<li>Data might actually end up in more than one place, needing different escaping mechanism\'s BUT NOT BOTH</li>\n<li>Data escaped for the wrong target is really not nice. (E.g. get an email with the subject "Go to Tommy\\\'s bar".)</li>\n</ol>\n\n<p>Esp #3 will occur if you escape data at the input layer (or you need to de-escape it again, etc).</p>\n\n<p>PS: I\'ll second the advice for not using magic_quotes, those are pure evil!</p>\n'}, {'answer_id': 77376, 'author': 'barce', 'author_id': 13518, 'author_profile': 'https://Stackoverflow.com/users/13518', 'pm_score': 2, 'selected': False, 'text': '<p>I find that using this function helps to strip out a lot of possible xss attacks:</p>\n<pre class="lang-php prettyprint-override"><code><?php\n\nfunction h($string, $esc_type = \'htmlall\')\n{\n switch ($esc_type) {\n case \'css\':\n $string = str_replace(array(\'<\', \'>\', \'\\\\\'), array(\'&lt;\', \'&gt;\', \'&#47;\'), $string);\n // get rid of various versions of javascript\n $string = preg_replace(\n \'/j\\s*[\\\\\\]*\\s*a\\s*[\\\\\\]*\\s*v\\s*[\\\\\\]*\\s*a\\s*[\\\\\\]*\\s*s\\s*[\\\\\\]*\\s*c\\s*[\\\\\\]*\\s*r\\s*[\\\\\\]*\\s*i\\s*[\\\\\\]*\\s*p\\s*[\\\\\\]*\\s*t\\s*[\\\\\\]*\\s*:/i\',\n \'blocked\', $string);\n $string = preg_replace(\n \'/@\\s*[\\\\\\]*\\s*i\\s*[\\\\\\]*\\s*m\\s*[\\\\\\]*\\s*p\\s*[\\\\\\]*\\s*o\\s*[\\\\\\]*\\s*r\\s*[\\\\\\]*\\s*t/i\',\n \'blocked\', $string);\n $string = preg_replace(\n \'/e\\s*[\\\\\\]*\\s*x\\s*[\\\\\\]*\\s*p\\s*[\\\\\\]*\\s*r\\s*[\\\\\\]*\\s*e\\s*[\\\\\\]*\\s*s\\s*[\\\\\\]*\\s*s\\s*[\\\\\\]*\\s*i\\s*[\\\\\\]*\\s*o\\s*[\\\\\\]*\\s*n\\s*[\\\\\\]*\\s*/i\',\n \'blocked\', $string);\n $string = preg_replace(\'/b\\s*[\\\\\\]*\\s*i\\s*[\\\\\\]*\\s*n\\s*[\\\\\\]*\\s*d\\s*[\\\\\\]*\\s*i\\s*[\\\\\\]*\\s*n\\s*[\\\\\\]*\\s*g:/i\', \'blocked\', $string);\n return $string;\n\n case \'html\':\n //return htmlspecialchars($string, ENT_NOQUOTES);\n return str_replace(array(\'<\', \'>\'), array(\'&lt;\' , \'&gt;\'), $string);\n\n case \'htmlall\':\n return htmlentities($string, ENT_QUOTES);\n case \'url\':\n return rawurlencode($string);\n case \'query\':\n return urlencode($string);\n\n case \'quotes\':\n // escape unescaped single quotes\n return preg_replace("%(?<!\\\\\\\\)\'%", "\\\\\'", $string);\n\n case \'hex\':\n // escape every character into hex\n $s_return = \'\';\n for ($x=0; $x < strlen($string); $x++) {\n $s_return .= \'%\' . bin2hex($string[$x]);\n }\n return $s_return;\n\n case \'hexentity\':\n $s_return = \'\';\n for ($x=0; $x < strlen($string); $x++) {\n $s_return .= \'&#x\' . bin2hex($string[$x]) . \';\';\n }\n return $s_return;\n\n case \'decentity\':\n $s_return = \'\';\n for ($x=0; $x < strlen($string); $x++) {\n $s_return .= \'&#\' . ord($string[$x]) . \';\';\n }\n return $s_return;\n\n case \'javascript\':\n // escape quotes and backslashes, newlines, etc.\n return strtr($string, array(\'\\\\\'=>\'\\\\\\\\\',"\'"=>"\\\\\'",\'"\'=>\'\\\\"\',"\\r"=>\'\\\\r\',"\\n"=>\'\\\\n\',\'</\'=>\'<\\/\'));\n\n case \'mail\':\n // safe way to display e-mail address on a web page\n return str_replace(array(\'@\', \'.\'),array(\' [AT] \', \' [DOT] \'), $string);\n\n case \'nonstd\':\n // escape non-standard chars, such as ms document quotes\n $_res = \'\';\n for($_i = 0, $_len = strlen($string); $_i < $_len; $_i++) {\n $_ord = ord($string{$_i});\n // non-standard char, escape it\n if($_ord >= 126){ \n $_res .= \'&#\' . $_ord . \';\'; \n } else {\n $_res .= $string{$_i};\n }\n }\n return $_res;\n\n default:\n return $string;\n }\n}\n \n?>\n</code></pre>\n<p><a href="http://www.codebelay.com/killxss.phps" rel="nofollow noreferrer">Source</a></p>\n'}, {'answer_id': 77396, 'author': 'Darren22', 'author_id': 13978, 'author_profile': 'https://Stackoverflow.com/users/13978', 'pm_score': 0, 'selected': False, 'text': '<p>I find the best way is using a class that allows you to bind your code so you never have to worry about manually escaping your data.</p>\n'}, {'answer_id': 77689, 'author': 'Adam', 'author_id': 13320, 'author_profile': 'https://Stackoverflow.com/users/13320', 'pm_score': -1, 'selected': False, 'text': "<p>It is difficult to implement a thorough sql injection/xss injection prevention on a site that doesn't cause false alarms. In a CMS the end user might want to use <code><script></code> or <code><object></code> that links to items from another site. </p>\n\n<p>I recommend having all users install FireFox with NoScript ;-)</p>\n"}, {'answer_id': 209743, 'author': 'Kornel', 'author_id': 27009, 'author_profile': 'https://Stackoverflow.com/users/27009', 'pm_score': 2, 'selected': False, 'text': '<p>I rely on <a href="http://phptal.motion-twin.com/" rel="nofollow noreferrer">PHPTAL</a> for that.</p>\n\n<p>Unlike Smarty and plain PHP, it escapes all output by default. This is a big win for security, because your site won\'t become vurnelable if you forget <code>htmlspecialchars()</code> or <code>|escape</code> somewhere.</p>\n\n<p>XSS is HTML-specific attack, so HTML output is the right place to prevent it. You should not try pre-filtering data in the database, because you could need to output data to another medium which doesn\'t accept HTML, but has its own risks.</p>\n'}, {'answer_id': 2660815, 'author': 'user319490', 'author_id': 319490, 'author_profile': 'https://Stackoverflow.com/users/319490', 'pm_score': 3, 'selected': False, 'text': "<p><strong>Template library.</strong> Or at least, that is what template libraries should do.\nTo prevent XSS <em>all</em> output should be encoded. This is not the task of the main application / control logic, it should solely be handled by the output methods.</p>\n\n<p>If you sprinkle htmlentities() thorughout your code, the overall design is wrong. And as you suggest, you might miss one or two spots.\nThat's why the only solution is rigorous html encoding <em>-> when</em> output vars get written into a html/xml stream.</p>\n\n<p>Unfortunately, most php template libraries only add their own template syntax, but don't concern themselves with output encoding, or localization, or html validation, or anything important. Maybe someone else knows a proper template library for php?</p>\n"}, {'answer_id': 2671681, 'author': 'Abeon', 'author_id': 320856, 'author_profile': 'https://Stackoverflow.com/users/320856', 'pm_score': 1, 'selected': False, 'text': '<p>You should at least validate all data going into the database. And try to validate all data leaving the database too.</p>\n\n<p>mysql_real_escape_string is good to prevent SQL injection, but XSS is trickier.\nYou should preg_match, stip_tags, or htmlentities where possible!</p>\n'}, {'answer_id': 5772431, 'author': 'Night Owl', 'author_id': 615686, 'author_profile': 'https://Stackoverflow.com/users/615686', 'pm_score': 1, 'selected': False, 'text': "<p>The best current method for preventing XSS in a PHP application is HTML Purifier (http://htmlpurifier.org/). One minor drawback to it is that it's a rather large library and is best used with an op code cache like APC. You would use this in any place where untrusted content is being outputted to the screen. It is much more thorough that htmlentities, htmlspecialchars, filter_input, filter_var, strip_tags, etc.</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4012/']
|
71,332 |
<p>I'm making a method combining Scrum with the OpenUP lifecycle and deliverables. I also want to keep the OpenUP disciplines apart from "Project Management". I can "hide" it so that it's not immediately obvious in my generated method site. But when you then navigate to the "Risk List" artefact for example the PM is still seen as contributing, and if you click on the link, you get taken to the PM Discipline page.</p>
<p>How can I remove it completely from my method without deleting it from the OpenUP library which I'm consuming?</p>
|
[{'answer_id': 15709283, 'author': 'Only You', 'author_id': 463478, 'author_profile': 'https://Stackoverflow.com/users/463478', 'pm_score': 3, 'selected': True, 'text': '<p>I\'ve never used EPF Composer.</p>\n\n<p>I did a little bit of google searches and I understand what you are looking for can be done through Configurations (select OpenUP in your Library view) and published View definitions.</p>\n\n<p>See slide 83 and 84 of this PPT document. You should be able to take it from there.</p>\n\n<p><a href="http://www.google.com/url?sa=t&rct=j&q=%22epf%20composer%22%20%22standard%20categories%22&source=web&cd=9&ved=0CFoQFjAI&url=http://www.mountainview-itsm.com/Mountainview/downloads/An_Introduction_to_EPF.ppt&ei=p9tVUfTwD4-i8gTFroEY&usg=AFQjCNGlAoGW_ujO2uRyTa_h9jYwJq2YfA" rel="nofollow">An Introduction to the Eclipse Process Framework</a>.</p>\n\n<p>In case the link does not work, I searched for "EPF Composer" "Standard categories" on google and the document is at the bottom of the first results page.</p>\n\n<p>Good luck.</p>\n'}, {'answer_id': 34000489, 'author': 'Matas Vaitkevicius', 'author_id': 1509764, 'author_profile': 'https://Stackoverflow.com/users/1509764', 'pm_score': 0, 'selected': False, 'text': '<p>To those who are to lazy <a href="https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=5&ved=0ahUKEwiUr9P6prjJAhVM2RoKHeQ7AWgQFgg0MAQ&url=http%3A%2F%2Fwww.mountainview-itsm.com%2Fitil-training%2Fdownloads%2FAn_Introduction_to_EPF.ppt&usg=AFQjCNHCNYUI70q5JaQKxZbpqMtdUIAu_w&cad=rja" rel="nofollow noreferrer">to search and browse slides</a>:</p>\n\n<p>Slide 83:<br>\nSelect sub-set of method library for publishing to HTML or exporting to MS. Use “Content” selections for course grain (Plug-in and package level) configuration. Use “Add/Subtract these Categories” for fine grain (element level) configuration.</p>\n\n<p><a href="https://i.stack.imgur.com/RJvxQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RJvxQ.png" alt="enter image description here"></a></p>\n\n<p>Slide 84:<br>\nCategories group related elements<br>\nViews defined by selecting Categories<br>\n<a href="https://i.stack.imgur.com/7iyuV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7iyuV.png" alt="enter image description here"></a></p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71332', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2455/']
|
71,336 |
<p>I'm not sure if many people know about this text-editor?</p>
<p>jEdit was kinda big in 2004, but now, Notepad++ seems to have taken the lead(on Windows)
Many of the plugins haven't been updated since 2003 and the overal layout and usage is confusing...</p>
<p>I'm sure jEdit has many nifty features, but I'll be damned if I can find out where to find them and how to use them. Reading that manual is a fulltime job on it's own.</p>
|
[{'answer_id': 71379, 'author': 'Wieczo', 'author_id': 4195, 'author_profile': 'https://Stackoverflow.com/users/4195', 'pm_score': 2, 'selected': False, 'text': '<p>I had to use during my vocational education for XML and XSLT. It had a lot of bugs and didn\'t work always. I couldn\'t get to like it, but if I had to test some XSLT I\'d give it another shot. I found Notepad++ and I am more than happy with it for what I need.</p>\n\n<p>To your question: Did you take a look at <a href="http://plugins.jedit.org/list.php" rel="nofollow noreferrer">jEdit\'s plugin list</a>? There are some plugins released 2008 and the latest version was released on 8th August 2008.</p>\n'}, {'answer_id': 71412, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve been using jEdit since 2003ish. I use it on my Ubuntu 8.04 box at home, however it does have a few bugs: sometimes when you click on a button which opens a dialog, such as "Open File", the dialog will be completely blank.</p>\n\n<p>This could be a Java thing, but it seems a strange issue.</p>\n\n<p>Other than that, I\'m quite happy with jEdit - it\'s the best general editor I\'ve found (so far) for Linux (<em>ducks as hordes of Vi and Emacs users light up their flame cannons</em>)</p>\n\n<p>I like the XML Editor plugin: auto-completion when you close XML (including HTML) tags, plus if you specify a DOCTYPE it gives you auto completion.</p>\n\n<p>There is also a handy plugin for visually viewing diffs between two files.</p>\n'}, {'answer_id': 71621, 'author': 'Vordreller', 'author_id': 11795, 'author_profile': 'https://Stackoverflow.com/users/11795', 'pm_score': 2, 'selected': False, 'text': '<p>Myeah, I just installed the 4.3pre15(latest) and it does look a bit better.</p>\n\n<p>Super feature is the automatic XML DTD creation you can get from one of the plugins.</p>\n\n<p>Now THAT is awsome, especially for big files</p>\n'}, {'answer_id': 71642, 'author': 'AJ.', 'author_id': 7211, 'author_profile': 'https://Stackoverflow.com/users/7211', 'pm_score': 6, 'selected': True, 'text': '<p>I\'ve been using jEdit for a few years now, mainly on windows, but also on Ubuntu.\nI use it for: SQL, awk, batch files, html, xml, javascript...\nJust about everything except .NET stuff (for which I use Visual Studio).<br />\nI love it.</p>\n<h2>summary</h2>\n<p>I use jEdit because it has the right balance for me of <strong>ease of setting up</strong> vs. <strong>features</strong> and <strong>customisability</strong>. For me, no other editor strikes quite as good a balance.</p>\n<h2>cons</h2>\n<ul>\n<li> It can be a bit hard to make it do the things you want. </li>\n</ul>\n<h2>pros</h2>\n<ul>\n<li> I love the <a href="http://plugins.jedit.org/list.php" rel="noreferrer"> plugins </a> </li>\n<li> Being able to define my own syntax highlighting etc. is just what I want from a text editor. </li>\n<li> The <a href="http://prdownloads.sourceforge.net/jedit/jedit4.3pre15manual-a4.pdf" rel="noreferrer">manual</a> is very good and quite readable. I strongly suggest reading it through to get an idea of what jEdit can do for you. (In fact, I suggest this for any software you use)\n<li> It\'s cross-platform. I used it just on windows for a long time, but now I also use Ubuntu, and it works there: I can even copy the configuration files over from my windows machine, and everything works. Nice. \n</ul>\n<h2>other editors</h2>\n<p>In the past I did take a look at <strong>Notepad++</strong>, but that was a while ago, and it didn\'t have a nice way to define your own syntax highlighting, which is important for me. I also paid for <strong>Textmate</strong> and <strong>UltraEdit</strong> at different times (both very good), but in the end, jEdit comes out on top for me.<br />\nI also used <strong>Eclipse</strong> for a year or so. It\'s fantastic, and it\'ll do anything you want, <em>but</em> you have to be really into Eclipse to get the most out of it.</p>\n'}, {'answer_id': 202975, 'author': 'coopr', 'author_id': 20564, 'author_profile': 'https://Stackoverflow.com/users/20564', 'pm_score': 2, 'selected': False, 'text': '<p>I have used jEdit for a number of years, both on PC and Mac (a bit funky on the Mac).</p>\n\n<p>Currently I use it primarily as a <strong>folding</strong> editor for a number of on-going documentation notes. I have use the folding at the text indent levels - an easy way to collapse and expand file sections, without any work to set up each section. </p>\n\n<p>The feature I really like are the command shortcut alternatives you can set up, the tool bar icon control, and the the abbreviation expansions. The Plugins I especially favor are the BufferTabs to display rows of file/buffer names, and the Whitespace and TextTools.</p>\n\n<p>I recently loaded the GroovyScriptEngine, in part because of the syntax coloring and control for groovy. I set up 2 seperate jEdit versions, in part to maintain seperate history lists, as I update a few dozen files repeatedly.</p>\n'}, {'answer_id': 475315, 'author': 'Jonik', 'author_id': 56285, 'author_profile': 'https://Stackoverflow.com/users/56285', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve occasionally wondered about the same thing (what happened to jEdit - though I\'m not sure if that was your main question).</p>\n\n<p>Apparently, the main developer, <a href="http://en.wikipedia.org/wiki/Slava_Pestov" rel="nofollow noreferrer">Slava Pestov</a>, left the project in 2006 (to focus on <a href="http://factorcode.org/" rel="nofollow noreferrer">Factor</a>, and his studies), and the jEdit development has never really picked up again after that. Which is a shame. :/ (I haven\'t actually followed closely, but I guess it\'s telling that there has not been a major release of jEdit in the last 4 and half years.)</p>\n\n<p>Now, while googling around, I found <a href="http://factorcode.org/slava/" rel="nofollow noreferrer">some info written by Slava</a> himself. It seems at that time he not only gave up jEdit, but developing in Java altogether, after becoming "increasingly frustrated" with the language.</p>\n'}, {'answer_id': 3528152, 'author': 'Robin', 'author_id': 220103, 'author_profile': 'https://Stackoverflow.com/users/220103', 'pm_score': 3, 'selected': False, 'text': '<p>I have been using jEdit for the last five years. And I agree with Mr. Mahan\'s comment above, jEdit has reached the "just works stage" and does not really need anymore development.</p>\n\n<p>I mainly use it for PHP web development and have tried everything from commercial IDEs (DreamWeaver) to php designer, NetBeans, Eclipse, Apanta and Notepad++. And nothing comes close for customization possibilities. If the plugin does not exist, chances you can whip something together with a BeanShell Macro (assuming you want to dig into Java).</p>\n\n<p>On Windows I use Notepad++ as well, but mainly as a Notepad replacement (I even renamed the notepad.exe)</p>\n\n<p>At the end of the day it comes down to taste. What is important to you and what will make you more productive. A distracting GUI and fluffy features can take you away from what you should be focusing on. </p>\n\n<p>And to boot I have converted a few developers to jEdit along the way.</p>\n'}, {'answer_id': 5681684, 'author': 'edh', 'author_id': 710459, 'author_profile': 'https://Stackoverflow.com/users/710459', 'pm_score': 2, 'selected': False, 'text': '<p>I loved Notepad++ on windows, but when I made the switch to Mac I was left behind. Since then I have been in tune with utilities that work across multiple platforms so that is why I switched to JEdit over 2 years ago and I have been loving it ever since. It works flawlessly on my Mac, never crashes, is fast, and has many many add-ons. It is based on Java so it works on many different platforms. I think Jedit is equal to or better than Notepad++ </p>\n\n<p>My favorite plug-in is the FTP module. I can open, edit and save files on my FTP server just as easily as if they were local.</p>\n'}, {'answer_id': 10281857, 'author': 'l0b0', 'author_id': 96588, 'author_profile': 'https://Stackoverflow.com/users/96588', 'pm_score': 3, 'selected': False, 'text': '<p>At the risk of performing necromancy:</p>\n\n<ol>\n<li>Because of the way it\'s been released the last decade or so, major Linux distributions usually lag quite far behind the latest stable version. The good news is that there are <a href="http://jedit.org/index.php?page=download#option_two" rel="nofollow">repositories</a> to install and upgrade it automatically on Ubuntu and more.</li>\n<li>For a couple years I shared configuration files between Windows, FreeBSD and Linux without problems. That\'s more than I can say about any other application I\'ve ever used.</li>\n<li>The only issue I\'ve heard about is that it used to be slow back in the dawn of time. Now it\'s really fast.</li>\n<li><em>Encodings</em> and <em>line endings</em> are handled more seamlessly than any other editor except IntelliJ IDEA.</li>\n<li><em>Vertical editing.</em> Just hold down <kbd>Ctrl</kbd> and drag to create a rectangular (or even a zero-width vertical) selection.</li>\n<li><em>Better search and replace than any other editor <strike>ever</strike> except IntelliJ IDEA.</em> I just started writing a list, but it has to be seen to be believed. Just <kbd>Ctrl</kbd>-<kbd>f</kbd> and see for yourself.</li>\n</ol>\n'}, {'answer_id': 25467953, 'author': 'margenn', 'author_id': 2703703, 'author_profile': 'https://Stackoverflow.com/users/2703703', 'pm_score': 3, 'selected': False, 'text': '<p>jEdit is by far, my prefered editor since 2010. It has a unique set of features that I didn\'t found in any other:</p>\n\n<p><strong>Multi OS</strong>: Win, Linux, Mac.</p>\n\n<p><strong>Portable</strong>: Just copy a folder and it is ready to use. All settings are kept in .XML and .properties files inside jEdit subfolder. This is crucial if you don\'t have admin rights on your enterprise workstation.</p>\n\n<p><strong>Search-Replace</strong>: The most enhanced I\'ve seen in a text editor: Full Regex specification with Bean Shell scripting capabilities for back references. For instance: Let\'s say you want to apply an increment on every number found in your text (replace 1 by 2, 10 by 11 and so on). Just search for regex "(\\d+)" and replace by a Java expression "Integer.parseInt(_1) + 1". It\'s just a simple example, but enough to show how powerful it is.</p>\n\n<p><strong>Database</strong>: Just select your SQL statement, press a button and get the resultset from MySQL, MsSql, Oracle, Teradata and any other Jdbc compatible RDBMS. Export results to csv. Works like a multi-database command line tool. Browse and navigate on your database schema. (SQL plugin).</p>\n\n<p><strong>Customization</strong>: Here is where jEdit shines. There are tons of features. The highlight is the ability to use any java API to expand it! Access them from your Beanshell scripting macros. Example: I needed a function that decode selected text from/to mime64. No problem! I Just downloaded a library from commons.apache.org and accessed it from a jEdit macro. It\'s just unbeliveable how expandable jEdit can be with this feature.</p>\n\n<p><strong>Highlight</strong>: Select a word or phrase and it is highlighted right away in the entire text. The mini-map of ocurrences is shown in the scrollbar. It allows quickly find, for example, a respective css style in separated file just using the mouse. No need for Ctrl+F or type anything. It works even on ordinary txt files. (Highlight Plugin)</p>\n\n<p><strong>Plugins</strong>: FTP, XML, Text Diff, Themes, Text Tabs, Highlighter, character map, Mail, Whitespaces, Abbrevs, Minimap...there are hundreds of them.</p>\n\n<p>There are dozens of other nice features that I won\'t describe here in order to keep this answer not too long. The complete article can be found <a href="http://margenn.blogspot.com.br/2010/08/jedit-text-editor-reasons-why-you.html" rel="nofollow" title="here">here</a> and the mime64 example <a href="http://margenn.blogspot.com.br/2011/08/jedit-macro-encode-and-decode-selection.html" rel="nofollow" title="here">here</a>.</p>\n\n<p>At first glance, jEdit is just another text editor. The full capabilities come into light when you start playing with it\'s endless customization/expansion power. My initial reluctance of accepting a java-written text editor disappeared when I realize that only a java text-editor could be so extensible. Its initial drawback turned into it\'s main advantage.</p>\n'}, {'answer_id': 35413411, 'author': 'Graham Hannington', 'author_id': 1334619, 'author_profile': 'https://Stackoverflow.com/users/1334619', 'pm_score': 2, 'selected': False, 'text': '<p>After many years, jEdit remains my favorite free validating XML editor. I love the seamless combination of XML validation with plain-text editing features such as regex search-and-replace across multiple files.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11795/']
|
71,365 |
<p>Presently, we've got several main projects each in their own repository. We will have to version-control up to a dozen additional projects. VisualSVN recommends to create 1 respository for our company and then vc all projects inside that. </p>
<blockquote>
<p>It's a good practice to create one repository for the entire company or department and store all your projects in this repository. Creating separate repository for each project is not a good idea because in that case you will not be able to perform Subversion operations like copy, diff and merge cross-project. <a href="http://www.visualsvn.com/support/topic/00017/" rel="nofollow noreferrer" title="Visualsvn.com">VisualSvn.com</a></p>
</blockquote>
<p>Currently we're using post-commit hooks to update the testing server with the latest commit and do other project specific actions (such as emailing certain people for one project but not for others) depending on which project has been committed.</p>
<p>As post-commit runs for the whole repository, is this still possible in such a situation? How would I go about decerning which project has changes? filter folder structure?</p>
|
[{'answer_id': 71410, 'author': 'Mikael Sundberg', 'author_id': 4422, 'author_profile': 'https://Stackoverflow.com/users/4422', 'pm_score': 1, 'selected': False, 'text': '<p>You can check the paths of the commited files to determine which project they belongs to. Just remember that a commit can modify several files at once, and each file could theoretically belong to a different project.</p>\n'}, {'answer_id': 71490, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 1, 'selected': True, 'text': "<p>I'm not sure I would agree with that VisualSVN recommendation. I have always set up separate repositories per project, and I've never run into a situation where I wish I could have merged across projects or something.</p>\n\n<p>If there is a chunk of common code that is shared among projects at your company, it should become a shared library project of its own (with its own repository, too).</p>\n"}, {'answer_id': 71543, 'author': 'Bruno De Fraine', 'author_id': 6918, 'author_profile': 'https://Stackoverflow.com/users/6918', 'pm_score': 1, 'selected': False, 'text': '<p>From the <a href="http://svnbook.red-bean.com/en/1.5/svn.ref.reposhooks.post-commit.html" rel="nofollow noreferrer"><code>post-commit</code> hook</a>, run the <a href="http://svnbook.red-bean.com/en/1.5/svn.ref.svnlook.c.changed.html" rel="nofollow noreferrer"><code>svnlook changed</code> command</a> to find out which paths are affected by a commit. You could use a <code>grep</code> to see if they include some project path.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/997/']
|
71,374 |
<p>We need to optimize the text rendering for a C# <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> application displaying a large number of small strings in an irregular grid. At any time there can be well over 5000 cells visible that update 4 times per second. The font family and size is consistent across the cells, though the color may vary from cell to cell, as will bold/italic/plain.</p>
<p>I've seen conflicting information on the web about <code>TextRenderer.DrawText</code> vs. <code>Graphics.DrawString</code> being the fastest/best, which reduces to a <a href="http://en.wikipedia.org/wiki/Graphics_Device_Interface" rel="noreferrer">GDI</a> vs. <a href="http://en.wikipedia.org/wiki/Graphics_Device_Interface#GDI.2B" rel="noreferrer">GDI+</a> comparison at the <a href="http://en.wikipedia.org/wiki/Windows_API" rel="noreferrer">Win32</a> level. </p>
<p>I've also seen radically different results on Windows XP vs. Windows Vista, but my main target is Windows XP. Articles promising great advances
under <a href="http://en.wikipedia.org/wiki/.NET_Framework_3.0#.NET_Framework_3.0" rel="noreferrer">WinFX</a> and <a href="http://en.wikipedia.org/wiki/DirectX#DirectX_10" rel="noreferrer">DirectX 10</a> aren't helpful here :-)</p>
<p>What's the best approach here? I'm not afraid of introducing a small C++/CLI layer and optimizing device context handling to squeeze out more performance, but I'd like some definitive advice about which direction to take.</p>
<p>EDIT:
Thanks for the initial responses. I'll be trying a combination of background bitmap rendering and sticking with the GDI equivalent calls.</p>
|
[{'answer_id': 71487, 'author': 'Phil Wright', 'author_id': 6276, 'author_profile': 'https://Stackoverflow.com/users/6276', 'pm_score': 2, 'selected': False, 'text': '<p>GDI is faster at drawing in general that GDI+. I worked on a project that had to draw thousands of lines and text strings and switching from GDI+ to GDI made a significant performance improvement. That was using Windows XP so I cannot comment on Vista. I would also recommend using double buffering for your drawing to also improve performance. Create a compatible off screen bitmap and reuse that each time you need to draw.</p>\n'}, {'answer_id': 71546, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>5000+ text rendering is slow even with GDI, especially if you need scrolling. Create a separate rendering thread and notify the UI thread every 200 ms and bitblt the current results. It gives a smooth user experience.</p>\n'}, {'answer_id': 71552, 'author': 'Mike Dimmick', 'author_id': 6970, 'author_profile': 'https://Stackoverflow.com/users/6970', 'pm_score': 4, 'selected': True, 'text': '<p>A Microsoft developer has posted a <a href="http://blogs.msdn.com/cjacks/archive/2006/05/19/602021.aspx" rel="noreferrer">GDI vs. GDI+ Text Rendering Performance</a> article on his blog which answers the raw speed question: on his system, GDI DrawText was about 6 times faster than GDI+ DrawString.</p>\n\n<p>If you need to be a real speed demon, TextOut is faster than DrawText, but you\'ll have to take care of clipping and word-wrapping yourself. ExtTextOut supports clipping.</p>\n\n<p>GDI rendering (TextRenderer) will be more consistent with other parts of Windows using GDI; GDI+ tries to be device-independent and so <a href="http://windowsclient.net/articles/gdiptext.aspx" rel="noreferrer">some spacing and emboldening are inconsistent</a>. See the SQL Server 2005 Surface Area Configuration tool for an example of inconsistent rendering.</p>\n'}, {'answer_id': 72720, 'author': 'Judah Gabriel Himango', 'author_id': 536, 'author_profile': 'https://Stackoverflow.com/users/536', 'pm_score': 2, 'selected': False, 'text': "<p>Creating a C++/CLI interop class to do the drawing in native code will result in crazy-fast drawing. We've witnesses this and measured it.</p>\n\n<p>If you're not up to doing that, we've found graphics.DrawString is just slightly faster than than TextRenderer.DrawText.</p>\n"}, {'answer_id': 4513455, 'author': 'fritz', 'author_id': 493388, 'author_profile': 'https://Stackoverflow.com/users/493388', 'pm_score': 2, 'selected': False, 'text': '<p>On my Windows 7 64 Bit system TextOut is even a bit slower than DrawString! TextRenderer.DrawText is much slower than DrawString.</p>\n'}, {'answer_id': 64655977, 'author': 'Chungalin', 'author_id': 2989229, 'author_profile': 'https://Stackoverflow.com/users/2989229', 'pm_score': 0, 'selected': False, 'text': '<p>From recent experience, fastest text output is achieved via <code>ExtTextOut</code> with <code>ETO_GLYPH_INDEX</code> flag. This comes at a price, and it’s that you aren’t printing characters anymore, but font glyphs directly. This means that you need to translate your regular character strings to glyph indexes strings prior calling <code>ExtTextOut</code>, either by calling <code>GetCharacterPlacement</code> everytime, or calling this function just once to build your own translation table, that will be valid until a new font is selected in the DC. Remember that glyph indexes are 16bit, so you can store them in a Unicode string and call <code>ExtTextOutW</code> version regardless of original string character size.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6996/']
|
71,381 |
<p>Is it really advantageous to move to Rake from ant?</p>
<p>Anyone migrated from ant and find something monumental?</p>
<p>FYI: Current environment is Ant for J2ME builds</p>
|
[{'answer_id': 71723, 'author': 'auramo', 'author_id': 4110, 'author_profile': 'https://Stackoverflow.com/users/4110', 'pm_score': 1, 'selected': False, 'text': '<p>You might want to check out <a href="http://incubator.apache.org/buildr/" rel="nofollow noreferrer">buildr</a> as well. It\'s a higher-level build-tool built on rake. IMHO it takes a lot of the good features from maven, and throws away the bad-ones. I haven\'t used it in anything big myself but I know people who have and are quite happy with it.</p>\n'}, {'answer_id': 90710, 'author': 'Peter Kelley', 'author_id': 14893, 'author_profile': 'https://Stackoverflow.com/users/14893', 'pm_score': 0, 'selected': False, 'text': '<p>Another tool that you might want to check out is <a href="http://gant.codehaus.org/" rel="nofollow noreferrer">Gant</a> if ant isn\'t meeting your needs. It adds full blown scripting support to ant but allows you to re-use your ant tasks as needed. It really depends on what you don\'t like about ant.</p>\n'}, {'answer_id': 123495, 'author': 'davetron5000', 'author_id': 3029, 'author_profile': 'https://Stackoverflow.com/users/3029', 'pm_score': 3, 'selected': False, 'text': '<p>Rake is great if you want:</p>\n\n<ul>\n<li>Access to a real programming language; conditionals and loops are all dead-simple, compared to Ant (in which they are nigh-impossible)</li>\n<li>File format that is easy to read and can be syntax checked</li>\n<li>More intuitive/predictable assignment of values to variables</li>\n</ul>\n\n<p>Rake is bad for you because:</p>\n\n<ul>\n<li>You need to provide a lot basic of the tasks (like running javac, creating jar files, etc.) yourself. Projects like <a href="http://raven.rubyforge.org/" rel="noreferrer">Raven</a> might help, but it seems geared toward auto-downloading dependencies and not so much automated a build/deploy process. Plus, the documentation is a bit lacking.</li>\n<li>Most java tools that can be automated are done as Ant tasks, which aren\'t easily runnable from Rake; starting up the JVM can be annoying at build time</li>\n</ul>\n'}, {'answer_id': 401797, 'author': 'Peter Mounce', 'author_id': 20971, 'author_profile': 'https://Stackoverflow.com/users/20971', 'pm_score': 4, 'selected': True, 'text': "<p>I would say yes, but I have a different perspective than a Java-environment guy, because I'm a .NET-environment guy. I had written and maintained a non-trivial build script (clean, generate-assembly-info, build, test, coverage, analysis, package) in msbuild (MS' XML-driven NAnt effort) and it was very painful:</p>\n\n<ul>\n<li>XML isn't friendly; it's very noisy</li>\n<li>No-one else on the team was interested in learning it to the point of performing more, and more useful, automations; so high bus factor (ie, if I get hit by a bus, they're stuck with it)</li>\n<li>It did not lend itself to refactoring or improvement - it was one of those 'touch-at-your-peril' things, you know?</li>\n<li>It needed custom C# tasks to be written to run the various tools the build needed (though to be fair, often these are written by the vendors)</li>\n</ul>\n\n<p>In about a work-week's worth of my time (got to love empty offices at Christmas time!), I've learned enough ruby+rake to replace the whole thing with a shorter (in terms of LOC) script with slightly more functionality, and more understandability (I hope, anyhow; haven't had it reviewed yet).</p>\n\n<p>It benefits from:\n - It's a new language, but a real language. My team-mates like learning new languages, and this, while a thin excuse, is still an excuse ;-) This might mitigate the bus-factor if I'm right.\n - It's a short hop (I gather) from here to capistrano, the automated/remote/distributed deployment tool from the RoR world. Despite being an MS-stack shop, we're gonna be using that in combination with IIS7 finally having a CLI config tool.</p>\n\n<p>So, yeah. Your mileage may vary, but it was worth it for me.</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/123/']
|
71,413 |
<p>Given a table of votes (users vote for a choice, and must supply an email address):</p>
<pre><code>votes
--
id: int
choice: int
timestamp: timestamp
ip: varchar
email: varchar
</code></pre>
<p>What's the best way to count "unique" votes (a user being a unique combination of email + ip) given the constraint they may only vote <em>twice</em> per hour?</p>
<p>It's possible to count the number of hours between first and last vote and determine the maximum number of allowed votes for that timeframe, but that allows users to compress all their votes into say, a single hour-long window, and still have them counted.</p>
<p>I realize anonymous online voting is inherently flawed, but I'm not sure how to do this with SQL. Should I be using an external script or whatever instead? (For each choice, for each email+ip pair, get a vote, calculate the next +1h timestamp, count/discard/tally votes, move on to the next hour, etc...)</p>
|
[{'answer_id': 71430, 'author': 'Galwegian', 'author_id': 3201, 'author_profile': 'https://Stackoverflow.com/users/3201', 'pm_score': 2, 'selected': False, 'text': '<p>Something like </p>\n\n<pre><code>select email, ip, count(choice)\nfrom votes\ngroup by email, ip, datepart(hour, timestamp)\n</code></pre>\n\n<p>If I understand correctly</p>\n'}, {'answer_id': 71489, 'author': 'GateKiller', 'author_id': 383, 'author_profile': 'https://Stackoverflow.com/users/383', 'pm_score': 0, 'selected': False, 'text': "<p>You could rewrite your insert statement to only allow votes to be inserted based on your contrainsts:</p>\n\n<pre><code>Insert Into Votes\n(Choice, Timestamp, IP, Email)\nSelect\nTop 1\n@Choice, @Timestamp, @IP, @Email\nFrom\nVotes\nWhere\n(Select Count(*) From Votes Where\n IP = @IP\n and Email = @Email\n and Timestamp > DateAdd(h, -2, GetDate())) < 3\n</code></pre>\n\n<p>You didn't mention which SQL language you were using so this is in SQL Server 2005.</p>\n"}, {'answer_id': 74262, 'author': 'AJ.', 'author_id': 7211, 'author_profile': 'https://Stackoverflow.com/users/7211', 'pm_score': 0, 'selected': False, 'text': '<p>I think this would do it: </p>\n\n<pre><code>SELECT choice, count(*) \nFROM votes v \nWHERE \n ( SELECT count(*) \n FROM votes v2\n WHERE v.email = v2.email \n AND v.ip = v2.ip \n AND v2.timestamp BETWEEN dateadd(hour, -1, v.timestamp) AND v.timestamp \n ) < 2 \n</code></pre>\n\n<p>FYI, To count votes where users can only vote once per hour, we could do this: </p>\n\n<pre><code>SELECT choice, count(*) \nFROM votes v \nWHERE NOT EXTISTS \n ( SELECT * \n FROM votes v2\n WHERE v.email = v2.email \n AND v.ip = v2.ip \n AND v2.timestamp BETWEEN dateadd(h,v.timestamp,-1) AND v.timestamp \n ) \n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
71,416 |
<p>I'm trying to do something like the following:</p>
<pre><code>enum E;
void Foo(E e);
enum E {A, B, C};
</code></pre>
<p>which the compiler rejects. I've had a quick look on Google and the consensus seems to be "you can't do it", but I can't understand why. Can anyone explain?</p>
<p>Clarification 2: I'm doing this as I have private methods in a class that take said enum, and I do not want the enum's values exposed - so, for example, I do not want anyone to know that E is defined as</p>
<pre><code>enum E {
FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X
}
</code></pre>
<p>as project X is not something I want my users to know about.</p>
<p>So, I wanted to forward declare the enum so I could put the private methods in the header file, declare the enum internally in the cpp, and distribute the built library file and header to people.</p>
<p>As for the compiler - it's GCC.</p>
|
[{'answer_id': 71428, 'author': 'prakash', 'author_id': 123, 'author_profile': 'https://Stackoverflow.com/users/123', 'pm_score': 1, 'selected': False, 'text': '<p>It seems it can not be forward-declared in GCC!</p>\n<p>An interesting discussion is <a href="http://bytes.com/forum/thread62285.html" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 71436, 'author': 'Alexey Feldgendler', 'author_id': 10682, 'author_profile': 'https://Stackoverflow.com/users/10682', 'pm_score': 3, 'selected': False, 'text': "<p>There is indeed no such thing as a forward declaration of enum. As an enum's definition doesn't contain any code that could depend on other code using the enum, it's usually not a problem to define the enum completely when you're first declaring it.</p>\n\n<p>If the only use of your enum is by private member functions, you can implement encapsulation by having the enum itself as a private member of that class. The enum still has to be fully defined at the point of declaration, that is, within the class definition. However, this is not a bigger problem as declaring private member functions there, and is not a worse exposal of implementation internals than that.</p>\n\n<p>If you need a deeper degree of concealment for your implementation details, you can break it into an abstract interface, only consisting of pure virtual functions, and a concrete, completely concealed, class implementing (inheriting) the interface. Creation of class instances can be handled by a factory or a static member function of the interface. That way, even the real class name, let alone its private functions, won't be exposed.</p>\n"}, {'answer_id': 71448, 'author': 'Carl Seleborg', 'author_id': 2095, 'author_profile': 'https://Stackoverflow.com/users/2095', 'pm_score': -1, 'selected': False, 'text': "<p>Because the enum can be an integral size of varying size (the compiler decides which size a given enum has), the pointer to the enum can also have varying size, since it's an integral type (chars have pointers of a different size on some platforms for instance).</p>\n\n<p>So the compiler can't even let you forward-declare the enum and user a pointer to it, because even there, it needs the size of the enum.</p>\n"}, {'answer_id': 71495, 'author': 'James Hopkin', 'author_id': 11828, 'author_profile': 'https://Stackoverflow.com/users/11828', 'pm_score': 4, 'selected': False, 'text': "<p>[My answer is wrong, but I've left it here because the comments are useful].</p>\n\n<p>Forward declaring enums is non-standard, because pointers to different enum types are not guaranteed to be the same size. The compiler may need to see the definition to know what size pointers can be used with this type.</p>\n\n<p>In practice, at least on all the popular compilers, pointers to enums are a consistent size. Forward declaration of enums is provided as a language extension by Visual C++, for example.</p>\n"}, {'answer_id': 71961, 'author': 'Laurie Cheers', 'author_id': 12066, 'author_profile': 'https://Stackoverflow.com/users/12066', 'pm_score': 3, 'selected': False, 'text': "<p>I'd do it this way:</p>\n\n<p>[in the public header]</p>\n\n<pre><code>typedef unsigned long E;\n\nvoid Foo(E e);\n</code></pre>\n\n<p>[in the internal header]</p>\n\n<pre><code>enum Econtent { FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X,\n FORCE_32BIT = 0xFFFFFFFF };\n</code></pre>\n\n<p>By adding FORCE_32BIT we ensure that Econtent compiles to a long, so it's interchangeable with E.</p>\n"}, {'answer_id': 72599, 'author': 'KJAWolf', 'author_id': 12302, 'author_profile': 'https://Stackoverflow.com/users/12302', 'pm_score': 9, 'selected': True, 'text': '<p>The reason the enum can\'t be forward declared is that, without knowing the values, the compiler can\'t know the storage required for the enum variable. C++ compilers are allowed to specify the actual storage space based on the size necessary to contain all the values specified. If all that is visible is the forward declaration, the translation unit can\'t know what storage size has been chosen – it could be a <code>char</code>, or an <code>int</code>, or something else.</p>\n<hr />\n<p>From Section 7.2.5 of the ISO C++ Standard:</p>\n<blockquote>\n<p>The <em>underlying type</em> of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than <code>int</code> unless the value of an enumerator cannot fit in an <code>int</code> or <code>unsigned int</code>. If the <em>enumerator-list</em> is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of <code>sizeof()</code> applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of <code>sizeof()</code> applied to the underlying type.</p>\n</blockquote>\n<p>Since the <em>caller</em> to the function must know the sizes of the parameters to correctly set up the call stack, the number of enumerations in an enumeration list must be known before the function prototype.</p>\n<p>Update:</p>\n<p>In C++0X, a syntax for forward declaring enum types has been proposed and accepted. You can see the proposal at <em><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2764.pdf" rel="nofollow noreferrer">Forward declaration of enumerations (rev.3)</a></em></p>\n'}, {'answer_id': 78426, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 0, 'selected': False, 'text': "<p>My solution to your problem would be to either:</p>\n\n<p>1 - use int instead of enums: Declare your ints in an anonymous namespace in your CPP file (not in the header):</p>\n\n<pre><code>namespace\n{\n const int FUNCTIONALITY_NORMAL = 0 ;\n const int FUNCTIONALITY_RESTRICTED = 1 ;\n const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;\n}\n</code></pre>\n\n<p>As your methods are private, no one will mess with the data. You could even go further to test if someone sends you an invalid data:</p>\n\n<pre><code>namespace\n{\n const int FUNCTIONALITY_begin = 0 ;\n const int FUNCTIONALITY_NORMAL = 0 ;\n const int FUNCTIONALITY_RESTRICTED = 1 ;\n const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;\n const int FUNCTIONALITY_end = 3 ;\n\n bool isFunctionalityCorrect(int i)\n {\n return (i >= FUNCTIONALITY_begin) && (i < FUNCTIONALITY_end) ;\n }\n}\n</code></pre>\n\n<p>2 : create a full class with limited const instantiations, like done in Java. Forward declare the class, and then define it in the CPP file, and instanciate only the enum-like values. I did something like that in C++, and the result was not as satisfying as desired, as it needed some code to simulate an enum (copy construction, operator =, etc.).</p>\n\n<p>3 : As proposed before, use the privately declared enum. Despite the fact an user will see its full definition, it won't be able to use it, nor use the private methods. So you'll usually be able to modify the enum and the content of the existing methods without needing recompiling of code using your class.</p>\n\n<p>My guess would be either the solution 3 or 1.</p>\n"}, {'answer_id': 78448, 'author': 'Vincent Robert', 'author_id': 268, 'author_profile': 'https://Stackoverflow.com/users/268', 'pm_score': 2, 'selected': False, 'text': '<p>If you really don\'t want your enum to appear in your header file <em>and</em> ensure that it is only used by private methods, then one solution can be to go with the <a href="https://cpppatterns.com/patterns/pimpl.html" rel="nofollow noreferrer">PIMPL</a> principle.</p>\n<p>It\'s a technique that ensure to hide the class internals in the headers by just declaring:</p>\n<pre><code>class A\n{\npublic:\n ...\nprivate:\n void* pImpl;\n};\n</code></pre>\n<p>Then in your implementation file (.cpp), you declare a class that will be the representation of the internals.</p>\n<pre><code>class AImpl\n{\npublic:\n AImpl(A* pThis): m_pThis(pThis) {}\n\n ... all private methods here ...\nprivate:\n A* m_pThis;\n};\n</code></pre>\n<p>You must dynamically create the implementation in the class constructor and delete it in the destructor and when implementing public method, you must use:</p>\n<pre><code>((AImpl*)pImpl)->PrivateMethod();\n</code></pre>\n<p>There are pros for using PIMPL. One is that it decouples your class header from its implementation, and there isn\'t any need to recompile other classes when changing one class implementation. Another is that is speeds up your compilation time, because your headers are so simple.</p>\n<p>But it\'s a pain to use, so you should really ask yourself if just declaring your enum as private in the header is that much a trouble.</p>\n'}, {'answer_id': 483320, 'author': 'xtofl', 'author_id': 6610, 'author_profile': 'https://Stackoverflow.com/users/6610', 'pm_score': -1, 'selected': False, 'text': "<p>You define an enumeration to restrict the possible values of elements of the type to a limited set. This restriction is to be enforced at compile time.</p>\n\n<p>When forward declaring the fact that you will use a 'limited set' later on doesn't add any value: subsequent code needs to know the possible values in order to benefit from it.</p>\n\n<p>Although the compiler <em>is</em> concerned about the size of the enumerated type, the <em>intent</em> of the enumeration gets lost when you forward declare it.</p>\n"}, {'answer_id': 685239, 'author': 'Dan Olson', 'author_id': 69283, 'author_profile': 'https://Stackoverflow.com/users/69283', 'pm_score': 2, 'selected': False, 'text': "<p>There's some dissent since this got bumped (sort of), so here's some relevant bits from the standard. Research shows that the standard doesn't really define forward declaration, nor does it explicitly state that enums can or can't be forward declared.</p>\n<p>First, from dcl.enum, section 7.2:</p>\n<blockquote>\n<p>The underlying type of an enumeration\nis an integral type that can represent\nall the enumerator values defined in\nthe enumeration. It is\nimplementation-defined which integral\ntype is used as the underlying type\nfor an enumeration except that the\nunderlying type shall not be larger\nthan int unless the value of an\nenumerator cannot fit in an int or\nunsigned int. If the enumerator-list\nis empty, the underlying type is as if\nthe enumeration had a single\nenumerator with value 0. The value of\nsizeof() applied to an enumeration\ntype, an object of enumeration type,\nor an enumerator, is the value of\nsizeof() applied to the underlying\ntype.</p>\n</blockquote>\n<p>So the underlying type of an enum is implementation-defined, with one minor restriction.</p>\n<p>Next we flip to the section on "incomplete types" (3.9), which is about as close as we come to any standard on forward declarations:</p>\n<blockquote>\n<p>A class that has been declared but not defined, or an array of unknown size or of\nincomplete element type, is an incompletely-defined object type.</p>\n<p>A class type (such as "class X") might be incomplete at one point in a translation\nunit and complete later on; the type "class X" is the same type at both points. The\ndeclared type of an array object might be an array of incomplete class type and\ntherefore incomplete; if the class type is completed later on in the translation unit,\nthe array type becomes complete; the array type at those two points is the same type.\nThe declared type of an array object might be an array of unknown size and therefore be\nincomplete at one point in a translation unit and complete later on; the array types at\nthose two points ("array of unknown bound of T" and "array of N T") are different\ntypes. The type of a pointer to array of unknown size, or of a type defined by a typedef\ndeclaration to be an array of unknown size, cannot be completed.</p>\n</blockquote>\n<p>So there, the standard pretty much laid out the types that can be forward declared. Enum wasn't there, so compiler authors generally regard forward declaring as disallowed by the standard due to the variable size of its underlying type.</p>\n<p>It makes sense, too. Enums are usually referenced in by-value situations, and the compiler would indeed need to know the storage size in those situations. Since the storage size is implementation defined, many compilers may just choose to use 32 bit values for the underlying type of every enum, at which point it becomes possible to forward declare them.</p>\n<p>An interesting experiment might be to try forward declaring an enum in Visual\xa0Studio, then forcing it to use an underlying type greater than sizeof(int) as explained above to see what happens.</p>\n"}, {'answer_id': 686303, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 3, 'selected': False, 'text': "<p>I am just noting that the reason actually <em>is</em> that the size of the enum is not yet known after forward declaration. Well, you use forward declaration of a struct to be able to pass a pointer around or refer to an object from a place that's referred to in the forward declared struct definition itself too.</p>\n<p>Forward declaring an enum would not be too useful, because one would wish to be able to pass around the enum by-value. You couldn't even have a pointer to it, because I recently got told some platforms use pointers of different size for <em>char</em> than for <em>int</em> or <em>long</em>. So it all depends on the content of the enum.</p>\n<p>The current C++ Standard explicitly disallows doing something like</p>\n<pre><code>enum X;\n</code></pre>\n<p>(in <code>7.1.5.3/1</code>). But the next C++ Standard due to next year allows the following, which convinced me the problem actually <em>has</em> to do with the underlying type:</p>\n<pre><code>enum X : int;\n</code></pre>\n<p>It's known as an "opaque" enum declaration. You can even use X <em>by value</em> in the following code. And its enumerators can later be defined in a later redeclaration of the enumeration. See <code>7.2</code> in the current working draft.</p>\n"}, {'answer_id': 717633, 'author': 'zhaorufei', 'author_id': 64469, 'author_profile': 'https://Stackoverflow.com/users/64469', 'pm_score': 1, 'selected': False, 'text': '<p>For <a href="https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B" rel="nofollow noreferrer">VC++</a>, here\'s the test about forward declaration and specifying the underlying type:</p>\n<ol>\n<li>The following code is compiled OK.</li>\n</ol>\n<pre>\n typedef int myint;\n enum T ;\n void foo(T * tp )\n {\n * tp = (T)0x12345678;\n }\n enum T : char\n {\n A\n };\n</pre>\n<p>But I got the warning for <code>/W4</code> (<code>/W3</code> does not incur this warning)</p>\n<blockquote>\n<p>warning C4480: nonstandard extension used: specifying underlying type for enum \'T\'</p>\n</blockquote>\n<ol start="2">\n<li>VC++ (Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86) looks buggy in the above case:</li>\n</ol>\n<ul>\n<li>when seeing enum T; VC assumes the enum type T uses default 4 bytes int as underlying type, so the generated assembly code is:</li>\n</ul>\n<pre>\n ?foo@@YAXPAW4T@@@Z PROC ; foo\n ; File e:\\work\\c_cpp\\cpp_snippet.cpp\n ; Line 13\n push ebp\n mov ebp, esp\n ; Line 14\n mov eax, DWORD PTR _tp$[ebp]\n mov DWORD PTR [eax], 305419896 ; 12345678H\n ; Line 15\n pop ebp\n ret 0\n ?foo@@YAXPAW4T@@@Z ENDP ; foo\n</pre>\n<p>The above assembly code is extracted from /Fatest.asm directly, not my personal guess.</p>\n<p>Do you see the</p>\n<pre><code>mov DWORD PTR[eax], 305419896 ; 12345678H\n</code></pre>\n<p>line?</p>\n<p>the following code snippet proves it:</p>\n<pre>\n int main(int argc, char *argv)\n {\n union {\n char ca[4];\n T t;\n }a;\n a.ca[0] = a.ca[1] = a.[ca[2] = a.ca[3] = 1;\n foo( &a.t) ;\n printf("%#x, %#x, %#x, %#x\\n", a.ca[0], a.ca[1], a.ca[2], a.ca[3] );\n return 0;\n }\n</pre>\n<p>The result is:</p>\n<p>0x78, 0x56, 0x34, 0x12</p>\n<ul>\n<li>After removing the forward declaration of enum T and move the definition of function foo after the enum T\'s definition: the result is OK:</li>\n</ul>\n<p>The above key instruction becomes:</p>\n<p>mov BYTE PTR [eax], 120 ; 00000078H</p>\n<p>The final result is:</p>\n<p>0x78, 0x1, 0x1, 0x1</p>\n<p>Note the value is not being overwritten.</p>\n<p>So using of the forward-declaration of enum in VC++ is considered harmful.</p>\n<p>BTW, to not surprise, the syntax for declaration of the underlying type is same as its in C#. In pratice I found it\'s worth to save three bytes by specifying the underlying type as char when talking to the embedded system, which is memory limited.</p>\n'}, {'answer_id': 990983, 'author': 'mavam', 'author_id': 1170277, 'author_profile': 'https://Stackoverflow.com/users/1170277', 'pm_score': 1, 'selected': False, 'text': '<p>In my projects, I adopted the <a href="http://www.ddj.com/cpp/184403894" rel="nofollow noreferrer">Namespace-Bound Enumeration</a> technique to deal with <code>enum</code>s from legacy and 3rd-party components. Here is an example:</p>\n\n<h3>forward.h:</h3>\n\n<pre><code>namespace type\n{\n class legacy_type;\n typedef const legacy_type& type;\n}\n</code></pre>\n\n<h3>enum.h:</h3>\n\n<pre><code>// May be defined here or pulled in via #include.\nnamespace legacy\n{\n enum evil { x , y, z };\n}\n\n\nnamespace type\n{\n using legacy::evil;\n\n class legacy_type\n {\n public:\n legacy_type(evil e)\n : e_(e)\n {}\n\n operator evil() const\n {\n return e_;\n }\n\n private:\n evil e_;\n };\n}\n</code></pre>\n\n<h3>foo.h:</h3>\n\n<pre><code>#include "forward.h"\n\nclass foo\n{\npublic:\n void f(type::type t);\n};\n</code></pre>\n\n<h3>foo.cc:</h3>\n\n<pre><code>#include "foo.h"\n\n#include <iostream>\n#include "enum.h"\n\nvoid foo::f(type::type t)\n{\n switch (t)\n {\n case legacy::x:\n std::cout << "x" << std::endl;\n break;\n case legacy::y:\n std::cout << "y" << std::endl;\n break;\n case legacy::z:\n std::cout << "z" << std::endl;\n break;\n default:\n std::cout << "default" << std::endl;\n }\n}\n</code></pre>\n\n<h3>main.cc:</h3>\n\n<pre><code>#include "foo.h"\n#include "enum.h"\n\nint main()\n{\n foo fu;\n fu.f(legacy::x);\n\n return 0;\n}\n</code></pre>\n\n<p>Note that the <code>foo.h</code> header does not have to know anything about <code>legacy::evil</code>. Only the files that use the legacy type <code>legacy::evil</code> (here: main.cc) need to include <code>enum.h</code>.</p>\n'}, {'answer_id': 1280969, 'author': 'user119017', 'author_id': 119017, 'author_profile': 'https://Stackoverflow.com/users/119017', 'pm_score': 8, 'selected': False, 'text': "<p>Forward declaration of enums is possible since C++11. Previously, the reason enum types couldn't be forward declared was because the size of the enumeration depended on its contents. As long as the size of the enumeration is specified by the application, it can be forward declared:</p>\n<pre><code>enum Enum1; // Illegal in C++03 and C++11; no size is explicitly specified.\nenum Enum2 : unsigned int; // Legal in C++11.\nenum class Enum3; // Legal in C++11, because enum class declarations have a default type of "int".\nenum class Enum4: unsigned int; // Legal C++11.\nenum Enum2 : unsigned short; // Illegal in C++11, because Enum2 was previously declared with a different type.\n</code></pre>\n"}, {'answer_id': 1932119, 'author': 'Brian R. Bondy', 'author_id': 3153, 'author_profile': 'https://Stackoverflow.com/users/3153', 'pm_score': 5, 'selected': False, 'text': '<p>Forward declaring things in C++ is very useful because it <a href="http://brianbondy.com/blog/id/5/slow-compilation-time" rel="nofollow noreferrer">dramatically speeds up compilation time</a>. You can forward declare several things in C++ including: <code>struct</code>, <code>class</code>, <code>function</code>, etc...</p>\n<p>But can you forward declare an <code>enum</code> in C++?</p>\n<p>No, you can\'t.</p>\n<p>But why not allow it? If it were allowed you could define your <code>enum</code> type in your header file, and your <code>enum</code> values in your source file. It sounds like it should be allowed, right?</p>\n<p>Wrong.</p>\n<p>In C++ there is no default type for <code>enum</code> like there is in C# (int). In C++ your <code>enum</code> type will be determined by the compiler to be any type that will fit the range of values you have for your <code>enum</code>.</p>\n<p>What does that mean?</p>\n<p>It means that your <code>enum</code>\'s underlying type cannot be fully determined until you have all of the values of the <code>enum</code> defined. Which means you cannot separate the declaration and definition of your <code>enum</code>. And therefore you cannot forward declare an <code>enum</code> in C++.</p>\n<p>The ISO C++ standard S7.2.5:</p>\n<blockquote>\n<p>The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than <code>int</code> unless the value of an enumerator cannot fit in an <code>int</code> or <code>unsigned int</code>. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of <code>sizeof()</code> applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of <code>sizeof()</code> applied to the underlying type.</p>\n</blockquote>\n<p>You can determine the size of an enumerated type in C++ by using the <code>sizeof</code> operator. The size of the enumerated type is the size of its underlying type. In this way you can guess which type your compiler is using for your <code>enum</code>.</p>\n<p>What if you specify the type of your <code>enum</code> explicitly like this:</p>\n<pre><code>enum Color : char { Red=0, Green=1, Blue=2};\nassert(sizeof Color == 1);\n</code></pre>\n<p>Can you then forward declare your <code>enum</code>?</p>\n<p>No. But why not?</p>\n<p>Specifying the type of an <code>enum</code> is not actually part of the current C++ standard. It is a VC++ extension. It will be part of C++0x though.</p>\n<p><a href="http://brianbondy.com/blog/id/93/forward-declaring-enums-in-c" rel="nofollow noreferrer">Source</a></p>\n'}, {'answer_id': 11382046, 'author': 'Leszek Swirski', 'author_id': 1509804, 'author_profile': 'https://Stackoverflow.com/users/1509804', 'pm_score': 2, 'selected': False, 'text': '<p>You can wrap the enum in a struct, adding in some constructors and type conversions, and forward declare the struct instead.</p>\n\n<pre><code>#define ENUM_CLASS(NAME, TYPE, VALUES...) \\\nstruct NAME { \\\n enum e { VALUES }; \\\n explicit NAME(TYPE v) : val(v) {} \\\n NAME(e v) : val(v) {} \\\n operator e() const { return e(val); } \\\n private:\\\n TYPE val; \\\n}\n</code></pre>\n\n<p>This appears to work:\n<a href="http://ideone.com/TYtP2" rel="nofollow">http://ideone.com/TYtP2</a></p>\n'}, {'answer_id': 11632184, 'author': 'Tom', 'author_id': 274460, 'author_profile': 'https://Stackoverflow.com/users/274460', 'pm_score': 7, 'selected': False, 'text': "<p>You can forward-declare an enum in C++11, so long as you declare its storage type at the same time. The syntax looks like this:</p>\n<pre><code>enum E : short;\nvoid foo(E e);\n\n....\n\nenum E : short\n{\n VALUE_1,\n VALUE_2,\n ....\n}\n</code></pre>\n<p>In fact, if the function never refers to the values of the enumeration, you don't need the complete declaration at all at that point.</p>\n<p>This is supported by G++ 4.6 and onwards (<code>-std=c++0x</code> or <code>-std=c++11</code> in more recent versions). Visual C++ 2013 supports this; in earlier versions it has some sort of non-standard support that I haven't figured out yet - I found some suggestion that a simple forward declaration is legal, but your mileage may vary.</p>\n"}, {'answer_id': 64886872, 'author': 'Pankaj Gaikar', 'author_id': 3307233, 'author_profile': 'https://Stackoverflow.com/users/3307233', 'pm_score': 0, 'selected': False, 'text': '<p>To anyone facing this for iOS/Mac/Xcode,</p>\n<p>If you are facing this while integrating C/C++ headers in XCode with Objective-C, <strong>just change the extension of your file from .mm to .m</strong></p>\n'}, {'answer_id': 74655121, 'author': 'Sunandan Nandi', 'author_id': 2722779, 'author_profile': 'https://Stackoverflow.com/users/2722779', 'pm_score': -1, 'selected': False, 'text': '<p>This way we can forward declare enum</p>\n<p><code>enum A : int;</code></p>\n<p>please refer the <a href="https://learn.microsoft.com/en-us/cpp/cpp/enumerations-cpp?view=msvc-170" rel="nofollow noreferrer">link</a> for details.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11437/']
|
71,417 |
<p>From question <em><a href="https://stackoverflow.com/questions/71323/how-to-replace-a-character-for-a-newline-in-vim">How to replace a character for a newline in Vim?</a></em>. You have to use \r when replacing text for a newline, like this</p>
<pre><code>:%s/%/\r/g
</code></pre>
<p>But when replacing end of lines and newlines for a character, you can do it like:</p>
<pre><code>:%s/\n/%/g
</code></pre>
<p>What section of the manual documents these behaviors, and what's the reasoning behind them?</p>
|
[{'answer_id': 71531, 'author': 'Aristotle Pagaltzis', 'author_id': 9410, 'author_profile': 'https://Stackoverflow.com/users/9410', 'pm_score': 6, 'selected': False, 'text': '<h3><a href="http://vimdoc.sf.net/htmldoc/pattern.html#NL-used-for-Nul" rel="noreferrer"><code>:help NL-used-for-Nul</code></a></h3>\n\n<blockquote>\n <h3>Technical detail:</h3>\n \n <p><code><Nul></code> characters in the file are stored as <code><NL></code> in memory. In the display\n they are shown as "<code>^@</code>". The translation is done when reading and writing\n files. To match a <code><Nul></code> with a search pattern you can just enter <a href="http://www.vim.org/htmldoc/insert.html#i_CTRL-@" rel="noreferrer">CTRL-@</a> or\n "<a href="http://www.vim.org/htmldoc/insert.html#i_CTRL-V" rel="noreferrer">CTRL-V</a> 000". This is probably just what you expect. Internally the\n character is replaced with a <code><NL></code> in the search pattern. What is unusual is\n that typing <a href="http://www.vim.org/htmldoc/insert.html#i_CTRL-V" rel="noreferrer">CTRL-V</a> <a href="http://www.vim.org/htmldoc/insert.html#i_CTRL-J" rel="noreferrer">CTRL-J</a> also inserts a <code><NL></code>, thus also searches for a <code><Nul></code>\n in the file. {Vi cannot handle <code><Nul></code> characters in the file at all}</p>\n</blockquote>\n\n<hr>\n'}, {'answer_id': 73438, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 8, 'selected': True, 'text': '<p>From <a href="http://vimdoc.sourceforge.net/htmldoc/pattern.html#/%5Cr" rel="noreferrer">vim docs on patterns</a>:</p>\n\n<blockquote>\n <p><code>\\r</code> matches <CR></p>\n \n <p><code>\\n</code> matches an end-of-line - \n When matching in a string instead of\n buffer text a literal newline\n character is matched.</p>\n</blockquote>\n'}, {'answer_id': 12388814, 'author': 'lmat - Reinstate Monica', 'author_id': 200985, 'author_profile': 'https://Stackoverflow.com/users/200985', 'pm_score': 8, 'selected': False, 'text': '<p>From <a href="http://vim.wikia.com/wiki/Search_and_replace" rel="noreferrer">http://vim.wikia.com/wiki/Search_and_replace</a> :</p>\n\n<blockquote>\n <p><strong>When Searching</strong></p>\n \n <p>...</p>\n \n <p><code>\\n</code> is newline, <code>\\r</code> is <code>CR</code> (carriage return = <code>Ctrl-M</code> = <code>^M</code>)</p>\n \n <p><strong>When Replacing</strong></p>\n \n <p>...</p>\n \n <p><code>\\r</code> is newline, <code>\\n</code> is a null byte (<code>0x00</code>).</p>\n</blockquote>\n'}, {'answer_id': 12389839, 'author': 'rking', 'author_id': 1410840, 'author_profile': 'https://Stackoverflow.com/users/1410840', 'pm_score': 7, 'selected': False, 'text': '<p>Another aspect to this is that <code>\\0</code>, which is traditionally NULL, is taken in\n<code>s//\\0/</code> to mean "the whole matched pattern". (Which, by the way, is redundant with, and longer than, <code>&</code>).</p>\n\n<ul>\n<li>So you can\'t use <code>\\0</code> to mean <code>NULL</code>, so you use <code>\\n</code></li>\n<li>So you can\'t use <code>\\n</code> to mean <code>\\n</code>, so you use <code>\\r</code>.</li>\n<li>So you can\'t use <code>\\r</code> to mean <code>\\r</code>, but I don\'t know who would want to add that char on purpose.</li>\n</ul>\n\n<p>—☈</p>\n'}, {'answer_id': 20491960, 'author': 'syockit', 'author_id': 219229, 'author_profile': 'https://Stackoverflow.com/users/219229', 'pm_score': 4, 'selected': False, 'text': '<p>First of all, open <a href="http://vimdoc.sourceforge.net/htmldoc/change.html#:s" rel="noreferrer"><code>:h :s</code></a> to see the section "4.2 Substitute" of documentation on "Change". Here\'s what the command accepts:</p>\n\n<pre><code>:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]\n</code></pre>\n\n<p>Notice the description about <code>pattern</code> and <code>string</code></p>\n\n<blockquote>\n <p>For the <code>{pattern}</code> see <a href="http://vimdoc.sourceforge.net/htmldoc/pattern.html#pattern" rel="noreferrer"><code>|pattern|</code></a>. <br>\n <code>{string}</code> can be a literal string, or something <br>\n special; see <a href="http://vimdoc.sourceforge.net/htmldoc/change.html#sub-replace-special" rel="noreferrer"><code>|sub-replace-special|</code></a>.</p>\n</blockquote>\n\n<p>So now you know that the search pattern and replacement patterns follow different rules.\nIf you follow the link to <code>|pattern|</code>, it takes you to the section that explains the whole regexp patterns used in Vim.</p>\n\n<p>Meanwhile, <code>|sub-replace-special|</code> takes you to the subsection of "4.2 Substitute", which contains the patterns for substitution, among which is <code>\\r</code> for line break/split.</p>\n\n<p>(The shortcut to this part of manual is <a href="http://vimdoc.sourceforge.net/htmldoc/change.html#:s%25" rel="noreferrer"><code>:h :s%</code></a>)</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5190/']
|
71,419 |
<p>I've heard many programmers, particularly Delphi programmers scorn the use of 'with'. </p>
<p>I thought it made programs run faster (only one reference to parent object) and that it was easier to read the code if used sensibly (less than a dozen lines of code and no nesting).</p>
<p>Here's an example:</p>
<pre><code>procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32);
begin
with ARect do FillRectS(Left, Top, Right, Bottom, Value);
end;
</code></pre>
<p>I like using <code>with</code>. What's wrong with me?</p>
|
[{'answer_id': 71432, 'author': 'Ralph M. Rickenbach', 'author_id': 4549416, 'author_profile': 'https://Stackoverflow.com/users/4549416', 'pm_score': 2, 'selected': False, 'text': '<p>I do not like it because it makes debbuging a hassle. You cannot read the value of a variable or the like by just hovering over it with a mouse.</p>\n'}, {'answer_id': 71438, 'author': 'Dan F', 'author_id': 11569, 'author_profile': 'https://Stackoverflow.com/users/11569', 'pm_score': 2, 'selected': False, 'text': "<p>This debate happens in Javascript a lot too.</p>\n\n<p>Basically, that With syntax makes it very hard to tell at a glance which Left/Top/etc property/method you're calling on.You could have a local variable called Left, and a property (it's been a while since I've done delphi, sorry if the name is wrong) called Left, perhaps even a function called Left. Anyone reading the code who isn't super familiar with the ARect structure could be very very lost.</p>\n"}, {'answer_id': 71447, 'author': 'Blorgbeard', 'author_id': 369, 'author_profile': 'https://Stackoverflow.com/users/369', 'pm_score': 2, 'selected': False, 'text': "<p>There's nothing wrong with it as long as you keep it simple and avoid ambiguities.</p>\n\n<p>As far as I'm aware, it doesn't speed anything up though - it's purely syntactic sugar.</p>\n"}, {'answer_id': 71470, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 4, 'selected': False, 'text': "<p>I prefer the VB syntax in this case because here, you need to prefix the members inside the with block with a <code>.</code> to avoid ambiguities:</p>\n\n<pre><code>With obj\n .Left = 10\n .Submit()\nEnd With\n</code></pre>\n\n<p>But really, there's nothing wrong with <code>with</code> in general.</p>\n"}, {'answer_id': 71471, 'author': 'Lars Truijens', 'author_id': 1242, 'author_profile': 'https://Stackoverflow.com/users/1242', 'pm_score': 5, 'selected': False, 'text': '<p>One annoyance with using with is that the debugger can\'t handle it. So it makes debugging more difficult.</p>\n\n<p>A bigger problem is that it is less easy to read the code. Especially if the with statement is a bit longer.</p>\n\n<pre><code>procedure TMyForm.ButtonClick(...)\nbegin\n with OtherForm do begin\n Left := 10;\n Top := 20;\n CallThisFunction;\n end;\nend;\n</code></pre>\n\n<p>Which Form\'s CallThisFunction will be called? Self (TMyForm) or OtherForm? You can\'t know without checking if OtherForm has a CallThisFunction method.</p>\n\n<p>And the biggest problem is that you can make bugs easy without even knowing it. What if both TMyForm and OtherForm have a CallThisFunction, but it\'s private. You might expect/want the OtherForm.CallThisFunction to be called, but it really is not. The compiler would have warned you if you didn\'t use the with, but now it doesn\'t.</p>\n\n<p>Using multiple objects in the with multiplies the problems. See <a href="http://blog.marcocantu.com/blog/with_harmful.html" rel="noreferrer">http://blog.marcocantu.com/blog/with_harmful.html</a></p>\n'}, {'answer_id': 71479, 'author': 'jedediah', 'author_id': 6342, 'author_profile': 'https://Stackoverflow.com/users/6342', 'pm_score': 1, 'selected': False, 'text': '<p>It permits incompetent or evil programmers to write unreadble code. Therefor, only use this feature if you are neither incompetent nor evil.</p>\n'}, {'answer_id': 71494, 'author': 'SoftDeveloper', 'author_id': 11805, 'author_profile': 'https://Stackoverflow.com/users/11805', 'pm_score': 2, 'selected': False, 'text': "<p>What you save in typing, you lose in readability.\nMany debuggers won't have a clue what you're referring to either so debugging is more difficult.\nIt doesn't make programs run faster.</p>\n\n<p>Consider making the code within your with statement a method of the object that you're refering to.</p>\n"}, {'answer_id': 71498, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>At work we give points for removing Withs from an existing Win 32 code base because of the extra effort needed to maintain code that uses them. I have found several bugs in a previous job where a local variable called BusinessComponent was masked by being within a With begin block for an object that a published property BusinessComponent of the same type. The compiler chose to use the published property and the code that meant to use the local variable crashed.</p>\n\n<p>I have seen code like</p>\n\n<p>With a,b,c,d do {except they are much longer names, just shortened here)\n begin\n i := xyz;<br>\n end;</p>\n\n<p>It can be a real pain trying to locate where xyz comes from. If it was c, I'd much sooner write it as </p>\n\n<p>i := c.xyz;</p>\n\n<p>You think it's pretty trivial to understand this but not in a function that was 800 lines long that used a with right at the start!</p>\n"}, {'answer_id': 71512, 'author': 'Graza', 'author_id': 11820, 'author_profile': 'https://Stackoverflow.com/users/11820', 'pm_score': 3, 'selected': False, 'text': '<p>It is not likely that "with" would make the code run faster, it is more likely that the compiler would compile it to the same executable code.</p>\n\n<p>The main reason people don\'t like "with" is that it can introduce confusion about namespace scope and precedence.</p>\n\n<p>There are cases when this is a real issue, and cases when this is a non-issue (non-issue cases would be as described in the question as "used sensibly").</p>\n\n<p>Because of the possible confusion, some developers choose to refrain from using "with" completely, even in cases where there may not be such confusion. This may seem dogmatic, however it can be argued that as code changes and grows, the use of "with" may remain even after code has been modified to an extent that would make the "with" confusing, and thus it is best not to introduce its use in the first place.</p>\n'}, {'answer_id': 71532, 'author': 'Matt Lacey', 'author_id': 1755, 'author_profile': 'https://Stackoverflow.com/users/1755', 'pm_score': -1, 'selected': False, 'text': "<p>We've recently banned it in our Delphi coding stnadards. </p>\n\n<p>The pros were frequently outweighing the cons.</p>\n\n<p>That is bugs were being introduced because of its misuse. These didn't justify the savings in time to write or execute the code.</p>\n\n<p>Yes, using with can led to (mildly) faster code execution.</p>\n\n<p>In the following, foo is only evaluated once:</p>\n\n<pre><code>with foo do\nbegin\n bar := 1;\n bin := x;\n box := 'abc';\nend\n</code></pre>\n\n<p>But, here it is evaluated three times:</p>\n\n<pre><code>foo.bar := 1;\nfoo.bin := x;\nfoo.box := 'abc';\n</code></pre>\n"}, {'answer_id': 71544, 'author': 'Flint', 'author_id': 11877, 'author_profile': 'https://Stackoverflow.com/users/11877', 'pm_score': 1, 'selected': False, 'text': '<blockquote>... run faster ...</blockquote>\n\n<p>Not necessarily - your compiler/interpreter is generally better at optimizing code than you are.</p>\n\n<p>I think it makes me say "yuck!" because it\'s lazy - when I\'m reading code (particularly someone else\'s) I like to see explicit code. So I\'d even write "this.field" instead of "field" in Java.</p>\n'}, {'answer_id': 2382602, 'author': 'Cruachan', 'author_id': 7315, 'author_profile': 'https://Stackoverflow.com/users/7315', 'pm_score': 2, 'selected': False, 'text': "<p>It's primarily a maintenance issue.</p>\n\n<p>The idea of WITH makes reasonable sense from a language point of view, and the argument that it keeps code, when used sensibly, smaller and clearer has some validity. However the problem is that most commercial code will be maintained by several different people over it's lifetime, and what starts out as a small, easily parsed, construct when written can easily mutate over time into unwieldy large structures where the scope of the WITH is not easily parsed by the maintainer. This naturally tends to produce bugs, and difficult to find ones at that. </p>\n\n<p>For example say we have a small function foo which contains three or four lines of code which have been wrapped inside a WITH block then there is indeed no issue. However a few years later this function may have expanded, under several programmers, into 40 or 50 lines of code still wrapped inside a WITH. This is now brittle, and is ripe for bugs to be introduced, particularly so if the maintainer stars introducing additional embedded WITH blocks.</p>\n\n<p>WITH has no other benefits - code should be parsed exactly the same and run at the same speed (I did some experiments with this in D6 inside tight loops used for 3D rendering and I could find no difference). The inability of the debugger to handle it is also an issue - but one that should have been fixed a while back and would be worth ignoring if there were any benefit. Unfortunately there isn't.</p>\n"}, {'answer_id': 2384989, 'author': 'markus_ja', 'author_id': 192292, 'author_profile': 'https://Stackoverflow.com/users/192292', 'pm_score': 4, 'selected': False, 'text': "<p>It would be great if the <code>with</code> statement would be extented the following way:</p>\n\n<pre><code>with x := ARect do\nbegin\n x.Left := 0;\n x.Rigth := 0;\n ...\nend;\n</code></pre>\n\n<p>You wouldn't need to declare a variable 'x'. It will be created by the compiler. It's quick to write and no confusion, which function is used.</p>\n"}, {'answer_id': 3126973, 'author': 'mmmm', 'author_id': 85592, 'author_profile': 'https://Stackoverflow.com/users/85592', 'pm_score': 2, 'selected': False, 'text': "<p>You can combine with statements, so you end up with </p>\n\n<pre><code>with Object1, Object2, Object3 do\nbegin\n //... Confusing statements here\nend\n</code></pre>\n\n<p>And if you think that the debugger is confused by one with, I don't see how anyone can determine what is going on in the <code>with</code> block</p>\n"}, {'answer_id': 3342110, 'author': 'ijcro', 'author_id': 403174, 'author_profile': 'https://Stackoverflow.com/users/403174', 'pm_score': -1, 'selected': False, 'text': '<p>For Delphi 2005 is exist hard error in with-do statement - evaluate pointer is lost and repace with pointer up. There have to use a local variable, not object type directly.</p>\n'}, {'answer_id': 12267500, 'author': 'Arnaud Bouchez', 'author_id': 458259, 'author_profile': 'https://Stackoverflow.com/users/458259', 'pm_score': 3, 'selected': False, 'text': "<p>In fact:</p>\n\n<pre><code>procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32);\nbegin\n with ARect do FillRectS(Left, Top, Right, Bottom, Value);\nend;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32);\nbegin\n FillRectS(ARect.Left, ARect.Top, ARect.Right, ARect.Bottom, Value);\nend;\n</code></pre>\n\n<p>Will generate exactly the same assembler code.</p>\n\n<p>The performance penalty can exist if the value of the <code>with</code> clause is a function or a method. In this case, if you want to have good maintenance AND good speed, just do what the compiler does behind the scene, i.e. <em>create a temporary variable</em>.</p>\n\n<p>In fact:</p>\n\n<pre><code>with MyRect do\nbegin\n Left := 0;\n Right := 0;\nend;\n</code></pre>\n\n<p>is encoded in pseudo-code as such by the compiler:</p>\n\n<pre><code>var aRect: ^TRect;\n\naRect := @MyRect;\naRect^.Left := 0;\naRect^.Right := 0;\n</code></pre>\n\n<p>Then <code>aRect</code> can be just a CPU register, but can also be a true temporary variable on stack. Of course, I use pointers here since <code>TRect</code> is a <code>record</code>. It is more direct for objects, since they already are pointers.</p>\n\n<p>Personally, I used with sometimes in my code, but I almost check every time the asm generated to ensure that it does what it should. Not everyone is able or has the time to do it, so IMHO a <em>local variable</em> is a good alternative to with.</p>\n\n<p>I really do not like such code:</p>\n\n<pre><code>for i := 0 to ObjList.Count-1 do\n for j := 0 to ObjList[i].NestedList.Count-1 do\n begin\n ObjList[i].NestedList[j].Member := 'Toto';\n ObjList[i].NestedList[j].Count := 10;\n end;\n</code></pre>\n\n<p>It is still pretty readable with with:</p>\n\n<pre><code>for i := 0 to ObjList.Count-1 do\n for j := 0 to ObjList[i].NestedList.Count-1 do\n with ObjList[i].NestedList[j] do\n begin\n Member := 'Toto';\n Count := 10;\n end;\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>for i := 0 to ObjList.Count-1 do\n with ObjList[i] do\n for j := 0 to NestedList.Count-1 do\n with NestedList[j] do\n begin\n Member := 'Toto';\n Count := 10;\n end;\n</code></pre>\n\n<p>but if the inner loop is huge, a local variable does make sense:</p>\n\n<pre><code>for i := 0 to ObjList.Count-1 do\nbegin\n Obj := ObjList[i];\n for j := 0 to Obj.NestedList.Count-1 do\n begin\n Nested := Obj.NestedList[j];\n Nested.Member := 'Toto';\n Nested.Count := 10;\n end;\nend;\n</code></pre>\n\n<p>This code won't be slower than <code>with</code>: compiler does it in fact behind the scene!</p>\n\n<p>By the way, it will allow easier debugging: you can put a breakpoint, then point your mouse on <code>Obj</code> or <code>Nested</code> directly to get the internal values.</p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11781/']
|
71,423 |
<p>I want to disable the selection of certain rows in a datagridview.</p>
<p>It must be possible to remove the select property for one or more datagridview rows in a datagridview shown in a winform. The goal is that the user can't select certain rows. (depending on a condition)</p>
<p>Thankx,</p>
|
[{'answer_id': 71665, 'author': 'szevvy', 'author_id': 11437, 'author_profile': 'https://Stackoverflow.com/users/11437', 'pm_score': 5, 'selected': True, 'text': "<p>If SelectionMode is FullRowSelect, then you'll need to override SetSelectedRowCore for that DataGridView, and not call the base SetSelectedRowCore for rows you don't want selected.</p>\n\n<p>If SelectionMode is not FullRowSelect, you'll want to additionally override SetSelectedCellCore (and not call the base SetSelectedCellCore for rows you don't want selected), as SetSelectedRowCore will only kick in if you click the row header and not an individual cell.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>public class MyDataGridView : DataGridView\n{\n protected override void SetSelectedRowCore(int rowIndex, bool selected)\n {\n if (selected && WantRowSelection(rowIndex))\n {\n base.SetSelectedRowCore(rowIndex, selected);\n }\n }\n\n protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected)\n {\n if (selected && WantRowSelection(rowIndex))\n {\n base.SetSelectedRowCore(rowIndex, selected);\n }\n }\n\n bool WantRowSelection(int rowIndex)\n {\n //return true if you want the row to be selectable, false otherwise\n }\n}\n</code></pre>\n\n<p>If you're using WinForms, crack open your designer.cs for the relevant form, and change the declaration of your DataGridView instance to use this new class instead of DataGridView, and also replace the this.blahblahblah = new System.Windows.Forms.DataGridView() to point to the new class.</p>\n"}, {'answer_id': 15474300, 'author': 'Asad Naeem', 'author_id': 390163, 'author_profile': 'https://Stackoverflow.com/users/390163', 'pm_score': -1, 'selected': False, 'text': '<pre><code>Private Sub dgvSomeDataGridView_SelectionChanged(sender As Object, e As System.EventArgs) Handles dgvSomeDataGridView.SelectionChanged\n dgvSomeDataGridView.ClearSelection()\nEnd Sub\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4392/']
|
71,429 |
<p><strong><em>Background:</em></strong>
I'm running a full-time job and a part-time job in the weekends, and both my employers have supplied a laptop for me to work on. Of course I also have my powerful workstation at home to work from, and sometimes when I'm at the office at my weekend job (it's in another city) I'm working from yet another workstation.</p>
<p><strong><em>Problem:</em></strong>
That makes a full 4 PC's I'm maintaining (software versions, licences and settings) just to do my work, and believe me, my list of prefered software is way too big.</p>
<p>I want to setup a Virtual Desktop on my VMware server, so I can work from the same installation and same session no matter which PC I'm working from.</p>
<p>Now I don't have the time and money to go through a full test of each setup, so I'd like to hear your experiences on the subject.</p>
<p><strong><em>Question:</em></strong>
Should I use a VMware virtual workstation with some remote logon software (like <a href="http://www.realvnc.com/" rel="nofollow noreferrer">realVNC</a>, <a href="http://www.teamviewer.com/" rel="nofollow noreferrer">teamviewer</a>, <a href="https://secure.logmein.com/" rel="nofollow noreferrer">logmein</a>, whatever...) or should I invest in a full VDI system like <a href="http://www.sun.com/software/vdi/index.jsp" rel="nofollow noreferrer">Sun</a> or <a href="http://www.vmware.com/products/vdi/" rel="nofollow noreferrer">VMware</a> provide?</p>
<p><strong><em>Edit:</em></strong>
I'm programming in Adobe Dreamweaver on Windows XP - but I run my servers on Debian and sometimes do quick edits in VIM too. First I intend to virtualize a WinXP with base installation, to see how it runs.</p>
|
[{'answer_id': 71449, 'author': 'prakash', 'author_id': 123, 'author_profile': 'https://Stackoverflow.com/users/123', 'pm_score': 0, 'selected': False, 'text': '<p>I guess you can live with Logmein Free. [Or Pro if u want those features]</p>\n'}, {'answer_id': 71450, 'author': 'RickyTheGeek', 'author_id': 7225, 'author_profile': 'https://Stackoverflow.com/users/7225', 'pm_score': 1, 'selected': False, 'text': '<p>Personally, I would go down the route of using a virtual workstation with some remote logon software. The network performance of VMWare has always been good in my experience, and depending on the OS, there may be a decent remote logon provided.</p>\n'}, {'answer_id': 71451, 'author': 'kfh', 'author_id': 6597, 'author_profile': 'https://Stackoverflow.com/users/6597', 'pm_score': 0, 'selected': False, 'text': "<p>Well, you don't say what OSs are involved, so.....</p>\n\n<p>For windows, I find that Remote Desktop works as well or better than anything else, although if you pay for the RealVNC version with the mirror driver, that's supposed to be as good.\nFor off site access for windows, www.logmein.com (the free version) works very well.</p>\n\n<p>If Unixes are involved, then VNC is definitely the way to go, there are various solutions for doing this remotely. Everything from redirection servers, to just forwarding a port in your firewall to an ssh server and setting up the various tunnels.</p>\n"}, {'answer_id': 71497, 'author': 'Silver Dragon', 'author_id': 9440, 'author_profile': 'https://Stackoverflow.com/users/9440', 'pm_score': 2, 'selected': False, 'text': '<p>If you want to work with the same installation, you should seriously consider the Remote Desktop Server/Client solution, bundled into every windows OS from XP. Basically, this app displays the view from your remote desktop to your local one, using highly compressed images; this works even via low-bandwidth internet connections\nWhile the XP version can only handle one user simultaneously, the one in Windows Server 2003 (and in Windows Server 2008, I presume) can handle multiple users (up to a certain limit).</p>\n\n<p>Disadvantages, and side-effects include:</p>\n\n<ul>\n<li>virtual pc via RDC is slow</li>\n<li>anything using the 3d acceleration will be slow (at least using XP/2003)</li>\n</ul>\n'}, {'answer_id': 72163, 'author': 'J Wynia', 'author_id': 1124, 'author_profile': 'https://Stackoverflow.com/users/1124', 'pm_score': 5, 'selected': True, 'text': '<p>I am a consultant and tend to work in a variety of environments. I carry a Thinkpad running VMWare Server over Ubuntu64 with 4GB of RAM. I\'ve got a 320GB secondary hard drive that I use just for VM\'s and have 25 or so different virtual machines that I boot up as the circumstances demand.</p>\n\n<p>They\'re a mix of Linux servers and workstations, Vista workstations and XP Workstations. I rarely use the VMWare server console. I access every one of them via one of the remote access methods.</p>\n\n<p>For Linux, I usually install FreeNX or NXServer for desktop access and just SSH for commandline. On Windows, I always use Remote Desktop (RDP), but, on XP, that only works on the "Pro" versions, not the "Home" versions. If all else fails, I install VNC and use that. VNC is at the bottom of my list because it really is a last resort. The only thing it\'s better than is not actually being able to use the machine.</p>\n\n<p>However, NX on Linux and RDP on Windows work WAY better than VNC. Other than little things like font smoothing and fancy desktop effects, the only big glitch would be if you are doing much with video or audio or DirectX-based stuff. Things like YouTube or other video do NOT like to work with any remote desktop protocol that I know of.</p>\n\n<p>As far as performance, using Linux as a host for VMWare provides really good management of system resources. The Windows-based VM\'s aren\'t able to just gobble up memory, but still get it when they need to.</p>\n\n<p>I do C# development all day in a virtual Vista workstation on Visual Studio 2008 and have absolutely no problems having 3-4 different solutions all open at once along with the normal stuff alongside over RDP on another machine, connected via wireless VPN. </p>\n\n<p>I can flip over to the host OS and it won\'t even be touching swap space at all. As far as I\'m concerned, it\'s a great way to work.</p>\n'}, {'answer_id': 145737, 'author': 'David Robbins', 'author_id': 19799, 'author_profile': 'https://Stackoverflow.com/users/19799', 'pm_score': 0, 'selected': False, 'text': '<p>Performance of VMWare is very good, and I can run a SQL Server slice, a web server slice and develop on my laptop simultaneously. The VM slices reside on a USB 2 portable drive and make it easy to port between my laptop and desktop.</p>\n\n<p>VM Console works well for accessing each environment, and depending on the configuration you set up with NAT vs. Bridging you can UNC to shares on slice.</p>\n\n<p>The nice by-product of this is that should you host machine take a nose dive you can quickly recover your development environment.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4112/']
|
71,440 |
<p>I have a UserControl in my Asp.net project that has a public property. I do not want this property to show up in the Visual Studio Property Window when a user highlights an instance of the UserControl in the IDE. What attribute (or other method) should I use to prevent it from showing up?</p>
<pre><code>class MyControl : System.Web.UI.UserControl {
// Attribute to prevent property from showing in VS Property Window?
public bool SampleProperty { get; set; }
// other stuff
}
</code></pre>
|
[{'answer_id': 71454, 'author': 'Phil Wright', 'author_id': 6276, 'author_profile': 'https://Stackoverflow.com/users/6276', 'pm_score': 5, 'selected': True, 'text': '<p>Use the following attribute ...</p>\n\n<pre><code>using System.ComponentModel;\n\n[Browsable(false)]\npublic bool SampleProperty { get; set; }\n</code></pre>\n\n<p>In VB.net, this <a href="https://stackoverflow.com/questions/71440/set-a-usercontrol-property-to-not-show-up-in-vs-properties-window#71481">will be</a>:</p>\n\n<pre><code><System.ComponentModel.Browsable(False)>\n</code></pre>\n'}, {'answer_id': 71459, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.c-sharpcorner.com/UploadFile/mgold/PropertyGridInCSharp11302005004139AM/PropertyGridInCSharp.aspx" rel="nofollow noreferrer">Tons of attributes</a> out there to control how the PropertyGrid works.</p>\n\n<pre><code>[Browsable(false)]\npublic bool HiddenProperty {get;set;}\n</code></pre>\n'}, {'answer_id': 71481, 'author': 'Codeslayer', 'author_id': 4021, 'author_profile': 'https://Stackoverflow.com/users/4021', 'pm_score': 2, 'selected': False, 'text': "<p>Use the <code>System.ComponentModel.Browsable</code> attribute to</p>\n\n<pre><code>> ' VB\n> \n> <System.ComponentModel.Browsable(False)>\n</code></pre>\n\n<p>or</p>\n\n<pre><code>// C#\n [System.ComponentModel.Browsable(false)]\n</code></pre>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51/']
|
71,468 |
<p>Does anybody know of a tool to test OCSP responses? Preferably, something that can be used from a Windows Command-line and/or can be included (easily) in a Java/python program </p>
|
[{'answer_id': 71674, 'author': 'Alexey Feldgendler', 'author_id': 10682, 'author_profile': 'https://Stackoverflow.com/users/10682', 'pm_score': 1, 'selected': False, 'text': '<p>The newpki client claims to be able to do that.\n<a href="http://www.newpki.org/" rel="nofollow noreferrer">http://www.newpki.org/</a></p>\n'}, {'answer_id': 71686, 'author': 'DustinB', 'author_id': 7888, 'author_profile': 'https://Stackoverflow.com/users/7888', 'pm_score': 0, 'selected': False, 'text': '<p>Can you test it over HTTP as described in the specs in Appendix A? If so, then you can use any web test util. Since you mentioned Java, <a href="http://jakarta.apache.org/jmeter/" rel="nofollow noreferrer">JMeter</a> comes to mind. With JMeter, you can create your java code to do validation, etc and re-use it in your test cases.</p>\n\n<p>Can you use something other than CMD line, such as a BASH script via <a href="http://cygwin.com" rel="nofollow noreferrer">Cygwin</a>?</p>\n\n<p>You\'d still have to script some things to validate the test, perhaps using <a href="http://www.openssl.org/docs/apps/ocsp.html" rel="nofollow noreferrer">openssl</a>?</p>\n\n<pre>\ncurl http://some.ocsp.url/ > resp.der\nopenssl ocsp -respin resp.der -text\n</pre>\n\n<p>See page <a href="http://www.ietf.org/rfc/rfc2560.txt" rel="nofollow noreferrer">http://www.ietf.org/rfc/rfc2560.txt</a></p>\n'}, {'answer_id': 72957, 'author': 'JJarava', 'author_id': 12344, 'author_profile': 'https://Stackoverflow.com/users/12344', 'pm_score': 3, 'selected': True, 'text': '<p>Looking a bit more, I think I\'ve found some answers:</p>\n\n<p>a) OpenSSL at the rescue:</p>\n\n<pre><code>openssl ocsp -whatever\n</code></pre>\n\n<p>For more info, <a href="http://www.openssl.org/docs/apps/ocsp.html" rel="nofollow noreferrer">http://www.openssl.org/docs/apps/ocsp.html</a></p>\n\n<p>b) <a href="http://www.openvalidation.org/" rel="nofollow noreferrer">http://www.openvalidation.org/</a> is another way of testing a cert. And via its links, I got to:</p>\n\n<ul>\n<li><a href="http://security.polito.it/tools/ocsp/" rel="nofollow noreferrer">http://security.polito.it/tools/ocsp/</a></li>\n<li>Ascertia OCSP Client tool (<a href="http://www.ascertia.com/products/ocsptool/" rel="nofollow noreferrer">http://www.ascertia.com/products/ocsptool/</a>)</li>\n<li>Ascertia OCSP Crusher tool (an OCSP load generator) (<a href="http://www.ascertia.com/products/ocspCrusher/" rel="nofollow noreferrer">http://www.ascertia.com/products/ocspCrusher/</a>)</li>\n</ul>\n\n<p>Thanks to all the answers!</p>\n'}, {'answer_id': 108678, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>bouncycastle has a Java crypto-provider and support for OCSP requests and responses. The differences between OCSPReq and OCSPRequest and OCSPResp and OCSPResponse class are a little confusing, though.</p>\n'}, {'answer_id': 3910224, 'author': 'ohe', 'author_id': 335247, 'author_profile': 'https://Stackoverflow.com/users/335247', 'pm_score': 1, 'selected': False, 'text': '<p>Here is a good ressource to have a simple OCSP Client or OCSP Responder with OpenSSL : <a href="http://backreference.org/2010/05/09/ocsp-verification-with-openssl/" rel="nofollow">http://backreference.org/2010/05/09/ocsp-verification-with-openssl/</a></p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
71,469 |
<p>Let's assume we've got the following Java code:</p>
<pre><code>public class Maintainer {
private Map<Enum, List<Listener>> map;
public Maintainer() {
this.map = new java.util.ConcurrentHashMap<Enum, List<Listener>>();
}
public void addListener( Listener listener, Enum eventType ) {
List<Listener> listeners;
if( ( listeners = map.get( eventType ) ) == null ) {
listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>();
map.put( eventType, listeners );
}
listeners.add( listener );
}
}
</code></pre>
<p>This code snippet is nothing but a bit improved listener pattern where each listener is telling what type of event it is interested in, and the provided method maintains a concurrent map of these relationships.</p>
<p>Initially, I wanted this method to be called via my own annotation framework, but bumped into a brick wall of various annotation limitations (e.g. you can't have <em>java.lang.Enum</em> as annotation param, also there's a set of various classloader issues) therefore decided to use Spring.</p>
<p>Could anyone tell me how do I Spring_ify_ this? What I want to achive is:<br>
1. Define <em>Maintainer</em> class as a Spring bean.<br>
2. Make it so that all sorts of listeners would be able to register themselves to <em>Maintainer</em> via XML by using <em>addListener</em> method. Spring doc nor Google are very generous in examples.</p>
<p>Is there a way to achieve this easily?</p>
|
[{'answer_id': 71504, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': True, 'text': "<p>What would be wrong with doing something like the following:</p>\n\n<p>Defining a 'Maintainer' interface with the addListener(Listener, Enum) method.</p>\n\n<p>Create a DefaultMaintainer class (as above) which implements Maintainer.</p>\n\n<p>Then, in each Listener class, 'inject' the Maintainer interface (constructor injection might be a good choice). The listener can then register itself with the Maintainer.</p>\n\n<p>other than that, I'm not 100% clear on exactly what your difficulty is with Spring at the moment! :)</p>\n"}, {'answer_id': 73129, 'author': 'Alexandre Victoor', 'author_id': 11897, 'author_profile': 'https://Stackoverflow.com/users/11897', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n <p>You said "... you can\'t have java.lang.Enum as"\n annotation param ..."</p>\n</blockquote>\n\n<p>I think you are wrong on that. I have recently used on a project something like this :</p>\n\n<pre><code>public @interface MyAnnotation {\n MyEnum value();\n}\n</code></pre>\n'}, {'answer_id': 75192, 'author': 'flicken', 'author_id': 12880, 'author_profile': 'https://Stackoverflow.com/users/12880', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n <p>1) Define Maintainer class as a Spring bean.</p>\n</blockquote>\n\n<p>Standard Spring syntax applies:</p>\n\n<pre><code><bean id="maintainer" class="com.example.Maintainer"/>\n</code></pre>\n\n<blockquote>\n <p>2) Make it so that all sorts of listeners would be able to register themselves to Maintainer via XML by using addListener method. Spring doc nor Google are very generous in examples.</p>\n</blockquote>\n\n<p>This is trickier. You <em>could</em> use <code>MethodInvokingFactoryBean</code> to individually call <code>maintainer#addListener</code>, like so:</p>\n\n<pre><code><bean id="listener" class="com.example.Listener"/>\n\n<bean id="maintainer.addListener" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">\n <property name="targetObject" ref="maintainer"/>\n <property name="targetMethod" value="addListener"/>\n <property name="arguments">\n <list>\n <ref>listener</ref>\n <value>com.example.MyEnum</value>\n </list>\n </property>\n</bean>\n</code></pre>\n\n<p>However, this is unwieldy, and potentially error-prone. I attempted something similar on a project, and created a Spring utility class to help out instead. I don\'t have the source code available at the moment, so I\'ll describe how to implement what I did. </p>\n\n<p>1) Refactor the event types listened to into a <code>MyListener</code> interface</p>\n\n<pre><code>public interface MyListener extends Listener {\n public Enum[] getEventTypes()\n}\n</code></pre>\n\n<p>Which changes the registration method to</p>\n\n<pre><code>public void addListener(MyListener listener)\n</code></pre>\n\n<p>2) Create Spring helper class that finds all relevant listeners in the context, and calls maintainer#addListener for each listener found. I would start with <code>BeanFilteringSupport</code>, and also implement <code>BeanPostProcessor</code> (or <code>ApplicationListener</code>) to register the beans after all beans have been instantiated.</p>\n'}, {'answer_id': 81555, 'author': 'mindas', 'author_id': 7345, 'author_profile': 'https://Stackoverflow.com/users/7345', 'pm_score': 0, 'selected': False, 'text': '<p>Thank you all for the answers. First, A quick follow up on all answers.<br>\n1. (alexvictor) Yes, you can have concrete <em>enum</em> as annotation param, but not <em>java.lang.Enum</em>.<br>\n2. Answer provided by flicken is correct, but unfortunately a bit scary. I am not a Spring expert but doing things this way (creating methods for easier Spring access) this seems to be a bit overkill, as is the <em>MethodInvokingFactoryBean</em> solution. Although I wanted to express my sincere thanks for your time and effort.<br>\n3. The answer by Phill is a bit unusual (instead of injecting listener bean, inject its maintainer!), but, I believe, the cleanest of all available. I think I will go down this path.</p>\n\n<p>Again, a big thanks you for your help.</p>\n'}, {'answer_id': 93461, 'author': 'finnw', 'author_id': 12048, 'author_profile': 'https://Stackoverflow.com/users/12048', 'pm_score': 2, 'selected': False, 'text': '<p>Slightly offtopic (as this is not about Spring) but there is a race condition in your implementation of AddListener:</p>\n\n<pre><code> if( ( listeners = map.get( eventType ) ) == null ) {\n listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>();\n map.put( eventType, listeners );\n }\n listeners.add( listener );\n</code></pre>\n\n<p>If two threads call this method at the same time (for an event type that previously had no listeners), map.get( eventType ) will return null in both threads, each thread will create its own CopyOnWriteArrayList (each containing a single listener), one thread will replace the list created by the other, and the first listener will be forgotten.</p>\n\n<p>To fix this, change:</p>\n\n<pre><code>private Map<Enum, List<Listener>> map;\n\n...\n\nmap.put( eventType, listeners );\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>private ConcurrentMap<Enum, List<Listener>> map;\n\n...\n\nmap.putIfAbsent( eventType, listeners );\nlisteners = map.get( eventType );\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7345/']
|
71,475 |
<p>I have created a namespace extension that is rooted under Desktop. The main purpose of the extension is to provide a virtual list of ZIP files that represent a list of configurable directories. When the user clicks one of the those items the contents of the related directory are zipped in place and the resulting ZIP file is stored in a cache folder.</p>
<p>All this works well aside a minor issue. If we go to Windows Explorer, open the extension and double click an item the opened file is the one from the cache. [CORRECT]</p>
<p>If on the other hand we open it by an Open Dialog the opened file is one from a Temporary Internet files directory. [INCORRECT]</p>
<p>What do I have to change for the Open Dialog (when used for example trough notepad.exe) to open the file from the cache folder and not from Temporary Internet files. I have tried to send allways the qualified file name in IShellFolder::GetDisplayNameOf but without any luck.</p>
|
[{'answer_id': 71504, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': True, 'text': "<p>What would be wrong with doing something like the following:</p>\n\n<p>Defining a 'Maintainer' interface with the addListener(Listener, Enum) method.</p>\n\n<p>Create a DefaultMaintainer class (as above) which implements Maintainer.</p>\n\n<p>Then, in each Listener class, 'inject' the Maintainer interface (constructor injection might be a good choice). The listener can then register itself with the Maintainer.</p>\n\n<p>other than that, I'm not 100% clear on exactly what your difficulty is with Spring at the moment! :)</p>\n"}, {'answer_id': 73129, 'author': 'Alexandre Victoor', 'author_id': 11897, 'author_profile': 'https://Stackoverflow.com/users/11897', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n <p>You said "... you can\'t have java.lang.Enum as"\n annotation param ..."</p>\n</blockquote>\n\n<p>I think you are wrong on that. I have recently used on a project something like this :</p>\n\n<pre><code>public @interface MyAnnotation {\n MyEnum value();\n}\n</code></pre>\n'}, {'answer_id': 75192, 'author': 'flicken', 'author_id': 12880, 'author_profile': 'https://Stackoverflow.com/users/12880', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n <p>1) Define Maintainer class as a Spring bean.</p>\n</blockquote>\n\n<p>Standard Spring syntax applies:</p>\n\n<pre><code><bean id="maintainer" class="com.example.Maintainer"/>\n</code></pre>\n\n<blockquote>\n <p>2) Make it so that all sorts of listeners would be able to register themselves to Maintainer via XML by using addListener method. Spring doc nor Google are very generous in examples.</p>\n</blockquote>\n\n<p>This is trickier. You <em>could</em> use <code>MethodInvokingFactoryBean</code> to individually call <code>maintainer#addListener</code>, like so:</p>\n\n<pre><code><bean id="listener" class="com.example.Listener"/>\n\n<bean id="maintainer.addListener" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">\n <property name="targetObject" ref="maintainer"/>\n <property name="targetMethod" value="addListener"/>\n <property name="arguments">\n <list>\n <ref>listener</ref>\n <value>com.example.MyEnum</value>\n </list>\n </property>\n</bean>\n</code></pre>\n\n<p>However, this is unwieldy, and potentially error-prone. I attempted something similar on a project, and created a Spring utility class to help out instead. I don\'t have the source code available at the moment, so I\'ll describe how to implement what I did. </p>\n\n<p>1) Refactor the event types listened to into a <code>MyListener</code> interface</p>\n\n<pre><code>public interface MyListener extends Listener {\n public Enum[] getEventTypes()\n}\n</code></pre>\n\n<p>Which changes the registration method to</p>\n\n<pre><code>public void addListener(MyListener listener)\n</code></pre>\n\n<p>2) Create Spring helper class that finds all relevant listeners in the context, and calls maintainer#addListener for each listener found. I would start with <code>BeanFilteringSupport</code>, and also implement <code>BeanPostProcessor</code> (or <code>ApplicationListener</code>) to register the beans after all beans have been instantiated.</p>\n'}, {'answer_id': 81555, 'author': 'mindas', 'author_id': 7345, 'author_profile': 'https://Stackoverflow.com/users/7345', 'pm_score': 0, 'selected': False, 'text': '<p>Thank you all for the answers. First, A quick follow up on all answers.<br>\n1. (alexvictor) Yes, you can have concrete <em>enum</em> as annotation param, but not <em>java.lang.Enum</em>.<br>\n2. Answer provided by flicken is correct, but unfortunately a bit scary. I am not a Spring expert but doing things this way (creating methods for easier Spring access) this seems to be a bit overkill, as is the <em>MethodInvokingFactoryBean</em> solution. Although I wanted to express my sincere thanks for your time and effort.<br>\n3. The answer by Phill is a bit unusual (instead of injecting listener bean, inject its maintainer!), but, I believe, the cleanest of all available. I think I will go down this path.</p>\n\n<p>Again, a big thanks you for your help.</p>\n'}, {'answer_id': 93461, 'author': 'finnw', 'author_id': 12048, 'author_profile': 'https://Stackoverflow.com/users/12048', 'pm_score': 2, 'selected': False, 'text': '<p>Slightly offtopic (as this is not about Spring) but there is a race condition in your implementation of AddListener:</p>\n\n<pre><code> if( ( listeners = map.get( eventType ) ) == null ) {\n listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>();\n map.put( eventType, listeners );\n }\n listeners.add( listener );\n</code></pre>\n\n<p>If two threads call this method at the same time (for an event type that previously had no listeners), map.get( eventType ) will return null in both threads, each thread will create its own CopyOnWriteArrayList (each containing a single listener), one thread will replace the list created by the other, and the first listener will be forgotten.</p>\n\n<p>To fix this, change:</p>\n\n<pre><code>private Map<Enum, List<Listener>> map;\n\n...\n\nmap.put( eventType, listeners );\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>private ConcurrentMap<Enum, List<Listener>> map;\n\n...\n\nmap.putIfAbsent( eventType, listeners );\nlisteners = map.get( eventType );\n</code></pre>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6508/']
|
71,476 |
<p>We need to get data out of some Hyperion cubes (databases) using SSIS. Are there any connection managers available for this? Has anyone done this? </p>
|
[{'answer_id': 84765, 'author': 'CodeRot', 'author_id': 14134, 'author_profile': 'https://Stackoverflow.com/users/14134', 'pm_score': 0, 'selected': False, 'text': "<p>I don't have any experience with Hyperion, but can you make use of the Script Task in SSIS?</p>\n"}, {'answer_id': 141349, 'author': 'Brad_Z', 'author_id': 22273, 'author_profile': 'https://Stackoverflow.com/users/22273', 'pm_score': 1, 'selected': False, 'text': "<p>There are some third party connectors out there. Don't think any exist from oracle or microsoft.</p>\n"}, {'answer_id': 11457735, 'author': 'jwj', 'author_id': 611797, 'author_profile': 'https://Stackoverflow.com/users/611797', 'pm_score': 1, 'selected': False, 'text': "<p>I know this is a very old question but I just happened upon it and thought I would offer some perspective. There isn't build in support for getting data from Hyperion with SSIS. There are a few ways to go, however. </p>\n\n<p>You can fairly easily export Hyperion data with a calc or report script to text/SQL. You could use SSIS to run a batch file that kicks off a Hyperion job that loads up a SQL database or text file, <em>then</em> load it with SSIS. </p>\n\n<p>There are a handful of tools with Essbase adapters so you can use those if you aren't using SSIS. </p>\n"}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
71,478 |
<p>Is it possible in <code>PHP (as it is in C++)</code> to declare a <code>class method</code> OUTSIDE the <code>class definition?</code></p>
|
[{'answer_id': 71502, 'author': 'Silver Dragon', 'author_id': 9440, 'author_profile': 'https://Stackoverflow.com/users/9440', 'pm_score': 1, 'selected': False, 'text': '<p>No. </p>\n\n<p>You can extend previously declared classes, though, if that helps.</p>\n'}, {'answer_id': 71545, 'author': 'Michał Niedźwiedzki', 'author_id': 2169, 'author_profile': 'https://Stackoverflow.com/users/2169', 'pm_score': 3, 'selected': False, 'text': '<p>No, as of PHP 5.2. However, you may use <code>__call</code> magic method to forward call to arbitrary function or method.</p>\n\n<pre><code>class A {\n\n public function __call($method, $args) {\n if ($method == \'foo\') {\n return call_user_func_array(\'bar\', $args);\n }\n }\n\n}\n\nfunction bar($x) {\n echo $x;\n}\n\n$a = new A();\n$a->foo(\'12345\'); // will result in calling bar(\'12345\')\n</code></pre>\n\n<p>In PHP 5.4 there is support for <em>traits</em>. Trait is an implementation of method(s) that cannot be instantiated as standalone object. Instead, trait can be used to extend class with contained implementation. Learn more on Traits <a href="http://www.stefan-marr.de/artikel/rfc-traits-for-php.html" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 71550, 'author': 'deresh', 'author_id': 11851, 'author_profile': 'https://Stackoverflow.com/users/11851', 'pm_score': 0, 'selected': False, 'text': '<p>No it is not posible. if you define function/method outside class construct it becomes global function.</p>\n'}, {'answer_id': 71551, 'author': 'Paul Dixon', 'author_id': 6521, 'author_profile': 'https://Stackoverflow.com/users/6521', 'pm_score': 2, 'selected': False, 'text': '<p>You could perhaps override <a href="http://php.net/manual/en/language.oop5.overloading.php" rel="nofollow noreferrer">__call or __callStatic</a> to locate a missing method at runtime, but you\'d have to make up your own system for locating and calling the code. For example, you could load a "Delegate" class to handle the method call.</p>\n\n<p>Here\'s an example - if you tried to call $foo->bar(), the class would attempt to create a FooDelegate_bar class, and call bar() on it with the same arguments. If you\'ve got class auto-loading set up, the delegate can live in a separate file until required...</p>\n\n<pre><code>class Foo {\n\n public function __call($method, $args) {\n $delegate="FooDelegate_".$method;\n if (class_exists($delegate))\n {\n $handler=new $delegate($this);\n return call_user_func_array(array(&$handler, $method), $args);\n }\n\n\n }\n\n}\n</code></pre>\n'}, {'answer_id': 71559, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 0, 'selected': False, 'text': "<p>C++ can't do this either. Did you mix up declaration with de<em>finition</em>?</p>\n"}, {'answer_id': 71611, 'author': 'joelhardi', 'author_id': 11438, 'author_profile': 'https://Stackoverflow.com/users/11438', 'pm_score': 0, 'selected': False, 'text': '<p>No, as everyone has said, it is not strictly possible.</p>\n\n<p>However, you can do <a href="http://www.symfony-project.org/book/1_0/17-Extending-Symfony" rel="nofollow noreferrer">something like this</a> to emulate a mixin in PHP or add methods to a class at runtime, which is about as close as you\'re going to get. Basically, it\'s just using design patterns to achieve the same functionality. Zope 3 does something similar to emulate mixins in Python, another language that doesn\'t support them directly.</p>\n'}, {'answer_id': 1267223, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Yes it is possible to add a method to a PHP class after it is defined. You want to use <a href="http://www.php.net/manual/en/ref.classkit.php" rel="noreferrer">classkit</a>, which is an "experimental" extension. It appears that this extension isn\'t enabled by default however, so it depends on if you can compile a custom PHP binary or load PHP DLLs if on windows (for instance Dreamhost does allow custom PHP binaries, and they\'re pretty easy to setup).</p>\n\n<pre><code><?php\nclass A { }\nclasskit_method_add(\'A\', \'bar\', \'$message\', \'echo $message;\', \n CLASSKIT_ACC_PUBLIC); \n$a = new A();\n$a->bar(\'Hello world!\');\n</code></pre>\n\n<p>Example from the PHP manual:</p>\n\n<pre><code><?php\nclass Example {\n function foo() {\n echo "foo!\\n";\n }\n}\n\n// create an Example object\n$e = new Example();\n\n// Add a new public method\nclasskit_method_add(\n \'Example\',\n \'add\',\n \'$num1, $num2\',\n \'return $num1 + $num2;\',\n CLASSKIT_ACC_PUBLIC\n);\n\n// add 12 + 4\necho $e->add(12, 4);\n</code></pre>\n'}, {'answer_id': 8020459, 'author': 'jocap', 'author_id': 305047, 'author_profile': 'https://Stackoverflow.com/users/305047', 'pm_score': 2, 'selected': False, 'text': '<p>As PHP 5.3 supports closures, you can dynamically define instance methods as variables holding closures:</p>\n\n<pre><code>$class->foo = function (&$self, $n) {\n print "Current \\$var: " . $self->var . "\\n";\n $self->var += $n;\n print "New \\$var: " .$self->var . "\\n";\n};\n</code></pre>\n\n<p>Taking <code>$self</code> (you can\'t use <code>$this</code> outside object context) as a reference (<code>&</code>), you can modify the instance.</p>\n\n<p>However, problems occur when you try to call the function normally:</p>\n\n<pre><code>$class->foo(2);\n</code></pre>\n\n<p>You get a fatal error. PHP thinks <code>foo</code> is a method of <code>$class</code>, because of the syntax. Also, you must pass the instance as the first argument.</p>\n\n<p>There is luckily a special function for calling functions by name called <code>call_user_func</code>:</p>\n\n<pre><code>call_user_func($class->foo, &$class, 2);\n# => Current $var: 0\n# => New $var: 2\n</code></pre>\n\n<p>Just remember to put <code>&</code> before the instance variable.</p>\n\n<p>What\'s even easier is if you use the <code>__call</code> magic method:</p>\n\n<pre><code>class MyClass {\n public function __call ($method, $arguments) {\n if (isset($this->$method)) {\n call_user_func_array($this->$method, array_merge(array(&$this), $arguments));\n }\n }\n}\n</code></pre>\n\n<p>Now you can call <code>$class->foo(2)</code> instead. The magic <code>__call</code> method catches the call to an unknown method, and calls the closure in the <code>$class->foo</code> variable with the same name as the called method.</p>\n\n<p>Of course, if <code>$class->var</code> was private, the closure in stored in the <code>$class->foo</code> variable wouldn\'t be able to access it.</p>\n'}]
|
2008/09/16
|
['https://Stackoverflow.com/questions/71478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.