qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
254,669 |
<p>I've been working with some C# legacy code and I've been seeing a lot of @ symbols in front of variable names. What does this signify or do?</p>
<p>Currently I'm seeing it a lot in front of variables with common names that aren't reserved. E.g.:</p>
<pre><code>MyProcedure(@step.LoadInstanceId, @step.ResultCode, @step.StatusCode);
</code></pre>
<p>Given that step isn't a reserved word, is there any reason that they should be escaped?</p>
|
[
{
"answer_id": 254674,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": 9,
"selected": true,
"text": "<p>It's just a way to allow declaring reserved keywords as vars.</p>\n\n<pre><code>void Foo(int @string)\n</code></pre>\n"
},
{
"answer_id": 254676,
"author": "Jacob Carpenter",
"author_id": 26627,
"author_profile": "https://Stackoverflow.com/users/26627",
"pm_score": 3,
"selected": false,
"text": "<p>This escapes reserved words in C#.</p>\n"
},
{
"answer_id": 254683,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>It allows you to use a reserved word, like 'public' for example, as a variable name.</p>\n\n<pre><code>string @public = \"foo\";\n</code></pre>\n\n<p>I would not recommend this, as it can lead to unecessary confusion. </p>\n"
},
{
"answer_id": 254684,
"author": "Gabe Hollombe",
"author_id": 30632,
"author_profile": "https://Stackoverflow.com/users/30632",
"pm_score": 4,
"selected": false,
"text": "<p>Putting @ in front of a string tells the compuler not to process escape sequences found within the string.</p>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/362314fe(VS.71).aspx\" rel=\"noreferrer\">the documentation</a>:</p>\n\n<p>The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:</p>\n\n<pre><code>@\"c:\\Docs\\Source\\a.txt\" // rather than \"c:\\\\Docs\\\\Source\\\\a.txt\"\n</code></pre>\n\n<p>To include a double quotation mark in an @-quoted string, double it:</p>\n\n<pre><code>@\"\"\"Ahoy!\"\" cried the captain.\" // \"Ahoy!\" cried the captain.\n</code></pre>\n\n<p>Another use of the @ symbol is to use referenced (/reference) identifiers that happen to be C# keywords. For more information, see <a href=\"http://msdn.microsoft.com/en-us/library/aa664670(VS.71).aspx\" rel=\"noreferrer\">2.4.2 Identifiers</a>.</p>\n"
},
{
"answer_id": 8575886,
"author": "mklein",
"author_id": 487371,
"author_profile": "https://Stackoverflow.com/users/487371",
"pm_score": 2,
"selected": false,
"text": "<p>The original question asks for a reason why one would escape a not-reserved word. What comes to my mind is that if <code>step</code> would become a reserved word in future the code example would still compile. I guess it is also a valid option for code generators.</p>\n"
},
{
"answer_id": 8575970,
"author": "Stilgar",
"author_id": 122507,
"author_profile": "https://Stackoverflow.com/users/122507",
"pm_score": 3,
"selected": false,
"text": "<p>The @ sign is used with identifiers that are the same as language keywords. There are two main uses for this\n - interoperating with non-C# code. In languages like VB or IronPython the keywords are not the same as in C# and they may have declared classes and properties with names that match C# keywords. If this feature was not present this code would not be accessible in C#.\n - machine generated code. If a code generator generates code based on some external source (for example WSDL) the generator can just prefix all identifiers with @ and not check and convert identifiers that match C# keywords.</p>\n\n<p>Are you sure that your case is not the second?</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7756/"
] |
I've been working with some C# legacy code and I've been seeing a lot of @ symbols in front of variable names. What does this signify or do?
Currently I'm seeing it a lot in front of variables with common names that aren't reserved. E.g.:
```
MyProcedure(@step.LoadInstanceId, @step.ResultCode, @step.StatusCode);
```
Given that step isn't a reserved word, is there any reason that they should be escaped?
|
It's just a way to allow declaring reserved keywords as vars.
```
void Foo(int @string)
```
|
254,673 |
<p>I have an abstract base class which acts as an interface.</p>
<p>I have two "sets" of derived classes, which implement half of the abstract class. ( one "set" defines the abstract virtual methods related to initialization, the other "set" defines those related to the actual "work". )</p>
<p>I then have derived classes which use multiple inheritance to construct fully defined classes ( and does not add anything itself ).</p>
<p>So: ( bad pseudocode )</p>
<pre><code>class AbsBase {
virtual void init() = 0;
virtual void work() = 0;
}
class AbsInit : public AbsBase {
void init() { do_this(); }
// work() still abs
}
class AbsWork : public AbsBase {
void work() { do_this(); }
// init() still abs
}
class NotAbsTotal : public AbsInit, public AbsWork {
// Nothing, both should be defined
}
</code></pre>
<p>First of all, can I do this? Can I inherit from two classes which are both derived from the same Base? (I hope so).</p>
<p>Here is the "real problem", though (I lied a bit above to simplify the example).</p>
<p>What I have really gone and done is add non abstract accessors methods to the base class:</p>
<pre><code>class AbsBase {
public:
void init() { init_impl(); }
void work() { work_impl(); }
private:
virtual void init_impl() = 0;
virtual void work_impl() = 0;
}
</code></pre>
<p>Because, a common idiom is to make all virtual methods private.</p>
<p>Unfortunately, now both AbsInit, and AbsWork inherit these methods, and so NotAbsTotal inherits "two of each" ( I realize I may be butchering what is really happening at compile time ).</p>
<p>Anyway, g++ complains that: "request for member init() is ambiguous" when trying to use the class.</p>
<p>I assume that, had I used my AbsBase class as a pure interface, this would have been avoided ( assuming that the top example is valid ).</p>
<p>So:
- Am I way off with my implementation?
- Is this a limitation of the idiom of making virtual methods private?
- How do I refactor my code to do what I want? ( Provide one common interface, but allow a way to swap out implementations for "sets" of member functions )</p>
<p>Edit:</p>
<p>Seems I am not the first one:
<a href="http://en.wikipedia.org/wiki/Diamond_problem" rel="noreferrer">http://en.wikipedia.org/wiki/Diamond_problem</a></p>
<p>Seems Virtual Inheritance is the solution here. I have heard of virtual inheritance before, but I have not wrapped my head around it. I am still open to suggestions.</p>
|
[
{
"answer_id": 254696,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<p>It can be done, although it gives most the shivers.</p>\n\n<p>You need to use \"virtual inheritance\", the syntax for which is something like</p>\n\n<pre><code>class AbsInit: public virtual AbsBase {...};\nclass AbsWork: public virtual AbsBase {...};\nclass NotAbsTotal: public AbsInit, public AbsWork {...};\n</code></pre>\n\n<p>Then you have to specify which function you want to use:</p>\n\n<pre><code>NotAbsTotal::work()\n{\n AbsInit::work_impl();\n}\n</code></pre>\n\n<p>(UPDATED with correct syntax)</p>\n"
},
{
"answer_id": 254704,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 1,
"selected": false,
"text": "<p>You need to to declare the inheritance as virtual:</p>\n\n<pre><code>struct AbsBase {\n virtual void init() = 0;\n virtual void work() = 0;\n};\n\nstruct AbsInit : virtual public AbsBase {\n void init() { }\n};\n\nstruct AbsWork : virtual public AbsBase {\n void work() { }\n};\n\nstruct NotAbsTotal : virtual public AbsInit, virtual public AbsWork {\n};\n\nvoid f(NotAbsTotal *p)\n{\n p->init();\n}\n\nNotAbsTotal x;\n</code></pre>\n"
},
{
"answer_id": 254713,
"author": "comingstorm",
"author_id": 210211,
"author_profile": "https://Stackoverflow.com/users/210211",
"pm_score": 6,
"selected": true,
"text": "<p>It looks like you want to do virtual inheritance. Whether that turns out to actually be a good idea is another question, but here's how you do it:</p>\n\n<pre><code>\nclass AbsBase {...};\nclass AbsInit: public virtual AbsBase {...};\nclass AbsWork: public virtual AbsBase {...};\nclass NotAbsTotal: public AbsInit, public AbsWork {...};\n</code></pre>\n\n<p>Basically, the default, non-virtual multiple inheritance will include a copy of <em>each base class</em> in the derived class, and includes all their methods. This is why you have two copies of AbsBase -- and the reason your method use is ambiguous is both sets of methods are loaded, so C++ has no way to know which copy to access!</p>\n\n<p>Virtual inheritance condenses all references to a virtual base class into one datastructure. This should make the methods from the base class unambiguous again. However, note: if there is additional data in the two intermediate classes, there may be some small additional runtime overhead, to enable the code to find the shared virtual base class.</p>\n"
},
{
"answer_id": 255356,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 0,
"selected": false,
"text": "<p>You have to start thinking in the terms of what you are trying to model here.</p>\n\n<p>Public inheritance should only ever be used to model an \"isa\" relationship, e.g. a dog is a animal, a square is a shape, etc.</p>\n\n<p>Have a look at Scott Meyer's book Effective C++ for an excellent essay on what the various aspects of OO design should only ever be interpreted as.</p>\n\n<p>Edit: I forgot to say that while the answers so far provided are technically correct I don't think any of them address the issues of what you are trying to model and that is the crux of your problem!</p>\n\n<p>HTH</p>\n\n<p>cheers,</p>\n\n<p>Rob</p>\n"
},
{
"answer_id": 18582513,
"author": "Techman92",
"author_id": 2741351,
"author_profile": "https://Stackoverflow.com/users/2741351",
"pm_score": 0,
"selected": false,
"text": "<p>I found a good and simple example at the below link. The article explains with an example program for calculating the area and perimeter of a rectangle. You can check it..cheers</p>\n\n<p>Multilevel Inheritance is an inheritance hierarchy wherein one derived class inherits from multiple Base Classes. Read more..</p>\n\n<p><a href=\"http://www.mobihackman.in/2013/09/multiple-inheritance-example.html\" rel=\"nofollow\">http://www.mobihackman.in/2013/09/multiple-inheritance-example.html</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29701/"
] |
I have an abstract base class which acts as an interface.
I have two "sets" of derived classes, which implement half of the abstract class. ( one "set" defines the abstract virtual methods related to initialization, the other "set" defines those related to the actual "work". )
I then have derived classes which use multiple inheritance to construct fully defined classes ( and does not add anything itself ).
So: ( bad pseudocode )
```
class AbsBase {
virtual void init() = 0;
virtual void work() = 0;
}
class AbsInit : public AbsBase {
void init() { do_this(); }
// work() still abs
}
class AbsWork : public AbsBase {
void work() { do_this(); }
// init() still abs
}
class NotAbsTotal : public AbsInit, public AbsWork {
// Nothing, both should be defined
}
```
First of all, can I do this? Can I inherit from two classes which are both derived from the same Base? (I hope so).
Here is the "real problem", though (I lied a bit above to simplify the example).
What I have really gone and done is add non abstract accessors methods to the base class:
```
class AbsBase {
public:
void init() { init_impl(); }
void work() { work_impl(); }
private:
virtual void init_impl() = 0;
virtual void work_impl() = 0;
}
```
Because, a common idiom is to make all virtual methods private.
Unfortunately, now both AbsInit, and AbsWork inherit these methods, and so NotAbsTotal inherits "two of each" ( I realize I may be butchering what is really happening at compile time ).
Anyway, g++ complains that: "request for member init() is ambiguous" when trying to use the class.
I assume that, had I used my AbsBase class as a pure interface, this would have been avoided ( assuming that the top example is valid ).
So:
- Am I way off with my implementation?
- Is this a limitation of the idiom of making virtual methods private?
- How do I refactor my code to do what I want? ( Provide one common interface, but allow a way to swap out implementations for "sets" of member functions )
Edit:
Seems I am not the first one:
<http://en.wikipedia.org/wiki/Diamond_problem>
Seems Virtual Inheritance is the solution here. I have heard of virtual inheritance before, but I have not wrapped my head around it. I am still open to suggestions.
|
It looks like you want to do virtual inheritance. Whether that turns out to actually be a good idea is another question, but here's how you do it:
```
class AbsBase {...};
class AbsInit: public virtual AbsBase {...};
class AbsWork: public virtual AbsBase {...};
class NotAbsTotal: public AbsInit, public AbsWork {...};
```
Basically, the default, non-virtual multiple inheritance will include a copy of *each base class* in the derived class, and includes all their methods. This is why you have two copies of AbsBase -- and the reason your method use is ambiguous is both sets of methods are loaded, so C++ has no way to know which copy to access!
Virtual inheritance condenses all references to a virtual base class into one datastructure. This should make the methods from the base class unambiguous again. However, note: if there is additional data in the two intermediate classes, there may be some small additional runtime overhead, to enable the code to find the shared virtual base class.
|
254,694 |
<p>I see little functional difference between using a property</p>
<pre><code>public readonly property foo as string
get
return bar
end get
end property
</code></pre>
<p>or a function</p>
<pre><code>public function foo() as string
return bar
end function
</code></pre>
<p>Why would I want to use one form over the other?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 254700,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "<p>It's purely a matter of appearance. Methods imply doing so action, while properties imply getting some data.</p>\n"
},
{
"answer_id": 254706,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>Besides the semantics mentioned by James (statement of intent), properties play a special role since their value is displayed by the debugger and may be used in visual designers.</p>\n\n<p>As a consequence, make sure that properties' values don't change without some outside action because otherwise, the debugger will screw up your program.</p>\n"
},
{
"answer_id": 254707,
"author": "Corey Gaudin",
"author_id": 31195,
"author_profile": "https://Stackoverflow.com/users/31195",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I know, it all compiles to the same thing. A property in IL for .NET is really just a getPropertyName and setPropertyName function for a property called PropertyName.</p>\n\n<p>So its really a matter of style in that regard. It just reads better to see the following:</p>\n\n<pre><code>person.Address.Street;\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>person.Address().Street();\n</code></pre>\n\n<p>So, in a way, its really a matter of code aesthetics. </p>\n\n<p>Unfortunately for me in <s>.NET</s> C#, is not as elegant as Ruby in that <code>()</code> are always optional.</p>\n"
},
{
"answer_id": 254714,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 5,
"selected": true,
"text": "<p>I read an interesting article recently in Visual Studio Magazine that discussed the different between Methods and Properties.</p>\n\n<p>Properties are supposed to return a value and the same value each time unless something else is called in between. </p>\n\n<p>A Method on the other hand is typically expected to do something in the background to get the value, or that the method may change the value each time it is called, like GetNextId() or something.</p>\n\n<p>DateTime.Now is a good example of a Property that should have been a Method since it returns a different value each time it is used.</p>\n\n<p><strong>For those interested- here is the article</strong></p>\n\n<p><a href=\"http://visualstudiomagazine.com/articles/2008/08/01/choose-between-methods-and-properties.aspx\" rel=\"noreferrer\">Choose Between Methods and Properties</a></p>\n"
},
{
"answer_id": 254780,
"author": "John Kraft",
"author_id": 7495,
"author_profile": "https://Stackoverflow.com/users/7495",
"pm_score": 2,
"selected": false,
"text": "<p>In my understanding, you cannot databind to methods; only properties. Thus properties carry that added benefit.</p>\n"
},
{
"answer_id": 254841,
"author": "Maxime Rouiller",
"author_id": 24975,
"author_profile": "https://Stackoverflow.com/users/24975",
"pm_score": 2,
"selected": false,
"text": "<p>If you are basing yourself upon the Framework Design Guidelines, you must be using a method only when you are actually performing an action or accessing resouces that could be expensive to use(database, network).</p>\n\n<p>The property give the user the impression that the values are stored in memory and that reading a property is fast while calling a method might have further implication than just \"get the value\".</p>\n\n<p>Brad Abrams actually wrote an <a href=\"http://blogs.msdn.com/brada/archive/2003/11/13/50672.aspx\" rel=\"nofollow noreferrer\">article</a> about it and is even posted on MSDN <a href=\"http://msdn.microsoft.com/en-us/library/bzwdh01d(VS.71).aspx#cpconpropertyusageguidelinesanchor1\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>I would highly suggest that you buy the book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321246756\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Framework Design Guidelines</a>. It's a must read for every developer.</p>\n"
},
{
"answer_id": 254873,
"author": "Ken Ray",
"author_id": 12253,
"author_profile": "https://Stackoverflow.com/users/12253",
"pm_score": 0,
"selected": false,
"text": "<p>My view is that if you look at the words - \"property\" compared to \"method\". The word \"property\" implies \"this is some value inherent in the object, like color, size, owner... calling a property would imply a relatively simple operation to return that value. Or, if it isn't a read-only property, setting the property is should also be a relatively simple (and low cost) operation.</p>\n\n<p>On the other hand, a \"method\" implies \"I have to do some real work to perform this task you are asking of me\" - while a method may well return a value (even if only to say \"Yes, I did that\"), it is doing a whole bunch of stuff to get that value for me - and in doing so, it will do some other operations associated with getting that value.</p>\n\n<p>So, it is mainly semantic - a read only property could just as satisfactorily be implemented as a method - but I would look at what is involved in returning that value, and the implications each would send to the person retrieving that property or calling that method.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736623/"
] |
I see little functional difference between using a property
```
public readonly property foo as string
get
return bar
end get
end property
```
or a function
```
public function foo() as string
return bar
end function
```
Why would I want to use one form over the other?
Thanks!
|
I read an interesting article recently in Visual Studio Magazine that discussed the different between Methods and Properties.
Properties are supposed to return a value and the same value each time unless something else is called in between.
A Method on the other hand is typically expected to do something in the background to get the value, or that the method may change the value each time it is called, like GetNextId() or something.
DateTime.Now is a good example of a Property that should have been a Method since it returns a different value each time it is used.
**For those interested- here is the article**
[Choose Between Methods and Properties](http://visualstudiomagazine.com/articles/2008/08/01/choose-between-methods-and-properties.aspx)
|
254,697 |
<p>I'm running a PL/SQL block that is supposed to be calling a stored procedure who's output parameters are supposed to be populating variables in the PL/SQL block.</p>
<p>The procedure compiles, and the PL/SQL block runs successfully. But I'd like to check the values of the variables populated by the procedure. Is there a way to output these values?</p>
<p>I'm using Free TOAD if that helps. </p>
<p>Thanks,</p>
|
[
{
"answer_id": 254727,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<pre><code>dbms_output.put_line(varHere);\n</code></pre>\n"
},
{
"answer_id": 255169,
"author": "darreljnz",
"author_id": 10538,
"author_profile": "https://Stackoverflow.com/users/10538",
"pm_score": 2,
"selected": false,
"text": "<p>You have a few options:</p>\n\n<ul>\n<li>Log with DBMS_OUTPUT</li>\n<li>Log to a file using UTL_FILE</li>\n<li>Use the Oracle debugger DBMS_DEBUG</li>\n</ul>\n\n<p>My preference is to log to a file using a fairly simple custom logging package. In my custom logging package I have a configurable flag to switch between file logging and DBMS_OUTPUT logging.</p>\n\n<p>The Oracle debugging API's are quite good but you definitely need a good debugging client. Oracle SQL Developer has fairly good support for it.</p>\n\n<p>There is also a log4plsql logger but I haven't used it.</p>\n"
},
{
"answer_id": 549713,
"author": "Dwayne King",
"author_id": 49715,
"author_profile": "https://Stackoverflow.com/users/49715",
"pm_score": 0,
"selected": false,
"text": "<p>A fourth option (the one I usually default to) also exists.....logging debugging messages to a database table. This gives you the advantage of being able to sort, query, filter your debug messages as required.</p>\n\n<p>As darreljnz mentioned above, log4plsql also probably supports logging to the database. I find that \n1) dbms_output has too many limitations\n2) logging to a file requires too much setup, and a database restart if the utl_file_dir parameter is not already set\n3) using dbms_debug without the help of a GUI is very cumbersome (but I've done it)</p>\n"
},
{
"answer_id": 549777,
"author": "Aussie Craig",
"author_id": 58757,
"author_profile": "https://Stackoverflow.com/users/58757",
"pm_score": 0,
"selected": false,
"text": "<p>If you can download a copy of Oracle jDeveloper <a href=\"http://www.oracle.com/technology/products/jdev/index.html\" rel=\"nofollow noreferrer\">jDeveloper Home page</a> or Oracle Visual Studio add in <a href=\"http://www.oracle.com/technology/tech/dotnet/tools/index.html\" rel=\"nofollow noreferrer\">VS Plugin</a>. Both are free, and allow you to debug (set breakpoint, inspect variables, ...) in PL/SQL on the db. You also need a \"debug\" privledge on the DB to do this. But, if you have dba rights you can grant that.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm running a PL/SQL block that is supposed to be calling a stored procedure who's output parameters are supposed to be populating variables in the PL/SQL block.
The procedure compiles, and the PL/SQL block runs successfully. But I'd like to check the values of the variables populated by the procedure. Is there a way to output these values?
I'm using Free TOAD if that helps.
Thanks,
|
```
dbms_output.put_line(varHere);
```
|
254,712 |
<p>Can I somehow disable spell-checking on HTML textfields (as seen in e.g. Safari)?</p>
|
[
{
"answer_id": 254716,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 10,
"selected": true,
"text": "<p><strong>Update</strong>: As suggested by a commenter (additional credit to <a href=\"https://stackoverflow.com/questions/3416867/how-can-i-disable-the-spell-checker-on-text-inputs-on-the-iphone\">How can I disable the spell checker on text inputs on the iPhone</a>), use this to handle all desktop and mobile browsers.</p>\n\n<pre><code><tag autocomplete=\"off\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\"/>\n</code></pre>\n\n<p>Original answer: Javascript cannot override user settings, so unless you use another mechanism other than textfields, this is not (or shouldn't be) possible.</p>\n"
},
{
"answer_id": 1245570,
"author": "Ms2ger",
"author_id": 33466,
"author_profile": "https://Stackoverflow.com/users/33466",
"pm_score": 8,
"selected": false,
"text": "<p>Yes, use <code>spellcheck=\"false\"</code>, as defined by <a href=\"https://html.spec.whatwg.org/multipage/interaction.html#spelling-and-grammar-checking\" rel=\"noreferrer\">HTML5</a>, for example:</p>\n\n<pre><code><textarea spellcheck=\"false\">\n ...\n</textarea>\n</code></pre>\n"
},
{
"answer_id": 4371814,
"author": "JCOC611",
"author_id": 532978,
"author_profile": "https://Stackoverflow.com/users/532978",
"pm_score": 3,
"selected": false,
"text": "<p>An IFrame WILL \"trigger\" the spell checker (if it has content-editable set to true) just as a textfield, at least in Chrome.</p>\n"
},
{
"answer_id": 50301368,
"author": "sensor",
"author_id": 567897,
"author_profile": "https://Stackoverflow.com/users/567897",
"pm_score": 4,
"selected": false,
"text": "<p>For Grammarly you can use:</p>\n\n<pre><code><textarea data-gramm=\"false\" />\n</code></pre>\n"
},
{
"answer_id": 53021984,
"author": "Artur INTECH",
"author_id": 2987689,
"author_profile": "https://Stackoverflow.com/users/2987689",
"pm_score": 2,
"selected": false,
"text": "<p>The following code snippet disables it for all <code>textarea</code> and <code>input[type=text]</code> elements:</p>\n\n<pre><code>(function () {\n function disableSpellCheck() {\n let selector = 'input[type=text], textarea';\n let textFields = document.querySelectorAll(selector);\n\n textFields.forEach(\n function (field, _currentIndex, _listObj) {\n field.spellcheck = false;\n }\n );\n }\n\n disableSpellCheck();\n})();\n</code></pre>\n"
},
{
"answer_id": 64810105,
"author": "Mac",
"author_id": 2158270,
"author_profile": "https://Stackoverflow.com/users/2158270",
"pm_score": 1,
"selected": false,
"text": "<p>While specifying <em>spellcheck="false"</em> in the < tag > will certainly disable that feature, it's handy to be able to toggle that functionality on and off as needed after the page has loaded. So here's a non-jQuery way to set the <em>spellcheck</em> attribute programmatically:</p>\n<p>:</p>\n<pre><code><textarea id="my-ta" spellcheck="whatever">abcd dcba</textarea>\n</code></pre>\n<p>:</p>\n<pre><code>function setSpellCheck( mode ) {\n var myTextArea = document.getElementById( "my-ta" )\n , myTextAreaValue = myTextArea.value\n ;\n myTextArea.value = '';\n myTextArea.setAttribute( "spellcheck", String( mode ) );\n myTextArea.value = myTextAreaValue;\n myTextArea.focus();\n}\n</code></pre>\n<p>:</p>\n<pre><code>setSpellCheck( true );\nsetSpellCheck( 'false' );\n</code></pre>\n<p>The function argument may be either boolean or string.</p>\n<p>No need to loop through the textarea contents, we just cut 'n paste what's there, and then set focus.</p>\n<p>Tested in <em>blink</em> engines (Chrome(ium), Edge, etc.)</p>\n"
},
{
"answer_id": 66101648,
"author": "Fom",
"author_id": 6151750,
"author_profile": "https://Stackoverflow.com/users/6151750",
"pm_score": 0,
"selected": false,
"text": "<p>If you have created your HTML element dynamically, you'll want to disable the attribute via JS. There is a little trap however:</p>\n<p>When setting <code>elem.contentEditable</code> you can use either the boolean <code>false</code> or the string <code>"false"</code>. But when you set <code>elem.spellcheck</code>, you can only use the boolean - for some reason. Your options are thus:</p>\n<pre><code>elem.spellcheck = false;\n</code></pre>\n<p>Or the option <a href=\"https://stackoverflow.com/a/64810105/6151750\">Mac</a> provided in his answer:</p>\n<pre><code>elem.setAttribute("spellcheck", "false"); // Both string and boolean work here. \n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136/"
] |
Can I somehow disable spell-checking on HTML textfields (as seen in e.g. Safari)?
|
**Update**: As suggested by a commenter (additional credit to [How can I disable the spell checker on text inputs on the iPhone](https://stackoverflow.com/questions/3416867/how-can-i-disable-the-spell-checker-on-text-inputs-on-the-iphone)), use this to handle all desktop and mobile browsers.
```
<tag autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>
```
Original answer: Javascript cannot override user settings, so unless you use another mechanism other than textfields, this is not (or shouldn't be) possible.
|
254,726 |
<p>I've been told that code such as:</p>
<pre><code>for (int i = 0; i < x.length(); i++) {
// blah
}
</code></pre>
<p>is actually O(n^2) because of the repeated calls to <code>x.length()</code>. Instead I should use:</p>
<pre><code>int l = x.length();
for (int i = 0; i < l; i++) {
// blah
}
</code></pre>
<p>Is this true? Is string length stored as a private integer attribute of the String class? Or does <code>String.length()</code> really walk the whole string just to determine its length?</p>
|
[
{
"answer_id": 254730,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 6,
"selected": false,
"text": "<p>No, the length of a java string is O(1) because java's string class stores the length as a field.</p>\n\n<p>The advice you've received is true of C, amongst other languages, but not java. C's strlen walks the char array looking for the end-of-string character. Joel's talked about it on the podcast, but in the context of C.</p>\n"
},
{
"answer_id": 254740,
"author": "JW.",
"author_id": 4321,
"author_profile": "https://Stackoverflow.com/users/4321",
"pm_score": -1,
"selected": false,
"text": "<p>According to <a href=\"http://www.docjar.com/html/api/java/lang/String.java.html\" rel=\"nofollow noreferrer\">this</a>, the length is a field of the String object.</p>\n"
},
{
"answer_id": 254742,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know how well the link will translate, but see the <a href=\"http://www.jdocs.com/javase/7.b12/java/lang/String.html#669\" rel=\"nofollow noreferrer\">source of <code>String#length</code></a>. In short, <code>#length()</code> has O(1) complexity because it's just returning a field. This is one of the many advantages of immutable strings.</p>\n"
},
{
"answer_id": 255307,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 4,
"selected": false,
"text": "<p>Contrary to what has been said so far, there is no guarantee that <code>String.length()</code> is a constant time operation in the number of characters contained in the string. Neither the javadocs for the <code>String</code> class nor the Java Language Specification require <code>String.length</code> to be a constant time operation.</p>\n\n<p>However, in Sun's implementation <code>String.length()</code> is a constant time operation. Ultimately, it's hard to imagine why any implementation would have a non-constant time implementation for this method.</p>\n"
},
{
"answer_id": 255412,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 2,
"selected": false,
"text": "<p>You should be aware that the <code>length()</code> method returns the number of UTF-16 code points, which is not necessarily the same as the number of characters in all cases.</p>\n\n<p>OK, the chances of that actually affecting you are pretty slim, but there's no harm in knowing it.</p>\n"
},
{
"answer_id": 255451,
"author": "Satish",
"author_id": 16519,
"author_profile": "https://Stackoverflow.com/users/16519",
"pm_score": 3,
"selected": false,
"text": "<p>String stores the length in a separate variable. Since string is immutable, the length will never change.\nIt will need to calculate the length only once when it is created, which happens when memory is allocated for it.\nHence its O(1)</p>\n"
},
{
"answer_id": 255471,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 3,
"selected": false,
"text": "<p>In the event you didn't know you could write it this way:</p>\n\n<pre><code>for (int i = 0, l = x.length(); i < l; i++) {\n // Blah\n}\n</code></pre>\n\n<p>It's just slightly cleaner since <code>l</code>'s scope is smaller.</p>\n"
},
{
"answer_id": 69908415,
"author": "Revanth Reddy Datla",
"author_id": 17373861,
"author_profile": "https://Stackoverflow.com/users/17373861",
"pm_score": 0,
"selected": false,
"text": "<p>No worries even though we are calling length() as a method on x.length(), Actually length is stored as a field/property in String class and this field/property returned by length() method whenever we call " x.length()".</p>\n<p>Check out this image link or below code snippet of length() method defined in String class-</p>\n<p><a href=\"https://i.stack.imgur.com/G8ba7.jpg\" rel=\"nofollow noreferrer\">ImageLink</a></p>\n<pre><code>public int length() {\n return value.length >> coder();\n}\n</code></pre>\n<p>length() method returns the length property which is already stored in String class.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8913/"
] |
I've been told that code such as:
```
for (int i = 0; i < x.length(); i++) {
// blah
}
```
is actually O(n^2) because of the repeated calls to `x.length()`. Instead I should use:
```
int l = x.length();
for (int i = 0; i < l; i++) {
// blah
}
```
Is this true? Is string length stored as a private integer attribute of the String class? Or does `String.length()` really walk the whole string just to determine its length?
|
No, the length of a java string is O(1) because java's string class stores the length as a field.
The advice you've received is true of C, amongst other languages, but not java. C's strlen walks the char array looking for the end-of-string character. Joel's talked about it on the podcast, but in the context of C.
|
254,732 |
<p>Is it possible to determine whether my web site is being accessed as a trusted site? In <a href="https://stackoverflow.com/questions/251696/best-way-to-readset-ie-options">another question</a> we determined that, in general, it is not prudent to have visibility to client IE settings. Would this qualify as an exception?</p>
<p>The reason I'd like to do this is that some functions won't work unless the site is being accessed as a trusted site (e.g. client-side sendmail -- don't ask), and I'd like to be able to warn users. Despite many warnings in the pages, many users still don't read, and send us nastygrams. We'd like to reduce the email volume by detecting this condition and flashing a big warning that basically says "<strong>You didn't read the warnings, and what you're trying to do won't work until you change your settings!</strong>" Any ideas are welcome.</p>
<p>EDIT: In our shop, client-side sendmail only works if the site is trusted, and I can't change that due to security requirements, nor can I switch to server-side sendmail. However, this is not the only reason that client-side sendmail will fail, so I can't simply catch a sendmail error to determine this. Also, I don't want this to degrade to a sendmail discussion.</p>
|
[
{
"answer_id": 254817,
"author": "Adam Alexander",
"author_id": 33164,
"author_profile": "https://Stackoverflow.com/users/33164",
"pm_score": 0,
"selected": false,
"text": "<p>from my understanding this is not possible but you may have some luck testing for a more specific condition, such as the availability of the specific technology or technologies you need. What type of requirements does your client code place on the browser (ActiveX, Java, scripting etc)? Knowing that will be a very good start toward figuring out how to test the client browser for the environment required by your client code.</p>\n"
},
{
"answer_id": 254913,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a test you could use:</p>\n\n<pre><code>function isTrustedIE(){\n try{\n var test=new ActiveXObject(\"Scripting.FileSystemObject\");\n }\n catch(e){\n return false;\n }\n\n return true;\n}\n</code></pre>\n\n<p>This will, of course, fail if the user has disabled that particular object, even on a trusted site.</p>\n"
},
{
"answer_id": 255125,
"author": "Gibbons",
"author_id": 1506,
"author_profile": "https://Stackoverflow.com/users/1506",
"pm_score": 0,
"selected": false,
"text": "<p>You can ask for the username of the currently logged on user, if you get it you will know the site is in the \"Trusted Sites\" or \"Local Intranet\" zones.</p>\n"
},
{
"answer_id": 259736,
"author": "luiscubal",
"author_id": 32775,
"author_profile": "https://Stackoverflow.com/users/32775",
"pm_score": 0,
"selected": false,
"text": "<p>Probably, a good way to deal with this, while still supporting unusual combinations, is to test whether or not a specific behavior was successful.</p>\n\n<p>For example, if you need to do</p>\n\n<pre><code>a.innerHTML = \"abc\"; \n</code></pre>\n\n<p>then you could check whether or not the innerHTML was changed. Unfortunately, I can not assure you that all features are detectable.\nAlso, try...catch statements may be very useful.</p>\n"
},
{
"answer_id": 15510784,
"author": "Ben Barden",
"author_id": 937239,
"author_profile": "https://Stackoverflow.com/users/937239",
"pm_score": 0,
"selected": false,
"text": "<p>In your situation (where the specific issue you're dealing with is a sendmail fail), I'd still suggest catching the sendmail fail, but then giving a somewhat more general answer. \"Your mail has failed. It might have failed for any of the following reasons\" and then throw in a bulleted list, with \"didn't make this site trusted\" nice and bold at the top. If sendmail is failing for reasons other than having your site untrusted, your users might need to know about that too, after all.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26671/"
] |
Is it possible to determine whether my web site is being accessed as a trusted site? In [another question](https://stackoverflow.com/questions/251696/best-way-to-readset-ie-options) we determined that, in general, it is not prudent to have visibility to client IE settings. Would this qualify as an exception?
The reason I'd like to do this is that some functions won't work unless the site is being accessed as a trusted site (e.g. client-side sendmail -- don't ask), and I'd like to be able to warn users. Despite many warnings in the pages, many users still don't read, and send us nastygrams. We'd like to reduce the email volume by detecting this condition and flashing a big warning that basically says "**You didn't read the warnings, and what you're trying to do won't work until you change your settings!**" Any ideas are welcome.
EDIT: In our shop, client-side sendmail only works if the site is trusted, and I can't change that due to security requirements, nor can I switch to server-side sendmail. However, this is not the only reason that client-side sendmail will fail, so I can't simply catch a sendmail error to determine this. Also, I don't want this to degrade to a sendmail discussion.
|
Here's a test you could use:
```
function isTrustedIE(){
try{
var test=new ActiveXObject("Scripting.FileSystemObject");
}
catch(e){
return false;
}
return true;
}
```
This will, of course, fail if the user has disabled that particular object, even on a trusted site.
|
254,737 |
<p>In JSP I can reference a bean's property by using the tag
${object.property}</p>
<p>Is there some way to deal with properties that might not exist? I have a JSP page that needs to deal with different types. Example:</p>
<pre><code>public class Person {
public String getName()
}
public class Employee extends Person {
public float getSalary()
}
</code></pre>
<p>In JSP I want to display a table of people with columns of name and salary. If the person is not an employee then salary should be blank. The row HTML might look like:</p>
<pre><code><tr>
<td><c:out value="${person.name}"></td>
<td><c:out value="${person.salary}"></td>
</tr>
</code></pre>
<p>Unfortunately if person is not an employee then it can't find salary and an error occurs. How would I solve this in JSP?</p>
<p>Edit: Is there an <strong>instanceof</strong> check in JSP tag language?</p>
|
[
{
"answer_id": 254769,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "<p>You could always have a type field.</p>\n\n<pre><code>public class Person {\n public String getType() { return \"Person\"; }\n public String getName()\n}\npublic class Employee extends Person {\n public String getType() { return \"Employee\"; }\n public float getSalary()\n}\n</code></pre>\n\n<p>Your JSP would look like</p>\n\n<pre><code><tr>\n <td><c:out value=\"${person.name}\"></td>\n <td><c:if test=\"'Employee' eq person.type\"><c:out value=\"${person.salary}\"></c:if></td>\n</tr>\n</code></pre>\n\n<p>Of course the Class class already has this...</p>\n\n<pre><code><tr>\n <td><c:out value=\"${person.name}\"></td>\n <td><c:if test=\"'Employee' eq person.class.simpleName\"><c:out value=\"${person.salary}\"></c:if></td>\n</tr>\n</code></pre>\n\n<p>You could also have `isEmployee()' method. </p>\n"
},
{
"answer_id": 254781,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "<p>One method would be to create a custom tag library and use polymorphism within it to handle the case where a <code>Person</code> <em>is-a</em> <code>Employee</code>.</p>\n\n<p>I haven't done this in a while for JSP, but frequently use a similar technique in GSP (Groovy/Grails Server Pages).</p>\n\n<p>Otherwise, you could put some logic in the <code>JSP</code> (not ideal) to test for <code>Employee</code>-ness:</p>\n\n<pre><code><% \n String salary\n if (person instanceof Employee) {\n salary = person.salary\n } else {\n salary = \"\" // or '&nbsp;'\n }\n%>\n<td><c:out value=\"${salary}\"></td>\n</code></pre>\n"
},
{
"answer_id": 254795,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 4,
"selected": true,
"text": "<p>Just use the EL empty operator IF it was a scoped attribute, unfortunately you'll have to go with surrounding your expression using employee.salary with <c:catch>:</p>\n\n<pre><code><c:catch var=\"err\">\n <c:out value=\"${employee.salary}\"/>\n</c:catch>\n</code></pre>\n\n<p>If you really need <em>instanceof</em>, you might consider a custom tag.</p>\n"
},
{
"answer_id": 254955,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 2,
"selected": false,
"text": "<p>If you want the class, just use <code>${person.class}</code>. You can also use <code>${person.class.name eq 'my.package.PersonClass'}</code></p>\n\n<p>You can also use the \"default\" on c:out.</p>\n\n<pre><code> <c:out value='${person.salary}' default=\"Null Value\" />\n</code></pre>\n"
},
{
"answer_id": 356082,
"author": "Adeel Ansari",
"author_id": 42769,
"author_profile": "https://Stackoverflow.com/users/42769",
"pm_score": 2,
"selected": false,
"text": "<p>Concise, but unchecked.</p>\n\n<pre><code><tr>\n <td>${person.name}</td> \n <td>${person.class.simpleName == 'Employee' ? person.salary : ''}</td>\n</tr>\n</code></pre>\n\n<blockquote>\n <p>Is there an instanceof check in JSP tag language?</p>\n</blockquote>\n\n<p>Not at the moment of this writing. I read somewhere that they have reserved it, <em>instanceof</em> keyword, in EL, may be for future. Moreover, there is a library available that has this specific tag. Look into that before deciding to create some custom tag for yourself. Here is the link, <a href=\"http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/intro.html\" rel=\"nofollow noreferrer\">Unstandard Tag Library</a>. </p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
] |
In JSP I can reference a bean's property by using the tag
${object.property}
Is there some way to deal with properties that might not exist? I have a JSP page that needs to deal with different types. Example:
```
public class Person {
public String getName()
}
public class Employee extends Person {
public float getSalary()
}
```
In JSP I want to display a table of people with columns of name and salary. If the person is not an employee then salary should be blank. The row HTML might look like:
```
<tr>
<td><c:out value="${person.name}"></td>
<td><c:out value="${person.salary}"></td>
</tr>
```
Unfortunately if person is not an employee then it can't find salary and an error occurs. How would I solve this in JSP?
Edit: Is there an **instanceof** check in JSP tag language?
|
Just use the EL empty operator IF it was a scoped attribute, unfortunately you'll have to go with surrounding your expression using employee.salary with <c:catch>:
```
<c:catch var="err">
<c:out value="${employee.salary}"/>
</c:catch>
```
If you really need *instanceof*, you might consider a custom tag.
|
254,765 |
<p>How can I detect whether or not an input box is currently a jQuery UI autocomplete? There doesn't seem to be a native method for this, but I'm hoping there is something simple like this:</p>
<pre><code>if ($("#q").autocomplete)
{
//Do something
}
</code></pre>
<p>That conditional, however, seems to always return true.</p>
|
[
{
"answer_id": 254786,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<p>It's true because once you've included the autocomplete js, every $() object now has a autocomplete() method defined (in case you want to activate autocomplete for those elements). Your if() is just saying that that function is not null.</p>\n\n<p>I, unfortunately don't have a system where I can check this (left the laptop home today), but I believe autocomplete adds a css class name to the elements it's using. You could look for that.</p>\n"
},
{
"answer_id": 255115,
"author": "Randy",
"author_id": 9361,
"author_profile": "https://Stackoverflow.com/users/9361",
"pm_score": 5,
"selected": true,
"text": "<pre><code>if ($(\"#q\").hasClass(\"ac_input\")) {\n // do something\n}\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>The class name in the JQuery UI autocomplete widget is now 'ui-autocomplete-input' so that code would be:</p>\n\n<pre><code>if ($(\"#q\").hasClass(\"ui-autocomplete-input\")) {\n // do something\n}\n</code></pre>\n"
},
{
"answer_id": 2713570,
"author": "CreativeNotice",
"author_id": 241633,
"author_profile": "https://Stackoverflow.com/users/241633",
"pm_score": 2,
"selected": false,
"text": "<p>You can use</p>\n\n<pre><code>if( $.isFunction( $.fn.autocomplete ) ){ }\n</code></pre>\n\n<p>.isFunction is part of the jQuery lib. (cite: <a href=\"http://james.padolsey.com/jquery/#v=1.4&fn=jQuery.isFunction\" rel=\"nofollow noreferrer\">http://james.padolsey.com/jquery/....isFunction</a>)</p>\n"
},
{
"answer_id": 6370280,
"author": "Matloob Ali",
"author_id": 373624,
"author_profile": "https://Stackoverflow.com/users/373624",
"pm_score": 3,
"selected": false,
"text": "<p>You can also find the autocomplete behavior attached to an input element by following line of code:</p>\n\n<pre><code>if ($('Selector').data('autocomplete')) {\n}\n</code></pre>\n"
},
{
"answer_id": 46068669,
"author": "Robin",
"author_id": 416740,
"author_profile": "https://Stackoverflow.com/users/416740",
"pm_score": 3,
"selected": false,
"text": "<p>If the autocomplete jquery UI plugin is already included for the page and you just want to check to see if a particular (input) element has been setup with autocomplete function, you can use the <strong>official API method</strong> as shown below:</p>\n\n<pre><code>if ($(\"#q\").autocomplete(\"instance\")) {\n console.log(\"autocomplete already setup for #q\");\n} else {\n console.log(\"NO autocomplete for #q\");\n}\n</code></pre>\n\n<p>More details can be found at <a href=\"http://api.jqueryui.com/autocomplete/#method-instance\" rel=\"noreferrer\">http://api.jqueryui.com/autocomplete/#method-instance</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] |
How can I detect whether or not an input box is currently a jQuery UI autocomplete? There doesn't seem to be a native method for this, but I'm hoping there is something simple like this:
```
if ($("#q").autocomplete)
{
//Do something
}
```
That conditional, however, seems to always return true.
|
```
if ($("#q").hasClass("ac_input")) {
// do something
}
```
**UPDATE**
The class name in the JQuery UI autocomplete widget is now 'ui-autocomplete-input' so that code would be:
```
if ($("#q").hasClass("ui-autocomplete-input")) {
// do something
}
```
|
254,784 |
<p>I have two objects, let's call them <strong><code>Input</code></strong> and <strong><code>Output</code></strong></p>
<p><strong><code>Input</code></strong> has properties <em><code>Input_ID</code></em>, <em><code>Label</code></em>, and <em><code>Input_Amt</code></em><br>
<strong><code>Output</code></strong> has properties <em><code>Output_ID</code></em> and <em><code>Output_Amt</code></em></p>
<p>I want to perform the equivalent SQL statement in LINQ:</p>
<pre><code>SELECT Label, Sum(Added_Amount) as Amount FROM
(SELECT I.Label, I.Input_Amt + ISNULL(O.Output_Amt, 0) as Added_Amount
FROM Input I LEFT OUTER JOIN Output O ON I.Input_ID = O.Output_ID)
GROUP BY Label
</code></pre>
<p>For the inner query, I'm writing something like:</p>
<pre><code>var InnerQuery = from i in input
join o in output
on i.Input_ID equals o.Output_ID into joined
from leftjoin in joined.DefaultIfEmpty()
select new
{
Label = i.Label,
AddedAmount = (i.Input_Amt + leftjoin.Output_Amt)
};
</code></pre>
<p>In testing, however, the statement returns null. What gives? </p>
<p>Also, how can I continue the desired query and perform the group after I've added my amounts together, all within a single LINQ statement?</p>
|
[
{
"answer_id": 254830,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>Which LINQ provider is this actually using? Are you actually talking to a database, or just working in-process? If you're using LINQ to SQL, you can turn the log on to see what SQL is being generated.</p>\n\n<p>I'm sure that InnerQuery itself won't be null - how are you examining the output?</p>\n"
},
{
"answer_id": 254908,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>Okay, now that I understand what's going on a bit better, the main problem is that you haven't got the equivalent of the ISNULL bit. Try this instead:</p>\n\n<pre><code>var InnerQuery = from i in input\n join o in output\n on i.Input_ID equals o.Output_ID into joined\n from leftjoin in joined.DefaultIfEmpty()\n select new\n {\n Label = i.Label,\n AddedAmount = (i.Input_Amt + (leftjoin == null ? 0 : leftjoin.Output_Amt))\n };\n</code></pre>\n"
},
{
"answer_id": 603490,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var labelsAndAmounts = input\n .GroupJoin\n (\n output,\n i => i.InputId,\n o => o.OutputId,\n (i, os) => new\n {\n i,\n oAmount = os.Any() ? os.Select(o => o.OutputAmt).Sum() : 0\n }\n )\n .GroupBy(x => x.i.Label)\n .Select(g => new\n {\n Label = g.Key,\n Amount = g.Select(x => x.i.InputAmt + x.oAmount).Sum()\n }\n );\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373/"
] |
I have two objects, let's call them **`Input`** and **`Output`**
**`Input`** has properties *`Input_ID`*, *`Label`*, and *`Input_Amt`*
**`Output`** has properties *`Output_ID`* and *`Output_Amt`*
I want to perform the equivalent SQL statement in LINQ:
```
SELECT Label, Sum(Added_Amount) as Amount FROM
(SELECT I.Label, I.Input_Amt + ISNULL(O.Output_Amt, 0) as Added_Amount
FROM Input I LEFT OUTER JOIN Output O ON I.Input_ID = O.Output_ID)
GROUP BY Label
```
For the inner query, I'm writing something like:
```
var InnerQuery = from i in input
join o in output
on i.Input_ID equals o.Output_ID into joined
from leftjoin in joined.DefaultIfEmpty()
select new
{
Label = i.Label,
AddedAmount = (i.Input_Amt + leftjoin.Output_Amt)
};
```
In testing, however, the statement returns null. What gives?
Also, how can I continue the desired query and perform the group after I've added my amounts together, all within a single LINQ statement?
|
Okay, now that I understand what's going on a bit better, the main problem is that you haven't got the equivalent of the ISNULL bit. Try this instead:
```
var InnerQuery = from i in input
join o in output
on i.Input_ID equals o.Output_ID into joined
from leftjoin in joined.DefaultIfEmpty()
select new
{
Label = i.Label,
AddedAmount = (i.Input_Amt + (leftjoin == null ? 0 : leftjoin.Output_Amt))
};
```
|
254,809 |
<p>The following code fails at runtime…</p>
<pre>
Dim Id As Guid = CType(e.CommandArgument, Guid)
</pre>
<p>It throws this exception…</p>
<pre>
System.InvalidCastException was unhandled by user code
Specified cast is not valid
</pre>
<p>Why can't I cast <strong><em>e.CommandArgument</em></strong> as a Guid?</p>
|
[
{
"answer_id": 254826,
"author": "Jonathan S.",
"author_id": 2034,
"author_profile": "https://Stackoverflow.com/users/2034",
"pm_score": 3,
"selected": true,
"text": "<p>Try:</p>\n\n<pre><code>Dim DeleteId As Guid = New Guid(Convert.ToString(e.CommandArgument))\n</code></pre>\n\n<p>This works...</p>\n\n<pre>\nDim DeleteId As Guid = New Guid(DirectCast(e.CommandArgument, String))\n</pre>\n"
},
{
"answer_id": 254829,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 1,
"selected": false,
"text": "<p>The message \"cast is not valid\" suggests that the datatype for one of the values does not match what's in the database. Can you put a breakpoint on the line where the value of DeleteId is set and see what the Guid looks like? Then, you can compare it with what you see in the database for DogId. I suspect that you will find your datatype problem there.</p>\n"
},
{
"answer_id": 254847,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>I'm gonna guess that e.CommandArgument is a string, which cannot by <em>cast</em> to a Guid. A Guid can be created from a string:</p>\n\n<p>In C#:</p>\n\n<pre><code> Guid DeleteId new Guid(e.CommandArgument);\n</code></pre>\n\n<p>I don't really know the VB.NET syntax, but I'll take a guess:</p>\n\n<pre><code> Dim DeleteId As Guid = New Guid(e.CommandArgument);\n</code></pre>\n"
},
{
"answer_id": 254851,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 1,
"selected": false,
"text": "<p>Your error has nothing to do with LINQ to SQL... it's a casting error. Use \"new Guid(e.CommandArgument)\".</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
The following code fails at runtime…
```
Dim Id As Guid = CType(e.CommandArgument, Guid)
```
It throws this exception…
```
System.InvalidCastException was unhandled by user code
Specified cast is not valid
```
Why can't I cast ***e.CommandArgument*** as a Guid?
|
Try:
```
Dim DeleteId As Guid = New Guid(Convert.ToString(e.CommandArgument))
```
This works...
```
Dim DeleteId As Guid = New Guid(DirectCast(e.CommandArgument, String))
```
|
254,811 |
<p>My app crashes when I do the following in the applicationDidFinishLaunching event in the app delegate:</p>
<pre><code>_textures[mytex] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"a.png"]];
</code></pre>
<p>However when I replace <code>@"a.png"</code> with</p>
<pre><code>@"/Users/MyUserName/Desktop/MyProjectFolder/a.png"
</code></pre>
<p>everything works fine. I've experimented with the relative path stuff for the <code>a.png</code> resource... but none of it has worked. How can I fix this? I'd like to just say <code>@"a.png"</code> for all the image resources (esp. since I did this in another app... where I was working directly with sample code).</p>
<p>So what is that magical setting?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 254933,
"author": "carson",
"author_id": 25343,
"author_profile": "https://Stackoverflow.com/users/25343",
"pm_score": 1,
"selected": false,
"text": "<p>You need to make sure a.png is imported as a resource into xCode. If you have done that then referencing it as just \"a.png\" should work.</p>\n"
},
{
"answer_id": 255209,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 4,
"selected": true,
"text": "<p><code>+[UIImage imageNamed:]</code> will look in your app bundle's resources to find the image. If you add an image to Xcode it will be default be added to the resource copy phase of your project. If you want to make sure it is being copied into your app bundle look at the list on the left side of your Xcode editor, under targets you will see your app name there, under that you will see several build phases, so long as <code>a.png</code> appears in the \"Copy Bundle Resources\" phase you should be good to go.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
] |
My app crashes when I do the following in the applicationDidFinishLaunching event in the app delegate:
```
_textures[mytex] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"a.png"]];
```
However when I replace `@"a.png"` with
```
@"/Users/MyUserName/Desktop/MyProjectFolder/a.png"
```
everything works fine. I've experimented with the relative path stuff for the `a.png` resource... but none of it has worked. How can I fix this? I'd like to just say `@"a.png"` for all the image resources (esp. since I did this in another app... where I was working directly with sample code).
So what is that magical setting?
Thanks!
|
`+[UIImage imageNamed:]` will look in your app bundle's resources to find the image. If you add an image to Xcode it will be default be added to the resource copy phase of your project. If you want to make sure it is being copied into your app bundle look at the list on the left side of your Xcode editor, under targets you will see your app name there, under that you will see several build phases, so long as `a.png` appears in the "Copy Bundle Resources" phase you should be good to go.
|
254,821 |
<p>I want to be able to load a serialized xml class to a Soap Envelope. I am starting so I am not filling the innards so it appears like:
<br /> </p>
<pre><code><Envelope
xmlns="http://schemas.xmlsoap.org/soap/envelope/" />
</code></pre>
<p>I want it to appear like: <br/></p>
<pre><code><Envelope
xmlns="http://schemas.xmlsoap.org/soap/envelope/" ></Envelope>`
</code></pre>
<p><br /></p>
<p>The class I wrote is this:
<br/></p>
<pre><code>[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/",ElementName="Envelope", IsNullable = true)]
public class TestXmlEnvelope
{
[System.Xml.Serialization.XmlElement(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
public System.Collections.ArrayList Body = new System.Collections.ArrayList();
} //class TestXmlEnvelope`
</code></pre>
<p>I am using this as an example since other people might want it in an individual element. I am sure this must be simple but sadly I don't know the right keyword for this.</p>
<p>As always thanks for your help.</p>
<p>[Edit] The error comes when I try to use this instruction</p>
<pre><code>System.Xml.Serialization.XmlSerializer xmlout = new System.Xml.Serialization.XmlSerializer(typeof(TestXmlEnvelope));
System.IO.MemoryStream memOut = new System.IO.MemoryStream();
xmlout.Serialize(memOut, envelope, namespc);
Microsoft.Web.Services.SoapEnvelope soapEnv = new Microsoft.Web.Services.SoapEnvelope();
soapEnv.Load(memOut);
</code></pre>
<p>It gives me error "Root Element not found". </p>
<p>[Edit] I fixed the error the problem was that after I serialized the object I didn't set the memOut.Position = 0. Still I hope this question helps other people that may want to do this.</p>
|
[
{
"answer_id": 254834,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": -1,
"selected": false,
"text": "<p>The two representations are equiavalent. Why do you need it to appear in the latter form?</p>\n"
},
{
"answer_id": 254894,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 5,
"selected": true,
"text": "<p>The main issue here is that the <code>XmlSerializer</code> calls <code>WriteEndElement()</code> on the <code>XmlWriter</code> when it would write an end tag. This, however, generates the shorthand <code><tag/></code> form when there is no content. The <code>WriteFullEndElement()</code> writes the end tag separately.</p>\n\n<p>You can inject your own <code>XmlTextWriter</code> into the middle that the serializer would then use to exhibit that functionality.</p>\n\n<p>Given that <code>serializer</code> is the appropriate <code>XmlSerializer</code>, try this:</p>\n\n<pre><code>public class XmlTextWriterFull : XmlTextWriter\n{\n public XmlTextWriterFull(TextWriter sink) : base(sink) { }\n\n public override void WriteEndElement()\n {\n base.WriteFullEndElement();\n }\n}\n\n...\n\nvar writer = new XmlTextWriterFull(innerwriter);\nserializer.Serialize(writer, obj);\n</code></pre>\n\n<p>[Edit] for the case of your added code, add facade constructors for:</p>\n\n<pre><code>public XmlTextWriterFull(Stream stream, Encoding enc) : base(stream, enc) { }\npublic XmlTextWriterFull(String str, Encoding enc) : base(str, enc) { }\n</code></pre>\n\n<p>Then, use the memory stream as your inner stream in the constructor as before:</p>\n\n<pre><code>System.IO.MemoryStream memOut = new System.IO.MemoryStream();\nXmlTextWriterFull writer = new XmlTextWriterFull(memOut, Encoding.UTF8Encoding); //Or the encoding of your choice\nxmlout.Serialize(writer, envelope, namespc);\n</code></pre>\n"
},
{
"answer_id": 1196834,
"author": "John Saunders",
"author_id": 76337,
"author_profile": "https://Stackoverflow.com/users/76337",
"pm_score": 1,
"selected": false,
"text": "<p>Note for the record: The OP was using the <a href=\"http://msdn.microsoft.com/en-us/library/ms977223.aspx#\" rel=\"nofollow noreferrer\">***Microsoft.***Web.Services.SoapEnvelope</a> class, which is part of the extremely obsolete WSE 1.0 product. This class derived from the XmlDocument class, so it's possible that the same issues would have been seen with XmlDocument.</p>\n\n<p>Under no circumstances should WSE be used for any new development, and if it is already in use, the code should be migrated as soon as possible. WCF or ASP.NET Web API are the only technologies that should be used for .NET web services going forward.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12924/"
] |
I want to be able to load a serialized xml class to a Soap Envelope. I am starting so I am not filling the innards so it appears like:
```
<Envelope
xmlns="http://schemas.xmlsoap.org/soap/envelope/" />
```
I want it to appear like:
```
<Envelope
xmlns="http://schemas.xmlsoap.org/soap/envelope/" ></Envelope>`
```
The class I wrote is this:
```
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/",ElementName="Envelope", IsNullable = true)]
public class TestXmlEnvelope
{
[System.Xml.Serialization.XmlElement(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
public System.Collections.ArrayList Body = new System.Collections.ArrayList();
} //class TestXmlEnvelope`
```
I am using this as an example since other people might want it in an individual element. I am sure this must be simple but sadly I don't know the right keyword for this.
As always thanks for your help.
[Edit] The error comes when I try to use this instruction
```
System.Xml.Serialization.XmlSerializer xmlout = new System.Xml.Serialization.XmlSerializer(typeof(TestXmlEnvelope));
System.IO.MemoryStream memOut = new System.IO.MemoryStream();
xmlout.Serialize(memOut, envelope, namespc);
Microsoft.Web.Services.SoapEnvelope soapEnv = new Microsoft.Web.Services.SoapEnvelope();
soapEnv.Load(memOut);
```
It gives me error "Root Element not found".
[Edit] I fixed the error the problem was that after I serialized the object I didn't set the memOut.Position = 0. Still I hope this question helps other people that may want to do this.
|
The main issue here is that the `XmlSerializer` calls `WriteEndElement()` on the `XmlWriter` when it would write an end tag. This, however, generates the shorthand `<tag/>` form when there is no content. The `WriteFullEndElement()` writes the end tag separately.
You can inject your own `XmlTextWriter` into the middle that the serializer would then use to exhibit that functionality.
Given that `serializer` is the appropriate `XmlSerializer`, try this:
```
public class XmlTextWriterFull : XmlTextWriter
{
public XmlTextWriterFull(TextWriter sink) : base(sink) { }
public override void WriteEndElement()
{
base.WriteFullEndElement();
}
}
...
var writer = new XmlTextWriterFull(innerwriter);
serializer.Serialize(writer, obj);
```
[Edit] for the case of your added code, add facade constructors for:
```
public XmlTextWriterFull(Stream stream, Encoding enc) : base(stream, enc) { }
public XmlTextWriterFull(String str, Encoding enc) : base(str, enc) { }
```
Then, use the memory stream as your inner stream in the constructor as before:
```
System.IO.MemoryStream memOut = new System.IO.MemoryStream();
XmlTextWriterFull writer = new XmlTextWriterFull(memOut, Encoding.UTF8Encoding); //Or the encoding of your choice
xmlout.Serialize(writer, envelope, namespc);
```
|
254,823 |
<p>I've got a form that's a few pages long. To traverse the form all I'm doing is showing and hiding container divs. The last page is a confirmation page before submitting. It takes the contents of the form and lays it out so the user can see what he/she just filled out. If they click on one of these it'll take them back to the page they were on (#nav1~3), focus on that field, and let them type in a new value if they need to.</p>
<p>Using jQuery, I made variables for EVERY field/radio/check/select/textarea/whatever. If my method seems silly please pwn me but basically, and this method works ok already, but I'm trying to <strong>scale</strong> it and I don't have any idea how because I don't really know what I'm doing. Thoughts?</p>
<pre>
var field1 = '<a href="#"
onclick="$(\'#nav1\').click();$(\'input#field-1\').focus();"
title="Click to edit">' +
$('input#field-1').val() + '</a>';
$('#field1-confirm').html(field1);
var field2 = '<a href="#"
onclick="$(\'#nav1\').click();$(\'input#field-2\').focus();"
title="Click to edit">' +
$('input#field-2').val() + '</a>';
$('#field2-confirm').html(field2);
</pre>
<p>And so on, with field3, 4, 5 ~ 25, etc.</p>
<p>If you could help out explaining in non-programmer terms, I'd love you forever.</p>
|
[
{
"answer_id": 254846,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 2,
"selected": false,
"text": "<p>I'd start with an introduction to arrays: <a href=\"http://www.hunlock.com/blogs/Mastering_Javascript_Arrays\" rel=\"nofollow noreferrer\">this one</a> looks pretty decent, for starters.</p>\n\n<p>Wrap your head around arrays and loops to get started, and you'll be well served.</p>\n"
},
{
"answer_id": 254865,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 3,
"selected": true,
"text": "<p>Without getting too complicated, you can make a function that handles the repetitive stuff. I haven't tested this, but you'll get the idea:</p>\n\n<pre><code>function valField(fieldName,navName) {\n var output = '<a href=\"javascript://\" onclick=\"$(\\''+navName+'\\').click();$(\\'input#'+fieldName+'\\').focus();\" title=\"Click to edit\">' + $('input#'+fieldName).val() + '</a>';\n $('#'+fieldName+'-confirm').html(output);\n}\n\nvalField(\"field-1\",\"nav1\")\nvalField(\"field-2\",\"nav1\")\nvalField(\"field-293\",\"nav3\")\n</code></pre>\n\n<p>When you get better at Javascript, you would probably just make a loop to handle all these \"valField()\" calls, or you would write something that would inspect your form, find what's there and generate event handlers to glue it all together automatically. That's certainly not \"n00bware\", but it gives you something to think about.</p>\n\n<p>Also instead of using this on your output:</p>\n\n<pre><code>$(\\''+navName+'\\').click();\n</code></pre>\n\n<p>You could replace it with whatever code is actually in the onclick of the nav tab.</p>\n\n<p>There are dozens of ways to solve this problem. Take it one step at a time.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've got a form that's a few pages long. To traverse the form all I'm doing is showing and hiding container divs. The last page is a confirmation page before submitting. It takes the contents of the form and lays it out so the user can see what he/she just filled out. If they click on one of these it'll take them back to the page they were on (#nav1~3), focus on that field, and let them type in a new value if they need to.
Using jQuery, I made variables for EVERY field/radio/check/select/textarea/whatever. If my method seems silly please pwn me but basically, and this method works ok already, but I'm trying to **scale** it and I don't have any idea how because I don't really know what I'm doing. Thoughts?
```
var field1 = '<a href="#"
onclick="$(\'#nav1\').click();$(\'input#field-1\').focus();"
title="Click to edit">' +
$('input#field-1').val() + '</a>';
$('#field1-confirm').html(field1);
var field2 = '<a href="#"
onclick="$(\'#nav1\').click();$(\'input#field-2\').focus();"
title="Click to edit">' +
$('input#field-2').val() + '</a>';
$('#field2-confirm').html(field2);
```
And so on, with field3, 4, 5 ~ 25, etc.
If you could help out explaining in non-programmer terms, I'd love you forever.
|
Without getting too complicated, you can make a function that handles the repetitive stuff. I haven't tested this, but you'll get the idea:
```
function valField(fieldName,navName) {
var output = '<a href="javascript://" onclick="$(\''+navName+'\').click();$(\'input#'+fieldName+'\').focus();" title="Click to edit">' + $('input#'+fieldName).val() + '</a>';
$('#'+fieldName+'-confirm').html(output);
}
valField("field-1","nav1")
valField("field-2","nav1")
valField("field-293","nav3")
```
When you get better at Javascript, you would probably just make a loop to handle all these "valField()" calls, or you would write something that would inspect your form, find what's there and generate event handlers to glue it all together automatically. That's certainly not "n00bware", but it gives you something to think about.
Also instead of using this on your output:
```
$(\''+navName+'\').click();
```
You could replace it with whatever code is actually in the onclick of the nav tab.
There are dozens of ways to solve this problem. Take it one step at a time.
|
254,844 |
<p>I was reading an article on MSDN Magazine about using the <a href="http://msdn.microsoft.com/en-us/magazine/cc700332.aspx" rel="noreferrer">Enumerable class in LINQ</a> to generate a random array. The article uses VB.NET and I'm not immediately sure what the equivalent is in C#:</p>
<pre><code>Dim rnd As New System.Random()
Dim numbers = Enumerable.Range(1, 100). _
OrderBy(Function() rnd.Next)
</code></pre>
|
[
{
"answer_id": 254860,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Random rnd = new Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());\n</code></pre>\n"
},
{
"answer_id": 254861,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 5,
"selected": true,
"text": "<p>The <a href=\"http://www.developerfusion.com/tools/convert/vb-to-csharp/\" rel=\"noreferrer\">Developer Fusion VB.Net to C# converter</a> says that the equivalent C# code is:</p>\n\n<pre><code>System.Random rnd = new System.Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());\n</code></pre>\n\n<p>For future reference, they also have a <a href=\"http://www.developerfusion.com/tools/convert/csharp-to-vb/\" rel=\"noreferrer\">C# to VB.Net converter</a>. There are <a href=\"http://www.dotnetspider.com/convert/Vb-To-Csharp.aspx\" rel=\"noreferrer\">several other tools</a> available for this as well.</p>\n"
},
{
"answer_id": 254875,
"author": "Adam Alexander",
"author_id": 33164,
"author_profile": "https://Stackoverflow.com/users/33164",
"pm_score": 1,
"selected": false,
"text": "<p>Best I can do off the top of my head without access to Visual Studio (crosses fingers):</p>\n\n<pre><code>System.Random rnd = New System.Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(rnd => rnd.Next);\n</code></pre>\n"
},
{
"answer_id": 254919,
"author": "Daniel Plaisted",
"author_id": 1509,
"author_profile": "https://Stackoverflow.com/users/1509",
"pm_score": 3,
"selected": false,
"text": "<p>I initially thought this would be a bad idea since the sort algorithm will need to do multiple comparisons for the numbers, and it will get a different sorting key for the same number each time it calls the lambda for that number. However, it looks like it only calls it once for each element in the list, and stores that value for later use. This code demonstrates this:</p>\n\n<pre><code>int timesCalled = 0;\nRandom rnd = new Random();\n\nList<int> numbers = Enumerable.Range(1, 100).OrderBy(r =>\n {\n timesCalled++;\n return rnd.Next();\n }\n).ToList();\n\nAssert.AreEqual(timesCalled, 100);\n</code></pre>\n"
},
{
"answer_id": 254957,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 1,
"selected": false,
"text": "<p>Using the <a href=\"http://www.itu.dk/research/c5\" rel=\"nofollow noreferrer\">C5 Generic Collection Library</a>, you could just use the builtin <code>Shuffle()</code> method:</p>\n\n<pre><code>IList<int> numbers = new ArrayList<int>(Enumerable.Range(1,100));\nnumbers.Shuffle();\n</code></pre>\n"
},
{
"answer_id": 3189638,
"author": "FouZ",
"author_id": 300141,
"author_profile": "https://Stackoverflow.com/users/300141",
"pm_score": 2,
"selected": false,
"text": "<p>What about something far more easy... </p>\n\n<pre><code>Enumerable.Range(1, 100).OrderBy(c=> Guid.NewGuid().ToString())\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29762/"
] |
I was reading an article on MSDN Magazine about using the [Enumerable class in LINQ](http://msdn.microsoft.com/en-us/magazine/cc700332.aspx) to generate a random array. The article uses VB.NET and I'm not immediately sure what the equivalent is in C#:
```
Dim rnd As New System.Random()
Dim numbers = Enumerable.Range(1, 100). _
OrderBy(Function() rnd.Next)
```
|
The [Developer Fusion VB.Net to C# converter](http://www.developerfusion.com/tools/convert/vb-to-csharp/) says that the equivalent C# code is:
```
System.Random rnd = new System.Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());
```
For future reference, they also have a [C# to VB.Net converter](http://www.developerfusion.com/tools/convert/csharp-to-vb/). There are [several other tools](http://www.dotnetspider.com/convert/Vb-To-Csharp.aspx) available for this as well.
|
254,849 |
<p>I have an MSBuild project where within it I have a task that calls multiple projects where I set BuildInParallel = "true"</p>
<p>Example:</p>
<p></p>
<pre><code> <Message Text="MSBuild project list = @(ProjList)" />
<!-- Compile in parallel -->
<MSBuild Projects="@(ProjList)"
Targets="Build"
Properties="Configuration=$(Configuration)"
BuildInParallel="true" />
</code></pre>
<p></p>
<p>These sub-projects actually invoke a command-line tool to do the actual 'building' - call it compile.exe. Doing crude profiling (thank you taskmgr.exe) of the build process has the following results:</p>
<p>based on the /m setting - I see that exact number of MSBuild.exe processes started which is expected of course - the total available concurrent build processes.</p>
<p>However what I expect to see is around that many number of processes of compile.exe. Basically each MSBuild process will just turn around and invoke compile.exe. What I see is that a number of compile.exe's are started, then they slowly finish until I just see one sole compile.exe still around. The tasks that each compile.exe take a different amount of time, so it's expected that one of them takes a lot longer than the others.</p>
<p>However no other compile.exe's are spawned until the first 'batch' of them are finished. In other words if I have /m:4 - I will see 4 compile.exe's until all finish, then another 4 will be spawned.</p>
<p>This isn't exactly completely parallel to me. Has anyone else seen this behavior. Am I just misunderstanding something?</p>
|
[
{
"answer_id": 254860,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Random rnd = new Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());\n</code></pre>\n"
},
{
"answer_id": 254861,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 5,
"selected": true,
"text": "<p>The <a href=\"http://www.developerfusion.com/tools/convert/vb-to-csharp/\" rel=\"noreferrer\">Developer Fusion VB.Net to C# converter</a> says that the equivalent C# code is:</p>\n\n<pre><code>System.Random rnd = new System.Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());\n</code></pre>\n\n<p>For future reference, they also have a <a href=\"http://www.developerfusion.com/tools/convert/csharp-to-vb/\" rel=\"noreferrer\">C# to VB.Net converter</a>. There are <a href=\"http://www.dotnetspider.com/convert/Vb-To-Csharp.aspx\" rel=\"noreferrer\">several other tools</a> available for this as well.</p>\n"
},
{
"answer_id": 254875,
"author": "Adam Alexander",
"author_id": 33164,
"author_profile": "https://Stackoverflow.com/users/33164",
"pm_score": 1,
"selected": false,
"text": "<p>Best I can do off the top of my head without access to Visual Studio (crosses fingers):</p>\n\n<pre><code>System.Random rnd = New System.Random();\nIEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(rnd => rnd.Next);\n</code></pre>\n"
},
{
"answer_id": 254919,
"author": "Daniel Plaisted",
"author_id": 1509,
"author_profile": "https://Stackoverflow.com/users/1509",
"pm_score": 3,
"selected": false,
"text": "<p>I initially thought this would be a bad idea since the sort algorithm will need to do multiple comparisons for the numbers, and it will get a different sorting key for the same number each time it calls the lambda for that number. However, it looks like it only calls it once for each element in the list, and stores that value for later use. This code demonstrates this:</p>\n\n<pre><code>int timesCalled = 0;\nRandom rnd = new Random();\n\nList<int> numbers = Enumerable.Range(1, 100).OrderBy(r =>\n {\n timesCalled++;\n return rnd.Next();\n }\n).ToList();\n\nAssert.AreEqual(timesCalled, 100);\n</code></pre>\n"
},
{
"answer_id": 254957,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 1,
"selected": false,
"text": "<p>Using the <a href=\"http://www.itu.dk/research/c5\" rel=\"nofollow noreferrer\">C5 Generic Collection Library</a>, you could just use the builtin <code>Shuffle()</code> method:</p>\n\n<pre><code>IList<int> numbers = new ArrayList<int>(Enumerable.Range(1,100));\nnumbers.Shuffle();\n</code></pre>\n"
},
{
"answer_id": 3189638,
"author": "FouZ",
"author_id": 300141,
"author_profile": "https://Stackoverflow.com/users/300141",
"pm_score": 2,
"selected": false,
"text": "<p>What about something far more easy... </p>\n\n<pre><code>Enumerable.Range(1, 100).OrderBy(c=> Guid.NewGuid().ToString())\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
] |
I have an MSBuild project where within it I have a task that calls multiple projects where I set BuildInParallel = "true"
Example:
```
<Message Text="MSBuild project list = @(ProjList)" />
<!-- Compile in parallel -->
<MSBuild Projects="@(ProjList)"
Targets="Build"
Properties="Configuration=$(Configuration)"
BuildInParallel="true" />
```
These sub-projects actually invoke a command-line tool to do the actual 'building' - call it compile.exe. Doing crude profiling (thank you taskmgr.exe) of the build process has the following results:
based on the /m setting - I see that exact number of MSBuild.exe processes started which is expected of course - the total available concurrent build processes.
However what I expect to see is around that many number of processes of compile.exe. Basically each MSBuild process will just turn around and invoke compile.exe. What I see is that a number of compile.exe's are started, then they slowly finish until I just see one sole compile.exe still around. The tasks that each compile.exe take a different amount of time, so it's expected that one of them takes a lot longer than the others.
However no other compile.exe's are spawned until the first 'batch' of them are finished. In other words if I have /m:4 - I will see 4 compile.exe's until all finish, then another 4 will be spawned.
This isn't exactly completely parallel to me. Has anyone else seen this behavior. Am I just misunderstanding something?
|
The [Developer Fusion VB.Net to C# converter](http://www.developerfusion.com/tools/convert/vb-to-csharp/) says that the equivalent C# code is:
```
System.Random rnd = new System.Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());
```
For future reference, they also have a [C# to VB.Net converter](http://www.developerfusion.com/tools/convert/csharp-to-vb/). There are [several other tools](http://www.dotnetspider.com/convert/Vb-To-Csharp.aspx) available for this as well.
|
254,859 |
<p>I am creating an integration server for the first time, and although I have two projects in my cruisecontrol config file, only the first one seems to be executing. My config file is pasted below.</p>
<pre><code><cruisecontrol>
<project name="cc-config">
<triggers>
<intervalTrigger seconds="60" />
</triggers>
<sourcecontrol type="svn">
<trunkUrl></trunkUrl>
<workingDirectory>C:\Program Files (x86)\CruiseControl.NET\server\config</workingDirectory>
</sourcecontrol>
</project>
<project name="stable_trunk">
<workingDirectoy>C:\working</workingDirectory>
<artifactDirectory>C:\artifact</artifactDirectory>
<triggers>
<intervalTrigger name="continuous" seconds="60"/>
</triggers>
<sourcecontrol type="svn">
<trunkUrl></trunkUrl>
<workingDirectory>C:\projects\security\trunk</workingDirectory>
</sourcecontrol>
<tasks>
<nant>
<executable>C:\projects\security\trunk\tools\nant-0.86-nightly-2008-08-18\bin\nant.exe</executable>
<buildFile>C:\projects\security\trunk\security.build</buildFile>
</nant>
</tasks>
<externalLinks>
<externalLink name="proj" url="projURL">
</externalLinks>
</project>
</cruisecontrol>
</code></pre>
<p>Can anybody help me?
thanks
Carter</p>
<p>Additional Information:</p>
<ul>
<li>The log file has no errors and no mention of the second project</li>
<li>The web interface only shows the first project</li>
</ul>
<p>It's as if the second project doesn't even exist.</p>
<p>The problem was a typo, and I missed the error in the log file. The WorkingDirectory tag was missing the last 'r'.</p>
|
[
{
"answer_id": 254884,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li><p>Have you checked your CCNet build logs for any anomalies? (<em>Edit Answer: Yes, and there weren't any.</em>)</p></li>\n<li><p>Logging into the CCNet web server, does the second project show up as a valid project?\n(<em>Edit Answer: No, it does not.</em>)</p></li>\n<li><p>If so, can you do a force build on it? (<em>Edit Answer: No, because it doesn't show up.</em>)</p></li>\n</ol>\n\n<p>So because of those answers, my next suggestion would be to start your cc server from the command line (rather than through the service) just to see if any messages come up.</p>\n\n<p>This is surprising, because generally when my CCNet config file has an error in it, the server crashes (quite hard), and always lets me know there's an issue. I'm really surprised you could be adding a project that isn't showing up or crashing the server.</p>\n\n<p>What you might try, is to go the simple route, and just add a 3rd, empty project and see if you can get /that/ to show up in your list. Also, you could try inserting a deliberate typo that you know will make it crash, and see if you can get that to show up. My concern is that you may be editing the wrong config file, or somehow CCNet isn't actually seeing the changes that you're making to it (source control sync issue?).</p>\n"
},
{
"answer_id": 255247,
"author": "Scott Saad",
"author_id": 4916,
"author_profile": "https://Stackoverflow.com/users/4916",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Interval+Trigger\" rel=\"nofollow noreferrer\">Interval triggers</a> have a default <strong>buildCondition</strong> of <strong>IfModificationExists</strong>, which means that a build will only be kicked off if a modication has been detected within your <a href=\"http://confluence.public.thoughtworks.org/display/CCNET/Source+Control+Blocks\" rel=\"nofollow noreferrer\">Source Control Block</a>.</p>\n\n<h3>from ccnet's docs on the buildCondition attribute</h3>\n\n<blockquote>\n <p>The condition that should be used to launch the integration. By default, this value is IfModificationExists, meaning that an integration will only be triggered if modifications have been detected. Set this attribute to ForceBuild in order to ensure that a build should be launched regardless of whether new modifications are detected. Use Source Control Blocks to specify what to watch for modifications.</p>\n</blockquote>\n\n<p>Therefore, if one is wanting a build to <em>always</em> be kicked off, regardless of whether modifications occurred in the source control, then one would need to specify <strong>ForceBuild</strong> for the <strong>buildCondition</strong> attribute. For example:</p>\n\n<pre><code><triggers>\n <intervalTrigger name=\"continuous\" buildCondition=\"ForceBuild\" seconds=\"60\"/>\n</triggers>\n</code></pre>\n"
},
{
"answer_id": 258969,
"author": "DilbertDave",
"author_id": 31580,
"author_profile": "https://Stackoverflow.com/users/31580",
"pm_score": 0,
"selected": false,
"text": "<p>Did you get to the bottom of this?</p>\n\n<p>If not then take a look at your log files (?:\\Program Files\\CruiseControl.NET\\server\\ccnet.log).</p>\n\n<p>I would recommend using the console app (ccnet.ext) rather than the service at this stage - you can see what is going on a bit easier.\nAlso, before starting the console, ensure that it is set to DEBUG logging by opening the ccnet.exe.config file, locating the <strong>log4net</strong> tag and setting <strong>level value=\"DEBUG\"</strong> within it's <strong>root</strong>.</p>\n\n<p>Start the console and let it run for a few minutes then stop it and look at the logs (post them here if you still have problems).</p>\n\n<p>Hope this helps.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26527/"
] |
I am creating an integration server for the first time, and although I have two projects in my cruisecontrol config file, only the first one seems to be executing. My config file is pasted below.
```
<cruisecontrol>
<project name="cc-config">
<triggers>
<intervalTrigger seconds="60" />
</triggers>
<sourcecontrol type="svn">
<trunkUrl></trunkUrl>
<workingDirectory>C:\Program Files (x86)\CruiseControl.NET\server\config</workingDirectory>
</sourcecontrol>
</project>
<project name="stable_trunk">
<workingDirectoy>C:\working</workingDirectory>
<artifactDirectory>C:\artifact</artifactDirectory>
<triggers>
<intervalTrigger name="continuous" seconds="60"/>
</triggers>
<sourcecontrol type="svn">
<trunkUrl></trunkUrl>
<workingDirectory>C:\projects\security\trunk</workingDirectory>
</sourcecontrol>
<tasks>
<nant>
<executable>C:\projects\security\trunk\tools\nant-0.86-nightly-2008-08-18\bin\nant.exe</executable>
<buildFile>C:\projects\security\trunk\security.build</buildFile>
</nant>
</tasks>
<externalLinks>
<externalLink name="proj" url="projURL">
</externalLinks>
</project>
</cruisecontrol>
```
Can anybody help me?
thanks
Carter
Additional Information:
* The log file has no errors and no mention of the second project
* The web interface only shows the first project
It's as if the second project doesn't even exist.
The problem was a typo, and I missed the error in the log file. The WorkingDirectory tag was missing the last 'r'.
|
1. Have you checked your CCNet build logs for any anomalies? (*Edit Answer: Yes, and there weren't any.*)
2. Logging into the CCNet web server, does the second project show up as a valid project?
(*Edit Answer: No, it does not.*)
3. If so, can you do a force build on it? (*Edit Answer: No, because it doesn't show up.*)
So because of those answers, my next suggestion would be to start your cc server from the command line (rather than through the service) just to see if any messages come up.
This is surprising, because generally when my CCNet config file has an error in it, the server crashes (quite hard), and always lets me know there's an issue. I'm really surprised you could be adding a project that isn't showing up or crashing the server.
What you might try, is to go the simple route, and just add a 3rd, empty project and see if you can get /that/ to show up in your list. Also, you could try inserting a deliberate typo that you know will make it crash, and see if you can get that to show up. My concern is that you may be editing the wrong config file, or somehow CCNet isn't actually seeing the changes that you're making to it (source control sync issue?).
|
254,864 |
<p>So I know it's considered somewhat good practice to always include curly braces for if, for, etc even though they're optional if there is only one following statement, for the reason that it's easier to accidentally do something like:</p>
<pre><code>if(something == true)
DoSomething();
DoSomethingElse();
</code></pre>
<p>when quickly editing code if you don't put the braces.</p>
<p>What about something like this though:</p>
<pre><code>if(something == true)
{ DoSomething(); }
</code></pre>
<p>That way you still take up fewer lines (which IMO increases readability) but still make it unlikely to accidentally make the mistake from above?</p>
<p>I ask because I don't believe I've ever seen this style before for if or loops, but I do see it used for getter and setter in C# properties like:</p>
<pre><code>public string Name
{get;set;}
</code></pre>
<p>Not asking what's best since that's too subjective, but rather just whether this would be considered acceptable style and if not, why not.</p>
|
[
{
"answer_id": 254866,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 3,
"selected": false,
"text": "<p>Instead of:</p>\n\n<pre><code>if(something == true)\n{ DoSomething(); }\n</code></pre>\n\n<p>Do this:</p>\n\n<pre><code>if(something == true) { DoSomething(); }\n</code></pre>\n"
},
{
"answer_id": 254867,
"author": "Stephen Walcher",
"author_id": 25375,
"author_profile": "https://Stackoverflow.com/users/25375",
"pm_score": 5,
"selected": true,
"text": "<p>When I come across a one-line if statement, I usually skip the curlys and keep everything on the same line:</p>\n\n<pre><code>if (something == true) DoSomething();\n</code></pre>\n\n<p>It's quick, easy, and saves space.</p>\n"
},
{
"answer_id": 254868,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 0,
"selected": false,
"text": "<p>There's no problem there... in fact, Visual Studio won't put that code on it's own line if you try to auto-format it. So, if that's more readable to you... you're good.</p>\n"
},
{
"answer_id": 254869,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>That way you still take up fewer lines (which IMO increases readability) </p>\n</blockquote>\n\n<p>I disagree that having fewer line breaks increases readability. The layout of the code should make its structure more visible, not hide it.</p>\n"
},
{
"answer_id": 254870,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 0,
"selected": false,
"text": "<p>If you really want to save lines of code, you can type it like this:</p>\n\n<pre><code>if(something == true) { DoSomething(); }\n</code></pre>\n\n<p>or this, without the braces</p>\n\n<pre><code>if(something == true) DoSomething(); \n</code></pre>\n"
},
{
"answer_id": 254871,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 3,
"selected": false,
"text": "<p>If you work in a team, you need come up with a standard. </p>\n\n<p>Personally I like doing:</p>\n\n<pre><code>if(foo)\n DoSomething();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if(foo) DoSomething();\n</code></pre>\n\n<p>I don't see a problem with not having the braces. The reason people cite, the one you mention about adding another statement on the line below, is one that I've never run in to.</p>\n"
},
{
"answer_id": 254876,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>I don't see why not. I've also used it for short functions. </p>\n\n<p>On the offensive style front, it's far better than the unspeakable:</p>\n\n<pre><code> if (something== true) {\n DoSomething();\n }\n</code></pre>\n\n<p>But, while we are on the topic of style, it's </p>\n\n<pre><code> if (something)\n</code></pre>\n\n<p>and </p>\n\n<pre><code> if (!something)\n</code></pre>\n\n<p>Never</p>\n\n<pre><code> if (something== true) \n</code></pre>\n\n<p>or</p>\n\n<pre><code> if (something== false) \n</code></pre>\n"
},
{
"answer_id": 254881,
"author": "Maxime Rouiller",
"author_id": 24975,
"author_profile": "https://Stackoverflow.com/users/24975",
"pm_score": 0,
"selected": false,
"text": "<p>I would recommend that you do like Stephen and Nicholas Mancuso told.</p>\n\n<p>Use:</p>\n\n<pre><code>if(something) { DoSomething(); }\n</code></pre>\n\n<p>With or without the bracket. As soon as you start using weird version of \"if\" statement, you will starting seeing your collegues looking at your code in a weird way.</p>\n\n<p>I normally use one liner for validation. </p>\n\n<p>Example:</p>\n\n<pre><code>if( param1 == null ) throw new ArgumentNullException(\"param1\");\n</code></pre>\n"
},
{
"answer_id": 254885,
"author": "Whytespot",
"author_id": 33185,
"author_profile": "https://Stackoverflow.com/users/33185",
"pm_score": 0,
"selected": false,
"text": "<p>As long as you're consistent it shouldn't be an issue. At a previous company that was the typical scenario, but at my current company they prefer to have the braces on seperate lines.</p>\n"
},
{
"answer_id": 254890,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "<p>I just ran into this problem yesterday while working on code written by somebody else. The original code was:</p>\n\n<pre><code>if (something == true) \n DoSomething();\n</code></pre>\n\n<p>and I wanted a debug print before calling <code>DoSomething()</code>. What I'd do instinctively</p>\n\n<pre><code>if (something == true) \n print(\"debug message\");\n DoSomething();\n</code></pre>\n\n<p>But that would make the <code>if</code> apply only to the debug message, while <code>DoSomething()</code> would be called unconditionally. That's why I'd rather have curly braces, so that the instinctive edit ends up as:</p>\n\n<pre><code>if (something == true) {\n print(\"debug message\");\n DoSomething();\n}\n</code></pre>\n"
},
{
"answer_id": 254904,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 1,
"selected": false,
"text": "<p>The whitespace in form of new lines, indentation, spacing, alignment and so on is an important aspect of typography and is widely used to improve readability of the text in articles, books and web sites. Not sure why it won't apply the same to the readability of code.</p>\n\n<p>Having said that, there's nothing wrong with you and your team using your style. As long as all of you agree on it.</p>\n"
},
{
"answer_id": 254905,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 3,
"selected": false,
"text": "<p>I tend to put opening braces on their own line like this:</p>\n\n<pre><code>if (condition)\n{\n statement;\n statement;\n}\n</code></pre>\n\n<p>So seeing something like:</p>\n\n<pre><code>if (condition)\n statement;\n statement;\n</code></pre>\n\n<p>stands out as wrong right away. If I only have one statement I just leave it as </p>\n\n<pre><code>if (condition)\n statement;\n</code></pre>\n\n<p>and put the braces in later if I have an extra statement to add. I don't really see any room for confusion.</p>\n\n<p>Putting the statement on the same line as the condition is a bad habit to get into, since when you're debugging, most debuggers count the whole thing as one line. (I realize that in C# this is not the case).</p>\n"
},
{
"answer_id": 254938,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 3,
"selected": false,
"text": "<p>Many people have suggested putting both on a single line. This may increase readability but at the cost of decreased debug-ability in my opinion. I've stepped through a lot of code written this way and it is more difficult to debug because of it.</p>\n\n<p>Some debuggers and IDEs might be able to step over both parts of a single line <code>if</code>-statement and clearly show whether the condition evaluated true or not but many other debuggers may treat it as a single line making it difficult to determine whether the body of the <code>if</code>-statement was called.</p>\n\n<p>For example the VS2008 debugger for C++ code will step over this as a single line making it difficult to determine whether Foo() was called.</p>\n\n<pre><code>if (a==b) { Foo(); }\n</code></pre>\n"
},
{
"answer_id": 254954,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "<p>Personally, I like all my blocks to have the same pattern. I always use braces for ifs and they always start a new line. I like the idiom for automatically define public properties of putting the { get; set; } on the same line. I just feel that having all blocks start with a brace on its own line improves readability. As others have pointed out, it also makes it clearer in the debugger if you are stepping over lines.</p>\n\n<p>If you disagree, then that's ok, too, but as others have said be consistent. To that end, you might want to share the \"code formatting\" settings between you and your co-workers so that the automatic formatting makes everything consistent for everyone.</p>\n\n<p>I would do:</p>\n\n<pre><code>if (something)\n{\n DoSomething();\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public string MyProperty { get; set; }\n</code></pre>\n"
},
{
"answer_id": 255020,
"author": "Eli",
"author_id": 27580,
"author_profile": "https://Stackoverflow.com/users/27580",
"pm_score": 0,
"selected": false,
"text": "<p>As long as you do it consistently, and make sure everyone working on your code knows how you do it, it doesn't matter what you do.</p>\n\n<p>Just do what you find most comfortable, then make sure everyone knows to always do it that way.</p>\n"
},
{
"answer_id": 255033,
"author": "Cybis",
"author_id": 32998,
"author_profile": "https://Stackoverflow.com/users/32998",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, I much prefer</p>\n\n<pre><code>if (something == true)\nif (something == false)\n</code></pre>\n\n<p>over</p>\n\n<pre><code>if (something)\nif (!something)\n</code></pre>\n\n<p>For me, the exclamation point is difficult to see at a glance, so is easy to miss. Note, however, that when I code in Python, I almost always prefer:</p>\n\n<pre><code>if something:\nif not something:\n</code></pre>\n\n<p>Unless I want to distinguish None from, e.g., empty list.</p>\n"
},
{
"answer_id": 255034,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 0,
"selected": false,
"text": "<p>I do occasionally like to do the</p>\n\n<pre><code>if(obj != null) obj.method();\n</code></pre>\n\n<p>But it's a guilty pleasure... I don't think it makes the code any more readable, so then why not follow a pattern everyone else is using. The one exception that I think is quite important is when you are showing how it's part of a bigger pattern, and helping the user see the pattern more easily:</p>\n\n<pre><code>public executeMethodOn(String cmd) {\n CommandObject co;\n\n if(\"CmdObject1\".equals(cmd)) co=new CmdObject1();\n if(\"CmdObject2\".equals(cmd)) co=new CmdObjec21();\n\n co.executeMethod();\n}\n</code></pre>\n\n<p>It makes the pattern much more obvious and helps people trying to insert new functionality see where it needs to go.</p>\n\n<p>That said, if you <em>ever</em> have a pattern like that, you are probably doing it wrong. I had to do this on a system that didn't have reflection, but I tried REALLY HARD to work around it, and if I'd had reflection, it would have been way awesomer.</p>\n"
},
{
"answer_id": 255038,
"author": "Berserk",
"author_id": 26313,
"author_profile": "https://Stackoverflow.com/users/26313",
"pm_score": 0,
"selected": false,
"text": "<p>I usually do this with one-line ifs:</p>\n\n<pre><code>if($something) {\n do_something();\n}\n</code></pre>\n\n<p>The one exception (I do Perl, not sure if this style is allowed in C#) is for loop controls, where I use the inverted one line style:</p>\n\n<pre><code>THING:\nfor my $thing (1 .. 10) {\n next THING if $thing % 3 == 0;\n}\n</code></pre>\n\n<p>With good syntax coloring it's possible to make those lines stand out sharply.</p>\n"
},
{
"answer_id": 255977,
"author": "dviljoen",
"author_id": 29021,
"author_profile": "https://Stackoverflow.com/users/29021",
"pm_score": 0,
"selected": false,
"text": "<p>You're all WRONG WRONG WRONG!!!!! ;-)</p>\n\n<p>Fortunately VS reformats all of your craziness into my personally approved format just by replacing the last curly brace in each file.</p>\n\n<p>Whitespace is a style thing. Since we have different reading styles and learning styles, it really doesn't matter how you do it anymore. The tools will let us switch back and forth. The only downside to this that I have ever noticed is the toll it takes on tracking changes in source control. When I reformat a K&R style file into a more sane format (my opinion) and check that change back into source control, it shows almost every line as having changed. That's a pain. But many diff utilities can ignore whitespace changes (although most only on a single line, not spanning lines). That is an issue. But not a show stopper.</p>\n"
},
{
"answer_id": 255985,
"author": "luiscubal",
"author_id": 32775,
"author_profile": "https://Stackoverflow.com/users/32775",
"pm_score": 0,
"selected": false,
"text": "<p>C gives a lot of freedom in formatting issues, so having them in the same line or in different lines is irrelevant for compiling purposes.</p>\n\n<p>As a result, that \"would it be bad\" only refers to coding conventions. It depends on the context. If you work on a team, it is a good idea to ask everyone else what they think and come up with a standard formatting style. If not, it's really up to you.</p>\n\n<p>So, if you think that it's better, go ahead. If not, then don't. It's really that simple(unless you use an IDE which imposes some styling conventions)</p>\n"
},
{
"answer_id": 1035872,
"author": "Stan Graves",
"author_id": 1715896,
"author_profile": "https://Stackoverflow.com/users/1715896",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer the horridly unspeakable syntax:</p>\n\n<pre><code>if (true == something) {\n doSomething1();\n}\n</code></pre>\n\n<p>Yes, that is the way K&R did it...and yes, I go back that far...and yes, that is good enough reason for me. This means that I get common syntax even when I do something like this:</p>\n\n<pre><code>if (-1 == doSomething()) {\n doSomethingElse();\n}\n</code></pre>\n\n<p>I put the curly braces in regardless of the number of the lines of code they contain. I have been bitten by the \"need to add a line of test code\" and missed the lack of curly braces one too many times. </p>\n\n<p>I always compare with the literal on the left. This avoids the \"testing an assignment\" bug (e.g. if (something = true) {...}). </p>\n\n<p>There is no more danger to the portability of \"(something == true)\" than there is with the overloaded set of values that mean \"true\" and \"false\" in a boolean comparison - but it is a different kind of danger. Are you writing in a language that considers \"empty\" (and/or zero and/or NULL and/or whitespace) to be \"true\" or \"false\"? I prefer a convention that is safe for every case...because I am lazy. </p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23822/"
] |
So I know it's considered somewhat good practice to always include curly braces for if, for, etc even though they're optional if there is only one following statement, for the reason that it's easier to accidentally do something like:
```
if(something == true)
DoSomething();
DoSomethingElse();
```
when quickly editing code if you don't put the braces.
What about something like this though:
```
if(something == true)
{ DoSomething(); }
```
That way you still take up fewer lines (which IMO increases readability) but still make it unlikely to accidentally make the mistake from above?
I ask because I don't believe I've ever seen this style before for if or loops, but I do see it used for getter and setter in C# properties like:
```
public string Name
{get;set;}
```
Not asking what's best since that's too subjective, but rather just whether this would be considered acceptable style and if not, why not.
|
When I come across a one-line if statement, I usually skip the curlys and keep everything on the same line:
```
if (something == true) DoSomething();
```
It's quick, easy, and saves space.
|
254,887 |
<p>I am looking for a clear, complete example of programmatically deleting all documents from a specific document library, via the Sharepoint object model. The doclib does not contain folders. I am looking to delete the documents completely (ie I don't want them in the Recycle Bin).</p>
<p>I know of SPWeb.ProcessBatchData, but somehow it never seems to work for me.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 254918,
"author": "Maxime Rouiller",
"author_id": 24975,
"author_profile": "https://Stackoverflow.com/users/24975",
"pm_score": 1,
"selected": false,
"text": "<p>You just have to go through all the files of your Document Library.</p>\n\n<pre><code>foreach(SPListItem item in SPContext.Current.Web.Lists[\"YourDocLibName\"].Items)\n{\n //TODO: Verify that the file is not checked-out before deleting\n item.File.Delete();\n}\n</code></pre>\n\n<p>Calling the delete method on a file from the API doesn't use the recycle bin. It's a straight delete. You still need to verify that the file is not checked-out.</p>\n\n<p>Here is some reference:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splist_members.aspx\" rel=\"nofollow noreferrer\">SPList</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem_members.aspx\" rel=\"nofollow noreferrer\">SPListItem</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfile.aspx\" rel=\"nofollow noreferrer\">SPFile</a></li>\n</ul>\n"
},
{
"answer_id": 255897,
"author": "Daniel McPherson",
"author_id": 897,
"author_profile": "https://Stackoverflow.com/users/897",
"pm_score": 4,
"selected": true,
"text": "<p>I would persevere with the ProcessBatchData approach, maybe this will help:</p>\n\n<blockquote>\n <p><a href=\"http://blog.thekid.me.uk\" rel=\"noreferrer\">Vincent Rothwell</a> has covered this\n best:\n <a href=\"http://blog.thekid.me.uk/archive/2007/02/24/deleting-a-considerable-number-of-items-from-a-list-in-sharepoint.aspx\" rel=\"noreferrer\">http://blog.thekid.me.uk/archive/2007/02/24/deleting-a-considerable-number-of-items-from-a-list-in-sharepoint.aspx</a></p>\n</blockquote>\n\n<p>Otherwise I'm not sure the other recommendation will work, as a Foreach loop will not like that the number of items in the collection changes with each delete. </p>\n\n<p>You are probably best placed doing a reverse for loop (I didn't test this code, just an example):</p>\n\n<pre><code>for (int i = SPItems.Length - 1; i >= 0; i--)\n{\n SPListItem item = SPItems[i];\n item.File.Delete();\n}\n</code></pre>\n"
},
{
"answer_id": 1012144,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>This is not the right way of deleting items.\nFollow post here\n<a href=\"http://praveenbattula.blogspot.com/2009/05/deleting-list-items-at-time-from-list.html\" rel=\"nofollow noreferrer\">http://praveenbattula.blogspot.com/2009/05/deleting-list-items-at-time-from-list.html</a></p>\n"
},
{
"answer_id": 7207839,
"author": "Richard Gear",
"author_id": 900948,
"author_profile": "https://Stackoverflow.com/users/900948",
"pm_score": 0,
"selected": false,
"text": "<p>Powershell way:</p>\n\n<pre><code>function ProcessFolder {\n param($folderUrl)\n $folder = $web.GetFolder($folderUrl)\n foreach ($file in $folder.Files) {\n #Ensure destination directory\n $destinationfolder = $destination + \"/\" + $folder.Url \n if (!(Test-Path -path $destinationfolder))\n {\n $dest = New-Item $destinationfolder -type directory \n }\n #Delete file by deleting parent SPListItem\n $list.Items.DeleteItemById($file.Item.Id)\n }\n}\n\n#Delete root Files\nProcessFolder($list.RootFolder.Url)\n\n#Delete files from Folders or Document Sets\nforeach ($folder in $list.Folders) {\n ProcessFolder($folder.Url)\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5782/"
] |
I am looking for a clear, complete example of programmatically deleting all documents from a specific document library, via the Sharepoint object model. The doclib does not contain folders. I am looking to delete the documents completely (ie I don't want them in the Recycle Bin).
I know of SPWeb.ProcessBatchData, but somehow it never seems to work for me.
Thanks!
|
I would persevere with the ProcessBatchData approach, maybe this will help:
>
> [Vincent Rothwell](http://blog.thekid.me.uk) has covered this
> best:
> <http://blog.thekid.me.uk/archive/2007/02/24/deleting-a-considerable-number-of-items-from-a-list-in-sharepoint.aspx>
>
>
>
Otherwise I'm not sure the other recommendation will work, as a Foreach loop will not like that the number of items in the collection changes with each delete.
You are probably best placed doing a reverse for loop (I didn't test this code, just an example):
```
for (int i = SPItems.Length - 1; i >= 0; i--)
{
SPListItem item = SPItems[i];
item.File.Delete();
}
```
|
254,895 |
<p>How do I embed a tag within a <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url" rel="nofollow noreferrer" title="url templatetag">url templatetag</a> in a django template?</p>
<p>Django 1.0 , Python 2.5.2</p>
<p>In views.py</p>
<pre><code>def home_page_view(request):
NUP={"HOMEPAGE": "named-url-pattern-string-for-my-home-page-view"}
variables = RequestContext(request, {'NUP':NUP})
return render_to_response('home_page.html', variables)
</code></pre>
<p>In home_page.html, the following</p>
<pre><code>NUP.HOMEPAGE = {{ NUP.HOMEPAGE }}
</code></pre>
<p>is displayed as </p>
<pre><code>NUP.HOMEPAGE = named-url-pattern-string-for-my-home-page-view
</code></pre>
<p>and the following url named pattern works ( as expected ),</p>
<pre><code>url template tag for NUP.HOMEPAGE = {% url named-url-pattern-string-for-my-home-page-view %}
</code></pre>
<p>and is displayed as </p>
<pre><code>url template tag for NUP.HOMEPAGE = /myhomepage/
</code></pre>
<p>but when <code>{{ NUP.HOMEPAGE }}</code> is embedded within a <code>{% url ... %}</code> as follows</p>
<pre><code>url template tag for NUP.HOMEPAGE = {% url {{ NUP.HOMEPAGE }} %}
</code></pre>
<p>this results in a template syntax error</p>
<pre><code>TemplateSyntaxError at /myhomepage/
Could not parse the remainder: '}}' from '}}'
Request Method: GET
Request URL: http://localhost:8000/myhomepage/
Exception Type: TemplateSyntaxError
Exception Value:
Could not parse the remainder: '}}' from '}}'
Exception Location: C:\Python25\Lib\site-packages\django\template\__init__.py in __init__, line 529
Python Executable: C:\Python25\python.exe
Python Version: 2.5.2
</code></pre>
<p>I was expecting <code>{% url {{ NUP.HOMEPAGE }} %}</code> to resolve to <code>{% url named-url-pattern-string-for-my-home-page-view %}</code> at runtime and be displayed as <code>/myhomepage/</code>.</p>
<p>Are embedded tags not supported in django? </p>
<p>is it possible to write a custom url template tag with embedded tags support to make this work?</p>
<p><code>{% url {{ NUP.HOMEPAGE }} %}</code></p>
|
[
{
"answer_id": 254942,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>That's seems way too dynamic. You're supposed to do</p>\n\n<pre><code>{% url named-url-pattern-string-for-my-home-page-view %}\n</code></pre>\n\n<p>And leave it at that. Dynamically filling in the name of the URL tag is -- frankly -- a little odd. </p>\n\n<p>If you want to use any of a large number of different URL tags, you'd have to do something like this</p>\n\n<pre><code>{% if tagoption1 %}<a href=\"{% url named-url-1 %}\">Text</a>{% endif %}\n</code></pre>\n\n<p>Which seems long-winded because, again, the dynamic thing you're trying to achieve seems a little odd.</p>\n\n<p>If you have something like a \"families\" or \"clusters\" of pages, perhaps separate template directories would be a way to manage this better. Each of the clusters of pages can inherit from a base templates and override small things like this navigation feature to keep all of the pages in the cluster looking similar but having one navigation difference for a \"local home\".</p>\n"
},
{
"answer_id": 254948,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 3,
"selected": true,
"text": "<p>Maybe you could try passing the final URL to the template, instead?</p>\n\n<p>Something like this:</p>\n\n<pre><code>from django.core.urlresolvers import reverse\n\ndef home_page_view(request):\n NUP={\"HOMEPAGE\": reverse('named-url-pattern-string-for-my-home-page-view')} \n variables = RequestContext(request, {'NUP':NUP})\n return render_to_response('home_page.html', variables)\n</code></pre>\n\n<p>Then in the template, the <code>NUP.HOMEPAGE</code> should the the url itself.</p>\n"
},
{
"answer_id": 751683,
"author": "Viesturs",
"author_id": 1660,
"author_profile": "https://Stackoverflow.com/users/1660",
"pm_score": 0,
"selected": false,
"text": "<p>Posted a bug to Django. They should be able to fix this on their side.</p>\n\n<p><a href=\"http://code.djangoproject.com/ticket/10823\" rel=\"nofollow noreferrer\">http://code.djangoproject.com/ticket/10823</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11452/"
] |
How do I embed a tag within a [url templatetag](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url "url templatetag") in a django template?
Django 1.0 , Python 2.5.2
In views.py
```
def home_page_view(request):
NUP={"HOMEPAGE": "named-url-pattern-string-for-my-home-page-view"}
variables = RequestContext(request, {'NUP':NUP})
return render_to_response('home_page.html', variables)
```
In home\_page.html, the following
```
NUP.HOMEPAGE = {{ NUP.HOMEPAGE }}
```
is displayed as
```
NUP.HOMEPAGE = named-url-pattern-string-for-my-home-page-view
```
and the following url named pattern works ( as expected ),
```
url template tag for NUP.HOMEPAGE = {% url named-url-pattern-string-for-my-home-page-view %}
```
and is displayed as
```
url template tag for NUP.HOMEPAGE = /myhomepage/
```
but when `{{ NUP.HOMEPAGE }}` is embedded within a `{% url ... %}` as follows
```
url template tag for NUP.HOMEPAGE = {% url {{ NUP.HOMEPAGE }} %}
```
this results in a template syntax error
```
TemplateSyntaxError at /myhomepage/
Could not parse the remainder: '}}' from '}}'
Request Method: GET
Request URL: http://localhost:8000/myhomepage/
Exception Type: TemplateSyntaxError
Exception Value:
Could not parse the remainder: '}}' from '}}'
Exception Location: C:\Python25\Lib\site-packages\django\template\__init__.py in __init__, line 529
Python Executable: C:\Python25\python.exe
Python Version: 2.5.2
```
I was expecting `{% url {{ NUP.HOMEPAGE }} %}` to resolve to `{% url named-url-pattern-string-for-my-home-page-view %}` at runtime and be displayed as `/myhomepage/`.
Are embedded tags not supported in django?
is it possible to write a custom url template tag with embedded tags support to make this work?
`{% url {{ NUP.HOMEPAGE }} %}`
|
Maybe you could try passing the final URL to the template, instead?
Something like this:
```
from django.core.urlresolvers import reverse
def home_page_view(request):
NUP={"HOMEPAGE": reverse('named-url-pattern-string-for-my-home-page-view')}
variables = RequestContext(request, {'NUP':NUP})
return render_to_response('home_page.html', variables)
```
Then in the template, the `NUP.HOMEPAGE` should the the url itself.
|
254,899 |
<p>I am trying to get Silverlight to work with a quick sample application and am calling a rest service on a another computer. The server that has the rest service has a clientaccesspolicy.xml which looks like:</p>
<pre><code><access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
</code></pre>
<p>And is being picked up (at least according to the the network traces I have run), and there is no request for crossdomain.xml. The C# code looks like:</p>
<pre><code>public Page()
{
InitializeComponent();
string restUrl = "http://example.com/rest_service.html?action=test_result";
WebClient testService = new WebClient();
testService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(testService_DownloadStringCompleted);
testService.DownloadStringAsync(new Uri(restUrl, UriKind.Absolute));
}
void testService_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
LoadTreeViewWithData(e.Result);
}
}
</code></pre>
<p>However, I always get the following Security Error back:</p>
<pre>
{System.Security.SecurityException ---> System.Security.SecurityException: Security error.
at System.Net.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.BrowserHttpWebRequest.c__DisplayClass5.b__4(Object sendState)
at System.Net.AsyncHelper.c__DisplayClass2.b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)}
</pre>
<p>What am I doing wrong? And why doesn't the security error tell me some more useful information?</p>
|
[
{
"answer_id": 255014,
"author": "C. Dragon 76",
"author_id": 5682,
"author_profile": "https://Stackoverflow.com/users/5682",
"pm_score": 4,
"selected": true,
"text": "<p>If you haven't already done so, I'd first try changing the restUrl to something simpler like a static HTML page on the same server (or if need be on your own server) just to verify your main code works.</p>\n\n<p>Assuming the security exception is specific to that REST URL (or site), you might take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/cc189008(VS.95).aspx\" rel=\"noreferrer\">URL Access Restrictions in Silverlight 2</a> article. There are some non-obvious security rules involving file types and \"internet zones\" in addition to the more well-known cross domain rules.</p>\n\n<p>I second the complaint about many exception messages in Silverlight not being very helpful. The above referenced MSDN article contains an amusing note: </p>\n\n<blockquote>\n <p>When users get an error that results from one of these access policies being violated, the error may not indicate the exact cause. </p>\n</blockquote>\n"
},
{
"answer_id": 2049271,
"author": "I liked the old Stack Overflow",
"author_id": 162529,
"author_profile": "https://Stackoverflow.com/users/162529",
"pm_score": 0,
"selected": false,
"text": "<p>Loading HTML pages from a \"Trusted Site\" failed for my local application (<a href=\"http://localhost/\" rel=\"nofollow noreferrer\">http://localhost/</a>) - until I added localhost to the list of Trusted Sites.</p>\n\n<p>Silverlight prevents \"cross zone\" calls (in my case Local Network vs. Trusted Sites) and \"cross scheme\" calls (e. g. http vs. https).</p>\n\n<p>And so far it only works with a \"crossdomain.xml\" file. I tried \"clientaccesspolicy.xml\" first, but didn't get it going.</p>\n"
},
{
"answer_id": 7113804,
"author": "Ruth",
"author_id": 406983,
"author_profile": "https://Stackoverflow.com/users/406983",
"pm_score": 2,
"selected": false,
"text": "<p>I couldn't do cross domain REST HTTP deletes without adding http-methods=\"*\" to the allow-from element in the clientaccesspolicy.xml. When I added the http-methods attribute, then everything worked and the SecurityException stopped happening.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] |
I am trying to get Silverlight to work with a quick sample application and am calling a rest service on a another computer. The server that has the rest service has a clientaccesspolicy.xml which looks like:
```
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
```
And is being picked up (at least according to the the network traces I have run), and there is no request for crossdomain.xml. The C# code looks like:
```
public Page()
{
InitializeComponent();
string restUrl = "http://example.com/rest_service.html?action=test_result";
WebClient testService = new WebClient();
testService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(testService_DownloadStringCompleted);
testService.DownloadStringAsync(new Uri(restUrl, UriKind.Absolute));
}
void testService_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
LoadTreeViewWithData(e.Result);
}
}
```
However, I always get the following Security Error back:
```
{System.Security.SecurityException ---> System.Security.SecurityException: Security error.
at System.Net.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.BrowserHttpWebRequest.c__DisplayClass5.b__4(Object sendState)
at System.Net.AsyncHelper.c__DisplayClass2.b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)}
```
What am I doing wrong? And why doesn't the security error tell me some more useful information?
|
If you haven't already done so, I'd first try changing the restUrl to something simpler like a static HTML page on the same server (or if need be on your own server) just to verify your main code works.
Assuming the security exception is specific to that REST URL (or site), you might take a look at the [URL Access Restrictions in Silverlight 2](http://msdn.microsoft.com/en-us/library/cc189008(VS.95).aspx) article. There are some non-obvious security rules involving file types and "internet zones" in addition to the more well-known cross domain rules.
I second the complaint about many exception messages in Silverlight not being very helpful. The above referenced MSDN article contains an amusing note:
>
> When users get an error that results from one of these access policies being violated, the error may not indicate the exact cause.
>
>
>
|
254,901 |
<p>does anybody know how could I get the TWO most largest values from the third column on the following array?</p>
<pre><code>$ar = array(array(1, 1, 7.50, 'Hello'),
array(1, 2, 18.90, 'Hello'),
array(3, 5, 11.50, 'Hello'),
array(2, 4, 15.90, 'Hello'));
</code></pre>
<p>Output should be:</p>
<pre><code>15.90
18.90
</code></pre>
<p>Thanks in advance</p>
|
[
{
"answer_id": 254920,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": true,
"text": "<p>If you're sure that the value (two) will never change, just iterate over the array and keep track of the two largest numbers. If not, sort the arrays using <a href=\"http://www.php.net/manual/en/function.usort.php\" rel=\"nofollow noreferrer\"><code>usort</code>()</a> and providing an appropriate callback. Then take the first two values:</p>\n\n<pre><code>function cmp($a, $b) {\n $a = $a[2];\n $b = $b[2];\n return $a == $b ? 0 : $a < $b ? 1 : -1;\n}\n\nusort($ar, 'cmp');\n</code></pre>\n"
},
{
"answer_id": 254925,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>One of the simplest ways to do this is to collect all the values into a single array, sort the array, then print out the first two values.</p>\n\n<p>There are more efficient ways that don't involve sorting the whole array, but the above should get you started.</p>\n"
},
{
"answer_id": 254949,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "<p>Sorting is O(n log n), but you can actually accomplish this in O(n) (that is, <em>faster</em>, if the array is big). Pseudocode follows:</p>\n\n<pre><code>first = array[0][2]\nsecond = array[1][2]\nif second > first\n first, second = second, first\nfor tuple in array[2:n]\n if tuple[2] > second\n second = tuple[2]\n if second > first\n first, second = second, first\n</code></pre>\n"
},
{
"answer_id": 254986,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "<p>A more general solution, for the n greatest values (pseudo-code)</p>\n\n<pre><code>def maxN(list, n):\n result = []\n curmin = 0\n for number in list:\n if number > curmin:\n binary insert number into result. #O(log n)\n if len(result) > n: \n truncate last element #O(1)\n curmin = new minimum in result list #O(1) since list is sorted\n\n return result\n</code></pre>\n\n<p>The whole thing will take... O(m log n), where m is the size of the list and n is the number of max elements you want. This is much better than if you sort the list, which takes O(n log n), for large n. </p>\n\n<p>But it's also overkill if you just want the max two elements.</p>\n"
},
{
"answer_id": 255373,
"author": "Hugh Bothwell",
"author_id": 33258,
"author_profile": "https://Stackoverflow.com/users/33258",
"pm_score": 0,
"selected": false,
"text": "<p>Where are you getting the array data from?\nHow often will the data change?\nCan you get the array already sorted by that field?\nIf there are a large number of data items, might it be worth doing a second query?</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
does anybody know how could I get the TWO most largest values from the third column on the following array?
```
$ar = array(array(1, 1, 7.50, 'Hello'),
array(1, 2, 18.90, 'Hello'),
array(3, 5, 11.50, 'Hello'),
array(2, 4, 15.90, 'Hello'));
```
Output should be:
```
15.90
18.90
```
Thanks in advance
|
If you're sure that the value (two) will never change, just iterate over the array and keep track of the two largest numbers. If not, sort the arrays using [`usort`()](http://www.php.net/manual/en/function.usort.php) and providing an appropriate callback. Then take the first two values:
```
function cmp($a, $b) {
$a = $a[2];
$b = $b[2];
return $a == $b ? 0 : $a < $b ? 1 : -1;
}
usort($ar, 'cmp');
```
|
254,912 |
<p>Given that these two examples are equivalent, which do you think is preferrable?</p>
<p><strong>Without explicit modifier</strong></p>
<pre><code>public class MyClass
{
string name = "james";
public string Name {
get { return name; }
set { name = value; }
}
void SomeMethod() { ... }
}
</code></pre>
<p><strong>With explicit modifier</strong></p>
<pre><code>public class MyClass
{
private string name = "james";
public string Name {
get { return name; }
set { name = value; }
}
private void SomeMethod() { ... }
}
</code></pre>
<hr>
<p>I've always used the latter, but recently I've started adopting the former style. The private is redundant as that's the default accessor modifier, so doesn't it make sense to exclude it?</p>
|
[
{
"answer_id": 254922,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 7,
"selected": true,
"text": "<p>I think explicity stating private helps in readability. It won't allow for a programmer to interpret its visibility differently.</p>\n"
},
{
"answer_id": 254924,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 3,
"selected": false,
"text": "<p>I always prefer to be explicit, even if it is redundant. This provides built-in code comments and can be helpful for the next guy, especially if he's a noob. :-)</p>\n"
},
{
"answer_id": 254927,
"author": "Oscar Cabrero",
"author_id": 14440,
"author_profile": "https://Stackoverflow.com/users/14440",
"pm_score": 1,
"selected": false,
"text": "<p>you are correct but since you want your code to be understandable for everyone i think you should include, you never know when if someone does not know this</p>\n"
},
{
"answer_id": 254928,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": false,
"text": "<p>Personally, I prefer the private modifier - I like explicitness. For fields, it also highlights that it's a member variable as opposed to a function variable (the only difference otherwise is location - which is okay if folks can indent properly, but can be confusing otherwise).</p>\n"
},
{
"answer_id": 254931,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 2,
"selected": false,
"text": "<p>Always use the explicit form. If for whatever reason the underlying assumption changes, the code with an explicit denotation of access won't break, whereas the implicit connotation my easily break.</p>\n\n<p>Also, when you are talking about different types of structures, they may have different default accessibilities. Without the explicit modifiers, the ownus is on the reader to know which structure has what default. E.g. in C#, struct fields default to <code>public</code>, class fields default to <code>private</code>, and class definitions default to <code>internal</code>.</p>\n"
},
{
"answer_id": 254937,
"author": "Adam Alexander",
"author_id": 33164,
"author_profile": "https://Stackoverflow.com/users/33164",
"pm_score": 0,
"selected": false,
"text": "<p>My understanding has always been members have \"internal\" accessibility unless stated otherwise. If that's true, the \"private\" modifier would be required to ensure those members are in fact private.</p>\n\n<p>Regardless of whether I'm correct about the above or not, leaving the modifier in place will increase the readability of the code in case another developer is later modifying this class and is curious about the accessibility. Hope this helps!</p>\n"
},
{
"answer_id": 254941,
"author": "Oliver Hallam",
"author_id": 19995,
"author_profile": "https://Stackoverflow.com/users/19995",
"pm_score": 2,
"selected": false,
"text": "<p>I go for explicit all the time. If nothing else it demonstrates your intention more clearly. If I want something to be private I will say so. Explicitly typing the modifier makes sure I think about it, rather than just leaving things private because its quicker. That an a long list of members line up better :)</p>\n"
},
{
"answer_id": 254953,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": "<p>Marking it as private makes it clear that it is deliberate, rather than \"I didn't actually think about it, so I don't know if it would be better as something else.\"; so I do like making it explicit. I wouldn't get religious about it, though.</p>\n\n<p>Also - this prevents having to remember rules... members are private by default, (outer) types are internal by default; nested types are private by default...</p>\n\n<p>Make it clear... make it explicit ;-p</p>\n"
},
{
"answer_id": 254960,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 5,
"selected": false,
"text": "<p>I always omit it for two reasons: to reduce visual clutter, and to do the right thing by default.</p>\n\n<p>In C#, everything defaults to the <strong>least visibility possible</strong>. A class member (field, method, property) defaults to private. A class defaults to internal. A nested class defaults to private.</p>\n\n<p>Thus if you omit your visibility except where you need it, you'll be automatically using the least visibility possible, which is the right way to do things anyway.</p>\n\n<p>If you need something to be <strong>more</strong> visible, then add the modifier. This makes it easy to see items that deviate from the default visibility.</p>\n\n<p>(Unfortunately, this rule only holds for C#. In VB .NET and in F#, the defaults are quite different and definitely not \"least visibility possible\" in most cases.)</p>\n"
},
{
"answer_id": 254961,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>I always specify the visibility explicitly. I prefer not letting the compiler guess my intentions.</p>\n"
},
{
"answer_id": 255450,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 4,
"selected": false,
"text": "<p>I've been developing full-time in C# for about 7 years now, and until I read this topic I didn't know what the default access modifier is. I knew that one existed, but I've never, ever used it.</p>\n\n<p>I like explicitly declaring my intent as I code. Both because the declarations are there for me to see when I go back and look at it, and because actually thinking and typing the word \"private\" when I write a method makes me think just a little more about what I have it in mind to do.</p>\n"
},
{
"answer_id": 260555,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 3,
"selected": false,
"text": "<p>I like to be super-explicit usually. I will go for specifying \"private\" always. However there is another reason : Programmers coming from programming languages where the default visibility is <strong>NOT</strong> private but public, for example PHP.</p>\n"
},
{
"answer_id": 2050137,
"author": "Olmo",
"author_id": 38670,
"author_profile": "https://Stackoverflow.com/users/38670",
"pm_score": 6,
"selected": false,
"text": "<p>It looks that we are the only one, but personally, <strong>I support</strong> the let's remove private campaign.</p>\n\n<p>My concern is that public and private are so similar, 6-7 chars length, blue, starting with 'p', so it's much harder to point a public method between 10 explicit private ones than between 10 that have no access attribute.</p>\n\n<p>Also, it's an advantage since lazy people in your team tend to save writing the modifier and making the method private, which is actually a good thing. Otherwise you end up with everything public.</p>\n\n<p>I usually prefer explicit over implicit, but that's more important in language corner cases (tricky cheats) that in a widespread feature. Here I think long-rung maintainability is more important.</p>\n\n<p>Also, I usually like when code is simple and clear in a <em>mathematical</em> way over when the code is explicit in order to preserve future coder's ignorance. That's the VB way, not C#...</p>\n"
},
{
"answer_id": 45309888,
"author": "mayo",
"author_id": 4848859,
"author_profile": "https://Stackoverflow.com/users/4848859",
"pm_score": 1,
"selected": false,
"text": "<p>First I will ask if there is a previous code convention/standard about that being used by the team. If there is any, you should follow it.</p>\n\n<p>If you have to define the convention, I will push for the explicit way. </p>\n\n<p>My reasons?;</p>\n\n<ul>\n<li>I like to keep the same structure (I mean a.-access modifier, b.-return-type/type, c.-name). </li>\n<li>I don't want (and I don't expect others) to remember all the modifiers by default (<a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/basic-concepts#member-access\" rel=\"nofollow noreferrer\">which are here</a>). </li>\n<li>Not all the languages have the same rules. </li>\n<li>And somehow I think that, somehow, forces the developer to think and be more conscious about the scope of the variable/method and the exposition of those. If you have some experience this will probably not apply, but if you are a newbie, or you work with people with less experience, I think that is useful. </li>\n</ul>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4590/"
] |
Given that these two examples are equivalent, which do you think is preferrable?
**Without explicit modifier**
```
public class MyClass
{
string name = "james";
public string Name {
get { return name; }
set { name = value; }
}
void SomeMethod() { ... }
}
```
**With explicit modifier**
```
public class MyClass
{
private string name = "james";
public string Name {
get { return name; }
set { name = value; }
}
private void SomeMethod() { ... }
}
```
---
I've always used the latter, but recently I've started adopting the former style. The private is redundant as that's the default accessor modifier, so doesn't it make sense to exclude it?
|
I think explicity stating private helps in readability. It won't allow for a programmer to interpret its visibility differently.
|
254,929 |
<p>I'm trying to figure out how to restrict access to a page unless the page is navigated to from a specific "gate" page. Essentially I want the page to be unaccessible unless you're coming from the page that comes before it in my sitemap. I'm not certain this is even possible. If possible, can you limit your suggestions to using either html or javascript?</p>
|
[
{
"answer_id": 254939,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>If possible, can you limit your suggestions to using either html or javascript?</p>\n</blockquote>\n\n<p>No. <strong>Because there is no secure way</strong> using only these two techniques. Everything that goes on on the client side may be manipulated (trivially easy). If you want to be sure, you have to enforce this on the server side by checking for the <code>REFERER</code> (sic!) header.</p>\n\n<p>Mind, even this can be manipulated.</p>\n\n<p>If you're using Apache with <code>mod_rewrite</code> enabled, the following code will restrict access according to the referring page:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_REFERER} !^http://www\\.example\\.com/.*\nRewriteRule /* http://www.example.com/access-denied.html [R,L]\n</code></pre>\n\n<p>EDIT: I just checked <a href=\"http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteRule\" rel=\"noreferrer\">the manual</a> … unfortunately, giving a 401 status code isn't possible here. So the above solution isn't perfect because although it blocks access, it doesn't set the HTTP status accordingly. :-/ Leaves a bad taste in my mouth.</p>\n"
},
{
"answer_id": 254946,
"author": "websch01ar",
"author_id": 32567,
"author_profile": "https://Stackoverflow.com/users/32567",
"pm_score": 0,
"selected": false,
"text": "<p>With javascript name a variable called \"previous\" and set its value to document.referrer. Then execute a condition to determine if the referrer is the proper page, and if not, redirect them</p>\n"
},
{
"answer_id": 254967,
"author": "Stephen Walcher",
"author_id": 25375,
"author_profile": "https://Stackoverflow.com/users/25375",
"pm_score": 2,
"selected": true,
"text": "<p>What if you encrypted a variable (like the current date) and placed that in the \"gate\" link. When you arrive at the new page, a script decrypts the variable and if it doesn't match or isn't even there, the script redirects to another page.</p>\n\n<p>Something like:</p>\n\n<pre><code><a href=\"restricted.php?pass=eERadWRWE3ad=\">Go!</a>\n</code></pre>\n\n<p><strong>Edit</strong>: I don't know JS well enough to print that code but I know there are <a href=\"http://www.google.com/search?q=javascript+encryption+library&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a\" rel=\"nofollow noreferrer\">several libraries</a> out there that can do all the encryption/decryption for you.</p>\n"
},
{
"answer_id": 254999,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 3,
"selected": false,
"text": "<p>The only effective way is to set and check some access token at the server (it is trivial to manipulate any data at the client, therefore plain JS and HTML are not enough; same for the <code>Referer</code> header). A simplified example in PHP:</p>\n\n<p>gate_page.php:</p>\n\n<pre><code><?php\nsession_start();\n$_SESSION['allowed_access'] = true;\n?><a href=\"protected_page.php\">Protected area</a>\n</code></pre>\n\n<p>protected_page.php:</p>\n\n<pre><code><?php\nsession_start();\nif (!$_SESSION['allowed_access']) {\n header('Location: gate_page.php');\n echo 'Go through the <a href=\"gate_page.php\">entry page</a> first.';\n exit();\n}\n\n// whatever happens to be at the protected page\n</code></pre>\n\n<p>Of course, it is easy to add some password checking and/or other security elements, this is the bare minimum.</p>\n"
},
{
"answer_id": 280989,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "<p><code>document.history.previous</code> should give you the URL of the last document in the history object. Otherwise, there's no better way of doing it via HTML and Javascript.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27171/"
] |
I'm trying to figure out how to restrict access to a page unless the page is navigated to from a specific "gate" page. Essentially I want the page to be unaccessible unless you're coming from the page that comes before it in my sitemap. I'm not certain this is even possible. If possible, can you limit your suggestions to using either html or javascript?
|
What if you encrypted a variable (like the current date) and placed that in the "gate" link. When you arrive at the new page, a script decrypts the variable and if it doesn't match or isn't even there, the script redirects to another page.
Something like:
```
<a href="restricted.php?pass=eERadWRWE3ad=">Go!</a>
```
**Edit**: I don't know JS well enough to print that code but I know there are [several libraries](http://www.google.com/search?q=javascript+encryption+library&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a) out there that can do all the encryption/decryption for you.
|
254,930 |
<p>I'm currently working on an application which requires transmission of speech encoded to a specific audio format.</p>
<pre><code>System.Speech.AudioFormat.SpeechAudioFormatInfo synthFormat =
new System.Speech.AudioFormat.SpeechAudioFormatInfo(System.Speech.AudioFormat.EncodingFormat.Pcm,
8000, 16, 1, 16000, 2, null);
</code></pre>
<p>This states that the audio is in PCM format, 8000 samples per second, 16 bits per sample, mono, 16000 average bytes per second, block alignment of 2.</p>
<p>When I attempt to execute the following code there is nothing written to my MemoryStream instance; however when I change from 8000 samples per second up to 11025 the audio data is written successfully.</p>
<pre><code>SpeechSynthesizer synthesizer = new SpeechSynthesizer();
waveStream = new MemoryStream();
PromptBuilder pbuilder = new PromptBuilder();
PromptStyle pStyle = new PromptStyle();
pStyle.Emphasis = PromptEmphasis.None;
pStyle.Rate = PromptRate.Fast;
pStyle.Volume = PromptVolume.ExtraLoud;
pbuilder.StartStyle(pStyle);
pbuilder.StartParagraph();
pbuilder.StartVoice(VoiceGender.Male, VoiceAge.Teen, 2);
pbuilder.StartSentence();
pbuilder.AppendText("This is some text.");
pbuilder.EndSentence();
pbuilder.EndVoice();
pbuilder.EndParagraph();
pbuilder.EndStyle();
synthesizer.SetOutputToAudioStream(waveStream, synthFormat);
synthesizer.Speak(pbuilder);
synthesizer.SetOutputToNull();
</code></pre>
<p>There are no exceptions or errors recorded when using a sample rate of 8000 and I couldn't find anything useful in the documentation regarding SetOutputToAudioStream and why it succeeds at 11025 samples per second and not 8000. I have a workaround involving a wav file that I generated and converted to the correct sample rate using some sound editing tools, but I would like to generate the audio from within the application if I can.</p>
<p>One particular point of interest was that the SpeechRecognitionEngine accepts that audio format and successfully recognized the speech in my synthesized wave file...</p>
<p>Update: Recently discovered that this audio format succeeds for certain installed voices, but fails for others. It fails specifically for LH Michael and LH Michelle, and failure varies for certain voice settings defined in the PromptBuilder.</p>
|
[
{
"answer_id": 336940,
"author": "Mark Heath",
"author_id": 7532,
"author_profile": "https://Stackoverflow.com/users/7532",
"pm_score": 1,
"selected": false,
"text": "<p>I have created some classes in my <a href=\"http://www.codeplex.com/naudio\" rel=\"nofollow noreferrer\">NAudio</a> library to allow you to convert your audio data to a different sample rate, if you are stuck with 11025 from the synthesizer. Have a look at <code>WaveFormatConversionStream</code> (which uses ACM) or <code>ResamplerDMO</code> (uses a DirectX Media Object)</p>\n"
},
{
"answer_id": 1540893,
"author": "Eric Brown",
"author_id": 175201,
"author_profile": "https://Stackoverflow.com/users/175201",
"pm_score": 3,
"selected": true,
"text": "<p>It's entirely possible that the LH Michael and LH Michelle voices simply don't support 8000 Hz sample rates (because they inherently generate samples > 8000 Hz). SAPI allows engines to reject unsupported rates.</p>\n"
},
{
"answer_id": 14016962,
"author": "user1925922",
"author_id": 1925922,
"author_profile": "https://Stackoverflow.com/users/1925922",
"pm_score": 1,
"selected": false,
"text": "<p>I was having a similar issue and wanted to post a reply in case it helps anyone. This thread got me towards finding the answer. My issue was, I was having the SpeechSynthesizer output to a WAV file, and then playing that WAV file with NAudio. When outputted to a file, it worked without modification. However, when trying to use a MemoryStream, it would play back, but so fast all you heard was a squeak.</p>\n\n<p>This code for outputting the SpeechSynthesizer fixed the issue, and no modification is needed on the NAudio side:</p>\n\n<pre><code>SpeechAudioFormatInfo synthFormat = new SpeechAudioFormatInfo(EncodingFormat.Pcm, 88200, 16, 1, 16000, 2, null);\nsynth.SetOutputToAudioStream(streamAudio, synthFormat);\n</code></pre>\n\n<p>The 88200 is the key. By default, this is 11025. Creating the SpeechAudioFormatInfo and setting it to 88200 is all that is needed.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24695/"
] |
I'm currently working on an application which requires transmission of speech encoded to a specific audio format.
```
System.Speech.AudioFormat.SpeechAudioFormatInfo synthFormat =
new System.Speech.AudioFormat.SpeechAudioFormatInfo(System.Speech.AudioFormat.EncodingFormat.Pcm,
8000, 16, 1, 16000, 2, null);
```
This states that the audio is in PCM format, 8000 samples per second, 16 bits per sample, mono, 16000 average bytes per second, block alignment of 2.
When I attempt to execute the following code there is nothing written to my MemoryStream instance; however when I change from 8000 samples per second up to 11025 the audio data is written successfully.
```
SpeechSynthesizer synthesizer = new SpeechSynthesizer();
waveStream = new MemoryStream();
PromptBuilder pbuilder = new PromptBuilder();
PromptStyle pStyle = new PromptStyle();
pStyle.Emphasis = PromptEmphasis.None;
pStyle.Rate = PromptRate.Fast;
pStyle.Volume = PromptVolume.ExtraLoud;
pbuilder.StartStyle(pStyle);
pbuilder.StartParagraph();
pbuilder.StartVoice(VoiceGender.Male, VoiceAge.Teen, 2);
pbuilder.StartSentence();
pbuilder.AppendText("This is some text.");
pbuilder.EndSentence();
pbuilder.EndVoice();
pbuilder.EndParagraph();
pbuilder.EndStyle();
synthesizer.SetOutputToAudioStream(waveStream, synthFormat);
synthesizer.Speak(pbuilder);
synthesizer.SetOutputToNull();
```
There are no exceptions or errors recorded when using a sample rate of 8000 and I couldn't find anything useful in the documentation regarding SetOutputToAudioStream and why it succeeds at 11025 samples per second and not 8000. I have a workaround involving a wav file that I generated and converted to the correct sample rate using some sound editing tools, but I would like to generate the audio from within the application if I can.
One particular point of interest was that the SpeechRecognitionEngine accepts that audio format and successfully recognized the speech in my synthesized wave file...
Update: Recently discovered that this audio format succeeds for certain installed voices, but fails for others. It fails specifically for LH Michael and LH Michelle, and failure varies for certain voice settings defined in the PromptBuilder.
|
It's entirely possible that the LH Michael and LH Michelle voices simply don't support 8000 Hz sample rates (because they inherently generate samples > 8000 Hz). SAPI allows engines to reject unsupported rates.
|
254,969 |
<p>I work in C#, and I've been pretty lax about using <code>using</code> blocks to declare objects that implement <code>IDisposable</code>, which you're apparently always supposed to do. However, I don't see an easy way of knowing when I'm slipping up. Visual Studio doesn't seem to indicate this in any way (am I just missing something?). Am I just supposed to check help every time I declare anything, and gradually build up an encyclopedic memory for which objects are and which are not disposable? Seems unnecessary, painful, and error-prone.</p>
<p>How do <em>you</em> handle this?</p>
<p><strong>EDIT:</strong></p>
<p>Looking at the related questions sidebar, I found <a href="https://stackoverflow.com/questions/2785/setting-objects-to-nullnothing-after-use-in-dot-net">another question</a> which made it clear that <code>Dispose()</code> is supposed to be called by the object's finalizer anyway. So even if you never call it yourself, it should eventually happen, meaning you won't have a memory leak if you don't use <code>using</code> (which is what I suppose I was really worried about all along). The only caveat is that the garbage collector doesn't know how much extra memory is being held by the object as unmanaged stuff, so it won't have an accurate idea how much memory will be freed by collecting the object. This will result in less-ideal-than-usual performance by the garbage collector.</p>
<p>In short, it's not the end of the world if I miss a <code>using</code>. I just wish something would generate at least a warning for it.</p>
<p>(Off-topic: why is there no special markdown for linking to another question?)</p>
<p><strong>EDIT:</strong></p>
<p>Ok, fine, stop clamoring. It's super duper all-fired <a href="http://www.youtube.com/watch?v=a1Y73sPHKxw" rel="nofollow noreferrer">dramatic-chipmunk</a>-level <strong><em>important</em></strong> to call <code>Dispose()</code> or we'll all <em>die</em>.</p>
<p>Now. Given that, why is it so easy — hell, why is it even <em>allowed</em> — to do it wrong? You have to go out of your way to do it right. Doing it like everything else results in armageddon (apparently). So much for encapsulation, huh?</p>
<p>[Stalks off, disgusted]</p>
|
[
{
"answer_id": 254971,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": "<p>FxCop <em>might</em> help (although it didn't spot a test I just fired at it); but yes: you are meant to check. <code>IDisposable</code> is simply such an important part of the system that you need to get into this habit. Using intellisense to look for <code>.D</code> is a good start (though not perfect).</p>\n\n<p>However, it doesn't take long to familiarize yourself with types that need disposal; generally anything involving anything external (connection, file, database), for example.</p>\n\n<p>ReSharper does the job too, offering a \"put into using construct\" option. It doesn't offer it as an error, though...</p>\n\n<p>Of course, if you are unsure - <em>try</em> <code>using</code> it: the compiler will laugh mockingly at you if you are being paranoid:</p>\n\n<pre><code>using (int i = 5) {}\n\nError 1 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable' \n</code></pre>\n"
},
{
"answer_id": 254987,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 0,
"selected": false,
"text": "<p>Like Fxcop (to which they're related), the code analysis tools in VS (if you have one of the higher-up editions) will find these cases too.</p>\n"
},
{
"answer_id": 255465,
"author": "Ryan",
"author_id": 29762,
"author_profile": "https://Stackoverflow.com/users/29762",
"pm_score": 0,
"selected": false,
"text": "<p>Always try to use the \"using\" blocks. For most objects, it doesn't make a big difference however I encountered a recent issue where I implemented an ActiveX control in a class and in didn't clean up gracefully unless the Dispose was called correctly. The bottom line is even if it doesn't seem to make much of a difference, try to do it correctly because some time it will make a difference.</p>\n"
},
{
"answer_id": 255494,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 4,
"selected": false,
"text": "<p>If an object implements the <code>IDisposable</code> interface, then it is for a reason and you are meant to call it and it shouldn't be viewed as optional. The easiest way to do that is to use a <code>using</code> block.</p>\n\n<p><code>Dispose()</code> is not intended to only be called by an object's finalizer and, in fact, many objects will implement <code>Dispose()</code> but no finalizer (which is perfectly valid).</p>\n\n<p>The whole idea behind the dispose pattern is that you are providing a somewhat deterministic way to release the <strong>unmanaged</strong> resources maintained by the object (or any object in it's inheritance chain). By not calling <code>Dispose()</code> properly you absolutely <em>can</em> run in to a memory leak (or any number of other issues).</p>\n\n<p>The <code>Dispose()</code> method is not in any way related to a destructor. The closest you get to a destructor in .NET is a finalizer. The using statement doesn't do any deallocation...in fact calling <code>Dispose()</code> doesn't do any deallocation on the managed heap; it only releases unmanaged resources that had been allocated. The managed resources aren't truely deallocated until the GC runs and collects the memory space allocated to that object graph.</p>\n\n<p>The best ways to determine if a class implements <code>IDisposable</code> are:</p>\n\n<ul>\n<li>IntelliSense (if it has a <code>Dispose()</code> or a <code>Close()</code> method)</li>\n<li>MSDN</li>\n<li>Reflector</li>\n<li>Compiler (if it doesn't implement <code>IDisposable</code> you get a compiler error)</li>\n<li>Common sense (if it <em>feels</em> like you should close/release the object after you're done, then you probably <em>should</em>)</li>\n<li>Semantics (if there is an <code>Open()</code>, there is probably a corresponding <code>Close()</code> that should be called)</li>\n<li>The compiler. Try placing it in a <code>using</code> statement. If it doesn't implement IDisposable, the compiler will generate an error.</li>\n</ul>\n\n<p>Think of the dispose pattern as being all about scope lifetime management. You want to acquire the resource as last as possible, use as quickly as possibly, and release as soon as possible. The using statement helps to do this by ensuring that a call to <code>Dispose()</code> will be made even if there are exceptions.</p>\n"
},
{
"answer_id": 256989,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>@Atario, not only the accepted answer is wrong, your own edit is as well. Imagine the following situation (<em>that actually occurred</em> in one CTP of Visual Studio 2005):</p>\n\n<p>For drawing graphics, you create pens without disposing them. Pens don't require a lot of memory but they use a GDI+ handle internally. If you don't dispose the pen, the GDI+ handle will not be released. If your application isn't memory intensive, quite some time can pass without the GC being called. However, the number of available GDI+ handles is restricted and soon enough, when you try to create a new pen, the operation will fail.</p>\n\n<p>In fact, in Visual Studio 2005 CTP, if you used the application long enough, all fonts would suddenly switch to “System”.</p>\n\n<p>This is precisely why it's <strong>not enough</strong> to rely on the GC for disposing. The memory usage doesn't necessarily corelate with the number of unmanaged resources that you acquire (and don't release). Therefore, these resoures may be exhausted long before the GC is called.</p>\n\n<p>Additionally, there's of course the whole aspects of side-effects that these resources may have (such as access locks) that prevent other applications from working properly.</p>\n"
},
{
"answer_id": 257057,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 2,
"selected": false,
"text": "<p>This is why (IMHO) C++'s RAII is superior to .NET's <code>using</code> statement.</p>\n\n<p>A lot of people said that <code>IDisposable</code> is only for un-managed resources, this is only true depending on how you define \"resource\". You can have a Read/Write lock implementing <code>IDisposable</code> and then the \"resource\" is the conceptual access to the code block. You can have an object that changes the cursor to hour-glass in the constructor and back to the previously saved value in <code>IDispose</code> and then the \"resource\" is the changed cursor. I would say that you use IDisposable when you want deterministic action to take place when leaving the scope no matter how the scope is left, but I have to admit that it's far less catchy than saying \"it's for managing un-managed resource management\".</p>\n\n<p>See also the question about <a href=\"https://stackoverflow.com/questions/173670/why-is-there-no-raii-in-net\">why there's no RAII in .NET</a>.</p>\n"
},
{
"answer_id": 257146,
"author": "Brent Rockwood",
"author_id": 31253,
"author_profile": "https://Stackoverflow.com/users/31253",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately, neither FxCop or StyleCop seem to warn on this. As other commenters have mentioned, it is usually quite important to make sure to call dispose. If I'm not sure, I always check the Object Browser (Ctrl+Alt+J) to look at the inheritance tree.</p>\n"
},
{
"answer_id": 257248,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I use using blocks primarily for this scenario:</p>\n\n<p>I'm consuming some external object (usually an IDisposable wrapped COM object in my case). The state of the object itself may cause it to throw an exception or how it affects my code may cause me to throw an exception, and perhaps in many different places. In general, I trust no code outside of my current method to behave itself.</p>\n\n<p>For the sake of argument, lets say I have 11 exit points to my method, 10 of which are inside this using block and 1 after it (which can be typical in some library code I've written).</p>\n\n<p>Since the object is automatically disposed of when exiting the using block, I don't need to have 10 different .Dispose() calls--it just happens. This results in cleaner code, since it is now less cluttered with dispose calls (~10 fewer lines of code in this case).</p>\n\n<p>There is also less risk of introducing IDisposable leak bugs (which can be time consuming to find) by somebody altering the code after me if they forget to call dispose, because it isn't necessary with a using block.</p>\n"
},
{
"answer_id": 264657,
"author": "The Giraffe",
"author_id": 34589,
"author_profile": "https://Stackoverflow.com/users/34589",
"pm_score": 2,
"selected": false,
"text": "<p>I don't really have anything to add to the general use of Using blocks but just wanted to add an exception to the rule:</p>\n\n<p>Any object that implements IDisposable apparently should not throw an exception during its Dispose() method. This worked perfectly until WCF (there may be others), and it's now possible that an exception is thrown by a WCF channel during Dispose(). If this happens when it's used in a Using block, this causes issues, and requires the implementation of exception handling. This obviously requires more knowledge of the inner workings, which is why Microsoft now recommends not using WCF channels in Using blocks (sorry could not find link, but plenty other results in Google), even though it implements IDisposable.. Just to make things more complicated!</p>\n"
},
{
"answer_id": 663274,
"author": "GrahamS",
"author_id": 79591,
"author_profile": "https://Stackoverflow.com/users/79591",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>In short, it's not the end of the world if I miss a using. I just wish something would generate at least a warning for it.</p>\n</blockquote>\n\n<p>The problem here is that you can't always deal with an IDisposable by just wrapping it up in a <code>using</code> block. Sometimes you need the object to hang around for a bit longer. In which case you will have to call its <code>Dispose</code> method explicitly yourself.</p>\n\n<p>A good example of this is where a <a href=\"https://stackoverflow.com/questions/659840/do-i-need-to-dispose-or-close-an-eventwaithandle\">class uses a private EventWaitHandle (or an AutoResetEvent)</a> to communicate between two threads and you want to Dispose of the WaitHandle once the thread is finished.</p>\n\n<p>So it isn't as simple as some tool just checking that you only create IDisposable objects within a <code>using</code> block.</p>\n"
},
{
"answer_id": 2234689,
"author": "scobi",
"author_id": 14582,
"author_profile": "https://Stackoverflow.com/users/14582",
"pm_score": 0,
"selected": false,
"text": "<p>According to <a href=\"https://stackoverflow.com/questions/24216/resharper-vs-coderush/1930393#1930393\">this link</a> the <a href=\"http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/\" rel=\"nofollow noreferrer\">CodeRush add-in</a> will detect and flag when local IDisposable variables aren't cleaned up, in real-time, as you type.</p>\n\n<p>Could meet you halfway on your quest.</p>\n"
},
{
"answer_id": 4737240,
"author": "usr-local-ΕΨΗΕΛΩΝ",
"author_id": 471213,
"author_profile": "https://Stackoverflow.com/users/471213",
"pm_score": -1,
"selected": false,
"text": "<p>I'm not getting the point of your question. Thanks to the garbage collector, memory leaks are close to impossible to occur. However, you need some robust logic.</p>\n\n<p>I use to create <code>IDisposable</code> classes like this:</p>\n\n<pre><code>public MyClass: IDisposable\n{\n\n private bool _disposed = false;\n\n //Destructor\n ~MyClass()\n { Dispose(false); }\n\n public void Dispose()\n { Dispose(true); }\n\n private void Dispose(bool disposing)\n {\n if (_disposed) return;\n GC.SuppressFinalize(this);\n\n /* actions to always perform */\n\n if (disposing) { /* actions to be performed when Dispose() is called */ }\n\n _disposed=true;\n}\n</code></pre>\n\n<p>Now, even if you miss to use <code>using</code> statement, the object will be eventually garbage-collected and proper destruction logic is executed. You may stop threads, end connections, save data, whatever you need (in <a href=\"http://logbus-ng.svn.sourceforge.net/viewvc/logbus-ng/trunk/logbus-core/It.Unina.Dis.Logbus/Clients/ClientBase.cs?revision=849&view=markup\" rel=\"nofollow\">this example</a>, I unsubscribe from a remote service and perform a remote delete call if needed)</p>\n\n<p>[Edit] obviously, calling Dispose as soon as possible helps application performance, and <strong>is</strong> a good practice. But, thanks to my example, if you forget to call Dispose it will be eventually called and the object is cleaned up.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33219/"
] |
I work in C#, and I've been pretty lax about using `using` blocks to declare objects that implement `IDisposable`, which you're apparently always supposed to do. However, I don't see an easy way of knowing when I'm slipping up. Visual Studio doesn't seem to indicate this in any way (am I just missing something?). Am I just supposed to check help every time I declare anything, and gradually build up an encyclopedic memory for which objects are and which are not disposable? Seems unnecessary, painful, and error-prone.
How do *you* handle this?
**EDIT:**
Looking at the related questions sidebar, I found [another question](https://stackoverflow.com/questions/2785/setting-objects-to-nullnothing-after-use-in-dot-net) which made it clear that `Dispose()` is supposed to be called by the object's finalizer anyway. So even if you never call it yourself, it should eventually happen, meaning you won't have a memory leak if you don't use `using` (which is what I suppose I was really worried about all along). The only caveat is that the garbage collector doesn't know how much extra memory is being held by the object as unmanaged stuff, so it won't have an accurate idea how much memory will be freed by collecting the object. This will result in less-ideal-than-usual performance by the garbage collector.
In short, it's not the end of the world if I miss a `using`. I just wish something would generate at least a warning for it.
(Off-topic: why is there no special markdown for linking to another question?)
**EDIT:**
Ok, fine, stop clamoring. It's super duper all-fired [dramatic-chipmunk](http://www.youtube.com/watch?v=a1Y73sPHKxw)-level ***important*** to call `Dispose()` or we'll all *die*.
Now. Given that, why is it so easy — hell, why is it even *allowed* — to do it wrong? You have to go out of your way to do it right. Doing it like everything else results in armageddon (apparently). So much for encapsulation, huh?
[Stalks off, disgusted]
|
FxCop *might* help (although it didn't spot a test I just fired at it); but yes: you are meant to check. `IDisposable` is simply such an important part of the system that you need to get into this habit. Using intellisense to look for `.D` is a good start (though not perfect).
However, it doesn't take long to familiarize yourself with types that need disposal; generally anything involving anything external (connection, file, database), for example.
ReSharper does the job too, offering a "put into using construct" option. It doesn't offer it as an error, though...
Of course, if you are unsure - *try* `using` it: the compiler will laugh mockingly at you if you are being paranoid:
```
using (int i = 5) {}
Error 1 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'
```
|
254,976 |
<p>I'm trying to create classes to read from my config file using ConfigurationSection and ConfigurationElementCollection but am having a hard time.</p>
<p>As an example of the config:</p>
<pre><code>
<PaymentMethodSettings>
<PaymentMethods>
<PaymentMethod name="blah blah" code="1"/>
<PaymentMethod name="blah blah" code="42"/>
<PaymentMethod name="blah blah" code="43"/>
<Paymentmethod name="Base blah">
<SubPaymentMethod name="blah blah" code="18"/>
<SubPaymentMethod name="blah blah" code="28"/>
<SubPaymentMethod name="blah blah" code="38"/>
</Paymentmethod>
</PaymentMethods>
</PaymentMethodSettings>
</code></pre>
|
[
{
"answer_id": 255012,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/2tw134k3.aspx\" rel=\"nofollow noreferrer\">This</a> should help you figure out how to create configuration sections correctly, and then read from them.</p>\n"
},
{
"answer_id": 255030,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": true,
"text": "<p>The magic here is to use ConfigurationSection classes.</p>\n\n<p>These classes just need to contain properties that match 1:1 with your configuration schema. You use attributes to let .NET know which properties match which elements.</p>\n\n<p>So, you could create PaymentMethod and have it inherit from ConfigurationSection</p>\n\n<p>And you would create SubPaymentMethod and have it inherit from ConfigurationElement.</p>\n\n<p>PaymentMethod would have a ConfigurationElementCollection of SubPaymentMethods in it as a property, that is how you wire up the complex types together.</p>\n\n<p>You don't need to write your own XML parsing code.</p>\n\n<pre><code>public class PaymentSection : ConfigurationSection\n{\n // Simple One\n [ConfigurationProperty(\"name\")]]\n public String name\n {\n get { return this[\"name\"]; }\n set { this[\"name\"] = value; }\n }\n\n}\n</code></pre>\n\n<p>etc...</p>\n\n<p>See here for how to create the ConfigurationElementCollections so you can have nested types:</p>\n\n<p><a href=\"http://blogs.neudesic.com/blogs/jason_jung/archive/2006/08/08/208.aspx\" rel=\"nofollow noreferrer\">http://blogs.neudesic.com/blogs/jason_jung/archive/2006/08/08/208.aspx</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25951/"
] |
I'm trying to create classes to read from my config file using ConfigurationSection and ConfigurationElementCollection but am having a hard time.
As an example of the config:
```
<PaymentMethodSettings>
<PaymentMethods>
<PaymentMethod name="blah blah" code="1"/>
<PaymentMethod name="blah blah" code="42"/>
<PaymentMethod name="blah blah" code="43"/>
<Paymentmethod name="Base blah">
<SubPaymentMethod name="blah blah" code="18"/>
<SubPaymentMethod name="blah blah" code="28"/>
<SubPaymentMethod name="blah blah" code="38"/>
</Paymentmethod>
</PaymentMethods>
</PaymentMethodSettings>
```
|
The magic here is to use ConfigurationSection classes.
These classes just need to contain properties that match 1:1 with your configuration schema. You use attributes to let .NET know which properties match which elements.
So, you could create PaymentMethod and have it inherit from ConfigurationSection
And you would create SubPaymentMethod and have it inherit from ConfigurationElement.
PaymentMethod would have a ConfigurationElementCollection of SubPaymentMethods in it as a property, that is how you wire up the complex types together.
You don't need to write your own XML parsing code.
```
public class PaymentSection : ConfigurationSection
{
// Simple One
[ConfigurationProperty("name")]]
public String name
{
get { return this["name"]; }
set { this["name"] = value; }
}
}
```
etc...
See here for how to create the ConfigurationElementCollections so you can have nested types:
<http://blogs.neudesic.com/blogs/jason_jung/archive/2006/08/08/208.aspx>
|
254,979 |
<p>I have 3 points (A, B and X) and a distance (d). I need to make a function that tests if point X is closer than distance d to any point on the line segment AB. </p>
<p>The question is firstly, is my solution correct and then to come up with a better (faster) solution.</p>
<p>My first pass is as follows</p>
<pre><code>AX = X-A
BX = X-B
AB = A-B
// closer than d to A (done squared to avoid needing to compute the sqrt in mag)
If d^2 > AX.mag^2 return true
// closer than d to B
If d^2 > BX.mag^2 return true
// "beyond" B
If (dot(BX,AB) < 0) return false
// "beyond" A
If (dot(AX,AB) > 0) return false
// find component of BX perpendicular to AB
Return (BX.mag)^2 - (dot(AB,BX)/AB.mag)^2 < d^2
</code></pre>
<p>This code will end up being run for a large set of P's and a large set of A/B/d triplets with the intent of finding all P's that pass for at least one A/B/d so I suspect that there is a way to reduce overall the cost based on that but I haven't looked into that yet.</p>
<p>(BTW: I am aware that some reordering, some temporary values and some algebraic identities could decrease the cost of the above. I just omitted them for clarity.)</p>
<hr>
<p><em>EDIT: this is a 2D problem (but solution that generalizes to 3D would be cool</em></p>
<p>Edit: On further reflection, I expect the hit rate to be around 50%. The X point can be formed in a nested hierarchy so I expect to be able to prune large subtrees as all-pass and all-fail. The A/B/d limiting the triplets will be more of a trick.</p>
<p>Edit: d is in the same order of magnitude as AB.</p>
<hr>
<p>edit: Artelius posted a nice solution. I'm not sure I understand exactly what he's getting at as I got off on a tangent before I fully understood it. Anyway another thought came to mind as a result:</p>
<ul>
<li>First Artelius' bit, pre-cacluate a matrix that will place AB centered ate the origin and aligned with the X-axis. (2 adds, 4 muls and 2 adds)</li>
<li>fold it all into the 1st quadrant (2 abs)</li>
<li>scale in X&Y to make the central portion of the zone into a unit square (2 mul)</li>
<li>test if the point is in that square (2 test) is so quit</li>
<li>test the end cap (go back to the unscaled values
<ul>
<li>translate in x to place the end at the origin (1 add)</li>
<li>square and add (2 mul, 1 add)</li>
<li>compare to d^2 (1 cmp)</li>
</ul></li>
</ul>
<p>I'm fairly sure this beats my solution.</p>
<p>(if nothing better comes along sone Artelius gets the "prize" :)</p>
|
[
{
"answer_id": 255024,
"author": "benjismith",
"author_id": 22979,
"author_profile": "https://Stackoverflow.com/users/22979",
"pm_score": 2,
"selected": false,
"text": "<p>Hmmmmmmm.... What's the hit-rate? How often does point \"X\" meet the proximity requirements?</p>\n\n<p>I think your existing algorithm is good, and any additional optimizations will come from tuning to the real data. For example, if the \"X\" point meets the proximity test 99% of the time, then I think your optimization strategy should be considerably different than if it only passes the test 1% of the time.</p>\n\n<hr>\n\n<p>Incidentally, when you get to the point where you're running this algorithm with thousands of points, you should organize all the points into a K-Dimensional Tree (or <a href=\"http://en.wikipedia.org/wiki/Kdtree\" rel=\"nofollow noreferrer\">KDTree</a>). It makes the calculation of \"nearest-neighbor\" much simpler.</p>\n\n<p>Your problem is a little more complex than a basic nearest-neighbor (because you're checking proximity-to-a-line-segment rather than just proximity-to-a-point) but I still think the KDTree will be handy.</p>\n"
},
{
"answer_id": 255120,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>This code will end up being run for a large set of P's and a large set of A/B/d triplets with the intent of finding all P's that pass for at least one A/B/d so I suspect that there is a way to reduce overall the cost based on that but I haven't looked into that yet.</p>\n</blockquote>\n\n<p>In the case when d ~ AB, for a given point X, you can first test whether X belongs to one of the many spheres of radius d and center Ai or Bi. Look at the picture:</p>\n\n<pre><code> ...... .....\n ........... ...........\n ...........................\n.......A-------------B.......\n ...........................\n ........... ...........\n ..... .....\n</code></pre>\n\n<p>The first two tests</p>\n\n<pre><code>If d^2 > AX.mag^2 return true\nIf d^2 > BX.mag^2 return true\n</code></pre>\n\n<p>are the fastest ones, and if d ~ AB they are also the ones with highest probability to succeed (given that the test succeeds at all). Given X, you can do all the \"sphere tests\" first, and then all the final ones:</p>\n\n<pre>Return (BX.mag)^2 - (dot(AB,BX)/AB.mag)^2 </pre>\n"
},
{
"answer_id": 255219,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 2,
"selected": false,
"text": "<p>If I read this correctly, then this is almost the same as the classic ray/sphere intersection test as used in 3D ray-tracing.</p>\n\n<p>In this case you have a sphere at location X of radius d, and you're trying to find out whether the line AB intersects the sphere. The one difference with ray-tracing is that in this case you've got a specific line AB, whereas in ray-tracing the ray is normally generalised as as <code>origin + distance * direction</code>, and you don't care how far along the infinite line <code>AB+</code> it is.</p>\n\n<p>In pseudo-code from my own ray-tracer (based on the algorithm given in \"An Introduction to Ray-tracing\" (ed. Glassner):</p>\n\n<pre><code>Vector v = X - A\nVector d = normalise(B - A) // unit direction vector of AB\ndouble b = dot(v, B - A)\ndouble discrim = b^2 - dot(v, v) + d^2\nif (discrim < 0)\n return false // definitely no intersection\n</code></pre>\n\n<p>If you've got this far, then there's <em>some</em> chance that your condition is met. You just have to figure out whether the intersection(s) is on the line AB:</p>\n\n<pre><code>discrim = sqrt(discrim)\ndouble t2 = b + discrim\nif (t2 <= 0)\n return false // intersection is before A\n\ndouble t1 = b - discrim\n\nresult = (t1 < length(AB) || (t2 < length(AB))\n</code></pre>\n"
},
{
"answer_id": 255235,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 3,
"selected": true,
"text": "<p>If your set of (A,B,d) in fixed, you can calculate a pair of matrices for each to translate the co-ordinate system, so that the line AB becomes the X axis, and the midpoint of AB is the origin.</p>\n\n<p>I <em>think</em> this is a simple way to construct the matrices:</p>\n\n<pre><code>trans = - ((A + B) / 2) // translate midpoint of AB to origin\n\nrot.col1 = AB / AB.mag // unit vector in AB direction\n\n 0 -1 \nrot.col2 = rot.col1 * ( ) // unit vector perp to AB\n 1 0 \n\nrot = rot.inverse() // but it needs to be done in reverse\n</code></pre>\n\n<p>Then you just take each X and do <code>rot * (X + trans)</code>.</p>\n\n<p>The region in question is actually symmetric in both the x and y axes now, so you can take the absolute value of the x co-ordinate, and of the y co-ordinate.</p>\n\n<p>Then you just need to check:</p>\n\n<pre><code>y < d && x < AB.mag/2 //\"along\" the line segment\n|| (x - AB.mag/2)^2 + y^2 < d^2 // the \"end cap\".\n</code></pre>\n\n<p>You can do another trick; the matrix can scale down by a factor of <code>AB.mag/2</code> (remember the matrices are only calculated once per (A,B) meaning that it's better that finding them is slower, than the actual check itself). This means your check becomes:</p>\n\n<pre><code>y < 2*d/AB.mag && x < 1\n|| (x - 1)^2 + y^2 < (2*d/AB.mag)^2\n</code></pre>\n\n<p>Having replaced two instances of AB.mag/2 with the constant 1, it might be a touch faster. And of course you can precalculate <code>2*d/AB.mag</code> and <code>(2*d/AB.mag)^2</code> as well.</p>\n\n<p>Whether this will work out faster than other methods depends on the inputs you give it. But if the length of AB is long compared to d, I think it will turn out considerably faster than the method you posted.</p>\n"
},
{
"answer_id": 356412,
"author": "Jason S",
"author_id": 44330,
"author_profile": "https://Stackoverflow.com/users/44330",
"pm_score": 1,
"selected": false,
"text": "<p>If the # of sets of A/B/d are large, and you're definitely in 2D, consider using <a href=\"http://en.wikipedia.org/wiki/R-tree\" rel=\"nofollow noreferrer\">R-trees</a> (or their octagonal equivalents) where each entry in the R-tree is the minimum bounding box of the A/B/d triple. This would let you eliminate having to test a lot of the A/B/d triples & focus your CPU power only on the few ones where each point X is within the bounding boxes of the A/B/d triple. Then do a more detailed test like the one you mention.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
I have 3 points (A, B and X) and a distance (d). I need to make a function that tests if point X is closer than distance d to any point on the line segment AB.
The question is firstly, is my solution correct and then to come up with a better (faster) solution.
My first pass is as follows
```
AX = X-A
BX = X-B
AB = A-B
// closer than d to A (done squared to avoid needing to compute the sqrt in mag)
If d^2 > AX.mag^2 return true
// closer than d to B
If d^2 > BX.mag^2 return true
// "beyond" B
If (dot(BX,AB) < 0) return false
// "beyond" A
If (dot(AX,AB) > 0) return false
// find component of BX perpendicular to AB
Return (BX.mag)^2 - (dot(AB,BX)/AB.mag)^2 < d^2
```
This code will end up being run for a large set of P's and a large set of A/B/d triplets with the intent of finding all P's that pass for at least one A/B/d so I suspect that there is a way to reduce overall the cost based on that but I haven't looked into that yet.
(BTW: I am aware that some reordering, some temporary values and some algebraic identities could decrease the cost of the above. I just omitted them for clarity.)
---
*EDIT: this is a 2D problem (but solution that generalizes to 3D would be cool*
Edit: On further reflection, I expect the hit rate to be around 50%. The X point can be formed in a nested hierarchy so I expect to be able to prune large subtrees as all-pass and all-fail. The A/B/d limiting the triplets will be more of a trick.
Edit: d is in the same order of magnitude as AB.
---
edit: Artelius posted a nice solution. I'm not sure I understand exactly what he's getting at as I got off on a tangent before I fully understood it. Anyway another thought came to mind as a result:
* First Artelius' bit, pre-cacluate a matrix that will place AB centered ate the origin and aligned with the X-axis. (2 adds, 4 muls and 2 adds)
* fold it all into the 1st quadrant (2 abs)
* scale in X&Y to make the central portion of the zone into a unit square (2 mul)
* test if the point is in that square (2 test) is so quit
* test the end cap (go back to the unscaled values
+ translate in x to place the end at the origin (1 add)
+ square and add (2 mul, 1 add)
+ compare to d^2 (1 cmp)
I'm fairly sure this beats my solution.
(if nothing better comes along sone Artelius gets the "prize" :)
|
If your set of (A,B,d) in fixed, you can calculate a pair of matrices for each to translate the co-ordinate system, so that the line AB becomes the X axis, and the midpoint of AB is the origin.
I *think* this is a simple way to construct the matrices:
```
trans = - ((A + B) / 2) // translate midpoint of AB to origin
rot.col1 = AB / AB.mag // unit vector in AB direction
0 -1
rot.col2 = rot.col1 * ( ) // unit vector perp to AB
1 0
rot = rot.inverse() // but it needs to be done in reverse
```
Then you just take each X and do `rot * (X + trans)`.
The region in question is actually symmetric in both the x and y axes now, so you can take the absolute value of the x co-ordinate, and of the y co-ordinate.
Then you just need to check:
```
y < d && x < AB.mag/2 //"along" the line segment
|| (x - AB.mag/2)^2 + y^2 < d^2 // the "end cap".
```
You can do another trick; the matrix can scale down by a factor of `AB.mag/2` (remember the matrices are only calculated once per (A,B) meaning that it's better that finding them is slower, than the actual check itself). This means your check becomes:
```
y < 2*d/AB.mag && x < 1
|| (x - 1)^2 + y^2 < (2*d/AB.mag)^2
```
Having replaced two instances of AB.mag/2 with the constant 1, it might be a touch faster. And of course you can precalculate `2*d/AB.mag` and `(2*d/AB.mag)^2` as well.
Whether this will work out faster than other methods depends on the inputs you give it. But if the length of AB is long compared to d, I think it will turn out considerably faster than the method you posted.
|
254,980 |
<p>As a follow-up to <a href="https://stackoverflow.com/questions/199518/how-to-programatically-add-mapped-network-passwords-winxp">this</a> question I am hoping someone can help with the <a href="http://msdn.microsoft.com/en-us/library/aa374794(VS.85).aspx" rel="nofollow noreferrer">CredEnumerate</a> API. </p>
<p>As I understand from the documentation the PCREDENTIALS out parameter is a "pointer to an array of pointers to credentials". I am able to successfully call the CredEnumerate API using C# but I am not sure of how to convert the PCREDENTIALS into something useful (like a list of credentials).</p>
<p>Edit: Here's the code I am using:</p>
<pre><code> int count = 0;
IntPtr pCredentials = IntPtr.Zero;
bool ret = false;
ret = CredEnumerate(null, 0, out count, out pCredentials);
if (ret != false)
{
IntPtr[] credentials = new IntPtr[count];
IntPtr p = pCredentials;
for (int i = 0; i < count; i++)
{
p = new IntPtr(p.ToInt32() + i);
credentials[i] = Marshal.ReadIntPtr(p);
}
List<Credential> creds = new List<Credential>(credentials.Length);
foreach (IntPtr ptr in credentials)
{
creds.Add((Credential)Marshal.PtrToStructure(ptr, typeof(Credential)));
}
}
</code></pre>
<p>Unfortunately, while this works for the first credential in the array—it gets generated and added to the list correctly—subsequent array items bomb at Marshal.PtrToStructure with the following error:</p>
<p><em>Attempted to read or write protected memory. This is often an indication that other memory is corrupt.</em></p>
<p>Any ideas? Anyone? Bueller?</p>
|
[
{
"answer_id": 255073,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 4,
"selected": true,
"text": "<p>You need to dereference the pointer to the array to get the array, then for each item in the array you will need to dereference the item to get the <code>PCREDENTIALS</code> instance.</p>\n\n<p>I found <a href=\"http://www.msnewsgroups.net/group/microsoft.public.dotnet.languages.csharp/topic33651.aspx\" rel=\"nofollow noreferrer\">this post with some example code</a> for performing what you want to do:</p>\n\n<pre><code>[DllImport(\"advapi32\", SetLastError = true, CharSet=CharSet.Unicode)]\nstatic extern bool CredEnumerate(string filter, int flag, out int count, out IntPtr\npCredentials);\n</code></pre>\n\n<p>...</p>\n\n<pre><code>int count = 0;\nIntPtr pCredentials = IntPtr.Zero;\nIntPtr[] credentials = null;\nbool ret = CredEnumerate(null, 0, out count, out pCredentials);\nif (ret != false)\n{\n credentials = new IntPtr[count];\n IntPtr p = pCredentials;\n for (int n = 0; n < count; n++)\n {\n credentials[n] = Marshal.ReadIntPtr(pCredentials,\n n * Marshal.SizeOf(typeof(IntPtr)));\n }\n} \nelse\n// failed....\n</code></pre>\n\n<p>Then for each pointer you'll need to use <code>Marshal.PtrToStructure</code> to dereference the pointer into a <code>PCREDENTIALS</code> struct instance (sorry I cannot find the typedef for <code>PCREDENTIALS</code> anywhere, I'll assume you have it - and if you do don't forget the correct MarshalAs attributes and StructLayout attribute when you do define it):</p>\n\n<pre><code>// assuming you have declared struct PCREDENTIALS\nvar creds = new List<PCREDENTIALS>(credentials.Length);\nforeach (var ptr in credentials)\n{\n creds.Add((PCREDENTIALS)Marshal.PtrToStructure(ptr, typeof(PCREDENTIALS)));\n}\n</code></pre>\n\n<p>You would obviously want to combine the example and <code>PtrToStructure</code> code for optimal results but I wanted to leave the integrity of the example intact.</p>\n"
},
{
"answer_id": 4815173,
"author": "Luis",
"author_id": 591994,
"author_profile": "https://Stackoverflow.com/users/591994",
"pm_score": 1,
"selected": false,
"text": "<p>You also need to calculate 'IntPtr p' correctly the code above is missing that and it will only fetch the 1st structure.</p>\n\n<p>Th following code will get all structures in 'IntPtr pCredentials'</p>\n\n<pre><code>int count;\nIntPtr pCredentials;\n\nif (CredEnumerate(filter, 0, out count, out pCredentials) != 0)\n{\n m_list = new List<PCREDENTIALS >(count);\n int sz = Marshal.SizeOf(pCredentials);\n\n for (int index = 0; index < count; index++)\n {\n IntPtr p = new IntPtr((sz == 4 ? pCredentials.ToInt32() : pCredentials.ToInt64()) + index * sz);\n m_list.Add((PCREDENTIALS)Marshal.PtrToStructure(p, typeof(PCREDENTIALS)));\n }\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12842/"
] |
As a follow-up to [this](https://stackoverflow.com/questions/199518/how-to-programatically-add-mapped-network-passwords-winxp) question I am hoping someone can help with the [CredEnumerate](http://msdn.microsoft.com/en-us/library/aa374794(VS.85).aspx) API.
As I understand from the documentation the PCREDENTIALS out parameter is a "pointer to an array of pointers to credentials". I am able to successfully call the CredEnumerate API using C# but I am not sure of how to convert the PCREDENTIALS into something useful (like a list of credentials).
Edit: Here's the code I am using:
```
int count = 0;
IntPtr pCredentials = IntPtr.Zero;
bool ret = false;
ret = CredEnumerate(null, 0, out count, out pCredentials);
if (ret != false)
{
IntPtr[] credentials = new IntPtr[count];
IntPtr p = pCredentials;
for (int i = 0; i < count; i++)
{
p = new IntPtr(p.ToInt32() + i);
credentials[i] = Marshal.ReadIntPtr(p);
}
List<Credential> creds = new List<Credential>(credentials.Length);
foreach (IntPtr ptr in credentials)
{
creds.Add((Credential)Marshal.PtrToStructure(ptr, typeof(Credential)));
}
}
```
Unfortunately, while this works for the first credential in the array—it gets generated and added to the list correctly—subsequent array items bomb at Marshal.PtrToStructure with the following error:
*Attempted to read or write protected memory. This is often an indication that other memory is corrupt.*
Any ideas? Anyone? Bueller?
|
You need to dereference the pointer to the array to get the array, then for each item in the array you will need to dereference the item to get the `PCREDENTIALS` instance.
I found [this post with some example code](http://www.msnewsgroups.net/group/microsoft.public.dotnet.languages.csharp/topic33651.aspx) for performing what you want to do:
```
[DllImport("advapi32", SetLastError = true, CharSet=CharSet.Unicode)]
static extern bool CredEnumerate(string filter, int flag, out int count, out IntPtr
pCredentials);
```
...
```
int count = 0;
IntPtr pCredentials = IntPtr.Zero;
IntPtr[] credentials = null;
bool ret = CredEnumerate(null, 0, out count, out pCredentials);
if (ret != false)
{
credentials = new IntPtr[count];
IntPtr p = pCredentials;
for (int n = 0; n < count; n++)
{
credentials[n] = Marshal.ReadIntPtr(pCredentials,
n * Marshal.SizeOf(typeof(IntPtr)));
}
}
else
// failed....
```
Then for each pointer you'll need to use `Marshal.PtrToStructure` to dereference the pointer into a `PCREDENTIALS` struct instance (sorry I cannot find the typedef for `PCREDENTIALS` anywhere, I'll assume you have it - and if you do don't forget the correct MarshalAs attributes and StructLayout attribute when you do define it):
```
// assuming you have declared struct PCREDENTIALS
var creds = new List<PCREDENTIALS>(credentials.Length);
foreach (var ptr in credentials)
{
creds.Add((PCREDENTIALS)Marshal.PtrToStructure(ptr, typeof(PCREDENTIALS)));
}
```
You would obviously want to combine the example and `PtrToStructure` code for optimal results but I wanted to leave the integrity of the example intact.
|
254,985 |
<p>The company I work for has a large webapp written in C++ as an ISAPI extension (not a filter). We're currently enhancing our system to integrate with several 3rd party tools that have SOAP interfaces. Rather than roll our own, I think it would probably be best if we used some SOAP library. Ideally, it would be free and open source, but have a license compatible with closed-source commercial software. We also need to support SSL for both incoming and outgoing SOAP messages.</p>
<p>One of the biggest concerns I have is that every SOAP library that I've looked at seems to have 2 modes of operation: standalone server and server module (either Apache module or ISAPI filter). Obviously, we can't use the standalone server. It seems to me that if it is running as a module, it won't be part of my app -- it won't have access to the rest of my code, so it won't be able to share data structures, etc. Is that a correct assumption? Each HTTP request processed by our app is handled by a separate thread (we manage our own thread pool), but we have lots of persistent data that is shared between those threads. I think the type of integration I'm looking for is to add some code to my app that looks at the request URL, sees that it is trying to access a SOAP service, and calls some function like soapService.handleRequest(). I'm not aware of anything that offers this sort of integration. We must be able to utilize data structures from our main app in the SOAP handler functions.</p>
<p>In addition to handling incoming SOAP requests, we're also going to be generating them (bi-directional communication with the 3rd parties). I assume pretty much any SOAP library will fulfill that purpose, right?</p>
<p>Can anyone suggest a SOAP library that is capable of this, or offer a suggestion on how to use a different paradigm? I've already looked at Apache Axis2, gSOAP and AlchemySOAP, but perhaps there's some feature of these that I overlooked. Thanks.</p>
|
[
{
"answer_id": 255073,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 4,
"selected": true,
"text": "<p>You need to dereference the pointer to the array to get the array, then for each item in the array you will need to dereference the item to get the <code>PCREDENTIALS</code> instance.</p>\n\n<p>I found <a href=\"http://www.msnewsgroups.net/group/microsoft.public.dotnet.languages.csharp/topic33651.aspx\" rel=\"nofollow noreferrer\">this post with some example code</a> for performing what you want to do:</p>\n\n<pre><code>[DllImport(\"advapi32\", SetLastError = true, CharSet=CharSet.Unicode)]\nstatic extern bool CredEnumerate(string filter, int flag, out int count, out IntPtr\npCredentials);\n</code></pre>\n\n<p>...</p>\n\n<pre><code>int count = 0;\nIntPtr pCredentials = IntPtr.Zero;\nIntPtr[] credentials = null;\nbool ret = CredEnumerate(null, 0, out count, out pCredentials);\nif (ret != false)\n{\n credentials = new IntPtr[count];\n IntPtr p = pCredentials;\n for (int n = 0; n < count; n++)\n {\n credentials[n] = Marshal.ReadIntPtr(pCredentials,\n n * Marshal.SizeOf(typeof(IntPtr)));\n }\n} \nelse\n// failed....\n</code></pre>\n\n<p>Then for each pointer you'll need to use <code>Marshal.PtrToStructure</code> to dereference the pointer into a <code>PCREDENTIALS</code> struct instance (sorry I cannot find the typedef for <code>PCREDENTIALS</code> anywhere, I'll assume you have it - and if you do don't forget the correct MarshalAs attributes and StructLayout attribute when you do define it):</p>\n\n<pre><code>// assuming you have declared struct PCREDENTIALS\nvar creds = new List<PCREDENTIALS>(credentials.Length);\nforeach (var ptr in credentials)\n{\n creds.Add((PCREDENTIALS)Marshal.PtrToStructure(ptr, typeof(PCREDENTIALS)));\n}\n</code></pre>\n\n<p>You would obviously want to combine the example and <code>PtrToStructure</code> code for optimal results but I wanted to leave the integrity of the example intact.</p>\n"
},
{
"answer_id": 4815173,
"author": "Luis",
"author_id": 591994,
"author_profile": "https://Stackoverflow.com/users/591994",
"pm_score": 1,
"selected": false,
"text": "<p>You also need to calculate 'IntPtr p' correctly the code above is missing that and it will only fetch the 1st structure.</p>\n\n<p>Th following code will get all structures in 'IntPtr pCredentials'</p>\n\n<pre><code>int count;\nIntPtr pCredentials;\n\nif (CredEnumerate(filter, 0, out count, out pCredentials) != 0)\n{\n m_list = new List<PCREDENTIALS >(count);\n int sz = Marshal.SizeOf(pCredentials);\n\n for (int index = 0; index < count; index++)\n {\n IntPtr p = new IntPtr((sz == 4 ? pCredentials.ToInt32() : pCredentials.ToInt64()) + index * sz);\n m_list.Add((PCREDENTIALS)Marshal.PtrToStructure(p, typeof(PCREDENTIALS)));\n }\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10861/"
] |
The company I work for has a large webapp written in C++ as an ISAPI extension (not a filter). We're currently enhancing our system to integrate with several 3rd party tools that have SOAP interfaces. Rather than roll our own, I think it would probably be best if we used some SOAP library. Ideally, it would be free and open source, but have a license compatible with closed-source commercial software. We also need to support SSL for both incoming and outgoing SOAP messages.
One of the biggest concerns I have is that every SOAP library that I've looked at seems to have 2 modes of operation: standalone server and server module (either Apache module or ISAPI filter). Obviously, we can't use the standalone server. It seems to me that if it is running as a module, it won't be part of my app -- it won't have access to the rest of my code, so it won't be able to share data structures, etc. Is that a correct assumption? Each HTTP request processed by our app is handled by a separate thread (we manage our own thread pool), but we have lots of persistent data that is shared between those threads. I think the type of integration I'm looking for is to add some code to my app that looks at the request URL, sees that it is trying to access a SOAP service, and calls some function like soapService.handleRequest(). I'm not aware of anything that offers this sort of integration. We must be able to utilize data structures from our main app in the SOAP handler functions.
In addition to handling incoming SOAP requests, we're also going to be generating them (bi-directional communication with the 3rd parties). I assume pretty much any SOAP library will fulfill that purpose, right?
Can anyone suggest a SOAP library that is capable of this, or offer a suggestion on how to use a different paradigm? I've already looked at Apache Axis2, gSOAP and AlchemySOAP, but perhaps there's some feature of these that I overlooked. Thanks.
|
You need to dereference the pointer to the array to get the array, then for each item in the array you will need to dereference the item to get the `PCREDENTIALS` instance.
I found [this post with some example code](http://www.msnewsgroups.net/group/microsoft.public.dotnet.languages.csharp/topic33651.aspx) for performing what you want to do:
```
[DllImport("advapi32", SetLastError = true, CharSet=CharSet.Unicode)]
static extern bool CredEnumerate(string filter, int flag, out int count, out IntPtr
pCredentials);
```
...
```
int count = 0;
IntPtr pCredentials = IntPtr.Zero;
IntPtr[] credentials = null;
bool ret = CredEnumerate(null, 0, out count, out pCredentials);
if (ret != false)
{
credentials = new IntPtr[count];
IntPtr p = pCredentials;
for (int n = 0; n < count; n++)
{
credentials[n] = Marshal.ReadIntPtr(pCredentials,
n * Marshal.SizeOf(typeof(IntPtr)));
}
}
else
// failed....
```
Then for each pointer you'll need to use `Marshal.PtrToStructure` to dereference the pointer into a `PCREDENTIALS` struct instance (sorry I cannot find the typedef for `PCREDENTIALS` anywhere, I'll assume you have it - and if you do don't forget the correct MarshalAs attributes and StructLayout attribute when you do define it):
```
// assuming you have declared struct PCREDENTIALS
var creds = new List<PCREDENTIALS>(credentials.Length);
foreach (var ptr in credentials)
{
creds.Add((PCREDENTIALS)Marshal.PtrToStructure(ptr, typeof(PCREDENTIALS)));
}
```
You would obviously want to combine the example and `PtrToStructure` code for optimal results but I wanted to leave the integrity of the example intact.
|
254,992 |
<p>I've got some RadioButtons in my XAML...</p>
<pre><code><StackPanel>
<RadioButton Name="RadioButton1" GroupName="Buttons" Click="ButtonsChecked" IsChecked="True">One</RadioButton>
<RadioButton Name="RadioButton2" GroupName="Buttons" Click="ButtonsChecked">Two</RadioButton>
<RadioButton Name="RadioButton3" GroupName="Buttons" Click="ButtonsChecked">Three</RadioButton>
</StackPanel>
</code></pre>
<p>And I can handle their click events in the Visual Basic code. This works...</p>
<pre>
Private Sub ButtonsChecked(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
Select Case CType(sender, RadioButton).Name
Case "RadioButton1"
'Do something one
Exit Select
Case "RadioButton2"
'Do something two
Exit Select
Case "RadioButton3"
'Do something three
Exit Select
End Select
End Sub
</pre>
<p>But, I'd like to improve it. This code fails...</p>
<pre><code><StackPanel>
<RadioButton Name="RadioButton1" GroupName="Buttons" Click="ButtonsChecked" Command="one" IsChecked="True">One</RadioButton>
<RadioButton Name="RadioButton2" GroupName="Buttons" Click="ButtonsChecked" Command="two">Two</RadioButton>
<RadioButton Name="RadioButton3" GroupName="Buttons" Click="ButtonsChecked" Command="three">Three</RadioButton>
</StackPanel>
</code></pre>
<pre>
Private Sub ButtonsChecked(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
Select Case CType(sender, RadioButton).Command
Case "one"
'Do something one
Exit Select
Case "two"
'Do something two
Exit Select
Case "three"
'Do something three
Exit Select
End Select
End Sub
</pre>
<p>In my XAML I get a blue squiggly underline on the <strong>Command=</strong> attributes and this tip... </p>
<pre>'CommandValueSerializer' ValueSerializer cannot convert from 'System.String'.</pre>
<p>In my VB I get a green squiggly underline on the <strong>Select Case</strong> line and this warning...</p>
<pre>Runtime errors might occur when converting 'System.Windows.Input.ICommand' to 'String'.</pre>
<p>Even better would be to use Enum type commands with full Intellisense and compile errors rather than runtime errors in case of typos. How can I improve this?</p>
|
[
{
"answer_id": 255225,
"author": "Ian Oakes",
"author_id": 21606,
"author_profile": "https://Stackoverflow.com/users/21606",
"pm_score": 5,
"selected": true,
"text": "<p>In order for commands to work you need to set up bindings in either your xaml or code behind. These command bindings must reference public static fields that have been previously declared. </p>\n\n<p>Then in your buttons Command attribute you will then need to also reference these same commands.</p>\n\n<pre><code><Window \n x:Class=\"RadioButtonCommandSample.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:RadioButtonCommandSample\"\n Title=\"Window1\" \n Height=\"300\" \n Width=\"300\"\n >\n <Window.CommandBindings>\n <CommandBinding Command=\"{x:Static local:Window1.CommandOne}\" Executed=\"CommandBinding_Executed\"/>\n <CommandBinding Command=\"{x:Static local:Window1.CommandTwo}\" Executed=\"CommandBinding_Executed\"/>\n <CommandBinding Command=\"{x:Static local:Window1.CommandThree}\" Executed=\"CommandBinding_Executed\"/>\n </Window.CommandBindings>\n <StackPanel>\n <RadioButton Name=\"RadioButton1\" GroupName=\"Buttons\" Command=\"{x:Static local:Window1.CommandOne}\" IsChecked=\"True\">One</RadioButton>\n <RadioButton Name=\"RadioButton2\" GroupName=\"Buttons\" Command=\"{x:Static local:Window1.CommandTwo}\">Two</RadioButton>\n <RadioButton Name=\"RadioButton3\" GroupName=\"Buttons\" Command=\"{x:Static local:Window1.CommandThree}\">Three</RadioButton>\n </StackPanel>\n</Window>\n\npublic partial class Window1 : Window\n{\n public static readonly RoutedCommand CommandOne = new RoutedCommand();\n public static readonly RoutedCommand CommandTwo = new RoutedCommand();\n public static readonly RoutedCommand CommandThree = new RoutedCommand();\n\n public Window1()\n {\n InitializeComponent();\n }\n\n private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)\n {\n if (e.Command == CommandOne)\n {\n MessageBox.Show(\"CommandOne\");\n }\n else if (e.Command == CommandTwo)\n {\n MessageBox.Show(\"CommandTwo\");\n }\n else if (e.Command == CommandThree)\n {\n MessageBox.Show(\"CommandThree\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 39902417,
"author": "Sridhar Ganapathy",
"author_id": 4437729,
"author_profile": "https://Stackoverflow.com/users/4437729",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Better Solution using WPF MVVM Design Pattern:</strong></p>\n\n<p>Radio Button Control XAML to Modelview.vb/ModelView.cs :</p>\n\n<pre><code>XAML Code:\n<RadioButton Content=\"On\" IsEnabled=\"True\" IsChecked=\"{Binding OnJob}\"/>\n<RadioButton Content=\"Off\" IsEnabled=\"True\" IsChecked=\"{Binding OffJob}\"/>\n</code></pre>\n\n<p>ViewModel.vb :</p>\n\n<pre><code>Private _OffJob As Boolean = False\nPrivate _OnJob As Boolean = False\n\nPublic Property OnJob As Boolean\n Get\n Return _OnJob\n End Get\n Set(value As Boolean)\n Me._OnJob = value\n End Set\nEnd Property\n\nPublic Property OffJob As Boolean\n Get\n Return _OffJob\n End Get\n Set(value As Boolean)\n Me._OffJob = value\n End Set\nEnd Property\n\nPrivate Sub FindCheckedItem()\n If(Me.OnJob = True)\n MessageBox.show(\"You have checked On\")\n End If\nIf(Me.OffJob = False)\n MessageBox.Show(\"You have checked Off\")\nEnd sub\n</code></pre>\n\n<p>One can use the same logic above to see if you checked any of the three Radio \nButtons viz. Option One, Option Two, Option Three. But checking if the Boolean set id true or false you can identify whether the radio button is checked or not.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
I've got some RadioButtons in my XAML...
```
<StackPanel>
<RadioButton Name="RadioButton1" GroupName="Buttons" Click="ButtonsChecked" IsChecked="True">One</RadioButton>
<RadioButton Name="RadioButton2" GroupName="Buttons" Click="ButtonsChecked">Two</RadioButton>
<RadioButton Name="RadioButton3" GroupName="Buttons" Click="ButtonsChecked">Three</RadioButton>
</StackPanel>
```
And I can handle their click events in the Visual Basic code. This works...
```
Private Sub ButtonsChecked(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
Select Case CType(sender, RadioButton).Name
Case "RadioButton1"
'Do something one
Exit Select
Case "RadioButton2"
'Do something two
Exit Select
Case "RadioButton3"
'Do something three
Exit Select
End Select
End Sub
```
But, I'd like to improve it. This code fails...
```
<StackPanel>
<RadioButton Name="RadioButton1" GroupName="Buttons" Click="ButtonsChecked" Command="one" IsChecked="True">One</RadioButton>
<RadioButton Name="RadioButton2" GroupName="Buttons" Click="ButtonsChecked" Command="two">Two</RadioButton>
<RadioButton Name="RadioButton3" GroupName="Buttons" Click="ButtonsChecked" Command="three">Three</RadioButton>
</StackPanel>
```
```
Private Sub ButtonsChecked(ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
Select Case CType(sender, RadioButton).Command
Case "one"
'Do something one
Exit Select
Case "two"
'Do something two
Exit Select
Case "three"
'Do something three
Exit Select
End Select
End Sub
```
In my XAML I get a blue squiggly underline on the **Command=** attributes and this tip...
```
'CommandValueSerializer' ValueSerializer cannot convert from 'System.String'.
```
In my VB I get a green squiggly underline on the **Select Case** line and this warning...
```
Runtime errors might occur when converting 'System.Windows.Input.ICommand' to 'String'.
```
Even better would be to use Enum type commands with full Intellisense and compile errors rather than runtime errors in case of typos. How can I improve this?
|
In order for commands to work you need to set up bindings in either your xaml or code behind. These command bindings must reference public static fields that have been previously declared.
Then in your buttons Command attribute you will then need to also reference these same commands.
```
<Window
x:Class="RadioButtonCommandSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:RadioButtonCommandSample"
Title="Window1"
Height="300"
Width="300"
>
<Window.CommandBindings>
<CommandBinding Command="{x:Static local:Window1.CommandOne}" Executed="CommandBinding_Executed"/>
<CommandBinding Command="{x:Static local:Window1.CommandTwo}" Executed="CommandBinding_Executed"/>
<CommandBinding Command="{x:Static local:Window1.CommandThree}" Executed="CommandBinding_Executed"/>
</Window.CommandBindings>
<StackPanel>
<RadioButton Name="RadioButton1" GroupName="Buttons" Command="{x:Static local:Window1.CommandOne}" IsChecked="True">One</RadioButton>
<RadioButton Name="RadioButton2" GroupName="Buttons" Command="{x:Static local:Window1.CommandTwo}">Two</RadioButton>
<RadioButton Name="RadioButton3" GroupName="Buttons" Command="{x:Static local:Window1.CommandThree}">Three</RadioButton>
</StackPanel>
</Window>
public partial class Window1 : Window
{
public static readonly RoutedCommand CommandOne = new RoutedCommand();
public static readonly RoutedCommand CommandTwo = new RoutedCommand();
public static readonly RoutedCommand CommandThree = new RoutedCommand();
public Window1()
{
InitializeComponent();
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (e.Command == CommandOne)
{
MessageBox.Show("CommandOne");
}
else if (e.Command == CommandTwo)
{
MessageBox.Show("CommandTwo");
}
else if (e.Command == CommandThree)
{
MessageBox.Show("CommandThree");
}
}
}
```
|
254,993 |
<p>In one of my projects I need to build an ASP.NET page and some of the controls need to be created dynamically. These controls are added to the page by the code-behind class and they have some event-handlers added to them. Upon the PostBacks these event-handlers have a lot to do with what controls are then shown on the page. To cut the story short, this doesn't work for me and I don't seem to be able to figure this out.</p>
<p>So, as my project is quite involved, I decided to create a short example that doesn't work either but if you can tweak it so that it works, that would be great and I would then be able to apply your solution to my original problem.</p>
<p>The following example should dynamically create three buttons on a panel. When one of the buttons is pressed all of the buttons should be dynamically re-created except for the button that was pressed. In other words, just hide the button that the user presses and show the other two.</p>
<p>For your solution to be helpful you can't statically create the buttons and then use the Visible property (or drastically change the example in other ways) - you have to re-create all the button controls dynamically upon every PostBack (not necessarily in the event-handler though). This is not a trick-question - I really don't know how to do this. Thank you very much for your effort. Here is my short example:</p>
<h2>From the Default.aspx file:</h2>
<pre><code><body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="ButtonsPanel" runat="server"></asp:Panel>
</div>
</form>
</body>
</code></pre>
<h2>From the Default.aspx.cs code-behind file:</h2>
<pre><code>using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DynamicControls
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
AddButtons();
}
protected void AddButtons()
{
var lastClick = (string) Session["ClickedButton"] ?? "";
ButtonsPanel.Controls.Clear();
if (!lastClick.Equals("1")) AddButtonControl("1");
if (!lastClick.Equals("2")) AddButtonControl("2");
if (!lastClick.Equals("3")) AddButtonControl("3");
}
protected void AddButtonControl(String id)
{
var button = new Button {Text = id};
button.Click += button_Click;
ButtonsPanel.Controls.Add(button);
}
private void button_Click(object sender, EventArgs e)
{
Session["ClickedButton"] = ((Button) sender).Text;
AddButtons();
}
}
}
</code></pre>
<p>My example shows the three buttons and when I click one of the buttons, the pressed button gets hidden. Seems to work; but after this first click, I have to click each button <strong>TWICE</strong> for it to get hidden. !?</p>
|
[
{
"answer_id": 255017,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>One thing I notice is that when you click a button you are invoking AddButtons() twice, once in the <code>Page_Load()</code> and once in the <code>button_Click()</code> method. You should probably wrap the one in <code>Page_Load()</code> in an <code>if (!IsPostBack)</code> block.</p>\n\n<pre><code>if (!IsPostBack)\n{\n AddButtons();\n}\n</code></pre>\n"
},
{
"answer_id": 255036,
"author": "gius",
"author_id": 19712,
"author_profile": "https://Stackoverflow.com/users/19712",
"pm_score": 0,
"selected": false,
"text": "<p>AFAIK, creating of controls should not be placed in Page_Load but in Page_PreInit (ViewState and SessionState is loaded before Page_Load but after Page_PreInit).</p>\n\n<p>With your problem, I would suggest to debug the AddButtons function to find out what exactly (and when) is stored in Session[\"ClickedButton\"]. Then, you should be able to figure out the problem.</p>\n"
},
{
"answer_id": 255037,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 3,
"selected": true,
"text": "<p>I think that you have to provide the same ID for your buttons every time you add them like this for example (in first line of <code>AddButtonControl</code> method):</p>\n\n<pre><code>var button = new Button { Text = id , ID = id };\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT</strong> - My solution without using session:</p>\n\n<pre><code>public partial class _Default : Page\n{\n protected override void OnPreInit(EventArgs e)\n {\n base.OnPreInit(e);\n AddButtons();\n }\n\n protected void AddButtons()\n {\n AddButtonControl(\"btn1\", \"1\");\n AddButtonControl(\"btn2\", \"2\");\n AddButtonControl(\"btn3\", \"3\");\n }\n\n protected void AddButtonControl(string id, string text)\n {\n var button = new Button { Text = text, ID = id };\n button.Click += button_Click;\n ButtonsPanel.Controls.Add(button);\n }\n\n private void button_Click(object sender, EventArgs e)\n {\n foreach (Control control in ButtonsPanel.Controls)\n control.Visible = !control.Equals(sender);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 255055,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "<p>You need to make sure that your dynamic controls are being added during the <code>Pre_Init</code> event.</p>\n\n<p>See here for the ASP.NET Page Lifecycle: <a href=\"http://msdn.microsoft.com/en-us/library/ms178472.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms178472.aspx</a></p>\n\n<p>When adding events you need to do it no later than the <code>Page_Load</code> method and they <em>need to be added every single request</em>, ie you should never wrap event assignment in a <code>!IsPostBack</code>.</p>\n\n<p>You need to create dynamic controls ever single request as well. ViewState will not handle the recreation on your behalf.</p>\n"
},
{
"answer_id": 255156,
"author": "Oscar Cabrero",
"author_id": 14440,
"author_profile": "https://Stackoverflow.com/users/14440",
"pm_score": 0,
"selected": false,
"text": "<p>the controls that are added dynamically are not cached so this migth me one of your problems</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/254993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3379/"
] |
In one of my projects I need to build an ASP.NET page and some of the controls need to be created dynamically. These controls are added to the page by the code-behind class and they have some event-handlers added to them. Upon the PostBacks these event-handlers have a lot to do with what controls are then shown on the page. To cut the story short, this doesn't work for me and I don't seem to be able to figure this out.
So, as my project is quite involved, I decided to create a short example that doesn't work either but if you can tweak it so that it works, that would be great and I would then be able to apply your solution to my original problem.
The following example should dynamically create three buttons on a panel. When one of the buttons is pressed all of the buttons should be dynamically re-created except for the button that was pressed. In other words, just hide the button that the user presses and show the other two.
For your solution to be helpful you can't statically create the buttons and then use the Visible property (or drastically change the example in other ways) - you have to re-create all the button controls dynamically upon every PostBack (not necessarily in the event-handler though). This is not a trick-question - I really don't know how to do this. Thank you very much for your effort. Here is my short example:
From the Default.aspx file:
---------------------------
```
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="ButtonsPanel" runat="server"></asp:Panel>
</div>
</form>
</body>
```
From the Default.aspx.cs code-behind file:
------------------------------------------
```
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DynamicControls
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
AddButtons();
}
protected void AddButtons()
{
var lastClick = (string) Session["ClickedButton"] ?? "";
ButtonsPanel.Controls.Clear();
if (!lastClick.Equals("1")) AddButtonControl("1");
if (!lastClick.Equals("2")) AddButtonControl("2");
if (!lastClick.Equals("3")) AddButtonControl("3");
}
protected void AddButtonControl(String id)
{
var button = new Button {Text = id};
button.Click += button_Click;
ButtonsPanel.Controls.Add(button);
}
private void button_Click(object sender, EventArgs e)
{
Session["ClickedButton"] = ((Button) sender).Text;
AddButtons();
}
}
}
```
My example shows the three buttons and when I click one of the buttons, the pressed button gets hidden. Seems to work; but after this first click, I have to click each button **TWICE** for it to get hidden. !?
|
I think that you have to provide the same ID for your buttons every time you add them like this for example (in first line of `AddButtonControl` method):
```
var button = new Button { Text = id , ID = id };
```
---
**EDIT** - My solution without using session:
```
public partial class _Default : Page
{
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
AddButtons();
}
protected void AddButtons()
{
AddButtonControl("btn1", "1");
AddButtonControl("btn2", "2");
AddButtonControl("btn3", "3");
}
protected void AddButtonControl(string id, string text)
{
var button = new Button { Text = text, ID = id };
button.Click += button_Click;
ButtonsPanel.Controls.Add(button);
}
private void button_Click(object sender, EventArgs e)
{
foreach (Control control in ButtonsPanel.Controls)
control.Visible = !control.Equals(sender);
}
}
```
|
255,006 |
<p>Is it possible to automatically launch an application from a USB flash drive (bypassing windows prompt asking user what he wants to do)? on windows XP or vista.</p>
<p>I looked into "autorun.inf" and "open" entry seems to work only for CD drives for Windows XP SP2+ and Vista. Is it possible to launch program automatically on all windows versions?</p>
<p>I don't care if autorun is disabled by user in Windows settings.</p>
|
[
{
"answer_id": 255028,
"author": "BobC",
"author_id": 31167,
"author_profile": "https://Stackoverflow.com/users/31167",
"pm_score": 2,
"selected": false,
"text": "<p>I've had something set up on my USB keys for a while now. Using the autorun.inf file will work, depending on your system's settings for autorun. Some disable it altogether after that little debacle with Sony a couple years back installing rootkit software on peoples' machines. Here're a couple articles to check out.</p>\n\n<p><a href=\"http://lifehacker.com/375320/label-a-flash-drive-with-your-name-and-number\" rel=\"nofollow noreferrer\">Label a Flash Drive with Your Name and Number</a></p>\n\n<p><a href=\"http://dailycupoftech.com/have-your-lost-usb-drive-ask-for-help/\" rel=\"nofollow noreferrer\">Have Your Lost USB Drive Ask For Help (1)</a> or <a href=\"https://web.archive.org/web/20130303191604/http://www.dailycupoftech.com/have-your-lost-usb-drive-ask-for-help\" rel=\"nofollow noreferrer\">2</a></p>\n"
},
{
"answer_id": 255067,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 5,
"selected": false,
"text": "<p>First of all, some people choose to disable autorun for security reasons; but Windows computers up to Vista have it enabled. Edit: <strong>Apparently the functionality was removed from Windows 7 onwards.</strong></p>\n\n<p>Put a file named autorun.inf in the root of your USB flash drive. This is what's in mine:</p>\n\n<pre><code>[Autorun]\nOpen=PStart.exe\nAction=Start portable apps\nIcon=diskicon.ico\n</code></pre>\n\n<p>What it does: when you insert this disk, starts <code>PStart.exe</code></p>\n\n<p>On older computers, the program specified in <code>Open=</code> will launch automatically.</p>\n\n<p>On most modern computers (Windows XP SP2+, Vista), dialog \"what do you want to do\" will be displayed (for security reasons), but what you have in <code>autorun.inf</code> will display as the selected default, with <code>Icon=</code> as icon and <code>Action=</code> as description. If you want to launch it, just click the \"OK\" button in the dialog.</p>\n\n<p>So, although I'm not aware of any way to start the application (e.g. <a href=\"http://pegtop.net/start/\" rel=\"noreferrer\">PStart</a>) immediately, it is possible to insert flash disk with this configuration and start application by clicking OK.</p>\n\n<p>Tested on different computers, running Windows XP without a SP, also on Windows XP sp 1, sp2, sp3, and on various Vistas (not sure which types, but should work all the way from Vista Home Basic to Vista Enterprise Super-Mega-Premium-Extended Edition) and \"Windows 7\". Also works on Windows 2000 (although autorun on Win2000 for removable drives is not enabled in default configuration).</p>\n\n<p>Note that some applications, in addition, may trigger the \"unknown/unsigned exacutable\" security dialog, as if you opened them manually.</p>\n\n<p>Edit: For more details, see also:<br>\n <a href=\"http://msdn.microsoft.com/en-us/magazine/cc301341.aspx\" rel=\"noreferrer\">Autoplay in Windows XP: Automatically Detect and React to New Devices on a System</a></p>\n"
},
{
"answer_id": 352784,
"author": "berlindev",
"author_id": 44276,
"author_profile": "https://Stackoverflow.com/users/44276",
"pm_score": 2,
"selected": false,
"text": "<p>you need <strong>UseAutoplay</strong> to let this work on usb.</p>\n\n<p>and if you take <strong>ShellExecute</strong> instead of <strong>open</strong> you can also open scripts/documents/...</p>\n\n<p><pre><code>\n[Autorun]\nShellExecute=System\\something.exe\nUseAutoplay=1 \n</pre></code></p>\n"
},
{
"answer_id": 352824,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>there are also U3 usb sticks arround, they will be reconised as cdrom drives in windows.\nif you put an a autorun.inf on one of those, it will get executed without the user being questioned.</p>\n\n<p>regards morla</p>\n"
},
{
"answer_id": 14873273,
"author": "ihebiheb",
"author_id": 1546137,
"author_profile": "https://Stackoverflow.com/users/1546137",
"pm_score": 0,
"selected": false,
"text": "<p>I found the solution in this blog</p>\n\n<p><a href=\"http://www.makeuseof.com/tag/autolaunch-apps-usb-stick-windows/\" rel=\"nofollow\">How To Auto-Launch Apps With A USB Stick [Windows]</a></p>\n\n<p>It worked fine for me</p>\n\n<p>(the article explains how to do it with AutoIT, a 3rd party app that must be installed on the host computer)</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19124/"
] |
Is it possible to automatically launch an application from a USB flash drive (bypassing windows prompt asking user what he wants to do)? on windows XP or vista.
I looked into "autorun.inf" and "open" entry seems to work only for CD drives for Windows XP SP2+ and Vista. Is it possible to launch program automatically on all windows versions?
I don't care if autorun is disabled by user in Windows settings.
|
First of all, some people choose to disable autorun for security reasons; but Windows computers up to Vista have it enabled. Edit: **Apparently the functionality was removed from Windows 7 onwards.**
Put a file named autorun.inf in the root of your USB flash drive. This is what's in mine:
```
[Autorun]
Open=PStart.exe
Action=Start portable apps
Icon=diskicon.ico
```
What it does: when you insert this disk, starts `PStart.exe`
On older computers, the program specified in `Open=` will launch automatically.
On most modern computers (Windows XP SP2+, Vista), dialog "what do you want to do" will be displayed (for security reasons), but what you have in `autorun.inf` will display as the selected default, with `Icon=` as icon and `Action=` as description. If you want to launch it, just click the "OK" button in the dialog.
So, although I'm not aware of any way to start the application (e.g. [PStart](http://pegtop.net/start/)) immediately, it is possible to insert flash disk with this configuration and start application by clicking OK.
Tested on different computers, running Windows XP without a SP, also on Windows XP sp 1, sp2, sp3, and on various Vistas (not sure which types, but should work all the way from Vista Home Basic to Vista Enterprise Super-Mega-Premium-Extended Edition) and "Windows 7". Also works on Windows 2000 (although autorun on Win2000 for removable drives is not enabled in default configuration).
Note that some applications, in addition, may trigger the "unknown/unsigned exacutable" security dialog, as if you opened them manually.
Edit: For more details, see also:
[Autoplay in Windows XP: Automatically Detect and React to New Devices on a System](http://msdn.microsoft.com/en-us/magazine/cc301341.aspx)
|
255,019 |
<p>Is there any way to do the equivalent of the following in a JSP without using scriptlet?</p>
<pre><code><% response.setContentType("text/plain"); %>
</code></pre>
<p>I can't simply use</p>
<p>because I need to set the content-type in 2 places (each in a different branch of a ) and the JSP compiler will only allow one such directive.</p>
<p>Also, I can't write two separate JSPs and forward to one or the other in a servlet because the JSP is triggered by the container when an authentication failure occurs.</p>
<p>Cheers,
Don</p>
|
[
{
"answer_id": 255023,
"author": "AlexJReid",
"author_id": 32320,
"author_profile": "https://Stackoverflow.com/users/32320",
"pm_score": 2,
"selected": false,
"text": "<pre><code><%@ page language=\"java\" contentType=\"text/plain\" %>\n</code></pre>\n\n<p>Edit:</p>\n\n<p>If you need to set the MIME type conditionally, you could use</p>\n\n<pre><code><% \nif( branch condition ) { \n response.setContentType(\"text/plain\");\n} else {\n response.setContentType(\"text/html\"); \n}\n%>\n</code></pre>\n\n<p>Obviously the above is a scriptlet which goes against the original question. Is there a particular reason for not wanting to use a scriptlet?</p>\n\n<p>A better approach may be to perform the branch logic in a servlet and forward the request to a JSP which only handles the display. You may choose to use two separate JSPs, one for each content type, if the content itself differs.</p>\n"
},
{
"answer_id": 255103,
"author": "myplacedk",
"author_id": 28683,
"author_profile": "https://Stackoverflow.com/users/28683",
"pm_score": 0,
"selected": false,
"text": "<p>A text/plain-response and a text/html-response sound like two very different responses with very little in common.</p>\n\n<p>Create 2 JPS's, and branch in the servlet in stead.</p>\n\n<p>If they do have common elements, you can still use includes.</p>\n"
},
{
"answer_id": 255105,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way is to create a Tag File tag that can do this, then use that.</p>\n\n<p>Create the file \"setMimeType.tag\" in your WEB-INF/tags directory.</p>\n\n<pre><code><%@tag description=\"put the tag description here\" pageEncoding=\"UTF-8\"%>\n<%@ attribute name=\"mimeType\" required=\"true\"%>\n<%\n response.setContentType(jspContext.findAttribute(\"mimeType\"));\n%>\n</code></pre>\n\n<p>Then, in your JSP add this to the header:</p>\n\n<pre><code><%@ taglib prefix=\"t\" tagdir=\"/WEB-INF/tags\" %>\n</code></pre>\n\n<p>Then in your JSP you can do:</p>\n\n<pre><code><t:setMimeType mimeType=\"text/plain\"/>\n</code></pre>\n\n<p>Yes, the Tag File is NOT script free, but the actual JSP page IS. You can argue I'm splitting hairs, but I'd disagree, as I think tag files are the perfect medium to put things like scripting, as they provide a nice bit on encapsulation and abstraction. Also, the only other solution is to write your own JSP Tag handler in Java, which is insane for something as simple as this.</p>\n\n<p>Requires JSP 2.0, but I find JSP Tag Files to be a great boon to JSP development.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
Is there any way to do the equivalent of the following in a JSP without using scriptlet?
```
<% response.setContentType("text/plain"); %>
```
I can't simply use
because I need to set the content-type in 2 places (each in a different branch of a ) and the JSP compiler will only allow one such directive.
Also, I can't write two separate JSPs and forward to one or the other in a servlet because the JSP is triggered by the container when an authentication failure occurs.
Cheers,
Don
|
```
<%@ page language="java" contentType="text/plain" %>
```
Edit:
If you need to set the MIME type conditionally, you could use
```
<%
if( branch condition ) {
response.setContentType("text/plain");
} else {
response.setContentType("text/html");
}
%>
```
Obviously the above is a scriptlet which goes against the original question. Is there a particular reason for not wanting to use a scriptlet?
A better approach may be to perform the branch logic in a servlet and forward the request to a JSP which only handles the display. You may choose to use two separate JSPs, one for each content type, if the content itself differs.
|
255,035 |
<p>How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.</p>
|
[
{
"answer_id": 255053,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 7,
"selected": true,
"text": "<pre><code>import time, datetime\n\nd = datetime.datetime.now()\nprint time.mktime(d.timetuple())\n</code></pre>\n"
},
{
"answer_id": 5872022,
"author": "fixermark",
"author_id": 57720,
"author_profile": "https://Stackoverflow.com/users/57720",
"pm_score": 5,
"selected": false,
"text": "<p>For UTC calculations, <code>calendar.timegm</code> is the inverse of <code>time.gmtime</code>.</p>\n\n<pre><code>import calendar, datetime\nd = datetime.datetime.utcnow()\nprint calendar.timegm(d.timetuple())\n</code></pre>\n"
},
{
"answer_id": 14369386,
"author": "gnu_lorien",
"author_id": 1609543,
"author_profile": "https://Stackoverflow.com/users/1609543",
"pm_score": 2,
"selected": false,
"text": "<p>In python, time.time() can return seconds as a floating point number that includes a decimal component with the microseconds. In order to convert a datetime back to this representation, you have to add the microseconds component because the direct timetuple doesn't include it.</p>\n\n<pre><code>import time, datetime\n\nposix_now = time.time()\n\nd = datetime.datetime.fromtimestamp(posix_now)\nno_microseconds_time = time.mktime(d.timetuple())\nhas_microseconds_time = time.mktime(d.timetuple()) + d.microsecond * 0.000001\n\nprint posix_now\nprint no_microseconds_time\nprint has_microseconds_time\n</code></pre>\n"
},
{
"answer_id": 47007272,
"author": "Clément",
"author_id": 695591,
"author_profile": "https://Stackoverflow.com/users/695591",
"pm_score": 4,
"selected": false,
"text": "<p>Note that Python now (3.5.2) includes a <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp\" rel=\"nofollow noreferrer\">built-in method</a> for this in <code>datetime</code> objects:</p>\n<pre><code>>>> import datetime\n>>> now = datetime.datetime(2020, 11, 18, 18, 52, 47, 874766)\n>>> now.timestamp() # Local time\n1605743567.874766\n>>> now.replace(tzinfo=datetime.timezone.utc).timestamp() # UTC\n1605725567.874766 # 5 hours delta (I'm in UTC-5)\n</code></pre>\n"
},
{
"answer_id": 58055713,
"author": "vishal",
"author_id": 8588108,
"author_profile": "https://Stackoverflow.com/users/8588108",
"pm_score": 0,
"selected": false,
"text": "<p>Best conversion from posix/epoch to datetime timestamp and the reverse:</p>\n\n<pre><code>this_time = datetime.datetime.utcnow() # datetime.datetime type\nepoch_time = this_time.timestamp() # posix time or epoch time\nthis_time = datetime.datetime.fromtimestamp(epoch_time)\n</code></pre>\n"
},
{
"answer_id": 64886073,
"author": "Marc",
"author_id": 2128265,
"author_profile": "https://Stackoverflow.com/users/2128265",
"pm_score": 0,
"selected": false,
"text": "<h1>It depends</h1>\n<p>Is your datetime object timezone aware or naive?</p>\n<h1>Timezone Aware</h1>\n<p>If it is aware it's simple</p>\n<pre><code>from datetime import datetime, timezone\naware_date = datetime.now(tz=timezone.utc)\nposix_timestamp = aware_date.timestamp()\n</code></pre>\n<p>as <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp\" rel=\"nofollow noreferrer\">date.timestamp()</a> gives you "POSIX timestamp"</p>\n<p><em><strong>NOTE</strong>: more accurate to call it an epoch/unix timestamp as <a href=\"https://en.wikipedia.org/wiki/Unix_time#Non-synchronous_Network_Time_Protocol-based_variant\" rel=\"nofollow noreferrer\">it may not be POSIX compliant</a></em></p>\n<h1>Timezone Naive</h1>\n<p>If it's not timezone aware (naive), then you'd need to know what timezone it was originally in so we can use <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.replace\" rel=\"nofollow noreferrer\">replace()</a> to convert it into a timezone aware date object. Let's assume that you've stored/retrieved it as UTC Naive. Here we create one, as an example:</p>\n<pre><code>from datetime import datetime, timezone\nnaive_date = datetime.utcnow() # this date is naive, but is UTC based\naware_date = naive_date.replace(tzinfo=timezone.utc) # this date is no longer naive\n\n# now we do as we did with the last one\n\nposix_timestamp = aware_date.timestamp()\n</code></pre>\n<p>It's always better to get to a timezone aware date as soon as you can to prevent issues that can arise with naive dates (as Python will often assume they are local times and can mess you up)</p>\n<p><em><strong>NOTE</strong>: also be careful with your understanding of the epoch as it is platform dependent</em></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.
|
```
import time, datetime
d = datetime.datetime.now()
print time.mktime(d.timetuple())
```
|
255,056 |
<p>I have a standard .NET windows service written in C#.</p>
<p>Can it install itself without using InstallUtil?
Should I use the service installer class? How should I use it?</p>
<p>I want to be able to call the following:</p>
<pre><code>MyService.exe -install
</code></pre>
<p>And it will have the same effect as calling:</p>
<pre><code>InstallUtil MyService.exe
</code></pre>
|
[
{
"answer_id": 255062,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 8,
"selected": true,
"text": "<p>Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...</p>\n\n<p><a href=\"http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/4d45e9ea5471cba4/4519371a77ed4a74\" rel=\"noreferrer\">Here's an example:</a></p>\n\n<pre><code>[RunInstaller(true)]\npublic sealed class MyServiceInstallerProcess : ServiceProcessInstaller\n{\n public MyServiceInstallerProcess()\n {\n this.Account = ServiceAccount.NetworkService;\n }\n}\n\n[RunInstaller(true)]\npublic sealed class MyServiceInstaller : ServiceInstaller\n{\n public MyServiceInstaller()\n {\n this.Description = \"Service Description\";\n this.DisplayName = \"Service Name\";\n this.ServiceName = \"ServiceName\";\n this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;\n }\n}\n\nstatic void Install(bool undo, string[] args)\n{\n try\n {\n Console.WriteLine(undo ? \"uninstalling\" : \"installing\");\n using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))\n {\n IDictionary state = new Hashtable();\n inst.UseNewContext = true;\n try\n {\n if (undo)\n {\n inst.Uninstall(state);\n }\n else\n {\n inst.Install(state);\n inst.Commit(state);\n }\n }\n catch\n {\n try\n {\n inst.Rollback(state);\n }\n catch { }\n throw;\n }\n }\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine(ex.Message);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 255097,
"author": "Brad Bruce",
"author_id": 5008,
"author_profile": "https://Stackoverflow.com/users/5008",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a class I use when writing services. I usually have an interactive screen that comes up when the service is not called. From there I use the class as needed. It allows for multiple named instances on the same machine -hence the InstanceID field</p>\n\n<p>Sample Call</p>\n\n<pre><code> IntegratedServiceInstaller Inst = new IntegratedServiceInstaller();\n Inst.Install(\"MySvc\", \"My Sample Service\", \"Service that executes something\",\n _InstanceID,\n// System.ServiceProcess.ServiceAccount.LocalService, // this is more secure, but only available in XP and above and WS-2003 and above\n System.ServiceProcess.ServiceAccount.LocalSystem, // this is required for WS-2000\n System.ServiceProcess.ServiceStartMode.Automatic);\n if (controller == null)\n {\n controller = new System.ServiceProcess.ServiceController(String.Format(\"MySvc_{0}\", _InstanceID), \".\");\n }\n if (controller.Status == System.ServiceProcess.ServiceControllerStatus.Running)\n {\n Start_Stop.Text = \"Stop Service\";\n Start_Stop_Debugging.Enabled = false;\n }\n else\n {\n Start_Stop.Text = \"Start Service\";\n Start_Stop_Debugging.Enabled = true;\n }\n</code></pre>\n\n<p>The class itself</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Diagnostics;\nusing Microsoft.Win32;\n\nnamespace MySvc\n{\n class IntegratedServiceInstaller\n {\n public void Install(String ServiceName, String DisplayName, String Description,\n String InstanceID,\n System.ServiceProcess.ServiceAccount Account, \n System.ServiceProcess.ServiceStartMode StartMode)\n {\n //http://www.theblacksparrow.com/\n System.ServiceProcess.ServiceProcessInstaller ProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();\n ProcessInstaller.Account = Account;\n\n System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();\n\n System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext();\n string processPath = Process.GetCurrentProcess().MainModule.FileName;\n if (processPath != null && processPath.Length > 0)\n {\n System.IO.FileInfo fi = new System.IO.FileInfo(processPath);\n\n String path = String.Format(\"/assemblypath={0}\", fi.FullName);\n String[] cmdline = { path };\n Context = new System.Configuration.Install.InstallContext(\"\", cmdline);\n }\n\n SINST.Context = Context;\n SINST.DisplayName = String.Format(\"{0} - {1}\", DisplayName, InstanceID);\n SINST.Description = String.Format(\"{0} - {1}\", Description, InstanceID);\n SINST.ServiceName = String.Format(\"{0}_{1}\", ServiceName, InstanceID);\n SINST.StartType = StartMode;\n SINST.Parent = ProcessInstaller;\n\n // http://bytes.com/forum/thread527221.html\n SINST.ServicesDependedOn = new String[] { \"Spooler\", \"Netlogon\", \"Netman\" };\n\n System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();\n SINST.Install(state);\n\n // http://www.dotnet247.com/247reference/msgs/43/219565.aspx\n using (RegistryKey oKey = Registry.LocalMachine.OpenSubKey(String.Format(@\"SYSTEM\\CurrentControlSet\\Services\\{0}_{1}\", ServiceName, InstanceID), true))\n {\n try\n {\n Object sValue = oKey.GetValue(\"ImagePath\");\n oKey.SetValue(\"ImagePath\", sValue);\n }\n catch (Exception Ex)\n {\n System.Windows.Forms.MessageBox.Show(Ex.Message);\n }\n }\n\n }\n public void Uninstall(String ServiceName, String InstanceID)\n {\n //http://www.theblacksparrow.com/\n System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();\n\n System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext(\"c:\\\\install.log\", null);\n SINST.Context = Context;\n SINST.ServiceName = String.Format(\"{0}_{1}\", ServiceName, InstanceID);\n SINST.Uninstall(null);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1015502,
"author": "adrianbanks",
"author_id": 116923,
"author_profile": "https://Stackoverflow.com/users/116923",
"pm_score": 5,
"selected": false,
"text": "<p>Take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.install.managedinstallerclass.installhelper.aspx\" rel=\"noreferrer\">InstallHelper</a> method of the <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.install.managedinstallerclass.aspx\" rel=\"noreferrer\">ManagedInstaller</a> class. You can install a service using:</p>\n\n<pre><code>string[] args;\nManagedInstallerClass.InstallHelper(args);\n</code></pre>\n\n<p>This is exactly what InstallUtil does. The arguments are the same as for InstallUtil.</p>\n\n<p>The benefits of this method are that it involves no messing in the registry, and it uses the same mechanism as InstallUtil. </p>\n"
},
{
"answer_id": 1812537,
"author": "Roman Starkov",
"author_id": 33080,
"author_profile": "https://Stackoverflow.com/users/33080",
"pm_score": 4,
"selected": false,
"text": "<p>You can always fall back to the good old WinAPI calls, although the amount of work involved is non-trivial. There is no requirement that .NET services be installed via a .NET-aware mechanism.</p>\n\n<p>To install:</p>\n\n<ul>\n<li>Open the service manager via <code>OpenSCManager</code>.</li>\n<li>Call <code>CreateService</code> to register the service.</li>\n<li>Optionally call <code>ChangeServiceConfig2</code> to set a description.</li>\n<li>Close the service and service manager handles with <code>CloseServiceHandle</code>.</li>\n</ul>\n\n<p>To uninstall:</p>\n\n<ul>\n<li>Open the service manager via <code>OpenSCManager</code>.</li>\n<li>Open the service using <code>OpenService</code>.</li>\n<li>Delete the service by calling <code>DeleteService</code> on the handle returned by <code>OpenService</code>.</li>\n<li>Close the service and service manager handles with <code>CloseServiceHandle</code>.</li>\n</ul>\n\n<p>The main reason I prefer this over using the <code>ServiceInstaller</code>/<code>ServiceProcessInstaller</code> is that you can register the service with your own custom command line arguments. For example, you might register it as <code>\"MyApp.exe -service\"</code>, then if the user runs your app without any arguments you could offer them a UI to install/remove the service.</p>\n\n<p>Running Reflector on <code>ServiceInstaller</code> can fill in the details missing from this brief explanation.</p>\n\n<p>P.S. Clearly this won't have \"the same effect as calling: InstallUtil MyService.exe\" - in particular, you won't be able to uninstall using InstallUtil. But it seems that perhaps this wasn't an actual stringent requirement for you.</p>\n"
},
{
"answer_id": 7757371,
"author": "John M",
"author_id": 127776,
"author_profile": "https://Stackoverflow.com/users/127776",
"pm_score": 2,
"selected": false,
"text": "<p>In the case of trying to install a command line application as a Windows service try the '<a href=\"http://nssm.cc/\" rel=\"nofollow noreferrer\">NSSM</a>' utility. Related ServerFault details found <a href=\"https://serverfault.com/questions/58025/install-service-in-windows-server-2008/321208#321208\">here</a>.</p>\n"
},
{
"answer_id": 30650205,
"author": "Kraang Prime",
"author_id": 3504007,
"author_profile": "https://Stackoverflow.com/users/3504007",
"pm_score": 3,
"selected": false,
"text": "<p>The above examples didn't really work for me, and the link to the forum as a #1 solution is awful to dig through. Here is a class I wrote (in part), and the other bit is merged from <a href=\"https://dl.dropboxusercontent.com/u/152585/ServiceInstaller.cs\" rel=\"nofollow noreferrer\">this link I found buried somewhere</a></p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nusing System.ServiceProcess;\nusing System.Runtime.InteropServices;\n\nnamespace SystemControl {\n class Services {\n\n#region \"Environment Variables\"\n public static string GetEnvironment(string name, bool ExpandVariables=true) {\n if ( ExpandVariables ) {\n return System.Environment.GetEnvironmentVariable( name );\n } else {\n return (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey( @\"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\\\" ).GetValue( name, \"\", Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames );\n }\n }\n\n public static void SetEnvironment( string name, string value ) {\n System.Environment.SetEnvironmentVariable(name, value);\n }\n#endregion\n\n#region \"ServiceCalls Native\"\n public static ServiceController[] List { get { return ServiceController.GetServices(); } }\n\n public static void Start( string serviceName, int timeoutMilliseconds ) {\n ServiceController service=new ServiceController( serviceName );\n try {\n TimeSpan timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds );\n\n service.Start();\n service.WaitForStatus( ServiceControllerStatus.Running, timeout );\n } catch {\n // ...\n }\n }\n\n public static void Stop( string serviceName, int timeoutMilliseconds ) {\n ServiceController service=new ServiceController( serviceName );\n try {\n TimeSpan timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds );\n\n service.Stop();\n service.WaitForStatus( ServiceControllerStatus.Stopped, timeout );\n } catch {\n // ...\n }\n }\n\n public static void Restart( string serviceName, int timeoutMilliseconds ) {\n ServiceController service=new ServiceController( serviceName );\n try {\n int millisec1=Environment.TickCount;\n TimeSpan timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds );\n\n service.Stop();\n service.WaitForStatus( ServiceControllerStatus.Stopped, timeout );\n\n // count the rest of the timeout\n int millisec2=Environment.TickCount;\n timeout=TimeSpan.FromMilliseconds( timeoutMilliseconds-( millisec2-millisec1 ) );\n\n service.Start();\n service.WaitForStatus( ServiceControllerStatus.Running, timeout );\n } catch {\n // ...\n }\n }\n\n public static bool IsInstalled( string serviceName ) {\n // get list of Windows services\n ServiceController[] services=ServiceController.GetServices();\n\n // try to find service name\n foreach ( ServiceController service in services ) {\n if ( service.ServiceName==serviceName )\n return true;\n }\n return false;\n }\n#endregion\n\n#region \"ServiceCalls API\"\n private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;\n private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010;\n\n [Flags]\n public enum ServiceManagerRights {\n Connect = 0x0001,\n CreateService = 0x0002,\n EnumerateService = 0x0004,\n Lock = 0x0008,\n QueryLockStatus = 0x0010,\n ModifyBootConfig = 0x0020,\n StandardRightsRequired = 0xF0000,\n AllAccess = (StandardRightsRequired | Connect | CreateService |\n EnumerateService | Lock | QueryLockStatus | ModifyBootConfig)\n }\n\n [Flags]\n public enum ServiceRights {\n QueryConfig = 0x1,\n ChangeConfig = 0x2,\n QueryStatus = 0x4,\n EnumerateDependants = 0x8,\n Start = 0x10,\n Stop = 0x20,\n PauseContinue = 0x40,\n Interrogate = 0x80,\n UserDefinedControl = 0x100,\n Delete = 0x00010000,\n StandardRightsRequired = 0xF0000,\n AllAccess = (StandardRightsRequired | QueryConfig | ChangeConfig |\n QueryStatus | EnumerateDependants | Start | Stop | PauseContinue |\n Interrogate | UserDefinedControl)\n }\n\n public enum ServiceBootFlag {\n Start = 0x00000000,\n SystemStart = 0x00000001,\n AutoStart = 0x00000002,\n DemandStart = 0x00000003,\n Disabled = 0x00000004\n }\n\n public enum ServiceState {\n Unknown = -1, // The state cannot be (has not been) retrieved.\n NotFound = 0, // The service is not known on the host server.\n Stop = 1, // The service is NET stopped.\n Run = 2, // The service is NET started.\n Stopping = 3,\n Starting = 4,\n }\n\n public enum ServiceControl {\n Stop = 0x00000001,\n Pause = 0x00000002,\n Continue = 0x00000003,\n Interrogate = 0x00000004,\n Shutdown = 0x00000005,\n ParamChange = 0x00000006,\n NetBindAdd = 0x00000007,\n NetBindRemove = 0x00000008,\n NetBindEnable = 0x00000009,\n NetBindDisable = 0x0000000A\n }\n\n public enum ServiceError {\n Ignore = 0x00000000,\n Normal = 0x00000001,\n Severe = 0x00000002,\n Critical = 0x00000003\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private class SERVICE_STATUS {\n public int dwServiceType = 0;\n public ServiceState dwCurrentState = 0;\n public int dwControlsAccepted = 0;\n public int dwWin32ExitCode = 0;\n public int dwServiceSpecificExitCode = 0;\n public int dwCheckPoint = 0;\n public int dwWaitHint = 0;\n }\n\n [DllImport(\"advapi32.dll\", EntryPoint = \"OpenSCManagerA\")]\n private static extern IntPtr OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerRights dwDesiredAccess);\n [DllImport(\"advapi32.dll\", EntryPoint = \"OpenServiceA\", CharSet = CharSet.Ansi)]\n private static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceRights dwDesiredAccess);\n [DllImport(\"advapi32.dll\", EntryPoint = \"CreateServiceA\")]\n private static extern IntPtr CreateService(IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceRights dwDesiredAccess, int dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword);\n [DllImport(\"advapi32.dll\")]\n private static extern int CloseServiceHandle(IntPtr hSCObject);\n [DllImport(\"advapi32.dll\")]\n private static extern int QueryServiceStatus(IntPtr hService, SERVICE_STATUS lpServiceStatus);\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int DeleteService(IntPtr hService);\n [DllImport(\"advapi32.dll\")]\n private static extern int ControlService(IntPtr hService, ServiceControl dwControl, SERVICE_STATUS lpServiceStatus);\n [DllImport(\"advapi32.dll\", EntryPoint = \"StartServiceA\")]\n private static extern int StartService(IntPtr hService, int dwNumServiceArgs, int lpServiceArgVectors);\n\n /// <summary>\n /// Takes a service name and tries to stop and then uninstall the windows serviceError\n /// </summary>\n /// <param name=\"ServiceName\">The windows service name to uninstall</param>\n public static void Uninstall(string ServiceName)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);\n try\n {\n IntPtr service = OpenService(scman, ServiceName, ServiceRights.StandardRightsRequired | ServiceRights.Stop | ServiceRights.QueryStatus);\n if (service == IntPtr.Zero)\n {\n throw new ApplicationException(\"Service not installed.\");\n }\n try\n {\n StopService(service);\n int ret = DeleteService(service);\n if (ret == 0)\n {\n int error = Marshal.GetLastWin32Error();\n throw new ApplicationException(\"Could not delete service \" + error);\n }\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Accepts a service name and returns true if the service with that service name exists\n /// </summary>\n /// <param name=\"ServiceName\">The service name that we will check for existence</param>\n /// <returns>True if that service exists false otherwise</returns>\n public static bool ServiceIsInstalled(string ServiceName)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);\n try\n {\n IntPtr service = OpenService(scman, ServiceName,\n ServiceRights.QueryStatus);\n if (service == IntPtr.Zero) return false;\n CloseServiceHandle(service);\n return true;\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Takes a service name, a service display name and the path to the service executable and installs / starts the windows service.\n /// </summary>\n /// <param name=\"ServiceName\">The service name that this service will have</param>\n /// <param name=\"DisplayName\">The display name that this service will have</param>\n /// <param name=\"FileName\">The path to the executable of the service</param>\n public static void InstallAndStart(string ServiceName, string DisplayName,\n string FileName)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect |\n ServiceManagerRights.CreateService);\n try\n {\n IntPtr service = OpenService(scman, ServiceName,\n ServiceRights.QueryStatus | ServiceRights.Start);\n if (service == IntPtr.Zero)\n {\n service = CreateService(scman, ServiceName, DisplayName,\n ServiceRights.QueryStatus | ServiceRights.Start, SERVICE_WIN32_OWN_PROCESS,\n ServiceBootFlag.AutoStart, ServiceError.Normal, FileName, null, IntPtr.Zero,\n null, null, null);\n }\n if (service == IntPtr.Zero)\n {\n throw new ApplicationException(\"Failed to install service.\");\n }\n try\n {\n StartService(service);\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Takes a service name and starts it\n /// </summary>\n /// <param name=\"Name\">The service name</param>\n public static void StartService(string Name)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);\n try\n {\n IntPtr hService = OpenService(scman, Name, ServiceRights.QueryStatus |\n ServiceRights.Start);\n if (hService == IntPtr.Zero)\n {\n throw new ApplicationException(\"Could not open service.\");\n }\n try\n {\n StartService(hService);\n }\n finally\n {\n CloseServiceHandle(hService);\n }\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Stops the provided windows service\n /// </summary>\n /// <param name=\"Name\">The service name that will be stopped</param>\n public static void StopService(string Name)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);\n try\n {\n IntPtr hService = OpenService(scman, Name, ServiceRights.QueryStatus |\n ServiceRights.Stop);\n if (hService == IntPtr.Zero)\n {\n throw new ApplicationException(\"Could not open service.\");\n }\n try\n {\n StopService(hService);\n }\n finally\n {\n CloseServiceHandle(hService);\n }\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Stars the provided windows service\n /// </summary>\n /// <param name=\"hService\">The handle to the windows service</param>\n private static void StartService(IntPtr hService)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n StartService(hService, 0, 0);\n WaitForServiceStatus(hService, ServiceState.Starting, ServiceState.Run);\n }\n\n /// <summary>\n /// Stops the provided windows service\n /// </summary>\n /// <param name=\"hService\">The handle to the windows service</param>\n private static void StopService(IntPtr hService)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n ControlService(hService, ServiceControl.Stop, status);\n WaitForServiceStatus(hService, ServiceState.Stopping, ServiceState.Stop);\n }\n\n /// <summary>\n /// Takes a service name and returns the <code>ServiceState</code> of the corresponding service\n /// </summary>\n /// <param name=\"ServiceName\">The service name that we will check for his <code>ServiceState</code></param>\n /// <returns>The ServiceState of the service we wanted to check</returns>\n public static ServiceState GetServiceStatus(string ServiceName)\n {\n IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);\n try\n {\n IntPtr hService = OpenService(scman, ServiceName,\n ServiceRights.QueryStatus);\n if (hService == IntPtr.Zero)\n {\n return ServiceState.NotFound;\n }\n try\n {\n return GetServiceStatus(hService);\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n finally\n {\n CloseServiceHandle(scman);\n }\n }\n\n /// <summary>\n /// Gets the service state by using the handle of the provided windows service\n /// </summary>\n /// <param name=\"hService\">The handle to the service</param>\n /// <returns>The <code>ServiceState</code> of the service</returns>\n private static ServiceState GetServiceStatus(IntPtr hService)\n {\n SERVICE_STATUS ssStatus = new SERVICE_STATUS();\n if (QueryServiceStatus(hService, ssStatus) == 0)\n {\n throw new ApplicationException(\"Failed to query service status.\");\n }\n return ssStatus.dwCurrentState;\n }\n\n /// <summary>\n /// Returns true when the service status has been changes from wait status to desired status\n /// ,this method waits around 10 seconds for this operation.\n /// </summary>\n /// <param name=\"hService\">The handle to the service</param>\n /// <param name=\"WaitStatus\">The current state of the service</param>\n /// <param name=\"DesiredStatus\">The desired state of the service</param>\n /// <returns>bool if the service has successfully changed states within the allowed timeline</returns>\n private static bool WaitForServiceStatus(IntPtr hService, ServiceState\n WaitStatus, ServiceState DesiredStatus)\n {\n SERVICE_STATUS ssStatus = new SERVICE_STATUS();\n int dwOldCheckPoint;\n int dwStartTickCount;\n\n QueryServiceStatus(hService, ssStatus);\n if (ssStatus.dwCurrentState == DesiredStatus) return true;\n dwStartTickCount = Environment.TickCount;\n dwOldCheckPoint = ssStatus.dwCheckPoint;\n\n while (ssStatus.dwCurrentState == WaitStatus)\n {\n // Do not wait longer than the wait hint. A good interval is\n // one tenth the wait hint, but no less than 1 second and no\n // more than 10 seconds.\n\n int dwWaitTime = ssStatus.dwWaitHint / 10;\n\n if (dwWaitTime < 1000) dwWaitTime = 1000;\n else if (dwWaitTime > 10000) dwWaitTime = 10000;\n\n System.Threading.Thread.Sleep(dwWaitTime);\n\n // Check the status again.\n\n if (QueryServiceStatus(hService, ssStatus) == 0) break;\n\n if (ssStatus.dwCheckPoint > dwOldCheckPoint)\n {\n // The service is making progress.\n dwStartTickCount = Environment.TickCount;\n dwOldCheckPoint = ssStatus.dwCheckPoint;\n }\n else\n {\n if (Environment.TickCount - dwStartTickCount > ssStatus.dwWaitHint)\n {\n // No progress made within the wait hint\n break;\n }\n }\n }\n return (ssStatus.dwCurrentState == DesiredStatus);\n }\n\n /// <summary>\n /// Opens the service manager\n /// </summary>\n /// <param name=\"Rights\">The service manager rights</param>\n /// <returns>the handle to the service manager</returns>\n private static IntPtr OpenSCManager(ServiceManagerRights Rights)\n {\n IntPtr scman = OpenSCManager(null, null, Rights);\n if (scman == IntPtr.Zero)\n {\n throw new ApplicationException(\"Could not connect to service control manager.\");\n }\n return scman;\n }\n\n#endregion\n\n }\n}\n</code></pre>\n\n<p>To install a service, run the InstallAndStart command as follows:</p>\n\n<pre><code> SystemControl.InstallAndStart(\n \"apache\",\n \"Apache Web Server\",\n @\"\"\"c:\\apache\\bin\\httpd.exe\"\" -k runservice\"\n );\n</code></pre>\n\n<p>Make sure the account that is running the program has permission to install services. You can always 'Run As Administrator' on the program.</p>\n\n<p>I have also included several commands for non-api access which do not install or remove services, but you can list them and control several (start, stop, restart). You really only need to elevate permissions for installing or removing services.</p>\n\n<p>There are a couple of commands for getting and setting environment variables as well, such as <code>OPENSSL_CONF</code> or <code>TEMP</code>. For the most part, the parameters and method names should be pretty self-explanatory.</p>\n"
},
{
"answer_id": 45245815,
"author": "Mansoor",
"author_id": 4240382,
"author_profile": "https://Stackoverflow.com/users/4240382",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Process QProc = new Process();\nQProc.StartInfo.FileName = \"cmd\";\nQProc.StartInfo.Arguments =\"/c InstallUtil \"+ \"\\\"\"+ filefullPath +\"\\\"\";\nQProc.StartInfo.WorkingDirectory = Environment.GetEnvironmentVariable(\"windir\") + @\"\\Microsoft.NET\\Framework\\v2.0.50727\\\";\nQProc.StartInfo.UseShellExecute = false;\n// QProc.StartInfo.CreateNoWindow = true;\nQProc.StartInfo.RedirectStandardOutput = true;\nQProc.Start();\n// QProc.WaitForExit();\nQProc.Close();\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20257/"
] |
I have a standard .NET windows service written in C#.
Can it install itself without using InstallUtil?
Should I use the service installer class? How should I use it?
I want to be able to call the following:
```
MyService.exe -install
```
And it will have the same effect as calling:
```
InstallUtil MyService.exe
```
|
Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...
[Here's an example:](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/4d45e9ea5471cba4/4519371a77ed4a74)
```
[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
public MyServiceInstallerProcess()
{
this.Account = ServiceAccount.NetworkService;
}
}
[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
public MyServiceInstaller()
{
this.Description = "Service Description";
this.DisplayName = "Service Name";
this.ServiceName = "ServiceName";
this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
}
}
static void Install(bool undo, string[] args)
{
try
{
Console.WriteLine(undo ? "uninstalling" : "installing");
using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
{
IDictionary state = new Hashtable();
inst.UseNewContext = true;
try
{
if (undo)
{
inst.Uninstall(state);
}
else
{
inst.Install(state);
inst.Commit(state);
}
}
catch
{
try
{
inst.Rollback(state);
}
catch { }
throw;
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
```
|
255,063 |
<p>Would there a more elegant way of writing the following syntax? </p>
<pre><code> Thread t0 = new Thread(new ParameterizedThreadStart(doWork));
t0.Start('someVal');
t0.Join();
Thread t1 = new Thread(new ParameterizedThreadStart(doWork));
t1.Start('someDiffVal');
t1.Join();
</code></pre>
<p>Presuming we want to pass 20 different values, what would the best way of setting this up be? Looping through and joining at the end?</p>
<p>If a new thread isn't instantiated (like below), it errors that the thread can't be restarted. For example:</p>
<pre><code> Thread t1 = new Thread(new ParameterizedThreadStart(doWork));
t1.Start('someVal');
t1.Start('someDiffVal');
</code></pre>
|
[
{
"answer_id": 255072,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>Why would you start a thread and then join against it immediately?</p>\n\n<p>I'd normally do something like this:</p>\n\n<pre><code>List<Thread> threads = new List<Thread>();\n\nforeach (string item in items)\n{\n string copy = item; // Important due to variable capture\n ThreadStart ts = () => DoWork(copy); // Strongly typed :)\n Thread t = new Thread(ts);\n t.Start();\n threads.Add(t);\n}\n\nforeach (Thread t in threads)\n{\n t.Join();\n}\n</code></pre>\n"
},
{
"answer_id": 255084,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>One other option (in .NET 4.0, or with the CTP) would be a form of <code>Parallel.ForEach</code>. Not necessarily viable yet, though. I also saw a good blog entry (can't remember by who) that used <code>IDisposable</code> here - i.e. </p>\n\n<pre><code>using(StartThread(arg1))\nusing(StartThread(arg2))\n{\n}\n</code></pre>\n\n<p>where the Dispose() method did a join on the thread that was spawned - i.e. when you exited the block, all are complete. Quite cute.</p>\n"
},
{
"answer_id": 255111,
"author": "mmr",
"author_id": 21981,
"author_profile": "https://Stackoverflow.com/users/21981",
"pm_score": 0,
"selected": false,
"text": "<p>Why not have your parameters be part of the class, make them properties, and have the get/set methods lock around them? If you have enough parameters, make the parameter object itself a property of the object, and then lock that parameter block. As in:</p>\n\n<pre><code>class GonnaDoSomeThreading {\n private Object mBlockLock = new Object();\n private MyParameterBlock mBlock;\n public MyParameterBlock Block {\n get { \n MyParameterBlock tmp;\n lock (mBlockLock){\n tmp = new MyParameterBlock(mBlock); //or some other cloning\n }\n return tmp; //use a tmp in order to make sure that modifications done\n //do not modify the block directly, but that modifications must\n //be 'committed' through the set function\n }\n set { lock (mBlockLock){ mBlock = value; } } \n }\n}\n</code></pre>\n\n<p>And then do your thread pool as already suggested. That way, you've got locks around the data access, so that if all of your threads need it, they can wait on one another.</p>\n\n<p>If you're doing this for something like image processing (where a lot of parallel objects can be done at once), then it might be better to break up your data into individualized chunks. IE, say you want to run some convolution over a largish image, and so want to break it up into two halves. Then, you can have a 'Fragmentimage' function which creates the image blocks that you're going to work on individually, and then a 'MergeFragments' function call to join all the results. So your fragment could look like:</p>\n\n<pre><code>class ThreadWorkFragment {\n <image type, like ushort>[] mDataArray;\n bool mDone;\n}\n</code></pre>\n\n<p>Put a lock around that fragment (ie, a list of objects and fragments, with each having a lock and so forth), so that when the thread accesses it's fragment, it can eventually state that it's 'done', release the lock, and then you can have a final merge function which just waits for those done booleans to be flagged. That way, if one of the threads dies before setting done, and you know the thread's dead, then you also know that the thread didn't finish its work and you need to do some error recovery; if you just wait for a join to happen, the thread could still have messed up its fragment.</p>\n\n<p>But there's a lot of those kinds of specific ideas to implement, based on the problem you're trying to solve.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30649/"
] |
Would there a more elegant way of writing the following syntax?
```
Thread t0 = new Thread(new ParameterizedThreadStart(doWork));
t0.Start('someVal');
t0.Join();
Thread t1 = new Thread(new ParameterizedThreadStart(doWork));
t1.Start('someDiffVal');
t1.Join();
```
Presuming we want to pass 20 different values, what would the best way of setting this up be? Looping through and joining at the end?
If a new thread isn't instantiated (like below), it errors that the thread can't be restarted. For example:
```
Thread t1 = new Thread(new ParameterizedThreadStart(doWork));
t1.Start('someVal');
t1.Start('someDiffVal');
```
|
Why would you start a thread and then join against it immediately?
I'd normally do something like this:
```
List<Thread> threads = new List<Thread>();
foreach (string item in items)
{
string copy = item; // Important due to variable capture
ThreadStart ts = () => DoWork(copy); // Strongly typed :)
Thread t = new Thread(ts);
t.Start();
threads.Add(t);
}
foreach (Thread t in threads)
{
t.Join();
}
```
|
255,071 |
<p>I've been tasked with implementing a Date/Time selector for several areas of our web project, and instructed to use a control that another developer created as part of it. The control I'm working on is supposed to allow the user to choose a date from a calendar, choose a format for the display of that date (from several pre-defined formats, or with a simple text override) and optionally a time string (which is really just freeform text).</p>
<p>The control I was instructed to use is documented here: <a href="http://www.west-wind.com/WebLog/posts/213015.aspx" rel="nofollow noreferrer">http://www.west-wind.com/WebLog/posts/213015.aspx</a>, and uses the DatePicker from jQuery.</p>
<p>After I implemented my control and tested it, I began integrating it into the pages which needed Date and/or time inputs. In my testing of those implementations, I discovered a bug: when I include multiple copies of my control on a page, only the first one gets the jQuery calendar. The others are not tied to it.</p>
<p>I have tried some of the methods suggested in a seemingly-related question (titled 'duplicating jquery datepicker'), such as calling the '.datepicker()' function on the west-wind control (which renders a textbox) via the $("css-selector").datepicker() syntax, and ASP.NET is guaranteeing unique IDs for all the text boxes.</p>
<p>So, in summation, it looks like this:</p>
<pre><code><page>
<mycontrol>
<west-windjQuerycontrol />
</mycontrol>
<mycontrol>
<west-windjQuerycontrol />
</mycontrol>
</page>
</code></pre>
<p>Now, the strange part: When there are multiple copies of the west-wind control on the page, without the other user control containing them, they work correctly. Other than the jQuery control, my control has nothing unusual about it: simply labels, textboxes, panels, and dropdowns. Something about bundling the West-Wind jQuery control into a user control seems to be breaking it.</p>
<p>Any advice? I've been banging my head against this for a while, hampered by my poor javascript skills and limited exposure to jQuery.</p>
<p>As pointed out below, it's hard to say without the HTML. I've included it below.</p>
<pre><code><form name="form1" method="post" action="ControlTest.aspx" id="form1">
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTU4NjEzMDEwOQ9kFgICAw9kFgQCAw9kFgRmD2QWAgIDD2QWAgIDDxBkZBYBZmQCAg9kFgICAw9kFgICAQ8QZGQWAWZkAgUPZBYEZg9kFgICAw9kFgICAw8QZGQWAWZkAgIPZBYCAgMPZBYCAgEPEGRkFgFmZGRDjfLpdb+XxaVaQYP2XkPil2Galw==" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/SSO/DE/WebResource.axd?d=jMPpL-KK8_mPj_ssZzGblw2&amp;t=633481894229838141" type="text/javascript"></script>
<script src="/SSO/DE/ScriptResource.axd?d=8KwRIGaNAD3hi2Loz3YV-uxgrdZpGe8nnwH5E3gxLW_lQpnYjRbyIYThTnHtD9rt0&amp;t=633613004148118290" type="text/javascript"></script>
<script src="/SSO/DE/ScriptResource.axd?d=8KwRIGaNAD3hi2Loz3YV-uxgrdZpGe8nnwH5E3gxLW-K0Kuw-pGK1O3mE_r1y3sjKmhHtQjSXeMtYSim0bjyGA2&amp;t=633613004148118290" type="text/javascript"></script>
<script src="/SSO/DE/ScriptResource.axd?d=Id5yAacLMZHF7TWlkgrrid30ZStmsXuLHcF6WQ404YLySP4Itj4qxv2wi9ffbsWQA86oLdnZPWkwDnu4NKxfG1Ue7qdGG1SbOfb4ooHVs7M1&amp;t=633481957084709567" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script src="/SSO/DE/ScriptResource.axd?d=Id5yAacLMZHF7TWlkgrrid30ZStmsXuLHcF6WQ404YLySP4Itj4qxv2wi9ffbsWQhT3MFELBAa2rFJZXnSlYAZIN7RT1npcBxJRsWGjJWIwTF0Es1m0vOd-xYnFqWJKz0&amp;t=633481957084709567" type="text/javascript"></script>
<div style="margin:25px 10px;width:100%;">
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('stupidThing', document.getElementById('form1'));
Sys.WebForms.PageRequestManager.getInstance()._updateControls([], [], [], 90);
//]]>
</script>
<div id="datePicker_Div0" class="AdminRowOdd DERow">
<div id="datePicker_Div1" class="DELabel">
<span id="datePicker_DateLabel">Date</span>
</div>
<div id="datePicker_Div2" class="DEInput datePicker">
<input name="datePicker$DateSelector" type="text" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateSelector\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="datePicker_DateSelector" style="width:80px;" />
<select name="datePicker$languageSelector" onchange="javascript:setTimeout('__doPostBack(\'datePicker$languageSelector\',\'\')', 0)" id="datePicker_languageSelector">
<option selected="selected" value="en-US">en-US</option>
<option value="fr-CA">fr-CA</option>
<option value="fr-FR">fr-FR</option>
<option value="es-ES">es-ES</option>
<option value="es-MX">es-MX</option>
</select>
</div>
</div>
<div id="datePicker_Div3" class="AdminRowEven DERow">
<div id="datePicker_Div4" class="DELabel">
<span id="datePicker_FormatChoiceLabel">Choose your display format: </span>
</div>
<div id="datePicker_Div5" class="DEInput">
<select name="datePicker$DateFormatSelector" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateFormatSelector\',\'\')', 0)" id="datePicker_DateFormatSelector">
<option selected="selected" value="Choose a date first">Choose a date first</option>
</select>
</div>
</div>
<div id="datePicker_Div6" class="AdminRowOdd DERow">
<div id="datePicker_Div7" class="DELabel">
<span id="datePicker_FormatOverrideLabel">Or enter your own text</span>
</div>
<div id="datePicker_Div8" class="DEInput">
<input name="datePicker$DateFormatOverride" type="text" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateFormatOverride\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="datePicker_DateFormatOverride" />
</div>
</div>
<br />
<div id="date1_Div0" class="AdminRowOdd DERow">
<div id="date1_Div1" class="DELabel">
<span id="date1_DateLabel">Date</span>
</div>
<div id="date1_Div2" class="DEInput datePicker">
<input name="date1$DateSelector" type="text" onchange="javascript:setTimeout('__doPostBack(\'date1$DateSelector\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="date1_DateSelector" style="width:80px;" />
<select name="date1$languageSelector" onchange="javascript:setTimeout('__doPostBack(\'date1$languageSelector\',\'\')', 0)" id="date1_languageSelector">
<option selected="selected" value="en-US">en-US</option>
<option value="fr-CA">fr-CA</option>
<option value="fr-FR">fr-FR</option>
<option value="es-ES">es-ES</option>
<option value="es-MX">es-MX</option>
</select>
</div>
</div>
<div id="date1_Div3" class="AdminRowEven DERow">
<div id="date1_Div4" class="DELabel">
<span id="date1_FormatChoiceLabel">Choose your display format:</span>
</div>
<div id="date1_Div5" class="DEInput">
<select name="date1$DateFormatSelector" onchange="javascript:setTimeout('__doPostBack(\'date1$DateFormatSelector\',\'\')', 0)" id="date1_DateFormatSelector">
<option selected="selected" value="Choose a date first">Choose a date first</option>
</select>
</div>
</div>
<div id="date1_Div6" class="AdminRowOdd DERow">
<div id="date1_Div7" class="DELabel">
<span id="date1_FormatOverrideLabel">Or enter your own text</span>
</div>
<div id="date1_Div8" class="DEInput">
<input name="date1$DateFormatOverride" type="text" onchange="javascript:setTimeout('__doPostBack(\'date1$DateFormatOverride\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="date1_DateFormatOverride" />
</div>
</div>
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWFQLr6MeTCwKb1Zr0AwKVt6utCQKIwaTjAQKdwYzzBwLiwsDhDQKIwdCLBAKHwbCtCgLRr42cCQKi9vj4DgK2lM6kBQLLrsUtAsaboRMC2+2u3QgCzu2GzQ4Cse7K3wQC2+3atQ0C1O26kwMCpdTivwwC1o2X2wsCoubqnQk8I1BK30Q/iVw/rExUww2Cs4bicw==" />
</div>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready( function() {
var cal = jQuery('#datePicker_DateSelector').datepicker({yearRange: '-1500:+100',dateFormat: 'm/d/yy'});
} );
Sys.Application.initialize();
//]]>
</script>
</form>
</code></pre>
|
[
{
"answer_id": 255072,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>Why would you start a thread and then join against it immediately?</p>\n\n<p>I'd normally do something like this:</p>\n\n<pre><code>List<Thread> threads = new List<Thread>();\n\nforeach (string item in items)\n{\n string copy = item; // Important due to variable capture\n ThreadStart ts = () => DoWork(copy); // Strongly typed :)\n Thread t = new Thread(ts);\n t.Start();\n threads.Add(t);\n}\n\nforeach (Thread t in threads)\n{\n t.Join();\n}\n</code></pre>\n"
},
{
"answer_id": 255084,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>One other option (in .NET 4.0, or with the CTP) would be a form of <code>Parallel.ForEach</code>. Not necessarily viable yet, though. I also saw a good blog entry (can't remember by who) that used <code>IDisposable</code> here - i.e. </p>\n\n<pre><code>using(StartThread(arg1))\nusing(StartThread(arg2))\n{\n}\n</code></pre>\n\n<p>where the Dispose() method did a join on the thread that was spawned - i.e. when you exited the block, all are complete. Quite cute.</p>\n"
},
{
"answer_id": 255111,
"author": "mmr",
"author_id": 21981,
"author_profile": "https://Stackoverflow.com/users/21981",
"pm_score": 0,
"selected": false,
"text": "<p>Why not have your parameters be part of the class, make them properties, and have the get/set methods lock around them? If you have enough parameters, make the parameter object itself a property of the object, and then lock that parameter block. As in:</p>\n\n<pre><code>class GonnaDoSomeThreading {\n private Object mBlockLock = new Object();\n private MyParameterBlock mBlock;\n public MyParameterBlock Block {\n get { \n MyParameterBlock tmp;\n lock (mBlockLock){\n tmp = new MyParameterBlock(mBlock); //or some other cloning\n }\n return tmp; //use a tmp in order to make sure that modifications done\n //do not modify the block directly, but that modifications must\n //be 'committed' through the set function\n }\n set { lock (mBlockLock){ mBlock = value; } } \n }\n}\n</code></pre>\n\n<p>And then do your thread pool as already suggested. That way, you've got locks around the data access, so that if all of your threads need it, they can wait on one another.</p>\n\n<p>If you're doing this for something like image processing (where a lot of parallel objects can be done at once), then it might be better to break up your data into individualized chunks. IE, say you want to run some convolution over a largish image, and so want to break it up into two halves. Then, you can have a 'Fragmentimage' function which creates the image blocks that you're going to work on individually, and then a 'MergeFragments' function call to join all the results. So your fragment could look like:</p>\n\n<pre><code>class ThreadWorkFragment {\n <image type, like ushort>[] mDataArray;\n bool mDone;\n}\n</code></pre>\n\n<p>Put a lock around that fragment (ie, a list of objects and fragments, with each having a lock and so forth), so that when the thread accesses it's fragment, it can eventually state that it's 'done', release the lock, and then you can have a final merge function which just waits for those done booleans to be flagged. That way, if one of the threads dies before setting done, and you know the thread's dead, then you also know that the thread didn't finish its work and you need to do some error recovery; if you just wait for a join to happen, the thread could still have messed up its fragment.</p>\n\n<p>But there's a lot of those kinds of specific ideas to implement, based on the problem you're trying to solve.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23902/"
] |
I've been tasked with implementing a Date/Time selector for several areas of our web project, and instructed to use a control that another developer created as part of it. The control I'm working on is supposed to allow the user to choose a date from a calendar, choose a format for the display of that date (from several pre-defined formats, or with a simple text override) and optionally a time string (which is really just freeform text).
The control I was instructed to use is documented here: <http://www.west-wind.com/WebLog/posts/213015.aspx>, and uses the DatePicker from jQuery.
After I implemented my control and tested it, I began integrating it into the pages which needed Date and/or time inputs. In my testing of those implementations, I discovered a bug: when I include multiple copies of my control on a page, only the first one gets the jQuery calendar. The others are not tied to it.
I have tried some of the methods suggested in a seemingly-related question (titled 'duplicating jquery datepicker'), such as calling the '.datepicker()' function on the west-wind control (which renders a textbox) via the $("css-selector").datepicker() syntax, and ASP.NET is guaranteeing unique IDs for all the text boxes.
So, in summation, it looks like this:
```
<page>
<mycontrol>
<west-windjQuerycontrol />
</mycontrol>
<mycontrol>
<west-windjQuerycontrol />
</mycontrol>
</page>
```
Now, the strange part: When there are multiple copies of the west-wind control on the page, without the other user control containing them, they work correctly. Other than the jQuery control, my control has nothing unusual about it: simply labels, textboxes, panels, and dropdowns. Something about bundling the West-Wind jQuery control into a user control seems to be breaking it.
Any advice? I've been banging my head against this for a while, hampered by my poor javascript skills and limited exposure to jQuery.
As pointed out below, it's hard to say without the HTML. I've included it below.
```
<form name="form1" method="post" action="ControlTest.aspx" id="form1">
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTU4NjEzMDEwOQ9kFgICAw9kFgQCAw9kFgRmD2QWAgIDD2QWAgIDDxBkZBYBZmQCAg9kFgICAw9kFgICAQ8QZGQWAWZkAgUPZBYEZg9kFgICAw9kFgICAw8QZGQWAWZkAgIPZBYCAgMPZBYCAgEPEGRkFgFmZGRDjfLpdb+XxaVaQYP2XkPil2Galw==" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/SSO/DE/WebResource.axd?d=jMPpL-KK8_mPj_ssZzGblw2&t=633481894229838141" type="text/javascript"></script>
<script src="/SSO/DE/ScriptResource.axd?d=8KwRIGaNAD3hi2Loz3YV-uxgrdZpGe8nnwH5E3gxLW_lQpnYjRbyIYThTnHtD9rt0&t=633613004148118290" type="text/javascript"></script>
<script src="/SSO/DE/ScriptResource.axd?d=8KwRIGaNAD3hi2Loz3YV-uxgrdZpGe8nnwH5E3gxLW-K0Kuw-pGK1O3mE_r1y3sjKmhHtQjSXeMtYSim0bjyGA2&t=633613004148118290" type="text/javascript"></script>
<script src="/SSO/DE/ScriptResource.axd?d=Id5yAacLMZHF7TWlkgrrid30ZStmsXuLHcF6WQ404YLySP4Itj4qxv2wi9ffbsWQA86oLdnZPWkwDnu4NKxfG1Ue7qdGG1SbOfb4ooHVs7M1&t=633481957084709567" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script src="/SSO/DE/ScriptResource.axd?d=Id5yAacLMZHF7TWlkgrrid30ZStmsXuLHcF6WQ404YLySP4Itj4qxv2wi9ffbsWQhT3MFELBAa2rFJZXnSlYAZIN7RT1npcBxJRsWGjJWIwTF0Es1m0vOd-xYnFqWJKz0&t=633481957084709567" type="text/javascript"></script>
<div style="margin:25px 10px;width:100%;">
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('stupidThing', document.getElementById('form1'));
Sys.WebForms.PageRequestManager.getInstance()._updateControls([], [], [], 90);
//]]>
</script>
<div id="datePicker_Div0" class="AdminRowOdd DERow">
<div id="datePicker_Div1" class="DELabel">
<span id="datePicker_DateLabel">Date</span>
</div>
<div id="datePicker_Div2" class="DEInput datePicker">
<input name="datePicker$DateSelector" type="text" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateSelector\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="datePicker_DateSelector" style="width:80px;" />
<select name="datePicker$languageSelector" onchange="javascript:setTimeout('__doPostBack(\'datePicker$languageSelector\',\'\')', 0)" id="datePicker_languageSelector">
<option selected="selected" value="en-US">en-US</option>
<option value="fr-CA">fr-CA</option>
<option value="fr-FR">fr-FR</option>
<option value="es-ES">es-ES</option>
<option value="es-MX">es-MX</option>
</select>
</div>
</div>
<div id="datePicker_Div3" class="AdminRowEven DERow">
<div id="datePicker_Div4" class="DELabel">
<span id="datePicker_FormatChoiceLabel">Choose your display format: </span>
</div>
<div id="datePicker_Div5" class="DEInput">
<select name="datePicker$DateFormatSelector" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateFormatSelector\',\'\')', 0)" id="datePicker_DateFormatSelector">
<option selected="selected" value="Choose a date first">Choose a date first</option>
</select>
</div>
</div>
<div id="datePicker_Div6" class="AdminRowOdd DERow">
<div id="datePicker_Div7" class="DELabel">
<span id="datePicker_FormatOverrideLabel">Or enter your own text</span>
</div>
<div id="datePicker_Div8" class="DEInput">
<input name="datePicker$DateFormatOverride" type="text" onchange="javascript:setTimeout('__doPostBack(\'datePicker$DateFormatOverride\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="datePicker_DateFormatOverride" />
</div>
</div>
<br />
<div id="date1_Div0" class="AdminRowOdd DERow">
<div id="date1_Div1" class="DELabel">
<span id="date1_DateLabel">Date</span>
</div>
<div id="date1_Div2" class="DEInput datePicker">
<input name="date1$DateSelector" type="text" onchange="javascript:setTimeout('__doPostBack(\'date1$DateSelector\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="date1_DateSelector" style="width:80px;" />
<select name="date1$languageSelector" onchange="javascript:setTimeout('__doPostBack(\'date1$languageSelector\',\'\')', 0)" id="date1_languageSelector">
<option selected="selected" value="en-US">en-US</option>
<option value="fr-CA">fr-CA</option>
<option value="fr-FR">fr-FR</option>
<option value="es-ES">es-ES</option>
<option value="es-MX">es-MX</option>
</select>
</div>
</div>
<div id="date1_Div3" class="AdminRowEven DERow">
<div id="date1_Div4" class="DELabel">
<span id="date1_FormatChoiceLabel">Choose your display format:</span>
</div>
<div id="date1_Div5" class="DEInput">
<select name="date1$DateFormatSelector" onchange="javascript:setTimeout('__doPostBack(\'date1$DateFormatSelector\',\'\')', 0)" id="date1_DateFormatSelector">
<option selected="selected" value="Choose a date first">Choose a date first</option>
</select>
</div>
</div>
<div id="date1_Div6" class="AdminRowOdd DERow">
<div id="date1_Div7" class="DELabel">
<span id="date1_FormatOverrideLabel">Or enter your own text</span>
</div>
<div id="date1_Div8" class="DEInput">
<input name="date1$DateFormatOverride" type="text" onchange="javascript:setTimeout('__doPostBack(\'date1$DateFormatOverride\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="date1_DateFormatOverride" />
</div>
</div>
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWFQLr6MeTCwKb1Zr0AwKVt6utCQKIwaTjAQKdwYzzBwLiwsDhDQKIwdCLBAKHwbCtCgLRr42cCQKi9vj4DgK2lM6kBQLLrsUtAsaboRMC2+2u3QgCzu2GzQ4Cse7K3wQC2+3atQ0C1O26kwMCpdTivwwC1o2X2wsCoubqnQk8I1BK30Q/iVw/rExUww2Cs4bicw==" />
</div>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready( function() {
var cal = jQuery('#datePicker_DateSelector').datepicker({yearRange: '-1500:+100',dateFormat: 'm/d/yy'});
} );
Sys.Application.initialize();
//]]>
</script>
</form>
```
|
Why would you start a thread and then join against it immediately?
I'd normally do something like this:
```
List<Thread> threads = new List<Thread>();
foreach (string item in items)
{
string copy = item; // Important due to variable capture
ThreadStart ts = () => DoWork(copy); // Strongly typed :)
Thread t = new Thread(ts);
t.Start();
threads.Add(t);
}
foreach (Thread t in threads)
{
t.Join();
}
```
|
255,077 |
<p>I have just installed VMWare Server 2.0 on a fresh Fedora Core 8 install. The ports for the web access console of VMWare are 8222 and 8333 (like the defaults).</p>
<p>When I try a remote http access to myserver:8222 it fails. But when I run</p>
<pre><code>/sbin/service iptables stop
</code></pre>
<p>access becomes possibles (although not very satisfactory). Thus, I have updated the conf file as follow</p>
<pre><code>cat /etc/sysconfig/iptables
# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p 50 -j ACCEPT
-A RH-Firewall-1-INPUT -p 51 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp --dport 5353 -d 224.0.0.251 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
# Custom authorization for VMWare administration
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8222 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8333 -j ACCEPT
COMMIT
</code></pre>
<p>yet, even after reloading the iptables settings it's still not working. Do anyone knows what I am doing wrong?</p>
|
[
{
"answer_id": 255331,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 3,
"selected": true,
"text": "<p>Your rules for VMware need to come before the REJECT entry; otherwise they'll never be reached.</p>\n\n<p>A good debugging tool is to add a LOG just before your rules to verify:</p>\n\n<pre><code>-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT\n# Custom authorization for VMWare administration\n-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8222 -j LOG --log-prefix=\"8222 \"\n-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8222 -j ACCEPT\n-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8333 -j LOG --log-prefix=\"8333 \"\n-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8333 -j ACCEPT\n-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited\n-A FORWARD -j REJECT --reject-with icmp-host-prohibited\nCOMMIT\n</code></pre>\n\n<p>Unlike other targets, <code>LOG</code> returns to allow further rules to be processed. The <code>ACCEPT</code> and <code>REJECT</code> targets terminate processing.</p>\n"
},
{
"answer_id": 285071,
"author": "Packetslave",
"author_id": 37062,
"author_profile": "https://Stackoverflow.com/users/37062",
"pm_score": 1,
"selected": false,
"text": "<p>A simple way to fix this would be to run system-config-securitylevel or system-config-securitylevel-tui and add 8222 and 8333 as trusted ports. This adds essentially the same iptables rules as you're doing manually.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18858/"
] |
I have just installed VMWare Server 2.0 on a fresh Fedora Core 8 install. The ports for the web access console of VMWare are 8222 and 8333 (like the defaults).
When I try a remote http access to myserver:8222 it fails. But when I run
```
/sbin/service iptables stop
```
access becomes possibles (although not very satisfactory). Thus, I have updated the conf file as follow
```
cat /etc/sysconfig/iptables
# Firewall configuration written by system-config-firewall
# Manual customization of this file is not recommended.
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:RH-Firewall-1-INPUT - [0:0]
-A INPUT -j RH-Firewall-1-INPUT
-A RH-Firewall-1-INPUT -i lo -j ACCEPT
-A RH-Firewall-1-INPUT -p icmp --icmp-type any -j ACCEPT
-A RH-Firewall-1-INPUT -p 50 -j ACCEPT
-A RH-Firewall-1-INPUT -p 51 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp --dport 5353 -d 224.0.0.251 -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m udp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -p tcp -m tcp --dport 631 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
# Custom authorization for VMWare administration
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8222 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8333 -j ACCEPT
COMMIT
```
yet, even after reloading the iptables settings it's still not working. Do anyone knows what I am doing wrong?
|
Your rules for VMware need to come before the REJECT entry; otherwise they'll never be reached.
A good debugging tool is to add a LOG just before your rules to verify:
```
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
# Custom authorization for VMWare administration
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8222 -j LOG --log-prefix="8222 "
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8222 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8333 -j LOG --log-prefix="8333 "
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 8333 -j ACCEPT
-A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
```
Unlike other targets, `LOG` returns to allow further rules to be processed. The `ACCEPT` and `REJECT` targets terminate processing.
|
255,078 |
<p>What's the difference between a string and a symbol in Ruby and when should I use one over the other?</p>
|
[
{
"answer_id": 255088,
"author": "websch01ar",
"author_id": 32567,
"author_profile": "https://Stackoverflow.com/users/32567",
"pm_score": -1,
"selected": false,
"text": "<p>A symbol is something you use to represent names and strings. You would want to use a symbol when you may have need to use a string several times as this far easier and more productive.</p>\n\n<p>And just found this via google, which may offer greater detail: <a href=\"http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols\" rel=\"nofollow noreferrer\">Here you go</a></p>\n"
},
{
"answer_id": 255092,
"author": "Codebeef",
"author_id": 12037,
"author_profile": "https://Stackoverflow.com/users/12037",
"pm_score": -1,
"selected": false,
"text": "<p>Symbols and strings are completely different <a href=\"http://onestepback.org/index.cgi/Tech/Ruby/SymbolsAreNotImmutableStrings.red\" rel=\"nofollow noreferrer\">this post</a> has a little insight into the differences. As to when and where to use them, there is a pretty extensive post on this subject over on <a href=\"http://blog.hasmanythrough.com/2008/4/19/symbols-are-not-pretty-strings\" rel=\"nofollow noreferrer\">has many :through</a>.</p>\n"
},
{
"answer_id": 255099,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 8,
"selected": true,
"text": "<p>The main difference is that multiple symbols representing a single value are identical whereas this is not true with strings. For example:</p>\n\n<pre><code>irb(main):007:0> :test.object_id\n=> 83618\nirb(main):008:0> :test.object_id\n=> 83618\nirb(main):009:0> :test.object_id\n=> 83618\n</code></pre>\n\n<p>Those are three references to the symbol <code>:test</code>, which are all the same object.</p>\n\n<pre><code>irb(main):010:0> \"test\".object_id\n=> -605770378\nirb(main):011:0> \"test\".object_id\n=> -605779298\nirb(main):012:0> \"test\".object_id\n=> -605784948\n</code></pre>\n\n<p>Those are three references to the string \"test\", but are all different objects.</p>\n\n<p>This means that using symbols can potentially save a good bit of memory depending on the application. It is also faster to compare symbols for equality since they are the same object, comparing identical strings is much slower since the string values need to be compared instead of just the object ids.</p>\n\n<p>As far as when to use which, I usually use strings for almost everything except things like hash keys where I really want a unique identifier, not a string.</p>\n"
},
{
"answer_id": 255909,
"author": "Grant Hutchins",
"author_id": 6304,
"author_profile": "https://Stackoverflow.com/users/6304",
"pm_score": 3,
"selected": false,
"text": "<p>An additional difference between <code>String</code> and <code>Symbol</code> is that a <code>String</code> has a lot more methods on it for string manipulation, while a <code>Symbol</code> is a relatively lean object.</p>\n\n<p>Check out the documentation for the <a href=\"http://www.ruby-doc.org/core/classes/String.html\" rel=\"noreferrer\"><code>String</code> class</a> and the <a href=\"http://www.ruby-doc.org/core/classes/Symbol.html\" rel=\"noreferrer\"><code>Symbol</code> class</a>.</p>\n"
},
{
"answer_id": 17775472,
"author": "Nitesh",
"author_id": 2535322,
"author_profile": "https://Stackoverflow.com/users/2535322",
"pm_score": -1,
"selected": false,
"text": "<p>Strings are Mutable , Symbols arre immutable<br>\nNote:Mutable objects can be changed after assignment while immutable objects can only\nbe overwritten\n<a href=\"http://www.robertsosinski.com/2009/01/11/the-difference-between-ruby-symbols-and-strings/\" rel=\"nofollow\">http://www.robertsosinski.com/2009/01/11/the-difference-between-ruby-symbols-and-strings/</a></p>\n"
},
{
"answer_id": 22454020,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>symbol is immutable and string is mutable.</p>\n\n<p>when we perform any operation on string then it create a new object and take memory. As we perform more and more operation on string means we are consuming more and more memory.</p>\n\n<p>symbol is object that are immutable mean if we perform any operation then it performs changes in original object, It will not create any object, that's why it is more profitable.</p>\n\n<p>for more info, you can <a href=\"http://www.robertsosinski.com/2009/01/11/the-difference-between-ruby-symbols-and-strings/\" rel=\"nofollow noreferrer\">click here</a></p>\n"
},
{
"answer_id": 23358644,
"author": "Feuda",
"author_id": 642616,
"author_profile": "https://Stackoverflow.com/users/642616",
"pm_score": 4,
"selected": false,
"text": "<p>What are the differences between Symbols and Strings? </p>\n\n<ol>\n<li>Symbols are immutable: Their value remains constant.</li>\n<li>Multiple uses of the same symbol have the same object ID and are the same object compared to string which will be a different object with unique object ID, everytime.</li>\n<li>You can't call any of the String methods like <code>split</code> on Symbols.</li>\n</ol>\n\n<p>From <a href=\"http://www.gaurishsharma.com/2013/04/understanding-differences-between-symbols-strings-in-ruby.html\" rel=\"noreferrer\">Understanding Differences Between Symbols & Strings in Ruby</a></p>\n\n<p>If you know Chinese, you can also read <a href=\"https://www.ibm.com/developerworks/cn/opensource/os-cn-rubysbl/\" rel=\"noreferrer\">理解 Ruby Symbol</a>.</p>\n"
},
{
"answer_id": 38193530,
"author": "Leo Le",
"author_id": 2001053,
"author_profile": "https://Stackoverflow.com/users/2001053",
"pm_score": 2,
"selected": false,
"text": "<p>There are two main differences between String and Symbol in Ruby.</p>\n\n<ol>\n<li><p>String is mutable and Symbol is not:</p>\n\n<ul>\n<li>Because the String is mutable, it can be change in somewhere and can lead to the result is not correct.</li>\n<li>Symbol is immutable.</li>\n</ul></li>\n<li><p>String is an Object so it needs memory allocation</p>\n\n<pre><code>puts \"abc\".object_id # 70322858612020\nputs \"abc\".object_id # 70322846847380\nputs \"abc\".object_id # 70322846815460\n</code></pre>\n\n<p>In the other hand, Symbol will return the same object:</p>\n\n<pre><code>puts :abc.object_id # 1147868\nputs :abc.object_id # 1147868\nputs :abc.object_id # 1147868\n</code></pre></li>\n</ol>\n\n<p>So the String will take more time to use and to compare than Symbol.</p>\n\n<p>Read \"<a href=\"http://www.reactive.io/tips/2009/01/11/the-difference-between-ruby-symbols-and-strings\" rel=\"nofollow noreferrer\">The Difference Between Ruby Symbols and Strings</a>\" for more information.</p>\n"
},
{
"answer_id": 39518834,
"author": "Nitin9791",
"author_id": 2873883,
"author_profile": "https://Stackoverflow.com/users/2873883",
"pm_score": 3,
"selected": false,
"text": "<p>The statement:</p>\n\n<pre><code>foo = \"bar\"\n</code></pre>\n\n<p>creates a new object in memory. If we repeat the statement:</p>\n\n<pre><code>foo = \"bar\"\n</code></pre>\n\n<p>We create another object.</p>\n\n<p>To understand it more clearly please try this code in IRB:</p>\n\n<pre><code>foo = \"bar\"\nputs \"string #{foo} with object id = #{foo.object_id}\"\nfoo = \"bar\"\nputs \"string #{foo} with object id = #{foo.object_id}\"\n</code></pre>\n\n<p>You will get output like:</p>\n\n<pre><code>string bar with object id = 70358547221180\nstring bar with object id = 70358548927060\n</code></pre>\n\n<p>which clearly shows there are two different object for the same string. Now if you use a symbol it will create <strong>one object per symbol</strong> so:</p>\n\n<pre><code>foo = :bar\nputs \"symbol #{foo} with object id = #{foo.object_id}\"\nfoo = :bar\nputs \"symbol #{foo} with object id = #{foo.object_id}\"\n</code></pre>\n\n<p>shows:</p>\n\n<pre><code>symbol bar with object id = 7523228\nsymbol bar with object id = 7523228\n</code></pre>\n\n<p>which means there is only one object for <code>:bar</code>.</p>\n\n<p>Further, Symbols are <strong>immutable</strong> and you can't call any of the String methods like <code>upcase</code> or <code>split</code> on Symbols.</p>\n\n<p>Comparing Symbols are faster than comparing Strings. Symbols can be thought of as constant/immutable strings that form a unique set that are effectively converted to memory pointers on the heap. This means comparing two symbols is fast because you are just comparing two integers (memory pointers). </p>\n\n<p>Strings are mutable so the memory pointer to their value on the heap can change after modification. This means comparison operations are slower because duplicates can exist that are semantically equivalent.</p>\n\n<p>Use a symbol when you are sure that the value will remain constant, for example use symbols for hash keys. Use a string when you want to change the value or want to use a string method on it.</p>\n"
},
{
"answer_id": 54203941,
"author": "Chimed Palden",
"author_id": 4110918,
"author_profile": "https://Stackoverflow.com/users/4110918",
"pm_score": 2,
"selected": false,
"text": "<p>Case where symbol can be disaster. Lets say you have\n<code>params.map(&:to_sym)</code> in your rails controller .\nNow here if you are converting the data provided by the user to symbol due to some reason then it could be dangerous. If the data provided by the user is too large and as we know that symbol is not a garbage collector, you might end up exhausting your server's memory which can takedown your website.</p>\n"
},
{
"answer_id": 68827126,
"author": "Abhishek Tanwar",
"author_id": 15002139,
"author_profile": "https://Stackoverflow.com/users/15002139",
"pm_score": 0,
"selected": false,
"text": "<p>The main difference is that string can have value inside a variable whereas symbol not . For example:</p>\n<pre><code>x = "hello"\np x => "hello"\np :x => :x\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
What's the difference between a string and a symbol in Ruby and when should I use one over the other?
|
The main difference is that multiple symbols representing a single value are identical whereas this is not true with strings. For example:
```
irb(main):007:0> :test.object_id
=> 83618
irb(main):008:0> :test.object_id
=> 83618
irb(main):009:0> :test.object_id
=> 83618
```
Those are three references to the symbol `:test`, which are all the same object.
```
irb(main):010:0> "test".object_id
=> -605770378
irb(main):011:0> "test".object_id
=> -605779298
irb(main):012:0> "test".object_id
=> -605784948
```
Those are three references to the string "test", but are all different objects.
This means that using symbols can potentially save a good bit of memory depending on the application. It is also faster to compare symbols for equality since they are the same object, comparing identical strings is much slower since the string values need to be compared instead of just the object ids.
As far as when to use which, I usually use strings for almost everything except things like hash keys where I really want a unique identifier, not a string.
|
255,081 |
<p>I have a situation where another developer is including source files from a project that I maintain in a project that he maintains. The nature of the files is such that each source file registers a "command" in an interpretive environment so all you have to do is link in a new source file to register a new "command". We can't put these files in a static library because, unless the project makes explicit reference to the symbols in the file, the linker will optimise the file away. </p>
<p>It seems like a potential solution is to have a file external to both projects that "includes" a list of source file names in both projects. The problem is that I have no idea whether or how this could be done. Suggestions, anyone?</p>
|
[
{
"answer_id": 255090,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 0,
"selected": false,
"text": "<p>Could you simply write a source file containing nothing but <code>#include</code> directives? I'm not sure if VS checks whether the dependent files have changed if they're not in the project proper, though.</p>\n"
},
{
"answer_id": 255159,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": true,
"text": "<p>There is no reason a source file can't be in multiple projects. Just add it as an 'existing item' in VS.</p>\n\n<p>If you are using precompiled headers then both projects will need equivalent set ups for this to work.</p>\n\n<p>You can also use a #pragma in a lib to force a symbol to be included when the linker would otherwise discard it.</p>\n\n<pre><code>#pragma comment(linker, \"/include:__mySymbol\")\n</code></pre>\n\n<p>See the MSDN document for <a href=\"http://msdn.microsoft.com/en-us/library/7f0aews7(VS.80).aspx\" rel=\"nofollow noreferrer\">#pragma comment</a> and the <a href=\"http://msdn.microsoft.com/en-us/library/2s3hwbhs(VS.80).aspx\" rel=\"nofollow noreferrer\">include</a> option</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19674/"
] |
I have a situation where another developer is including source files from a project that I maintain in a project that he maintains. The nature of the files is such that each source file registers a "command" in an interpretive environment so all you have to do is link in a new source file to register a new "command". We can't put these files in a static library because, unless the project makes explicit reference to the symbols in the file, the linker will optimise the file away.
It seems like a potential solution is to have a file external to both projects that "includes" a list of source file names in both projects. The problem is that I have no idea whether or how this could be done. Suggestions, anyone?
|
There is no reason a source file can't be in multiple projects. Just add it as an 'existing item' in VS.
If you are using precompiled headers then both projects will need equivalent set ups for this to work.
You can also use a #pragma in a lib to force a symbol to be included when the linker would otherwise discard it.
```
#pragma comment(linker, "/include:__mySymbol")
```
See the MSDN document for [#pragma comment](http://msdn.microsoft.com/en-us/library/7f0aews7(VS.80).aspx) and the [include](http://msdn.microsoft.com/en-us/library/2s3hwbhs(VS.80).aspx) option
|
255,098 |
<p>I am experimenting with calling delegate functions from a delegate array. I've been able to create the array of delegates, but how do I call the delegate?</p>
<pre><code>public delegate void pd();
public static class MyClass
{
static void p1()
{
//...
}
static void p2 ()
{
//...
}
//...
static pd[] delegates = new pd[] {
new pd( MyClass.p1 ),
new pd( MyClass.p2)
/* ... */
};
}
public class MainClass
{
static void Main()
{
// Call pd[0]
// Call pd[1]
}
}
</code></pre>
<p><strong>EDIT:</strong> The reason for the array is that I need to call the delegate functions by an index as needed. They are not run in response to an event. I see a critical (stupid) error in my code as I had tried to execute the delegate function using the pd[] type rather than the name of the array (delegates).</p>
|
[
{
"answer_id": 255107,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 3,
"selected": false,
"text": "<pre><code>public class MainClass\n{\n static void Main()\n {\n pd[0]();\n pd[1]();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 255113,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "<p>If they're all the same type, why not just combine them into a single multicast delegate?</p>\n\n<pre><code>static pd delegateInstance = new pd(MyClass.p1) + new pd(MyClass.p2) ...;\n\n...\npd();\n</code></pre>\n"
},
{
"answer_id": 255252,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 3,
"selected": false,
"text": "<p>In .Net, any delegate is in fact actually a \"multicast\" delegate (it inherits from this built-in base class), and therefore contains an internal linked list which can contain any number of target delegates. </p>\n\n<p>You can access this list by calling the method GetInvocationList() on the delegate itself. This method returns an array of Delegates... </p>\n\n<p>The only restriction is that all the delegates inside of a given delegate's linked list must have the same signature, (be of the same delegate type). If you need your collection to be able to contain delegates of disparate types, then you need to construct your own list or collection class. </p>\n\n<p>But if this is ok, then you can \"call\" the delegates in a given delegate's invocation list like this:</p>\n\n<pre><code>public delegate void MessageArrivedHandler(MessageBase msg);\npublic class MyClass\n{\n public event MessageArrivedHandler MessageArrivedClientHandler; \n\n public void CallEachDelegate(MessageBase msg)\n {\n if (MessageArrivedClientHandler == null)\n return;\n Delegate[] clientList = MessageArrivedClientHandler.GetInvocationList();\n foreach (Delegate d in clientList)\n {\n if (d is MessageArrivedHandler)\n (d as MessageArrivedHandler)(msg);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 13284760,
"author": "Garric",
"author_id": 1808515,
"author_profile": "https://Stackoverflow.com/users/1808515",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n pd[0]();\n pd[1]();\n }\n\n public delegate void delegates();\n\n static delegates[] pd = new delegates[] \n { \n new delegates(MyClass.p1), \n new delegates(MyClass.p2) \n };\n\n public static class MyClass\n {\n public static void p1()\n {\n MessageBox.Show(\"1\");\n }\n\n public static void p2()\n {\n MessageBox.Show(\"2\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 13285006,
"author": "Garric",
"author_id": 1808515,
"author_profile": "https://Stackoverflow.com/users/1808515",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n pd[0](1);\n pd[1](2);\n }\n\n public delegate void delegates(int par);\n static delegates[] pd = new delegates[] \n { \n new delegates(MyClass.p1), \n new delegates(MyClass.p2) \n };\n public static class MyClass\n {\n\n public static void p1(int par)\n {\n MessageBox.Show(par.ToString());\n }\n\n public static void p2(int par)\n {\n MessageBox.Show(par.ToString());\n }\n\n\n }\n\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7899/"
] |
I am experimenting with calling delegate functions from a delegate array. I've been able to create the array of delegates, but how do I call the delegate?
```
public delegate void pd();
public static class MyClass
{
static void p1()
{
//...
}
static void p2 ()
{
//...
}
//...
static pd[] delegates = new pd[] {
new pd( MyClass.p1 ),
new pd( MyClass.p2)
/* ... */
};
}
public class MainClass
{
static void Main()
{
// Call pd[0]
// Call pd[1]
}
}
```
**EDIT:** The reason for the array is that I need to call the delegate functions by an index as needed. They are not run in response to an event. I see a critical (stupid) error in my code as I had tried to execute the delegate function using the pd[] type rather than the name of the array (delegates).
|
If they're all the same type, why not just combine them into a single multicast delegate?
```
static pd delegateInstance = new pd(MyClass.p1) + new pd(MyClass.p2) ...;
...
pd();
```
|
255,104 |
<p>I'm working on a WinForms app and I have a user control in it. The buttons in the user control raise events up to the form to be handled by other code. One of the buttons starts some processses that will cause problems if they run simultaneously. I have logic in the code to manage the state so typically a user can't run the process if it's already running. However, if the user double-clicks the button it will start the process twice so quickly that it's tough for me to prevent it.</p>
<p>I'm wondering, what's the best way to handle this?</p>
<p>I started out by disabling the button in the click event but the second click comes in before the first click causes the button to be disabled. Setting other flags in the code didn't catch it either.</p>
<p>I'm considering adding some sort of sync lock on the code that raises the event but I'm wondering if any of you have a better idea. </p>
<p>Since this project is mostly complete I'm looking for answers that don't involve a radical rewrite of the app (like implementing the composite application block), however, feel free to post those ideas too since I can use them in my next projects.</p>
|
[
{
"answer_id": 255118,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": -1,
"selected": false,
"text": "<p>Disable the button after the user first clicks it and before starting the task. When task completes, re-enable the button.</p>\n"
},
{
"answer_id": 255129,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 2,
"selected": false,
"text": "<p>The disable flag on that button would not be set until the button event handler completes, and any additional clicks will be queued in the windows message queue behind the first click. Make sure the button event handler completes quickly to free up the UI thread. There are several ways of doing this, but all involve eather spawning a thread or keeping a worker thread ready and waiting for an AutoResetEvent.</p>\n"
},
{
"answer_id": 255138,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 4,
"selected": true,
"text": "<p>Make sure that your button disabling or any other locking that you do is the /first/ thing that you do in your event handler. I would be extremely surprised if you could queue up two click events before even the first instruction fires, but I suppose that's possible if you're on a very slow computer that's bogged down with other apps.</p>\n\n<p>In that event, use a flag.</p>\n\n<pre><code>private bool runningExclusiveProcess = false;\n\npublic void onClickHandler(object sender, EventArgs e)\n{\n if (!runningExclusiveProcess)\n {\n runningExclusiveProcess = true;\n myButton.Enabled = false;\n\n // Do super secret stuff here\n\n // If your task is synchronous, then undo your flag here:\n runningExclusiveProcess = false;\n myButton.Enabled = true;\n }\n}\n\n// Otherwise, if your task is asynchronous with a callback, then undo your flag here:\npublic void taskCompletedCallback()\n{\n runningExclusiveProcess = false;\n myButton.Enabled = true;\n}\n</code></pre>\n\n<p>If you can still get in two clicks off of something like that, then make sure you're not accidentally subscribed to a doubleClick event, or anything else wonky is going on.</p>\n"
},
{
"answer_id": 255303,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Are you handling the event twice?</strong></p>\n\n<p>I am <em>very</em> surprised to read that the second click is coming in before you can disable the button. I would look to make sure you aren't hooking up the event twice. I have done this by accident before. You will then get two events, almost instantaneously.</p>\n"
},
{
"answer_id": 258484,
"author": "Michael Zuschlag",
"author_id": 33086,
"author_profile": "https://Stackoverflow.com/users/33086",
"pm_score": 0,
"selected": false,
"text": "<p>By any chance, are you labeling the button with an icon? By all means use code to prevent running two processes at once, but you can reduce double-clicking on the human side if your button looks and acts like a conventional command button (rectangular, text label only, \"raised\" surface that depresses on a click). Just a thought. </p>\n"
},
{
"answer_id": 261671,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Disable the button as soon as it is clicked. So, the event can't be handled twice. As soon as the event had been handled, you can re-enable the button.</p>\n"
},
{
"answer_id": 261685,
"author": "mjwills",
"author_id": 34092,
"author_profile": "https://Stackoverflow.com/users/34092",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>I started out by disabling the button\n in the click event but the second\n click comes in before the first click\n causes the button to be disabled.\n Setting other flags in the code didn't\n catch it either.</p>\n</blockquote>\n\n<p>Given WinForms is inherently single-threaded, it should not be possible for the second click to fire before the processing for the first has completed (unless you are using new threads or BackgroundWorkers etc).</p>\n\n<p>Can you show us a sample illustrating your problem?</p>\n"
},
{
"answer_id": 1055638,
"author": "nbdeveloper",
"author_id": 119436,
"author_profile": "https://Stackoverflow.com/users/119436",
"pm_score": 0,
"selected": false,
"text": "<p>The checked answer is close, if anecdotal at best. To the uninitated it's missing too much code to make sense. I've written an article about using Timers and Threads and the code example is REALLY easy to understand. Try reading through it and seeing if you can set the flags from the example above by running your task process in a new Thread:</p>\n\n<p><a href=\"http://www.robault.com/category/Threading.aspx\" rel=\"nofollow noreferrer\">http://www.robault.com/category/Threading.aspx</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10221/"
] |
I'm working on a WinForms app and I have a user control in it. The buttons in the user control raise events up to the form to be handled by other code. One of the buttons starts some processses that will cause problems if they run simultaneously. I have logic in the code to manage the state so typically a user can't run the process if it's already running. However, if the user double-clicks the button it will start the process twice so quickly that it's tough for me to prevent it.
I'm wondering, what's the best way to handle this?
I started out by disabling the button in the click event but the second click comes in before the first click causes the button to be disabled. Setting other flags in the code didn't catch it either.
I'm considering adding some sort of sync lock on the code that raises the event but I'm wondering if any of you have a better idea.
Since this project is mostly complete I'm looking for answers that don't involve a radical rewrite of the app (like implementing the composite application block), however, feel free to post those ideas too since I can use them in my next projects.
|
Make sure that your button disabling or any other locking that you do is the /first/ thing that you do in your event handler. I would be extremely surprised if you could queue up two click events before even the first instruction fires, but I suppose that's possible if you're on a very slow computer that's bogged down with other apps.
In that event, use a flag.
```
private bool runningExclusiveProcess = false;
public void onClickHandler(object sender, EventArgs e)
{
if (!runningExclusiveProcess)
{
runningExclusiveProcess = true;
myButton.Enabled = false;
// Do super secret stuff here
// If your task is synchronous, then undo your flag here:
runningExclusiveProcess = false;
myButton.Enabled = true;
}
}
// Otherwise, if your task is asynchronous with a callback, then undo your flag here:
public void taskCompletedCallback()
{
runningExclusiveProcess = false;
myButton.Enabled = true;
}
```
If you can still get in two clicks off of something like that, then make sure you're not accidentally subscribed to a doubleClick event, or anything else wonky is going on.
|
255,114 |
<p>Let's make this very easy. What I want:</p>
<pre><code>@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.
</code></pre>
<p>How to print duplicate values of a array/hash?</p>
|
[
{
"answer_id": 255144,
"author": "Dave",
"author_id": 32938,
"author_profile": "https://Stackoverflow.com/users/32938",
"pm_score": 0,
"selected": false,
"text": "<p>Use a dictionary, put the value in the key, and the count in the value.</p>\n\n<p>Ah, just noticed you've tagged as perl</p>\n\n<pre>\nwhile ([...]) {\n $hash{[dbvalue]}++\n}\n</pre>\n"
},
{
"answer_id": 255177,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 4,
"selected": true,
"text": "<pre><code>sub duplicate {\n my @args = @_;\n my %items;\n for my $element(@args) {\n $items{$element}++;\n }\n return grep {$items{$_} > 1} keys %items;\n}\n</code></pre>\n"
},
{
"answer_id": 255188,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 2,
"selected": false,
"text": "<p>The extra verbose, extra readable version of what you want to do:</p>\n\n<p><pre><code>\nsub duplicate {\n my %value_hash;\n foreach my $val (@_) {\n $value_hash{$val} +=1;\n }\n my @arr;\n while (my ($val, $num) = each(%value_hash)) {\n if ($num > 1) {\n push(@arr, $val)\n }\n }\n return @arr;\n}\n</pre></code></p>\n\n<p>This can be shortened considerably, but I intentionally left it verbose so that you can follow along.</p>\n\n<p>I didn't test it, though, so watch out for my typos.</p>\n"
},
{
"answer_id": 255191,
"author": "Amanibhavam",
"author_id": 33238,
"author_profile": "https://Stackoverflow.com/users/33238",
"pm_score": 2,
"selected": false,
"text": "<pre><code># assumes inputs can be hash keys\n@a = (1, 2, 3, 3, 4, 4, 5);\n\n# keep count for each unique input\n%h = ();\nmap { $h{$_}++ } @a;\n\n# duplicate inputs have count > 1\n@dupes = grep { $h{$_} > 1 } keys %h;\n\n# should print 3, 4\nprint join(\", \", sort @dupes), \"\\n\";\n</code></pre>\n"
},
{
"answer_id": 256221,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": -1,
"selected": false,
"text": "<p>I'm going golfing!</p>\n\n<pre><code>sub duplicate {\n my %count;\n grep $count{$_}++, @_;\n}\n\n@array = qw/one two one/;\nmy @duplicates = duplicate(@array);\nprint \"@duplicates\"; # This should now print 'one'.\n\n# or if returning *exactly* 1 occurrence of each duplicated item is important\nsub duplicate {\n my %count;\n grep ++$count{$_} == 2, @_;\n}\n</code></pre>\n"
},
{
"answer_id": 256442,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 0,
"selected": false,
"text": "<p>Unspecified in the question is the order in which the duplicates should be returned.</p>\n\n<p>I can think of several possibilities: don't care; by order of first/second/last occurrence in the input list; sorted.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33232/"
] |
Let's make this very easy. What I want:
```
@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.
```
How to print duplicate values of a array/hash?
|
```
sub duplicate {
my @args = @_;
my %items;
for my $element(@args) {
$items{$element}++;
}
return grep {$items{$_} > 1} keys %items;
}
```
|
255,133 |
<p>I'm a long-time ActionScript 2 user, now getting started with ActionScript 3. The one thing I'm missing is an easy way to duplicate the functionality of AS2's MovieClip.onReleaseOutside. It is almost always necessary to implement this event, otherwise you get funny bugs like flash thinks your mouse is down when really it's up. </p>
<p>According to the <a href="http://livedocs.adobe.com/flex/2/langref/migration.html" rel="nofollow noreferrer">AS2 to AS3 Migration Guide</a>, I'm supposed to use <code>flash.display.InteractiveObject.setCapture()</code> for this, however it does not exist as far as I can tell. I guess this document is out of date or incorrect. I've found a few posts on the web about how to duplicate this functionality, but they either have their own problems:</p>
<ul>
<li><a href="http://www.arpitonline.com/blog/?p=33" rel="nofollow noreferrer">This one</a> triggers onReleaseOutside even if there was no corresponding onPress event. </li>
<li><a href="http://www.kirupa.com/forum/showpost.php?p=1948182&postcount=204" rel="nofollow noreferrer">This one</a> seems very inefficient, you'll add and remove an event listener every time the mouse is clicked anywhere inside your app.</li>
</ul>
<p>There has to be an easier way, don't tell me Adobe forgot about this when rewriting Actionscript?</p>
<p>Example AS2 code:</p>
<pre><code>// Assume myMC is a simple square or something on the stage
myMC.onPress = function() {
this._rotation = 45;
}
myMC.onRelease = myMC.onReleaseOutside = function() {
this._rotation = 0;
}
</code></pre>
<p>Without the onReleaseOutside handler, if you pressed down on the squre, dragged your mouse outside of it, and released the mouse, then the square would not un-rotate, and appear to be stuck.</p>
|
[
{
"answer_id": 256007,
"author": "Ronnie Liew",
"author_id": 1987,
"author_profile": "https://Stackoverflow.com/users/1987",
"pm_score": 2,
"selected": false,
"text": "<p>Have you looked at this event:</p>\n\n<pre><code>flash.events.Event.MOUSE_LEAVE\n</code></pre>\n\n<p><br />\n<br />\nFrom the documentation:</p>\n\n<p><strong>Dispatched by the Stage object when the mouse pointer moves out of the stage area.\nThe Event.MOUSE_LEAVE constant defines the value of the type property of a mouseLeave event object.</strong>\n<br />\n<br /></p>\n\n<p>It will solve your problem if you are only interested whether the user's mouse if off the stage instead of just outside that particular MovieClip.</p>\n"
},
{
"answer_id": 256022,
"author": "Rafe",
"author_id": 27497,
"author_profile": "https://Stackoverflow.com/users/27497",
"pm_score": 2,
"selected": false,
"text": "<p>root.addEventListener(MouseEvent.UP, onMouseReleaseOutside);</p>\n\n<p>You define onMouseReleaseOutside of course. Basically any MouseEvent.UP (a mouse release) that happens outside of your button (or mc) will hit the stage instead of your button. This is the way i usually catch it.</p>\n"
},
{
"answer_id": 257441,
"author": "Antti",
"author_id": 6037,
"author_profile": "https://Stackoverflow.com/users/6037",
"pm_score": 4,
"selected": true,
"text": "<p>Simple and foolproof:</p>\n\n<pre><code>button.addEventListener( MouseEvent.MOUSE_DOWN, mouseDownHandler );\nbutton.addEventListener( MouseEvent.MOUSE_UP, buttonMouseUpHandler ); // *\n\nfunction mouseDownHandler( event : MouseEvent ) : void {\n trace( \"onPress\" );\n // this will catch the event anywhere\n event.target.stage.addEventListener( MouseEvent.MOUSE_UP, mouseUpHandler );\n}\n\nfunction buttonMouseUpHandler( event : MouseEvent ) : void {\n trace( \"onRelease\" );\n // don't bubble up, which would trigger the mouse up on the stage\n event.stopImmediatePropagation( );\n}\n\nfunction mouseUpHandler( event : MouseEvent ) : void {\n trace( \"onReleaseOutside\" );\n event.target.removeEventListener( MouseEvent.MOUSE_UP, mouseUpHandler );\n}\n</code></pre>\n\n<p>If you don't care about the difference between onRelease and onReleaseOutside (for example with draggable items) you an skip the mouse up listener on the button itself (commented here with an asterisk).</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569/"
] |
I'm a long-time ActionScript 2 user, now getting started with ActionScript 3. The one thing I'm missing is an easy way to duplicate the functionality of AS2's MovieClip.onReleaseOutside. It is almost always necessary to implement this event, otherwise you get funny bugs like flash thinks your mouse is down when really it's up.
According to the [AS2 to AS3 Migration Guide](http://livedocs.adobe.com/flex/2/langref/migration.html), I'm supposed to use `flash.display.InteractiveObject.setCapture()` for this, however it does not exist as far as I can tell. I guess this document is out of date or incorrect. I've found a few posts on the web about how to duplicate this functionality, but they either have their own problems:
* [This one](http://www.arpitonline.com/blog/?p=33) triggers onReleaseOutside even if there was no corresponding onPress event.
* [This one](http://www.kirupa.com/forum/showpost.php?p=1948182&postcount=204) seems very inefficient, you'll add and remove an event listener every time the mouse is clicked anywhere inside your app.
There has to be an easier way, don't tell me Adobe forgot about this when rewriting Actionscript?
Example AS2 code:
```
// Assume myMC is a simple square or something on the stage
myMC.onPress = function() {
this._rotation = 45;
}
myMC.onRelease = myMC.onReleaseOutside = function() {
this._rotation = 0;
}
```
Without the onReleaseOutside handler, if you pressed down on the squre, dragged your mouse outside of it, and released the mouse, then the square would not un-rotate, and appear to be stuck.
|
Simple and foolproof:
```
button.addEventListener( MouseEvent.MOUSE_DOWN, mouseDownHandler );
button.addEventListener( MouseEvent.MOUSE_UP, buttonMouseUpHandler ); // *
function mouseDownHandler( event : MouseEvent ) : void {
trace( "onPress" );
// this will catch the event anywhere
event.target.stage.addEventListener( MouseEvent.MOUSE_UP, mouseUpHandler );
}
function buttonMouseUpHandler( event : MouseEvent ) : void {
trace( "onRelease" );
// don't bubble up, which would trigger the mouse up on the stage
event.stopImmediatePropagation( );
}
function mouseUpHandler( event : MouseEvent ) : void {
trace( "onReleaseOutside" );
event.target.removeEventListener( MouseEvent.MOUSE_UP, mouseUpHandler );
}
```
If you don't care about the difference between onRelease and onReleaseOutside (for example with draggable items) you an skip the mouse up listener on the button itself (commented here with an asterisk).
|
255,147 |
<p>In python, if I say</p>
<pre><code>print 'h'
</code></pre>
<p>I get the letter h and a newline. If I say </p>
<pre><code>print 'h',
</code></pre>
<p>I get the letter h and no newline. If I say</p>
<pre><code>print 'h',
print 'm',
</code></pre>
<p>I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?</p>
<p>The print statements are different iterations of the same loop so I can't just use the + operator.</p>
|
[
{
"answer_id": 255154,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 9,
"selected": true,
"text": "<pre><code>import sys\n\nsys.stdout.write('h')\nsys.stdout.flush()\n\nsys.stdout.write('m')\nsys.stdout.flush()\n</code></pre>\n\n<p>You need to call <a href=\"https://docs.python.org/library/io.html#io.IOBase.flush\" rel=\"noreferrer\"><code>sys.stdout.flush()</code></a> because otherwise it will hold the text in a buffer and you won't see it.</p>\n"
},
{
"answer_id": 255172,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 8,
"selected": false,
"text": "<p>In <a href=\"https://docs.python.org/whatsnew/3.0.html#print-is-a-function\" rel=\"noreferrer\">Python 3</a>, use</p>\n\n<pre><code>print('h', end='')\n</code></pre>\n\n<p>to suppress the endline terminator, and</p>\n\n<pre><code>print('a', 'b', 'c', sep='')\n</code></pre>\n\n<p>to suppress the whitespace separator between items. See <a href=\"https://docs.python.org/library/functions.html#print\" rel=\"noreferrer\">the documentation for <code>print</code></a></p>\n"
},
{
"answer_id": 255199,
"author": "Dan",
"author_id": 444,
"author_profile": "https://Stackoverflow.com/users/444",
"pm_score": 5,
"selected": false,
"text": "<p>Greg is right-- you can use sys.stdout.write</p>\n\n<p>Perhaps, though, you should consider refactoring your algorithm to accumulate a list of <whatevers> and then</p>\n\n<pre><code>lst = ['h', 'm']\nprint \"\".join(lst)\n</code></pre>\n"
},
{
"answer_id": 255306,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 4,
"selected": false,
"text": "<pre><code>Python 2.5.2 (r252:60911, Sep 27 2008, 07:03:14)\n[GCC 4.3.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> print \"hello\",; print \"there\"\nhello there\n>>> print \"hello\",; sys.stdout.softspace=False; print \"there\"\nhellothere\n</code></pre>\n\n<p>But really, you should use <code>sys.stdout.write</code> directly.</p>\n"
},
{
"answer_id": 255336,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 4,
"selected": false,
"text": "<p>For completeness, one other way is to clear the softspace value after performing the write.</p>\n\n<pre><code>import sys\nprint \"hello\",\nsys.stdout.softspace=0\nprint \"world\",\nprint \"!\"\n</code></pre>\n\n<p>prints <code>helloworld !</code></p>\n\n<p>Using stdout.write() is probably more convenient for most cases though.</p>\n"
},
{
"answer_id": 410850,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Or use a <code>+</code>, i.e.:</p>\n\n<pre><code>>>> print 'me'+'no'+'likee'+'spacees'+'pls'\nmenolikeespaceespls\n</code></pre>\n\n<p>Just make sure all are concatenate-able objects.</p>\n"
},
{
"answer_id": 1036396,
"author": "John Machin",
"author_id": 84270,
"author_profile": "https://Stackoverflow.com/users/84270",
"pm_score": 3,
"selected": false,
"text": "<p>Regain control of your console! Simply:</p>\n\n<pre><code>from __past__ import printf\n</code></pre>\n\n<p>where <code>__past__.py</code> contains:</p>\n\n<pre><code>import sys\ndef printf(fmt, *varargs):\n sys.stdout.write(fmt % varargs)\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>>>> printf(\"Hello, world!\\n\")\nHello, world!\n>>> printf(\"%d %d %d\\n\", 0, 1, 42)\n0 1 42\n>>> printf('a'); printf('b'); printf('c'); printf('\\n')\nabc\n>>>\n</code></pre>\n\n<p>Bonus extra: If you don't like <code>print >> f, ...</code>, you can extending this caper to fprintf(f, ...).</p>\n"
},
{
"answer_id": 20677875,
"author": "Abd",
"author_id": 3118564,
"author_profile": "https://Stackoverflow.com/users/3118564",
"pm_score": 4,
"selected": false,
"text": "<p>This may look stupid, but seems to be the simplest:</p>\n\n<pre><code> print 'h',\n print '\\bm'\n</code></pre>\n"
},
{
"answer_id": 21369899,
"author": "techdude101",
"author_id": 3238586,
"author_profile": "https://Stackoverflow.com/users/3238586",
"pm_score": 1,
"selected": false,
"text": "<p>You can use print like the printf function in C.</p>\n\n<p>e.g.</p>\n\n<p>print \"%s%s\" % (x, y)</p>\n"
},
{
"answer_id": 23247362,
"author": "Benjamin",
"author_id": 1027842,
"author_profile": "https://Stackoverflow.com/users/1027842",
"pm_score": 2,
"selected": false,
"text": "<p>In python 2.6:</p>\n\n<pre><code>>>> print 'h','m','h'\nh m h\n>>> from __future__ import print_function\n>>> print('h',end='')\nh>>> print('h',end='');print('m',end='');print('h',end='')\nhmh>>>\n>>> print('h','m','h',sep='');\nhmh\n>>>\n</code></pre>\n\n<p>So using print_function from __future__ you can set explicitly the <strong>sep</strong> and <strong>end</strong> parameteres of print function.</p>\n"
},
{
"answer_id": 24686404,
"author": "Michael Murphy",
"author_id": 1991735,
"author_profile": "https://Stackoverflow.com/users/1991735",
"pm_score": 1,
"selected": false,
"text": "<pre><code>print(\"{0}{1}{2}\".format(a, b, c))\n</code></pre>\n"
},
{
"answer_id": 26343928,
"author": "joker",
"author_id": 1051589,
"author_profile": "https://Stackoverflow.com/users/1051589",
"pm_score": 3,
"selected": false,
"text": "<p>I am not adding a new answer. I am just putting the best marked answer in a better format.\nI can see that the best answer by rating is using <code>sys.stdout.write(someString)</code>. You can try this out:</p>\n\n<pre><code> import sys\n Print = sys.stdout.write\n Print(\"Hello\")\n Print(\"World\")\n</code></pre>\n\n<p>will yield:</p>\n\n<pre><code>HelloWorld\n</code></pre>\n\n<p>That is all.</p>\n"
},
{
"answer_id": 27295541,
"author": "Aaron McDaid",
"author_id": 146041,
"author_profile": "https://Stackoverflow.com/users/146041",
"pm_score": 0,
"selected": false,
"text": "<p><code>sys.stdout.write</code> is (in Python 2) the only robust solution. Python 2 printing is insane. Consider this code:</p>\n\n<pre><code>print \"a\",\nprint \"b\",\n</code></pre>\n\n<p>This will print <code>a b</code>, leading you to suspect that it is printing a trailing space. But this is not correct. Try this instead:</p>\n\n<pre><code>print \"a\",\nsys.stdout.write(\"0\")\nprint \"b\",\n</code></pre>\n\n<p>This will print <code>a0b</code>. How do you explain that? <strong><em>Where have the spaces gone?</em></strong></p>\n\n<p>I still can't quite make out what's really going on here. Could somebody look over my best guess:</p>\n\n<p><em>My attempt at deducing the rules when you have a trailing <code>,</code> on your <code>print</code></em>:</p>\n\n<p>First, let's assume that <code>print ,</code> (in Python 2) doesn't print any whitespace (spaces <em>nor</em> newlines).</p>\n\n<p>Python 2 does, however, pay attention to how you are printing - are you using <code>print</code>, or <code>sys.stdout.write</code>, or something else? If you make two <em>consecutive</em> calls to <code>print</code>, then Python will insist on putting in a space in between the two.</p>\n"
},
{
"answer_id": 29714273,
"author": "Mrinal",
"author_id": 4290713,
"author_profile": "https://Stackoverflow.com/users/4290713",
"pm_score": -1,
"selected": false,
"text": "<pre><code>import sys\na=raw_input()\nfor i in range(0,len(a)):\n sys.stdout.write(a[i])\n</code></pre>\n"
},
{
"answer_id": 42319647,
"author": "ahmed khattab",
"author_id": 6309432,
"author_profile": "https://Stackoverflow.com/users/6309432",
"pm_score": 0,
"selected": false,
"text": "<pre><code>print('''first line \\\nsecond line''')\n</code></pre>\n\n<p>it will produce </p>\n\n<blockquote>\n <p>first line second line</p>\n</blockquote>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4343/"
] |
In python, if I say
```
print 'h'
```
I get the letter h and a newline. If I say
```
print 'h',
```
I get the letter h and no newline. If I say
```
print 'h',
print 'm',
```
I get the letter h, a space, and the letter m. How can I prevent Python from printing the space?
The print statements are different iterations of the same loop so I can't just use the + operator.
|
```
import sys
sys.stdout.write('h')
sys.stdout.flush()
sys.stdout.write('m')
sys.stdout.flush()
```
You need to call [`sys.stdout.flush()`](https://docs.python.org/library/io.html#io.IOBase.flush) because otherwise it will hold the text in a buffer and you won't see it.
|
255,153 |
<p>how do i determine what a mysql db's charset is set to? in the cli?</p>
|
[
{
"answer_id": 255163,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "<pre><code>SHOW CREATE DATABASE db-name\n</code></pre>\n\n<p>Will show you the default character set for the database,</p>\n\n<pre><code>SHOW CREATE TABLE db-name.table-name\n</code></pre>\n\n<p>Will show you the character set for a specific table (along with a lot of other information).</p>\n"
},
{
"answer_id": 255242,
"author": "sebthebert",
"author_id": 24820,
"author_profile": "https://Stackoverflow.com/users/24820",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the command \"show table status\", </p>\n\n<p>it will show you a lot of information (including character set) about your tables</p>\n\n<p>mysql> show table status;</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18285/"
] |
how do i determine what a mysql db's charset is set to? in the cli?
|
```
SHOW CREATE DATABASE db-name
```
Will show you the default character set for the database,
```
SHOW CREATE TABLE db-name.table-name
```
Will show you the character set for a specific table (along with a lot of other information).
|
255,157 |
<p>In the context of a Google App Engine Webapp framework application:</p>
<p>I want to changed the request verb of a request in the case a
parameter _method is provided, for example if a POST request comes in
with a parameter _method=PUT, I need to change the request to call the
put method of the handler. This is to cope with the way prototype.js
works with verbs like PUT and DELETE(workaround for IE). Here is my
first attempt:</p>
<pre>
class MyRequestHandler(webapp.RequestHandler):
def initialize(self, request, response):
m = request.get('_method')
if m:
request.method = m.upper()
webapp.RequestHandler.initialize(self, request, response)
</pre>
<p>The problem is, for some reason whenever the redirect is done, the
self.request.params are emptied by the time the handling method(put or
delete) is called, even though they were populated when initialize was
called. Anyone have a clue why this is? As a workaround I thought I
could clone the params at initialize() time, but .copy() did not work,
and I haven't found a way to do that either.</p>
<p><em>Update: I received a very helpful response from Arachnid. The solution I ended up with uses a metaclass. It is found below.</em></p>
|
[
{
"answer_id": 255906,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 2,
"selected": false,
"text": "<p>Calling the handler from initialize isn't the right way anyway - if you do that, the webapp will then call the original handler as well.</p>\n\n<p>Instead, you have a couple of options:</p>\n\n<ul>\n<li>You can subclass webapp.WSGIApplication and override <strong>call</strong> to select the method based on _method when it exists.</li>\n<li>You can check for the existence of _method in initialize, and if it exists, modify the request object's 'REQUEST_METHOD' environment variable accordingly. That will cause the WSGIApplication class to execute the method you choose.</li>\n</ul>\n\n<p>Either way, take a look at google/appengine/ext/webapp/<strong>init</strong>.py in the SDK so you can see how it works.</p>\n"
},
{
"answer_id": 257094,
"author": "airportyh",
"author_id": 5304,
"author_profile": "https://Stackoverflow.com/users/5304",
"pm_score": 2,
"selected": false,
"text": "<p>Thats Arachnid for your response. Pointing me to the source of the framework was really helpful. Last I looked the source wasn't there(there was only .pyc), maybe it changed with the new version of the SDK. For my situation I think overriding WSGIApplication would have been the right thing to do. However, I chose to use a metaclass instead, because it didn't require me to cargo-cult(copy) a bunch of the framework code into my code and then modifying it. This is my solution:</p>\n\n<pre>\nclass RequestHandlerMetaclass(type):\n def __init__(cls, name, bases, dct):\n super(RequestHandlerMetaclass, cls).__init__(name, bases, dct)\n org_post = getattr(cls, 'post')\n def post(self, *params, **kws):\n verb = self.request.get('_method')\n if verb:\n verb = verb.upper()\n if verb == 'DELETE':\n self.delete(*params, **kws)\n elif verb == 'PUT':\n self.put(*params, **kws)\n else:\n org_post(self, *params, **kws)\n setattr(cls, 'post', post)\n\nclass MyRequestHandler(webapp.RequestHandler):\n __metaclass__ = RequestHandlerMetaclass\n</pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
] |
In the context of a Google App Engine Webapp framework application:
I want to changed the request verb of a request in the case a
parameter \_method is provided, for example if a POST request comes in
with a parameter \_method=PUT, I need to change the request to call the
put method of the handler. This is to cope with the way prototype.js
works with verbs like PUT and DELETE(workaround for IE). Here is my
first attempt:
```
class MyRequestHandler(webapp.RequestHandler):
def initialize(self, request, response):
m = request.get('_method')
if m:
request.method = m.upper()
webapp.RequestHandler.initialize(self, request, response)
```
The problem is, for some reason whenever the redirect is done, the
self.request.params are emptied by the time the handling method(put or
delete) is called, even though they were populated when initialize was
called. Anyone have a clue why this is? As a workaround I thought I
could clone the params at initialize() time, but .copy() did not work,
and I haven't found a way to do that either.
*Update: I received a very helpful response from Arachnid. The solution I ended up with uses a metaclass. It is found below.*
|
Calling the handler from initialize isn't the right way anyway - if you do that, the webapp will then call the original handler as well.
Instead, you have a couple of options:
* You can subclass webapp.WSGIApplication and override **call** to select the method based on \_method when it exists.
* You can check for the existence of \_method in initialize, and if it exists, modify the request object's 'REQUEST\_METHOD' environment variable accordingly. That will cause the WSGIApplication class to execute the method you choose.
Either way, take a look at google/appengine/ext/webapp/**init**.py in the SDK so you can see how it works.
|
255,170 |
<p>I am making a site that publishes articles in issues each month. It is straightforward, and I think using a Markdown editor (like the <a href="http://code.google.com/p/wmd/" rel="noreferrer">WMD</a> one here in Stack Overflow) would be perfect.</p>
<p>However, <strong>they do need the ability to have images right-aligned in a given paragraph</strong>.</p>
<p>I can't see a way to do that with the current system - is it possible?</p>
|
[
{
"answer_id": 255182,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 9,
"selected": true,
"text": "<p>You can embed HTML in Markdown, so you can do something like this:</p>\n\n<pre><code><img style=\"float: right;\" src=\"whatever.jpg\">\n\nContinue markdown text...\n</code></pre>\n"
},
{
"answer_id": 1228126,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code><div style=\"float:left;margin:0 10px 10px 0\" markdown=\"1\">\n \n</div>\n</code></pre>\n\n<p>The attribute <code>markdown</code> possibility inside Markdown.</p>\n"
},
{
"answer_id": 4178054,
"author": "ma11hew28",
"author_id": 242933,
"author_profile": "https://Stackoverflow.com/users/242933",
"pm_score": 3,
"selected": false,
"text": "<p>Even cleaner would be to just put <code>p#given img { float: right }</code> in the style sheet, or in the <code><head></code> and wrapped in <code>style</code> tags. Then, just use the markdown <code></code>.</p>\n"
},
{
"answer_id": 5054055,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Embedding CSS is bad:</p>\n\n<pre><code>\n</code></pre>\n\n<p>CSS in another file:</p>\n\n<pre><code>img[alt=Flowers] { float: right; }\n</code></pre>\n"
},
{
"answer_id": 8484967,
"author": "yoyo",
"author_id": 1095122,
"author_profile": "https://Stackoverflow.com/users/1095122",
"pm_score": -1,
"selected": false,
"text": "<p>Simplest is to wrap the image in a center tag, like so ...</p>\n\n<pre><code><center></center>\n</code></pre>\n\n<p>Anything to do with Markdown can be tested here - <a href=\"http://daringfireball.net/projects/markdown/dingus\" rel=\"nofollow\">http://daringfireball.net/projects/markdown/dingus</a></p>\n\n<p>Sure, <code><center></code> may be deprecated, but it's simple and it works!</p>\n"
},
{
"answer_id": 14508301,
"author": "learnvst",
"author_id": 276193,
"author_profile": "https://Stackoverflow.com/users/276193",
"pm_score": 5,
"selected": false,
"text": "<p>I like to be super lazy by using tables to align images with the vertical pipe (<code>|</code>) syntax. This is supported by some Markdown flavours (and is also supported by <a href=\"https://en.wikipedia.org/wiki/Textile_(markup_language)\" rel=\"noreferrer\">Textile</a> if that floats your boat):</p>\n\n<pre><code>| I am text to the left |  |\n</code></pre>\n\n<p>or</p>\n\n<pre><code>|  | I am text to the right |\n</code></pre>\n\n<p>It is not the most flexible solution, but it is good for most of my simple needs, is easy to read in markdown format, and you don't need to remember any CSS or raw HTML.</p>\n"
},
{
"answer_id": 16278366,
"author": "gerwitz",
"author_id": 5610,
"author_profile": "https://Stackoverflow.com/users/5610",
"pm_score": 6,
"selected": false,
"text": "<p>Many Markdown \"extra\" processors support attributes. So you can include a class name like so (PHP Markdown Extra):</p>\n\n<pre><code>{.callout}\n</code></pre>\n\n<p>or, alternatively (Maruku, <a href=\"https://kramdown.gettalong.org/syntax.html#attribute-list-definitions\" rel=\"noreferrer\">Kramdown</a>, <a href=\"https://pythonhosted.org/Markdown/extensions/attr_list.html\" rel=\"noreferrer\">Python Markdown</a>):</p>\n\n<pre><code>{: .callout}\n</code></pre>\n\n<p>Then, of course, you can use a stylesheet the proper way:\n</p>\n\n<pre><code>.callout {\n float: right;\n}\n</code></pre>\n\n<p>If yours supports this syntax, it gives you the best of both worlds: no embedded markup, and a stylesheet abstract enough to not need to be modified by your content editor.</p>\n"
},
{
"answer_id": 16372869,
"author": "abbood",
"author_id": 766570,
"author_profile": "https://Stackoverflow.com/users/766570",
"pm_score": 2,
"selected": false,
"text": "<p>As greg <a href=\"https://stackoverflow.com/a/255182/766570\">said</a> you can embed HTML content in Markdown, but one of the points of Markdown is to avoid having to have extensive (or any, for that matter) CSS/HTML markup knowledge, right? This is what I do:</p>\n\n<p>In my Markdown file I simply instruct all my wiki editors to embed wrap all images with something that looks like this:</p>\n\n<pre><code>'<div> // Put image here </div>`\n</code></pre>\n\n<p>(of course.. they don't know what <code><div></code> means, but that shouldn't matter)</p>\n\n<p>So the Markdown file looks like this:</p>\n\n<pre><code><div>\n![optional image description][1]\n</div>\n\n[1]: /image/path\n</code></pre>\n\n<p>And in the CSS content that wraps the whole page I can do whatever I want with the image tag:</p>\n\n<pre><code>img {\n float: right;\n}\n</code></pre>\n\n<p>Of course you can do more with the CSS content... (in this particular case, wrapping the <code>img</code> tag with div prevents other text from wrapping against the image... this is just an example, though), but IMHO the point of <em>Markdown</em> is that you don't want potentially non-technical people getting into the ins and outs of CSS/HTML.. it's up to you as a web developer to make your CSS content that wraps the page as generic and clean as possible, but then again your editors need not know about that.</p>\n"
},
{
"answer_id": 19040921,
"author": "jameh",
"author_id": 1402511,
"author_profile": "https://Stackoverflow.com/users/1402511",
"pm_score": 3,
"selected": false,
"text": "<p>If you implement it in Python, there is <a href=\"http://pythonhosted.org/Markdown/extensions/attr_list.html\" rel=\"nofollow noreferrer\">an extension</a> that lets you add HTML key/value pairs, and class/id labels. The syntax is for this is:</p>\n\n<pre><code>{: style=\"float:right\"}\n</code></pre>\n\n<p>Or, if embedded styling doesn't float your boat,</p>\n\n<pre><code>{: .floatright}\n</code></pre>\n\n<p>with a corresponding stylesheet, <code>stylish.css</code>:</p>\n\n<pre><code>.floatright {\n float: right;\n /* etc. */\n}\n</code></pre>\n"
},
{
"answer_id": 37607513,
"author": "icarito",
"author_id": 1112124,
"author_profile": "https://Stackoverflow.com/users/1112124",
"pm_score": 3,
"selected": false,
"text": "<p>I liked <a href=\"https://stackoverflow.com/a/14508301/1112124\">learnvst's answer</a> of using the tables because it is quite readable (which is one purpose of writing Markdown).</p>\n\n<p>However, in the case of GitBook's Markdown parser I had to, in addition to an empty header line, add a separator line under it, for the table to be recognized and properly rendered:</p>\n\n<pre><code>| - | - |\n|---|---|\n| I am text to the left |  |\n|  | I am text to the right |\n</code></pre>\n\n<p>Separator lines need to include at least three dashes <code>---</code> .</p>\n"
},
{
"answer_id": 39614958,
"author": "OzzyCzech",
"author_id": 355316,
"author_profile": "https://Stackoverflow.com/users/355316",
"pm_score": 7,
"selected": false,
"text": "<p>I found a nice solution in <strong>pure Markdown</strong> with a little <strong>CSS 3 hack</strong> :-)</p>\n\n<pre><code>\n\n\n</code></pre>\n\n<p>Follow the CSS 3 code float image on the left or right, when the <code>image alt</code> ends with <code><</code> or <code>></code>.</p>\n\n<pre><code>img[alt$=\">\"] {\n float: right;\n}\n\nimg[alt$=\"<\"] {\n float: left;\n}\n\nimg[alt$=\"><\"] {\n display: block;\n max-width: 100%;\n height: auto;\n margin: auto;\n float: none!important;\n}\n</code></pre>\n"
},
{
"answer_id": 43691462,
"author": "tremor",
"author_id": 2839538,
"author_profile": "https://Stackoverflow.com/users/2839538",
"pm_score": 6,
"selected": false,
"text": "<p>I have an alternative to the methods above that used the ALT tag and a CSS selector on the alt tag... Instead, add a URL hash like this:</p>\n\n<p>First your Markdown image code:</p>\n\n<pre><code>\n\n\n</code></pre>\n\n<p>Note the added URL hash #center.</p>\n\n<p>Now add this rule in CSS using CSS 3 attribute selectors to select images with a certain path.</p>\n\n<pre><code>img[src*='#left'] {\n float: left;\n}\nimg[src*='#right'] {\n float: right;\n}\nimg[src*='#center'] {\n display: block;\n margin: auto;\n}\n</code></pre>\n\n<p>You should be able to use a URL hash like this almost like defining a class name and it isn't a misuse of the ALT tag like some people had commented about for that solution. It also won't require any additional extensions. Do one for float right and left as well or any other styles you might want.</p>\n"
},
{
"answer_id": 48699229,
"author": "Zuha Karim",
"author_id": 7589751,
"author_profile": "https://Stackoverflow.com/users/7589751",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same task, and I aligned my images to the right by adding this:</p>\n\n<pre><code><div style=\"text-align: right\"><img src=\"/default/image/sms.png\" width=\"100\" /></div>\n</code></pre>\n\n<p>For aligning your image to the left or center, replace</p>\n\n<pre><code><div style=\"text-align: right\">\n</code></pre>\n\n<p>with</p>\n\n<pre><code><div style=\"text-align: center\">\n<div style=\"text-align: left\">\n</code></pre>\n"
},
{
"answer_id": 61921006,
"author": "Andersonfrfilho",
"author_id": 8157632,
"author_profile": "https://Stackoverflow.com/users/8157632",
"pm_score": -1,
"selected": false,
"text": "<p>this work for me </p>\n\n<pre class=\"lang-html prettyprint-override\"><code><p align=\"center\">\n <img src=\"/LogoOfficial.png\" width=\"300\" >\n</p>\n</code></pre>\n"
},
{
"answer_id": 69747905,
"author": "rahul-ahuja",
"author_id": 12818901,
"author_profile": "https://Stackoverflow.com/users/12818901",
"pm_score": -1,
"selected": false,
"text": "<p><b>Align image and text side-by-side as part of a paragraph in a single block, within a warning box.</b></p>\n<pre><code><div class="warning" style='background-color:#EDF2F7; color:#1A2067; border-left: solid #718096 4px; border-radius: 4px;'>\n<p style='padding:0.7em; margin-left:0.7em; display: inline-block;'>\n<img src="typora_images/image-20211028083121348.png" style="zoom:70%; float:right; padding:0.7em"/>\n<b>isomorphism</b> &rarr; In mathematics, an isomorphism is a structure-preserving mapping between two structures of the same type that can be reversed by an inverse mapping.<br>\n</p>\n</div>\n</code></pre>\n<p><b>Output :</b></p>\n<p><a href=\"https://i.stack.imgur.com/EAVm6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EAVm6.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 71658868,
"author": "dopexxx",
"author_id": 6383205,
"author_profile": "https://Stackoverflow.com/users/6383205",
"pm_score": -1,
"selected": false,
"text": "<p>I think the easiest solution is to directly specify <code>align="right"</code>:</p>\n<pre><code><img align="right" src=/logo.png" alt="logo" width="100"/>\n</code></pre>\n"
},
{
"answer_id": 71981760,
"author": "Chetan B B",
"author_id": 17783052,
"author_profile": "https://Stackoverflow.com/users/17783052",
"pm_score": 0,
"selected": false,
"text": "<p>You can directly use align property:</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> <img align=\"right\" width=\"100\" height=\"100\" src=\"https://images.unsplash.com/photo-1650620109005-099c2de720f8?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxM3x8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60\"></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 73398133,
"author": "N. Joppi",
"author_id": 8832723,
"author_profile": "https://Stackoverflow.com/users/8832723",
"pm_score": 0,
"selected": false,
"text": "<p>The best and most customizable option:</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 style=\"display:flex; align-items: center;\">\n <div style=\"flex:1\">\n <img src=\"https://www.researchgate.net/profile/Jinsong-Chong/publication/233165295/figure/fig5/AS:667635838640135@1536188196882/Initial-contour-Figure-9-Detection-result-in-low-resolution-image-in-low-resolution-image.ppm\"/>\n </div>\n <div style=\"flex:1;padding-left:10px;\">\n <img src=\"https://www.researchgate.net/profile/Miguel-Vega-4/publication/228966464/figure/fig1/AS:669376512544781@1536603205341/a-Observed-low-resolution-multispectral-image-b-Panchromatic-image-c.ppm\" />\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This will align the first to the left, and the second to the right. Works for more than 2 images too.</p>\n"
},
{
"answer_id": 73721756,
"author": "Bill Hoag",
"author_id": 40422,
"author_profile": "https://Stackoverflow.com/users/40422",
"pm_score": 0,
"selected": false,
"text": "<p>For a simple approach to just indenting your image a bit, just use some non-breaking spaces with an <code>img</code> element. E.g., <code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src="https://user-images.githubusercontent.com/123456/123456789-3aabedfe-deab-4242-97a0-a6641e675e68.png" /></code></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9913/"
] |
I am making a site that publishes articles in issues each month. It is straightforward, and I think using a Markdown editor (like the [WMD](http://code.google.com/p/wmd/) one here in Stack Overflow) would be perfect.
However, **they do need the ability to have images right-aligned in a given paragraph**.
I can't see a way to do that with the current system - is it possible?
|
You can embed HTML in Markdown, so you can do something like this:
```
<img style="float: right;" src="whatever.jpg">
Continue markdown text...
```
|
255,189 |
<p>If I have a type defined as a <strong>set of</strong> an enumerated type, it's easy to create an empty set with [], but how do I create a <em>full</em> set?</p>
<p>EDIT: Yeah, the obvious solution is to use a for loop. That's also a really bad solution if there's another way. Does anyone know of a way that'll work in constant time?</p>
|
[
{
"answer_id": 255321,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 3,
"selected": false,
"text": "<p>Per Barry's suggestion:</p>\n\n<pre><code>FillChar(VarSet, SizeOf(VarSet), $FF);\n</code></pre>\n"
},
{
"answer_id": 257903,
"author": "Gerry Coll",
"author_id": 22545,
"author_profile": "https://Stackoverflow.com/users/22545",
"pm_score": 5,
"selected": true,
"text": "<p>Low() and High() are \"compiler magic\" functions that can be evaluated at compile time.\nThis allows their use in constant declarations like the following:</p>\n\n<pre>\nvar\n MySet : TBorderIcons;\n MySet2 : TBorderIcons;\nconst\n AllIcons : TBorderIcons = [Low(TBorderIcon)..High(TBorderIcon)];\nbegin\n MySet := [Low(TBorderIcon)..High(TBorderIcon)];\n MySet2 := AllIcons;\nend;\n</pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32914/"
] |
If I have a type defined as a **set of** an enumerated type, it's easy to create an empty set with [], but how do I create a *full* set?
EDIT: Yeah, the obvious solution is to use a for loop. That's also a really bad solution if there's another way. Does anyone know of a way that'll work in constant time?
|
Low() and High() are "compiler magic" functions that can be evaluated at compile time.
This allows their use in constant declarations like the following:
```
var
MySet : TBorderIcons;
MySet2 : TBorderIcons;
const
AllIcons : TBorderIcons = [Low(TBorderIcon)..High(TBorderIcon)];
begin
MySet := [Low(TBorderIcon)..High(TBorderIcon)];
MySet2 := AllIcons;
end;
```
|
255,194 |
<p>I'm working on a Grails project using Hibernate (GORM). I have the following Domain Models:</p>
<pre><code>ClientContact {
static hasMany = [owners: Person]
static belongsTo = [Person]
}
Person {
static hasMany = [clientContacts: ClientContact]
}
</code></pre>
<p>When I try to retrieve all the <code>ClientContacts</code> with a specific owner (<code>Person</code>), I'm running into some funny issues. I'm using the following query criteria:</p>
<pre><code>def query = {
owners {
eq("id", Long.parseLong(params.ownerId))
}
}
def criteria = ClientContact.createCriteria()
def results = criteria.list(params, query)
</code></pre>
<p>The problem is when I iterate through each of my <code>ClientContacts</code> in the results, they only have <strong>the one owner</strong> - when in fact, most have many other owners. What gives? I know hibernate/GORM uses lazy fetching, but I thought it would fetch all of the other owners on a <code>ClientContact</code> when I tried to access them.</p>
<p>Any thoughts? I would like to continue using the <em>list()</em> function since it provides some nice paging features.</p>
|
[
{
"answer_id": 255295,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 0,
"selected": false,
"text": "<p>Two quick observations:</p>\n\n<ol>\n<li>The [Grails Documentation](<a href=\"http://grails.org/doc/1.0.x/guide/5.%20Object%20Relational%20Mapping%20(GORM).html#5.2.1.3\" rel=\"nofollow noreferrer\">http://grails.org/doc/1.0.x/guide/5.%20Object%20Relational%20Mapping%20(GORM).html#5.2.1.3</a> Many-to-many) says that a <strong>many-to-many</strong> association has to be manually coded, the default scaffolding won't do it. </li>\n<li>You may need to use the <code>eqId()</code> criterion - see <a href=\"http://grails.org/doc/1.0.x/ref/Domain%20Classes/createCriteria.html\" rel=\"nofollow noreferrer\">createCriteria</a></li>\n</ol>\n"
},
{
"answer_id": 311865,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 0,
"selected": false,
"text": "<p>id and version are special properties of all GORM classes. You don't need to specify them in the class declaration, and you can't use the standard criterion with them.</p>\n\n<p>You definitely need to use the eqID criterion</p>\n\n<pre><code> def query = {\n owners {\n eqId(Long.parseLong(params.ownerId))\n }\n }\n def criteria = ClientContact.createCriteria()\n def results = criteria.list(params, query)\n</code></pre>\n"
},
{
"answer_id": 9035504,
"author": "Pawel Gwozdz",
"author_id": 1173774,
"author_profile": "https://Stackoverflow.com/users/1173774",
"pm_score": 3,
"selected": true,
"text": "<p>I know this thread is very old, but I just encountered exactly the same problem today and the solution seems to be usage of aliases, so instead:</p>\n\n<pre><code>def query = {\n owners {\n eq(\"id\", Long.parseLong(params.ownerId))\n }\n}\n</code></pre>\n\n<p>one can try:</p>\n\n<pre><code>def query = {\n createAlias(\"owners\", \"o\")\n eq(\"o.id\", Long.parseLong(params.ownerId))\n}\n</code></pre>\n\n<p>The first query creates left outer joins and the second creates inner joins. Please see this link for more detailed description: <a href=\"http://adhockery.blogspot.com/2009/06/querying-by-association-redux.html\" rel=\"nofollow\">http://adhockery.blogspot.com/2009/06/querying-by-association-redux.html</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21832/"
] |
I'm working on a Grails project using Hibernate (GORM). I have the following Domain Models:
```
ClientContact {
static hasMany = [owners: Person]
static belongsTo = [Person]
}
Person {
static hasMany = [clientContacts: ClientContact]
}
```
When I try to retrieve all the `ClientContacts` with a specific owner (`Person`), I'm running into some funny issues. I'm using the following query criteria:
```
def query = {
owners {
eq("id", Long.parseLong(params.ownerId))
}
}
def criteria = ClientContact.createCriteria()
def results = criteria.list(params, query)
```
The problem is when I iterate through each of my `ClientContacts` in the results, they only have **the one owner** - when in fact, most have many other owners. What gives? I know hibernate/GORM uses lazy fetching, but I thought it would fetch all of the other owners on a `ClientContact` when I tried to access them.
Any thoughts? I would like to continue using the *list()* function since it provides some nice paging features.
|
I know this thread is very old, but I just encountered exactly the same problem today and the solution seems to be usage of aliases, so instead:
```
def query = {
owners {
eq("id", Long.parseLong(params.ownerId))
}
}
```
one can try:
```
def query = {
createAlias("owners", "o")
eq("o.id", Long.parseLong(params.ownerId))
}
```
The first query creates left outer joins and the second creates inner joins. Please see this link for more detailed description: <http://adhockery.blogspot.com/2009/06/querying-by-association-redux.html>
|
255,202 |
<p>When I type <code>git diff</code>, I want to view the output with my visual diff tool of choice (SourceGear "diffmerge" on Windows). How do I configure git to do this?</p>
|
[
{
"answer_id": 255212,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 10,
"selected": true,
"text": "<p>Since Git1.6.3, you can use the <strong>git difftool script</strong>: see <a href=\"https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/949242#949242\">my answer below</a>.</p>\n\n<hr>\n\n<p>May be this <a href=\"https://web.archive.org/web/20170508180316/http://git.net:80/ml/version-control.msysgit/2008-06/msg00200.html\" rel=\"noreferrer\">article</a> will help you. Here are the best parts:</p>\n\n<p>There are two different ways to specify an external diff tool. </p>\n\n<p>The first is the method you used, by setting the GIT_EXTERNAL_DIFF variable. However, the variable is supposed to point to the full path of the executable. Moreover, the executable specified by GIT_EXTERNAL_DIFF will be called with a fixed set of 7 arguments:</p>\n\n<pre><code>path old-file old-hex old-mode new-file new-hex new-mode\n</code></pre>\n\n<p>As most diff tools will require a different order (and only some) of the arguments, you will most likely have to specify a wrapper script instead, which in turn calls the real diff tool.</p>\n\n<p>The second method, which I prefer, is to <strong>configure the external diff tool via \"git\nconfig\"</strong>. Here is what I did:</p>\n\n<p>1) Create a wrapper script \"git-diff-wrapper.sh\" which contains something like</p>\n\n<pre><code>-->8-(snip)--\n#!/bin/sh\n\n# diff is called by git with 7 parameters:\n# path old-file old-hex old-mode new-file new-hex new-mode\n\n\"<path_to_diff_executable>\" \"$2\" \"$5\" | cat\n--8<-(snap)--\n</code></pre>\n\n<p>As you can see, only the second (\"old-file\") and fifth (\"new-file\") arguments will be\npassed to the diff tool.</p>\n\n<p>2) Type</p>\n\n<pre><code>$ git config --global diff.external <path_to_wrapper_script>\n</code></pre>\n\n<p>at the command prompt, replacing with the path to \"git-diff-wrapper.sh\", so your ~/.gitconfig contains</p>\n\n<pre><code>-->8-(snip)--\n[diff]\n external = <path_to_wrapper_script>\n--8<-(snap)--\n</code></pre>\n\n<p>Be sure to use the correct syntax to specify the paths to the wrapper script and diff\ntool, i.e. use forward slashed instead of backslashes. In my case, I have</p>\n\n<pre><code>[diff]\n external = \\\"c:/Documents and Settings/sschuber/git-diff-wrapper.sh\\\"\n</code></pre>\n\n<p>in .gitconfig and</p>\n\n<pre><code>\"d:/Program Files/Beyond Compare 3/BCompare.exe\" \"$2\" \"$5\" | cat\n</code></pre>\n\n<p>in the wrapper script. Mind the trailing \"cat\"!</p>\n\n<p>(I suppose the '<code>| cat</code>' is needed only for some programs which may not return a proper or consistent return status. You might want to try without the trailing cat if your diff tool has explicit return status)</p>\n\n<p>(<a href=\"https://stackoverflow.com/users/20520/diomidis-spinellis\">Diomidis Spinellis</a> adds <a href=\"https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-my-preferred-diff-tool-viewer/255212#comment96247087_255212\">in the comments</a>: </p>\n\n<blockquote>\n <p>The <code>cat</code> command is required, because <a href=\"http://man7.org/linux/man-pages/man1/diff.1.html\" rel=\"noreferrer\"><code>diff(1)</code></a>, by default exits with an error code if the files differ.<br>\n Git expects the external diff program to exit with an error code only if an actual error occurred, e.g. if it run out of memory.<br>\n By piping the output of <code>git</code> to <code>cat</code> the non-zero error code is masked.<br>\n More efficiently, the program could just run <code>exit</code> with and argument of 0.)</p>\n</blockquote>\n\n<hr>\n\n<p>That (the article quoted above) is the theory for external tool <strong>defined through config file</strong> (not through environment variable).<br>\nIn practice (still for config file definition of external tool), you can refer to:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/780425/how-do-i-setup-diffmerge-with-msysgit-gitk/783667#783667\">How do I setup DiffMerge with msysgit / gitk?</a> which illustrates the concrete settings of DiffMerge and WinMerge for MsysGit and gitk</li>\n<li><a href=\"https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/773973#773973\">How can I set up an editor to work with Git on Windows?</a> for the definition of Notepad++ as an external editor.</li>\n</ul>\n"
},
{
"answer_id": 392899,
"author": "Milan Gardian",
"author_id": 23843,
"author_profile": "https://Stackoverflow.com/users/23843",
"pm_score": 3,
"selected": false,
"text": "<h2>Introduction</h2>\n<p>For reference I'd like to include my variation on <a href=\"https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-my-preferred-diff-tool-viewer/255212#255212\">VonC's answer</a>. Keep in mind that I am using the MSys version of Git (1.6.0.2 at this time) with modified PATH, and running Git itself from PowerShell (or cmd.exe), not the Bash shell.</p>\n<p>I introduced a new command, <code>gitdiff</code>. Running this command temporarily redirects <code>git diff</code> to use a visual diff program of your choice (as opposed to VonC's solution that does it permanently). This allows me to have both the default Git diff functionality (<code>git diff</code>) as well as visual diff functionality (<code>gitdiff</code>). Both commands take the same parameters, so for example to visually diff changes in a particular file you can type</p>\n<pre><code>gitdiff path/file.txt\n</code></pre>\n<h2>Setup</h2>\n<p>Note that <code>$GitInstall</code> is used as a placeholder for the directory where Git is installed.</p>\n<ol>\n<li><p>Create a new file, <code>$GitInstall\\cmd\\gitdiff.cmd</code></p>\n<pre><code> @echo off\n setlocal\n for /F "delims=" %%I in ("%~dp0..") do @set path=%%~fI\\bin;%%~fI\\mingw\\bin;%PATH%\n if "%HOME%"=="" @set HOME=%USERPROFILE%\n set GIT_EXTERNAL_DIFF=git-diff-visual.cmd\n set GIT_PAGER=cat\n git diff %*\n endlocal\n</code></pre>\n</li>\n<li><p>Create a new file, <code>$GitInstall\\bin\\git-diff-visual.cmd</code> (replacing <code>[visual_diff_exe]</code> placeholder with full path to the diff program of your choice)</p>\n<pre><code> @echo off\n rem diff is called by git with 7 parameters:\n rem path old-file old-hex old-mode new-file new-hex new-mode\n echo Diffing "%5"\n "[visual_diff_exe]" "%2" "%5"\n exit 0\n</code></pre>\n</li>\n<li><p>You're now done. Running <code>gitdiff</code> from within a Git repository should now invoke your visual diff program for every file that was changed.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 573579,
"author": "Steve Hanov",
"author_id": 15947,
"author_profile": "https://Stackoverflow.com/users/15947",
"pm_score": 4,
"selected": false,
"text": "<h2>Solution for Windows/<a href=\"https://en.wikipedia.org/wiki/MinGW#History\" rel=\"nofollow noreferrer\">MSYS</a> Git</h2>\n<p>After reading the answers, I discovered a simpler way that involves changing only one file.</p>\n<ol>\n<li><p>Create a batch file to invoke your diff program, with argument 2 and 5. This file must be somewhere in your path. (If you don't know where that is, put it in <em>C:\\windows</em>.) Call it, for example, "gitdiff.bat". Mine is:</p>\n<pre><code>@echo off\nREM This is gitdiff.bat\n"C:\\Program Files\\WinMerge\\WinMergeU.exe" %2 %5\n</code></pre>\n</li>\n<li><p>Set the environment variable to point to your batch file. For example:<code>GIT_EXTERNAL_DIFF=gitdiff.bat</code>. Or through PowerShell by typing <code>git config --global diff.external gitdiff.bat</code>.</p>\n<p>It is important to not use quotes, or specify any path information, otherwise it won't work. That's why <em>gitdiff.bat</em> must be in your path.</p>\n</li>\n</ol>\n<p>Now when you type "git diff", it will invoke your external diff viewer.</p>\n"
},
{
"answer_id": 732555,
"author": "Brad Robinson",
"author_id": 77002,
"author_profile": "https://Stackoverflow.com/users/77002",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a batch file that works for Windows - assumes DiffMerge installed in default location, handles x64, handles forward to backslash replacement as necessary and has ability to install itself. Should be easy to replace DiffMerge with your favourite diff program.</p>\n\n<p>To install:</p>\n\n<pre><code>gitvdiff --install \n</code></pre>\n\n<p>gitvdiff.bat:</p>\n\n<pre><code>@echo off\n\nREM ---- Install? ----\nREM To install, run gitvdiff --install\n\nif %1==--install goto install\n\n\n\nREM ---- Find DiffMerge ----\n\nif DEFINED ProgramFiles^(x86^) (\n Set DIFF=\"%ProgramFiles(x86)%\\SourceGear\\DiffMerge\\DiffMerge.exe\"\n) else (\n Set DIFF=\"%ProgramFiles%\\SourceGear\\DiffMerge\\DiffMerge.exe\"\n)\n\n\n\nREM ---- Switch forward slashes to back slashes ----\n\nset oldW=%2\nset oldW=%oldW:/=\\%\nset newW=%5\nset newW=%newW:/=\\%\n\n\nREM ---- Launch DiffMerge ----\n\n%DIFF% /title1=\"Old Version\" %oldW% /title2=\"New Version\" %newW%\n\ngoto :EOF\n\n\n\nREM ---- Install ----\n:install\nset selfL=%~dpnx0\nset selfL=%selfL:\\=/%\n@echo on\ngit config --global diff.external %selfL%\n@echo off\n\n\n:EOF\n</code></pre>\n"
},
{
"answer_id": 901386,
"author": "Jakub Narębski",
"author_id": 46058,
"author_profile": "https://Stackoverflow.com/users/46058",
"pm_score": 5,
"selected": false,
"text": "<p>Since Git version 1.6.3 there is "<strong><a href=\"http://schacon.github.com/git/git-difftool.html\" rel=\"nofollow noreferrer\" title=\"git-difftool - Show changes using common diff tools\">git difftool</a></strong>" which you can configure to use your favorite graphical diff tool.</p>\n<p>Currently supported (at the time of writing this answer) out-of-the-box are <em><a href=\"http://kdiff3.sourceforge.net/\" rel=\"nofollow noreferrer\">KDiff3</a>, <a href=\"https://apps.kde.org/kompare/\" rel=\"nofollow noreferrer\">Kompare</a>, <a href=\"https://tkdiff.sourceforge.io/\" rel=\"nofollow noreferrer\">tkdiff</a>, <a href=\"http://meldmerge.org/\" rel=\"nofollow noreferrer\">Meld</a>, <a href=\"http://furius.ca/xxdiff/\" rel=\"nofollow noreferrer\">xxdiff</a>, emerge, vimdiff, gvimdiff, ecmerge, <a href=\"http://diffuse.sourceforge.net/index.html\" rel=\"nofollow noreferrer\">Diffuse</a></em> and <em>opendiff</em>; if the tool you want to use isn't on this list, you can always use '<code>difftool.<tool>.cmd</code>' configuration option.</p>\n<p>"git difftool" accepts the same options as "git diff".</p>\n"
},
{
"answer_id": 949242,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 8,
"selected": false,
"text": "<p>To complete my previous <a href=\"https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/255212#255212\">"diff.external" config answer</a> above:</p>\n<p>As <a href=\"https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/901386#901386\">mentioned by Jakub</a>, Git1.6.3 introduced <a href=\"http://marc.info/?l=git&m=123025539212603&w=2\" rel=\"noreferrer\">git <strong>difftool</strong></a>, originally proposed in September 2008:</p>\n<p>USAGE=<code>'[--tool=tool] [--commit=ref] [--start=ref --end=ref] [--no-prompt] [file to merge]'</code><br />\n(See <code>--extcmd</code> in the last part of this answer)</p>\n<p><code>$LOCAL</code> contains the contents of the file from the starting revision and <code>$REMOTE</code> contains the contents of the file in the ending revision.<br />\n<code>$BASE</code> contains the contents of the file in the wor</p>\n<blockquote>\n<p>It's basically <code>git-mergetool</code> modified to operate on the git index/worktree.</p>\n<p>The usual use case for this script is when you have either staged or unstaged changes and you'd like to see the changes in a side-by-side diff viewer (e.g. <code>xxdiff</code>, <code>tkdiff</code>, etc).</p>\n</blockquote>\n<pre><code>git difftool [<filename>*]\n</code></pre>\n<blockquote>\n<p>Another use case is when you'd like to see the same information but are comparing arbitrary commits (this is the part where the revarg parsing could be better)</p>\n</blockquote>\n<pre><code>git difftool --start=HEAD^ --end=HEAD [-- <filename>*]\n</code></pre>\n<p>The last use case is when you'd like to compare your current worktree to something other than HEAD (e.g. a tag)</p>\n<pre><code>git difftool --commit=v1.0.0 [-- <filename>*]\n</code></pre>\n<p><strong>Note: since Git 2.5, <code>git config diff.tool winmerge</code> is enough!</strong><br />\nSee "<a href=\"https://stackoverflow.com/a/30699239/6309\">git mergetool winmerge</a>"</p>\n<p>And <a href=\"https://stackoverflow.com/a/10879804/6309\">since Git 1.7.11</a>, you have the option <code>--dir-diff</code>, in order to to spawn external diff tools that can compare two directory hierarchies at a time after populating two temporary directories, instead of running an instance of the external tool once per a file pair.</p>\n<hr />\n<p>Before Git 2.5:</p>\n<p>Practical case for configuring <code>difftool</code> with your custom diff tool:</p>\n<pre><code>C:\\myGitRepo>git config --global diff.tool winmerge\nC:\\myGitRepo>git config --global difftool.winmerge.cmd "winmerge.sh \\"$LOCAL\\" \\"$REMOTE\\""\nC:\\myGitRepo>git config --global difftool.prompt false\n</code></pre>\n<p>With winmerge.sh stored in a directory part of your PATH:</p>\n<pre><code>#!/bin/sh\necho Launching WinMergeU.exe: $1 $2\n"C:/Program Files/WinMerge/WinMergeU.exe" -u -e "$1" "$2" -dl "Local" -dr "Remote"\n</code></pre>\n<p>If you have another tool (kdiff3, P4Diff, ...), create another shell script, and the appropriate <code>difftool.myDiffTool.cmd</code> config directive.<br />\nThen you can easily switch tools with the <code>diff.tool</code> config.</p>\n<p>You have also this <a href=\"http://www.davesquared.net/2009/05/setting-up-git-difftool-on-windows.html\" rel=\"noreferrer\">blog entry by Dave</a> to add other details.<br />\n(Or <a href=\"https://stackoverflow.com/q/2468230/6309\">this question</a> for the <code>winmergeu</code> options)</p>\n<p>The interest with this setting is the <strong><code>winmerge.sh</code>script</strong>: you can customize it to take into account special cases.</p>\n<p>See for instance <a href=\"https://stackoverflow.com/users/216735/david-marble\">David Marble</a>'s <a href=\"https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/4116806#4116806\">answer below</a> for an example which deals with:</p>\n<ul>\n<li><em>new</em> files in either origin or destination</li>\n<li><em>removed</em> files in either origin or destination</li>\n</ul>\n<hr />\n<p>As <a href=\"https://stackoverflow.com/users/398582/kem-mason\">Kem Mason</a> mentions in <a href=\"https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/4881489#4881489\">his answer</a>, you can also <strong>avoid any wrapper by using the <code>--extcmd</code> option</strong>:</p>\n<pre><code>--extcmd=<command>\n</code></pre>\n<blockquote>\n<p>Specify a custom command for viewing diffs. <code>git-difftool</code> ignores the configured defaults and runs <strong><code>$command $LOCAL $REMOTE</code></strong> when this option is specified.</p>\n</blockquote>\n<p>For instance, this is how <a href=\"http://git.661346.n2.nabble.com/PATCH-gitk-Use-git-difftool-for-external-diffs-td4810847.html\" rel=\"noreferrer\"><code>gitk</code> is able to run/use any <code>diff</code> tool</a>.</p>\n"
},
{
"answer_id": 1339962,
"author": "Seba Illingworth",
"author_id": 93451,
"author_profile": "https://Stackoverflow.com/users/93451",
"pm_score": 6,
"selected": false,
"text": "<p>With new git <em>difftool</em>, its as simple as adding this to your <em>.gitconfig</em> file:</p>\n\n<pre><code>[diff]\n tool = any-name\n[difftool \"any-name\"]\n cmd = \"\\\"C:/path/to/my/ext/diff.exe\\\" \\\"$LOCAL\\\" \\\"$REMOTE\\\"\"\n</code></pre>\n\n<p>Optionally, also add:</p>\n\n<pre><code>[difftool]\n prompt = false\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/1220309/git-difftool-open-all-diff-files-immediately-not-in-serial/1291578#1291578\">Also check out <strong><em>diffall</em></strong></a>, a simple script I wrote to extend the annoying (IMO) default diff behaviour of opening each in serial.</p>\n\n<p>Global .gitconfig on Windows is in <code>%USERPROFILE%\\.gitconfig</code></p>\n"
},
{
"answer_id": 1607200,
"author": "Fire Crow",
"author_id": 80479,
"author_profile": "https://Stackoverflow.com/users/80479",
"pm_score": 3,
"selected": false,
"text": "<p>For a Linux version of how to configure a diff tool on Git versions prior to 1.6.3 (1.6.3 added difftool to Git), <a href=\"http://technotales.wordpress.com/2009/05/17/git-diff-with-vimdiff/\" rel=\"nofollow noreferrer\">this</a> is a great concise tutorial.</p>\n<p>In brief:</p>\n<p>Step 1: add this to your .gitconfig</p>\n<pre><code>[diff]\n external = git_diff_wrapper\n[pager]\n diff =\n</code></pre>\n<p>Step 2: create a file named git_diff_wrapper, put it somewhere in your $PATH</p>\n<pre><code>#!/bin/sh\n\nvimdiff "$2" "$5"\n</code></pre>\n"
},
{
"answer_id": 2267755,
"author": "Bilal and Olga",
"author_id": 253511,
"author_profile": "https://Stackoverflow.com/users/253511",
"pm_score": 1,
"selected": false,
"text": "<p>I use <a href=\"https://en.wikipedia.org/wiki/Kompare\" rel=\"nofollow noreferrer\">Kompare</a> on Ubuntu:</p>\n<pre><code>sudo apt-get install kompare\n</code></pre>\n<p>To compare two branches:</p>\n<pre><code>git difftool -t kompare <my_branch> master\n</code></pre>\n"
},
{
"answer_id": 2442822,
"author": "Charles Merriam",
"author_id": 1320510,
"author_profile": "https://Stackoverflow.com/users/1320510",
"pm_score": 7,
"selected": false,
"text": "<p>Try this solution:</p>\n<pre><code>$ meld my_project_using_git\n</code></pre>\n<p><a href=\"http://meldmerge.org/\" rel=\"nofollow noreferrer\">Meld</a> understands Git and provides navigating around the recent changes.</p>\n"
},
{
"answer_id": 2547322,
"author": "idbrii",
"author_id": 79125,
"author_profile": "https://Stackoverflow.com/users/79125",
"pm_score": 3,
"selected": false,
"text": "<p>If you're doing this through <a href=\"https://en.wikipedia.org/wiki/Cygwin\" rel=\"nofollow noreferrer\">Cygwin</a>, you may need to use <strong>cygpath</strong>:</p>\n<pre><code>$ git config difftool.bc3.cmd "git-diff-bcomp-wrapper.sh \\$LOCAL \\$REMOTE"\n$ cat git-diff-bcomp-wrapper.sh\n#!/bin/sh\n"c:/Program Files (x86)/Beyond Compare 3/BComp.exe" `cygpath -w $1` `cygpath -w $2`\n</code></pre>\n"
},
{
"answer_id": 3837231,
"author": "Jiqing Tang",
"author_id": 463611,
"author_profile": "https://Stackoverflow.com/users/463611",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to try out <a href=\"http://github.com/jiqingtang/xd\" rel=\"nofollow noreferrer\">xd</a>, which is a GUI wrapper for Git/SVN diff. It is <em>not</em> a diff tool itself.</p>\n<p>You run <code>xd</code> when you want to run <code>git diff</code> or <code>svn diff</code> and it will show you a list of files, a preview window and you can launch any diff tool you like, including tkdiff, xxdiff, gvimdiff, Emacs (ediff), <a href=\"https://en.wikipedia.org/wiki/XEmacs\" rel=\"nofollow noreferrer\">XEmacs</a> (ediff), <a href=\"http://meldmerge.org/\" rel=\"nofollow noreferrer\">Meld</a>, <a href=\"http://diffuse.sourceforge.net/index.html\" rel=\"nofollow noreferrer\">Diffuse</a>, <a href=\"https://en.wikipedia.org/wiki/Kompare\" rel=\"nofollow noreferrer\">Kompare</a> and <a href=\"http://kdiff3.sourceforge.net/\" rel=\"nofollow noreferrer\">KDiff3</a>. You can also run any custom tool.</p>\n<p>Unfortunately the tool doesn't support Windows.</p>\n<p><strong>Disclosure</strong>: I am the author of this tool.</p>\n"
},
{
"answer_id": 4116806,
"author": "David Marble",
"author_id": 216735,
"author_profile": "https://Stackoverflow.com/users/216735",
"pm_score": 4,
"selected": false,
"text": "<p>Building on <a href=\"https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-my-preferred-diff-tool-viewer/255212#255212\">VonC's answer</a> to deal with file removals and additions, use the following commands and scripts:</p>\n<pre><code>git config --global diff.tool winmerge\ngit config --global difftool.winmerge.cmd "winmerge.sh \\"$LOCAL\\" \\"$REMOTE\\" \\"$BASE\\""\ngit config --global difftool.prompt false\n</code></pre>\n<p>Which is the same as putting this in your global file <em>.gitconfig</em>:</p>\n<pre><code>[diff]\n tool = winmerge\n[difftool "winmerge"]\n cmd = winmerge.bat "$LOCAL" "$REMOTE" "$BASE"\n[difftool]\n prompt = false\n</code></pre>\n<p>Then put the following in file <em>winmerge.sh</em> which must be on your path:</p>\n<pre><code>#!/bin/sh\nNULL="/dev/null"\nif [ "$2" = "$NULL" ] ; then\n echo "removed: $3"\nelif [ "$1" = "$NULL" ] ; then\n echo "added: $3"\nelse\n echo "changed: $3"\n "C:/Program Files (x86)/WinMerge/WinMergeU.exe" -e -ub -dl "Base" -dr "Mine" "$1" "$2"\nfi\n</code></pre>\n"
},
{
"answer_id": 4881489,
"author": "Kem Mason",
"author_id": 398582,
"author_profile": "https://Stackoverflow.com/users/398582",
"pm_score": 5,
"selected": false,
"text": "<p>I have one addition to this. I like to regularly use a diff app that isn't supported as one of the default tools (e.g. kaleidoscope), via </p>\n\n<pre><code>git difftool -t\n</code></pre>\n\n<p>I also like to have the default <code>diff</code> just be the regular command line, so setting the <code>GIT_EXTERNAL_DIFF</code> variable isn't an option.</p>\n\n<p>You can use an arbitrary <code>diff</code> app as a one-off with this command:</p>\n\n<pre><code>git difftool --extcmd=/usr/bin/ksdiff\n</code></pre>\n\n<p>It just passes the 2 files to the command you specify, so you probably don't need a wrapper either.</p>\n"
},
{
"answer_id": 7298214,
"author": "LuxuryMode",
"author_id": 479180,
"author_profile": "https://Stackoverflow.com/users/479180",
"pm_score": 3,
"selected": false,
"text": "<p>If you're on a Mac and have <a href=\"https://en.wikipedia.org/wiki/Xcode\" rel=\"nofollow noreferrer\">Xcode</a>, then you have <a href=\"https://en.wikipedia.org/wiki/Apple_Developer_Tools#FileMerge\" rel=\"nofollow noreferrer\">FileMerge</a> installed. The terminal command is opendiff, so you can just do:</p>\n<pre><code>git difftool -t opendiff\n</code></pre>\n"
},
{
"answer_id": 9120254,
"author": "Sharas",
"author_id": 1107786,
"author_profile": "https://Stackoverflow.com/users/1107786",
"pm_score": 3,
"selected": false,
"text": "<p>This works for me on Windows 7. There isn't any need for intermediary <em><a href=\"https://en.wikipedia.org/wiki/Bourne_shell\" rel=\"nofollow noreferrer\">sh</a></em> scripts</p>\n<p>Contents of .gitconfig:</p>\n<pre><code> [diff]\n tool = kdiff3\n\n [difftool]\n prompt = false\n\n [difftool "kdiff3"]\n path = C:/Program Files (x86)/KDiff3/kdiff3.exe\n cmd = "$LOCAL" "$REMOTE"\n</code></pre>\n"
},
{
"answer_id": 17587613,
"author": "abo-abo",
"author_id": 1350992,
"author_profile": "https://Stackoverflow.com/users/1350992",
"pm_score": 1,
"selected": false,
"text": "<p>I've been using this bit in file <code>~/.gitconfig</code> for a long time:</p>\n<pre><code>[diff]\n external = ~/Dropbox/source/bash/git-meld\n</code></pre>\n<p>With <code>git-meld</code>:</p>\n<pre><code>#!/bin/bash\nif [ "$DISPLAY" = "" ];\nthen\n diff $2 $5\nelse\n meld $2 $5\nfi\n</code></pre>\n<p>But now I got tired of always using <a href=\"http://meldmerge.org/\" rel=\"nofollow noreferrer\">Meld</a> in a graphical environment, and it's not trivial to invoke the normal diff with this setup, so I switched to this:</p>\n<pre><code>[alias]\n v = "!sh -c 'if [ $# -eq 0 ] ; then git difftool -y -t meld ; else git difftool -y $@ ; fi' -"\n</code></pre>\n<p>With this setup, things like this work:</p>\n<pre><code>git v\ngit v --staged\ngit v -t kompare\ngit v --staged -t tkdiff\n</code></pre>\n<p>And I still get to keep the good old <code>git diff</code>.</p>\n"
},
{
"answer_id": 20389035,
"author": "Theodore Sternberg",
"author_id": 3068121,
"author_profile": "https://Stackoverflow.com/users/3068121",
"pm_score": 2,
"selected": false,
"text": "<p>I tried the fancy stuff here (with tkdiff) and nothing worked for me. So I wrote the following script, tkgitdiff. It does what I need it to do.</p>\n\n<pre><code>$ cat tkgitdiff\n#!/bin/sh\n\n#\n# tkdiff for git.\n# Gives you the diff between HEAD and the current state of your file.\n#\n\nnewfile=$1\ngit diff HEAD -- $newfile > /tmp/patch.dat\ncp $newfile /tmp\nsavedPWD=$PWD\ncd /tmp\npatch -R $newfile < patch.dat\ncd $savedPWD\ntkdiff /tmp/$newfile $newfile\n</code></pre>\n"
},
{
"answer_id": 20422642,
"author": "suhailvs",
"author_id": 2351696,
"author_profile": "https://Stackoverflow.com/users/2351696",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <code>git difftool</code>.</p>\n<p>For example, if you have <a href=\"http://meldmerge.org/\" rel=\"nofollow noreferrer\">Meld</a>, you can edit the branches <code>master</code> and <code>devel</code> by:</p>\n<pre><code>git config --global diff.external meld\ngit difftool master..devel\n</code></pre>\n"
},
{
"answer_id": 21416192,
"author": "drzaus",
"author_id": 1037948,
"author_profile": "https://Stackoverflow.com/users/1037948",
"pm_score": 0,
"selected": false,
"text": "<p>If you happen to already have a diff tool associated with filetypes (say, because you installed TortoiseSVN which comes with a diff viewer) you could just pipe the regular <code>git diff</code> output to a \"temp\" file, then just open that file directly without needing to know anything about the viewer:</p>\n\n<pre><code>git diff > \"~/temp.diff\" && start \"~/temp.diff\"\n</code></pre>\n\n<p>Setting it as a global alias works even better: <code>git what</code></p>\n\n<pre><code>[alias]\n what = \"!f() { git diff > \"~/temp.diff\" && start \"~/temp.diff\"; }; f\"\n</code></pre>\n"
},
{
"answer_id": 26732990,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>A short summary of the previous great answers:</p>\n<pre><code>git difftool --tool-help\ngit config --global diff.tool <chosen tool>\ngit config --global --add difftool.prompt false\n</code></pre>\n<p>Then use it by typing (optionally specifying the file name as well):</p>\n<pre><code>git difftool\n</code></pre>\n"
},
{
"answer_id": 32663282,
"author": "G. I. Joe",
"author_id": 2986881,
"author_profile": "https://Stackoverflow.com/users/2986881",
"pm_score": 3,
"selected": false,
"text": "<p>Install <a href=\"http://meldmerge.org/\" rel=\"nofollow noreferrer\">Meld</a>:</p>\n<pre><code> # apt-get install meld\n</code></pre>\n<p>Then choose that as the difftool:</p>\n<pre><code> $ git config --global diff.tool meld\n</code></pre>\n<p>If you want to run it in the console, type:</p>\n<pre><code> $ git difftool\n</code></pre>\n<p>If you want to use graphic mode, type:</p>\n<pre><code> $ git mergetool\n</code></pre>\n<p>And the output would be:</p>\n<pre><code> 'git mergetool' will now attempt to use one of the following tools:\n meld opendiff kdiff3 tkdiff xxdiff tortoisemerge gvimdiff diffuse\n diffmerge ecmerge p4merge araxis bc3 codecompare emerge vimdiff\n Merging:\n www/css/style.css\n www/js/controllers.js\n\n Normal merge conflict for 'www/css/style.css':\n {local}: modified file\n {remote}: modified file\n Hit return to start merge resolution tool (meld):\n</code></pre>\n<p>So just press <kbd>Enter</kbd> to use meld (default). This would open graphic mode. Make the magic save and press that that resolve the merge. That's all.</p>\n"
},
{
"answer_id": 34724511,
"author": "camjocotem",
"author_id": 3232582,
"author_profile": "https://Stackoverflow.com/users/3232582",
"pm_score": 0,
"selected": false,
"text": "<p>If you're not one for the command line then if you install <a href=\"https://en.wikipedia.org/wiki/TortoiseGit\" rel=\"nofollow noreferrer\">TortoiseGit</a>, you can right click on a file to get a TortoiseGit submenu with the "Diff later" option.</p>\n<p>When you select this on the first file, you can then right click on the second file, go to the TortoiseGit submenu and select "Diff with ==yourfilehere==".\nThis will give the TortoiseGit merge GUI for the result.</p>\n"
},
{
"answer_id": 37109430,
"author": "Shreyas",
"author_id": 3098229,
"author_profile": "https://Stackoverflow.com/users/3098229",
"pm_score": 2,
"selected": false,
"text": "<p>On Mac OS X,</p>\n<pre><code>git difftool -t diffuse\n</code></pre>\n<p>does the job for me in the Git folder. For installing <a href=\"http://diffuse.sourceforge.net/index.html\" rel=\"nofollow noreferrer\">Diffuse</a>, one can use port -</p>\n<pre><code>sudo port install diffuse\n</code></pre>\n"
},
{
"answer_id": 44663812,
"author": "David Rawson",
"author_id": 5241933,
"author_profile": "https://Stackoverflow.com/users/5241933",
"pm_score": 3,
"selected": false,
"text": "<p>After looking at some other external diff tools, I found that the <code>diff</code> view in IntelliJ IDEA (and Android Studio) is the best one for me.</p>\n<h1>Step 1 - setup IntelliJ IDEA to be run from the command line</h1>\n<p>If you want to use IntelliJ IDEA as your diff tool you should first setup IntelliJ IDEA to be run from the command line following the instructions <a href=\"https://www.jetbrains.com/help/idea/running-intellij-idea-as-a-diff-or-merge-command-line-tool.html\" rel=\"noreferrer\">here</a>:</p>\n<p><strong>On macOS or UNIX:</strong></p>\n<ol>\n<li>Make sure IntelliJ IDEA is running.</li>\n<li>On the main menu, choose <code>Tools | Create Command-line Launcher</code>. The dialog box Create Launcher Script opens, with the suggested path and name of the launcher script. You can accept default, or specify your own path.\nMake notice of it, as you'll need it later.\nOutside of IntelliJ IDEA, add the path and name of the launcher script to your path.</li>\n</ol>\n<p><strong>On Windows:</strong></p>\n<ol>\n<li>Specify the location of the IntelliJ IDEA executable in the Path system environment variable. In this case, you will be able to invoke the IntelliJ IDEA executable and other IntelliJ IDEA commands from any directory.</li>\n</ol>\n<h1>Step 2 - configure git to use IntelliJ IDEA as the difftool</h1>\n<p>Following the instructions on <a href=\"http://brian.pontarelli.com/2013/10/25/using-idea-for-git-merging-and-diffing/\" rel=\"noreferrer\">this blog post</a>:</p>\n<p><strong>Bash</strong></p>\n<pre><code>export INTELLIJ_HOME /Applications/IntelliJ\\ IDEA\\ CE.app/Contents/MacOS\nPATH=$IDEA_HOME $PATH\n</code></pre>\n<p><strong>Fish</strong></p>\n<pre><code>set INTELLIJ_HOME /Applications/IntelliJ\\ IDEA\\ CE.app/Contents/MacOS\nset PATH $INTELLIJ_HOME $PATH\n</code></pre>\n<p>Now add the following to your git config:</p>\n<pre><code>[merge]\n tool = intellij\n[mergetool "intellij"]\n cmd = idea merge $(cd $(dirname "$LOCAL") && pwd)/$(basename "$LOCAL") $(cd $(dirname "$REMOTE") && pwd)/$(basename "$REMOTE") $(cd $(dirname "$BASE") && pwd)/$(basename "$BASE") $(cd $(dirname "$MERGED") && pwd)/$(basename "$MERGED")\n trustExitCode = true\n[diff]\n tool = intellij\n[difftool "intellij"]\n cmd = idea diff $(cd $(dirname "$LOCAL") && pwd)/$(basename "$LOCAL") $(cd $(dirname "$REMOTE") && pwd)/$(basename "$REMOTE")\n</code></pre>\n<p>You can try it out with <code>git difftool</code> or <code>git difftool HEAD~1</code></p>\n"
},
{
"answer_id": 53837839,
"author": "dolphus333",
"author_id": 1429266,
"author_profile": "https://Stackoverflow.com/users/1429266",
"pm_score": 2,
"selected": false,
"text": "<p>The following can be gleaned from the other answers here, but for me it's difficult, (too much information), so here's the 'just type it in' answer for tkdiff:</p>\n\n<pre><code>git difftool --tool=tkdiff <path to the file to be diffed>\n</code></pre>\n\n<p>You can substitute the executable name of your favorite diffing tool for tkdiff. As long as (e.g. tkdiff), (or your favorite diffing tool) is in your PATH, it will be launched.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3891/"
] |
When I type `git diff`, I want to view the output with my visual diff tool of choice (SourceGear "diffmerge" on Windows). How do I configure git to do this?
|
Since Git1.6.3, you can use the **git difftool script**: see [my answer below](https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-visual-diff-program/949242#949242).
---
May be this [article](https://web.archive.org/web/20170508180316/http://git.net:80/ml/version-control.msysgit/2008-06/msg00200.html) will help you. Here are the best parts:
There are two different ways to specify an external diff tool.
The first is the method you used, by setting the GIT\_EXTERNAL\_DIFF variable. However, the variable is supposed to point to the full path of the executable. Moreover, the executable specified by GIT\_EXTERNAL\_DIFF will be called with a fixed set of 7 arguments:
```
path old-file old-hex old-mode new-file new-hex new-mode
```
As most diff tools will require a different order (and only some) of the arguments, you will most likely have to specify a wrapper script instead, which in turn calls the real diff tool.
The second method, which I prefer, is to **configure the external diff tool via "git
config"**. Here is what I did:
1) Create a wrapper script "git-diff-wrapper.sh" which contains something like
```
-->8-(snip)--
#!/bin/sh
# diff is called by git with 7 parameters:
# path old-file old-hex old-mode new-file new-hex new-mode
"<path_to_diff_executable>" "$2" "$5" | cat
--8<-(snap)--
```
As you can see, only the second ("old-file") and fifth ("new-file") arguments will be
passed to the diff tool.
2) Type
```
$ git config --global diff.external <path_to_wrapper_script>
```
at the command prompt, replacing with the path to "git-diff-wrapper.sh", so your ~/.gitconfig contains
```
-->8-(snip)--
[diff]
external = <path_to_wrapper_script>
--8<-(snap)--
```
Be sure to use the correct syntax to specify the paths to the wrapper script and diff
tool, i.e. use forward slashed instead of backslashes. In my case, I have
```
[diff]
external = \"c:/Documents and Settings/sschuber/git-diff-wrapper.sh\"
```
in .gitconfig and
```
"d:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat
```
in the wrapper script. Mind the trailing "cat"!
(I suppose the '`| cat`' is needed only for some programs which may not return a proper or consistent return status. You might want to try without the trailing cat if your diff tool has explicit return status)
([Diomidis Spinellis](https://stackoverflow.com/users/20520/diomidis-spinellis) adds [in the comments](https://stackoverflow.com/questions/255202/how-do-i-view-git-diff-output-with-my-preferred-diff-tool-viewer/255212#comment96247087_255212):
>
> The `cat` command is required, because [`diff(1)`](http://man7.org/linux/man-pages/man1/diff.1.html), by default exits with an error code if the files differ.
>
> Git expects the external diff program to exit with an error code only if an actual error occurred, e.g. if it run out of memory.
>
> By piping the output of `git` to `cat` the non-zero error code is masked.
>
> More efficiently, the program could just run `exit` with and argument of 0.)
>
>
>
---
That (the article quoted above) is the theory for external tool **defined through config file** (not through environment variable).
In practice (still for config file definition of external tool), you can refer to:
* [How do I setup DiffMerge with msysgit / gitk?](https://stackoverflow.com/questions/780425/how-do-i-setup-diffmerge-with-msysgit-gitk/783667#783667) which illustrates the concrete settings of DiffMerge and WinMerge for MsysGit and gitk
* [How can I set up an editor to work with Git on Windows?](https://stackoverflow.com/questions/10564/how-can-i-set-up-an-editor-to-work-with-git-on-windows/773973#773973) for the definition of Notepad++ as an external editor.
|
255,214 |
<p>I keep seeing references to the visitor pattern in blogs but I've got to admit, I just don't get it. I read the <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="noreferrer">wikipedia article for the pattern</a> and I understand its mechanics but I'm still confused as to when I'd use it.</p>
<p>As someone who just recently really <strong>got</strong> the decorator pattern and is now seeing uses for it absolutely everywhere I'd like to be able to really understand intuitively this seemingly handy pattern as well.</p>
|
[
{
"answer_id": 255224,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 7,
"selected": false,
"text": "<p>The reason for your confusion is probably that the Visitor is a fatal misnomer. Many (prominent<sup>1</sup>!) programmers have stumbled over this problem. What it actually does is implement <a href=\"http://en.wikipedia.org/wiki/Double_dispatch\" rel=\"noreferrer\">double dispatching</a> in languages that don't support it natively (most of them don't).</p>\n\n<hr>\n\n<p><sup>1)</sup> My favourite example is Scott Meyers, acclaimed author of “Effective C++”, who called this one of his <a href=\"http://www.artima.com/cppsource/top_cpp_aha_moments.html\" rel=\"noreferrer\">most important C++ aha! moments <em>ever</em></a>.</p>\n"
},
{
"answer_id": 255229,
"author": "Oddthinking",
"author_id": 8014,
"author_profile": "https://Stackoverflow.com/users/8014",
"pm_score": 5,
"selected": false,
"text": "<p>One way to look at it is that the visitor pattern is a way of letting your clients add additional methods to all of your classes in a particular class hierarchy.</p>\n\n<p>It is useful when you have a fairly stable class hierarchy, but you have changing requirements of what needs to be done with that hierarchy.</p>\n\n<p>The classic example is for compilers and the like. An Abstract Syntax Tree (AST) can accurately define the structure of the programming language, but the operations you might want to do on the AST will change as your project advances: code-generators, pretty-printers, debuggers, complexity metrics analysis.</p>\n\n<p>Without the Visitor Pattern, every time a developer wanted to add a new feature, they would need to add that method to every feature in the base class. This is particularly hard when the base classes appear in a separate library, or are produced by a separate team.</p>\n\n<p>(I have heard it argued that the Visitor pattern is in conflict with good OO practices, because it moves the operations of the data away from the data. The Visitor pattern is useful in precisely the situation that the normal OO practices fail.)</p>\n"
},
{
"answer_id": 255300,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 8,
"selected": false,
"text": "<p>I'm not very familiar with the Visitor pattern. Let's see if I got it right. Suppose you have a hierarchy of animals</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class Animal { };\nclass Dog: public Animal { };\nclass Cat: public Animal { };\n</code></pre>\n\n<p>(Suppose it is a complex hierarchy with a well-established interface.)</p>\n\n<p>Now we want to add a new operation to the hierarchy, namely we want each animal to make its sound. As far as the hierarchy is this simple, you can do it with straight polymorphism:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class Animal\n{ public: virtual void makeSound() = 0; };\n\nclass Dog : public Animal\n{ public: void makeSound(); };\n\nvoid Dog::makeSound()\n{ std::cout << \"woof!\\n\"; }\n\nclass Cat : public Animal\n{ public: void makeSound(); };\n\nvoid Cat::makeSound()\n{ std::cout << \"meow!\\n\"; }\n</code></pre>\n\n<p>But proceeding in this way, each time you want to add an operation you must modify the interface to every single class of the hierarchy. Now, suppose instead that you are satisfied with the original interface, and that you want to make the fewest possible modifications to it.</p>\n\n<p>The Visitor pattern allows you to move each new operation in a suitable class, and you need to extend the hierarchy's interface only once. Let's do it. First, we define an abstract operation (the \"Visitor\" class in <a href=\"https://en.wikipedia.org/wiki/Design_Patterns\" rel=\"noreferrer\">GoF</a>) which has a method for every class in the hierarchy:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class Operation\n{\npublic:\n virtual void hereIsADog(Dog *d) = 0;\n virtual void hereIsACat(Cat *c) = 0;\n};\n</code></pre>\n\n<p>Then, we modify the hierarchy in order to accept new operations:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class Animal\n{ public: virtual void letsDo(Operation *v) = 0; };\n\nclass Dog : public Animal\n{ public: void letsDo(Operation *v); };\n\nvoid Dog::letsDo(Operation *v)\n{ v->hereIsADog(this); }\n\nclass Cat : public Animal\n{ public: void letsDo(Operation *v); };\n\nvoid Cat::letsDo(Operation *v)\n{ v->hereIsACat(this); }\n</code></pre>\n\n<p>Finally, we implement the actual operation, <em>without modifying neither Cat nor Dog</em>:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class Sound : public Operation\n{\npublic:\n void hereIsADog(Dog *d);\n void hereIsACat(Cat *c);\n};\n\nvoid Sound::hereIsADog(Dog *d)\n{ std::cout << \"woof!\\n\"; }\n\nvoid Sound::hereIsACat(Cat *c)\n{ std::cout << \"meow!\\n\"; }\n</code></pre>\n\n<p>Now you have a way to add operations without modifying the hierarchy anymore.\nHere is how it works:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>int main()\n{\n Cat c;\n Sound theSound;\n c.letsDo(&theSound);\n}\n</code></pre>\n"
},
{
"answer_id": 255437,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 5,
"selected": false,
"text": "<p>The <strong>Visitor</strong> design pattern works really well for \"recursive\" structures like directory trees, XML structures, or document outlines.</p>\n\n<p>A Visitor object visits each node in the recursive structure: each directory, each XML tag, whatever. The Visitor object doesn't loop through the structure. Instead Visitor methods are applied to each node of the structure. </p>\n\n<p>Here's a typical recursive node structure. Could be a directory or an XML tag.\n[If your a Java person, imagine of a lot of extra methods to build and maintain the children list.]</p>\n\n<pre><code>class TreeNode( object ):\n def __init__( self, name, *children ):\n self.name= name\n self.children= children\n def visit( self, someVisitor ):\n someVisitor.arrivedAt( self )\n someVisitor.down()\n for c in self.children:\n c.visit( someVisitor )\n someVisitor.up()\n</code></pre>\n\n<p>The <code>visit</code> method applies a Visitor object to each node in the structure. In this case, it's a top-down visitor. You can change the structure of the <code>visit</code> method to do bottom-up or some other ordering.</p>\n\n<p>Here's a superclass for visitors. It's used by the <code>visit</code> method. It \"arrives at\" each node in the structure. Since the <code>visit</code> method calls <code>up</code> and <code>down</code>, the visitor can keep track of the depth.</p>\n\n<pre><code>class Visitor( object ):\n def __init__( self ):\n self.depth= 0\n def down( self ):\n self.depth += 1\n def up( self ):\n self.depth -= 1\n def arrivedAt( self, aTreeNode ):\n print self.depth, aTreeNode.name\n</code></pre>\n\n<p>A subclass could do things like count nodes at each level and accumulate a list of nodes, generating a nice path hierarchical section numbers.</p>\n\n<p>Here's an application. It builds a tree structure, <code>someTree</code>. It creates a <code>Visitor</code>, <code>dumpNodes</code>. </p>\n\n<p>Then it applies the <code>dumpNodes</code> to the tree. The <code>dumpNode</code> object will \"visit\" each node in the tree.</p>\n\n<pre><code>someTree= TreeNode( \"Top\", TreeNode(\"c1\"), TreeNode(\"c2\"), TreeNode(\"c3\") )\ndumpNodes= Visitor()\nsomeTree.visit( dumpNodes )\n</code></pre>\n\n<p>The TreeNode <code>visit</code> algorithm will assure that every TreeNode is used as an argument to the Visitor's <code>arrivedAt</code> method.</p>\n"
},
{
"answer_id": 478672,
"author": "Daniel C. Sobral",
"author_id": 53013,
"author_profile": "https://Stackoverflow.com/users/53013",
"pm_score": 7,
"selected": false,
"text": "<p>Everyone here is correct, but I think it fails to address the \"when\". First, from Design Patterns:</p>\n\n<blockquote>\n <p>Visitor lets you define a new\n operation without changing the classes\n of the elements on which it operates.</p>\n</blockquote>\n\n<p>Now, let's think of a simple class hierarchy. I have classes 1, 2, 3 and 4 and methods A, B, C and D. Lay them out like in a spreadsheet: the classes are lines and the methods are columns.</p>\n\n<p>Now, Object Oriented design presumes you are more likely to grow new classes than new methods, so adding more lines, so to speak, is easier. You just add a new class, specify what's different in that class, and inherits the rest.</p>\n\n<p>Sometimes, though, the classes are relatively static, but you need to add more methods frequently -- adding columns. The standard way in an OO design would be to add such methods to all classes, which can be costly. The Visitor pattern makes this easy.</p>\n\n<p>By the way, this is the problem that Scala's pattern matches intends to solve.</p>\n"
},
{
"answer_id": 15308066,
"author": "kaosad",
"author_id": 1711215,
"author_profile": "https://Stackoverflow.com/users/1711215",
"pm_score": 3,
"selected": false,
"text": "<p>In my opinion, the amount of work to add a new operation is more or less the same using <code>Visitor Pattern</code> or direct modification of each element structure. Also, if I were to add new element class, say <code>Cow</code>, the Operation interface will be affected and this propagates to all existing class of elements, therefore requiring recompilation of all element classes. So what is the point?</p>\n"
},
{
"answer_id": 17308440,
"author": "mixturez",
"author_id": 1795195,
"author_profile": "https://Stackoverflow.com/users/1795195",
"pm_score": 3,
"selected": false,
"text": "<p>Visitor Pattern as the same underground implementation to Aspect Object programming.. </p>\n\n<p>For example if you define a new operation without changing the classes of the elements on which it operates </p>\n"
},
{
"answer_id": 18122785,
"author": "Richard Gomes",
"author_id": 62131,
"author_profile": "https://Stackoverflow.com/users/62131",
"pm_score": 4,
"selected": false,
"text": "<p>There are at least three very good reasons for using the Visitor Pattern:</p>\n\n<ol>\n<li><p>Reduce proliferation of code which is only slightly different when data structures change.</p></li>\n<li><p>Apply the same computation to several data structures, without changing the code which implements the computation.</p></li>\n<li><p>Add information to legacy libraries without changing the legacy code.</p></li>\n</ol>\n\n<p>Please have a look at <a href=\"http://rgomes-info.blogspot.com/2013/01/a-better-implementation-of-visitor.html\">an article I've written about this</a>.</p>\n"
},
{
"answer_id": 20205309,
"author": "Carl",
"author_id": 13760,
"author_profile": "https://Stackoverflow.com/users/13760",
"pm_score": 1,
"selected": false,
"text": "<p>While I have understood the how and when, I have never understood the why. In case it helps anyone with a background in a language like C++, you want to <a href=\"https://en.wikipedia.org/wiki/Double_dispatch#Double_dispatch_is_more_than_function_overloading\" rel=\"nofollow\">read this</a> very carefully.</p>\n\n<p>For the lazy, we use the visitor pattern because <strong>\"while virtual functions are dispatched dynamically in C++, function overloading is done statically\"</strong>.</p>\n\n<p>Or, put another way, to make sure that CollideWith(ApolloSpacecraft&) is called when you pass in a SpaceShip reference that is actually bound to an ApolloSpacecraft object.</p>\n\n<pre><code>class SpaceShip {};\nclass ApolloSpacecraft : public SpaceShip {};\nclass ExplodingAsteroid : public Asteroid {\npublic:\n virtual void CollideWith(SpaceShip&) {\n cout << \"ExplodingAsteroid hit a SpaceShip\" << endl;\n }\n virtual void CollideWith(ApolloSpacecraft&) {\n cout << \"ExplodingAsteroid hit an ApolloSpacecraft\" << endl;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 24595957,
"author": "Seyed Morteza Mousavi",
"author_id": 953975,
"author_profile": "https://Stackoverflow.com/users/953975",
"pm_score": 3,
"selected": false,
"text": "<p>I found it easier in following links:</p>\n\n<p>In\n<a href=\"http://web.archive.org/web/20120618142236/http://www.remondo.net/visitor-pattern-example-csharp/\" rel=\"noreferrer\">http://www.remondo.net/visitor-pattern-example-csharp/</a> I found an example that shows an mock example that shows what is benefit of visitor pattern. Here you have different container classes for <code>Pill</code>:</p>\n\n<pre><code>namespace DesignPatterns\n{\n public class BlisterPack\n {\n // Pairs so x2\n public int TabletPairs { get; set; }\n }\n\n public class Bottle\n {\n // Unsigned\n public uint Items { get; set; }\n }\n\n public class Jar\n {\n // Signed\n public int Pieces { get; set; }\n }\n}\n</code></pre>\n\n<p>As you see in above, You <code>BilsterPack</code> contain pairs of Pills' so you need to multiply number of pair's by 2. Also you may notice that <code>Bottle</code> use <code>unit</code> which is different datatype and need to be cast.</p>\n\n<p>So in main method you may calculate pill count using following code:</p>\n\n<pre><code>foreach (var item in packageList)\n{\n if (item.GetType() == typeof (BlisterPack))\n {\n pillCount += ((BlisterPack) item).TabletPairs * 2;\n }\n else if (item.GetType() == typeof (Bottle))\n {\n pillCount += (int) ((Bottle) item).Items;\n }\n else if (item.GetType() == typeof (Jar))\n {\n pillCount += ((Jar) item).Pieces;\n }\n}\n</code></pre>\n\n<p>Notice that above code violate <code>Single Responsibility Principle</code>. That means you must change main method code if you add new type of container. Also making switch longer is bad practice. </p>\n\n<p>So by introducing following code:</p>\n\n<pre><code>public class PillCountVisitor : IVisitor\n{\n public int Count { get; private set; }\n\n #region IVisitor Members\n\n public void Visit(BlisterPack blisterPack)\n {\n Count += blisterPack.TabletPairs * 2;\n }\n\n public void Visit(Bottle bottle)\n {\n Count += (int)bottle.Items;\n }\n\n public void Visit(Jar jar)\n {\n Count += jar.Pieces;\n }\n\n #endregion\n}\n</code></pre>\n\n<p>You moved responsibility of counting number of <code>Pill</code>s to class called <code>PillCountVisitor</code> (And we removed switch case statement). That mean's whenever you need to add new type of pill container you should change only <code>PillCountVisitor</code> class. Also notice <code>IVisitor</code> interface is general for using in another scenarios.</p>\n\n<p>By adding Accept method to pill container class:</p>\n\n<pre><code>public class BlisterPack : IAcceptor\n{\n public int TabletPairs { get; set; }\n\n #region IAcceptor Members\n\n public void Accept(IVisitor visitor)\n {\n visitor.Visit(this);\n }\n\n #endregion\n}\n</code></pre>\n\n<p>we allow visitor to visit pill container classes.</p>\n\n<p>At the end we calculate pill count using following code:</p>\n\n<pre><code>var visitor = new PillCountVisitor();\n\nforeach (IAcceptor item in packageList)\n{\n item.Accept(visitor);\n}\n</code></pre>\n\n<p>That mean's: Every pill container allow the <code>PillCountVisitor</code> visitor to see their pills count. He know how to count your pill's.</p>\n\n<p>At the <code>visitor.Count</code> has the value of pills.</p>\n\n<p>In\n<a href=\"http://butunclebob.com/ArticleS.UncleBob.IuseVisitor\" rel=\"noreferrer\">http://butunclebob.com/ArticleS.UncleBob.IuseVisitor</a> you see real scenario in which you can not use <a href=\"https://stackoverflow.com/questions/126409/ways-to-eliminate-switch-in-code\">polymorphism</a> (the answer) to follow Single Responsibility Principle. In fact in:</p>\n\n<pre><code>public class HourlyEmployee extends Employee {\n public String reportQtdHoursAndPay() {\n //generate the line for this hourly employee\n }\n}\n</code></pre>\n\n<p>the <code>reportQtdHoursAndPay</code> method is for reporting and representation and this violate the Single Responsibility Principle. So it is better to use visitor pattern to overcome the problem.</p>\n"
},
{
"answer_id": 30078229,
"author": "Fuhrmanator",
"author_id": 1168342,
"author_profile": "https://Stackoverflow.com/users/1168342",
"pm_score": 3,
"selected": false,
"text": "<p>Cay Horstmann has a great example of where to apply <a href=\"http://bcs.wiley.com/he-bcs/Books?action=mininav&bcsId=2561&itemId=0471744875&assetId=73207&resourceId=6077&newwindow=true\" rel=\"nofollow noreferrer\">Visitor in his OO Design and patterns book</a>. He summarizes the problem:</p>\n\n<blockquote>\n <p>Compound objects often have a complex structure, composed of individual elements. Some elements may again have child elements. ... An operation on an element visits its child elements, applies the operation to them, and combines the results. ... However, it is not easy to add new operations to such a design. </p>\n</blockquote>\n\n<p>The reason it's not easy is because operations are added within the structure classes themselves. For example, imagine you have a File System:</p>\n\n<p><img src=\"https://www.plantuml.com/plantuml/svg/LOkn3i8m44FtVCKftr5rGXsxTEqIKYDEvDBexXZozuG118jb-zdsuDgI9Y7pNZ1KEVjJIhZp0O8qxoIGAzG2LuVUKWR5QVg6UTxhmWLRDuViTJqFH4f6oxQ6N98DD_2x9fPM8AZ-I-E55TbFxP_p_-m5.svg\" alt=\"FileSystem class diagram\"></p>\n\n<p>Here are some operations (functionalities) we might want to implement with this structure:</p>\n\n<ul>\n<li>Display the names of the node elements (a file listing)</li>\n<li>Display the calculated the size of the node elements (where a directory's size includes the size of all its child elements)</li>\n<li>etc.</li>\n</ul>\n\n<p>You could add functions to each class in the FileSystem to implement the operations (and people have done this in the past as it's very obvious how to do it). The problem is that whenever you add a new functionality (the \"etc.\" line above), you might need to add more and more methods to the structure classes. At some point, after some number of operations you've added to your software, the methods in those classes don't make sense anymore in terms of the classes' functional cohesion. For example, you have a <code>FileNode</code> that has a method <code>calculateFileColorForFunctionABC()</code> in order to implement the latest visualization functionality on the file system. </p>\n\n<p>The Visitor Pattern (like many design patterns) was born from the <em>pain and suffering</em> of developers who knew there was a better way to allow their code to change without requiring a lot of changes everywhere and also respecting good design principles (high cohesion, low coupling). It's my opinion that it's hard to understand the usefulness of a lot of patterns until you've felt that pain. Explaining the pain (like we attempt to do above with the \"etc.\" functionalities that get added) takes up space in the explanation and is a distraction. Understanding patterns is hard for this reason.</p>\n\n<p>Visitor allows us to decouple the functionalities on the data structure (e.g., <code>FileSystemNodes</code>) from the data structures themselves. The pattern allows the design to respect cohesion -- data structure classes are simpler (they have fewer methods) and also the functionalities are encapsulated into <code>Visitor</code> implementations. This is done via <em>double-dispatching</em> (which is the complicated part of the pattern): using <code>accept()</code> methods in the structure classes and <code>visitX()</code> methods in the Visitor (the functionality) classes: </p>\n\n<p><img src=\"https://www.plantuml.com/plantuml/svg/ZOwn2iCm34HtVuN8r2xzWf2fPCmIo9J5TLGgQZd6LWkcvDzhboHZw2BGwVJkufESrq4pH4aMymnavCLMFMX2GFQIW95l6A8Y9nZksY1KTRqlJJEwbYpsAGhowBfvmWfqXBRluAC0j37evNHMYp9Mntp8xk82Oc-HqSc1kRfIG2DpI1lw-Ek_aWD5oiorv_23l8ksTSkiLTdpLtbH9VNIbByl.svg\" alt=\"FileSystem class diagram with Visitor applied\"></p>\n\n<p>This structure allows us to add new functionalities that work on the structure as concrete Visitors (without changing the structure classes). </p>\n\n<p><img src=\"https://www.plantuml.com/plantuml/svg/hOv12i8m44NtESNGbMuyGUbAkYn2eQjkOZhYO9AM90fL2fx6WtaI4qcBRegYcu7vy-VzRm-aEswu0kjwYNuQ4kwe9DjJWu2gSpqeL5iqbf5sQ7PS82HfEYrPLkkS99QzTQXgNRGD9i0jv6K15mR0XS3EBPPiO49owm_U7Ln0gfEeKBiPSx8cWyArfX_Hyr-VbQp8acV6djKJSWhQsCspeZBbHtbW8NMLXR_OSMDyK4I-r_kI_88hwOp_Gzwljvye3m00.svg\" alt=\"FileSystem class diagram with Visitor applied\"></p>\n\n<p>For example, a <code>PrintNameVisitor</code> that implements the directory listing functionality, and a <code>PrintSizeVisitor</code> that implements the version with the size. We could imagine one day having an 'ExportXMLVisitor` that generates the data in XML, or another visitor that generates it in JSON, etc. We could even have a visitor that displays my directory tree using a <a href=\"http://www.graphviz.org/doc/info/lang.html\" rel=\"nofollow noreferrer\">graphical language such as DOT</a>, to be visualized with another program.</p>\n\n<p>As a final note: The complexity of Visitor with its double-dispatch means it is harder to understand, to code and to debug. In short, it has a high geek factor and goes agains the KISS principle. <a href=\"http://www.infoq.com/articles/design-patterns-magic-or-myth\" rel=\"nofollow noreferrer\">In a survey done by researchers, Visitor was shown to be a controversial pattern (there wasn't a consensus about its usefulness). Some experiments even showed it didn't make code easier to maintain.</a> </p>\n"
},
{
"answer_id": 35406737,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow noreferrer\">Visitor</a></p>\n\n<blockquote>\n <p>Visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function</p>\n</blockquote>\n\n<p>Visitor structure:</p>\n\n<p><a href=\"https://i.stack.imgur.com/PpfGR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PpfGR.png\" alt=\"enter image description here\"></a></p>\n\n<p><em>Use Visitor pattern if:</em></p>\n\n<ol>\n<li><em>Similar operations have to be performed</em> on objects of different types grouped in a structure </li>\n<li>You need to execute many distinct and unrelated operations. <em>It separates Operation from objects Structure</em></li>\n<li>New operations have to be added without change in object structure</li>\n<li><em>Gather related operations into a single class</em> rather than force you to change or derive classes</li>\n<li>Add functions to class libraries for which you <em>either do not have the source or cannot change the source</em></li>\n</ol>\n\n<p>Even though <em>Visitor</em> pattern provides flexibility to add new operation without changing the existing code in Object, this flexibility has come with a drawback. </p>\n\n<p><em>If a new Visitable object has been added, it requires code changes in Visitor & ConcreteVisitor classes</em>. There is a workaround to address this issue : Use reflection, which will have impact on performance. </p>\n\n<p>Code snippet:</p>\n\n<pre><code>import java.util.HashMap;\n\ninterface Visitable{\n void accept(Visitor visitor);\n}\n\ninterface Visitor{\n void logGameStatistics(Chess chess);\n void logGameStatistics(Checkers checkers);\n void logGameStatistics(Ludo ludo); \n}\nclass GameVisitor implements Visitor{\n public void logGameStatistics(Chess chess){\n System.out.println(\"Logging Chess statistics: Game Completion duration, number of moves etc..\"); \n }\n public void logGameStatistics(Checkers checkers){\n System.out.println(\"Logging Checkers statistics: Game Completion duration, remaining coins of loser\"); \n }\n public void logGameStatistics(Ludo ludo){\n System.out.println(\"Logging Ludo statistics: Game Completion duration, remaining coins of loser\"); \n }\n}\n\nabstract class Game{\n // Add game related attributes and methods here\n public Game(){\n\n }\n public void getNextMove(){};\n public void makeNextMove(){}\n public abstract String getName();\n}\nclass Chess extends Game implements Visitable{\n public String getName(){\n return Chess.class.getName();\n }\n public void accept(Visitor visitor){\n visitor.logGameStatistics(this);\n }\n}\nclass Checkers extends Game implements Visitable{\n public String getName(){\n return Checkers.class.getName();\n }\n public void accept(Visitor visitor){\n visitor.logGameStatistics(this);\n }\n}\nclass Ludo extends Game implements Visitable{\n public String getName(){\n return Ludo.class.getName();\n }\n public void accept(Visitor visitor){\n visitor.logGameStatistics(this);\n }\n}\n\npublic class VisitorPattern{\n public static void main(String args[]){\n Visitor visitor = new GameVisitor();\n Visitable games[] = { new Chess(),new Checkers(), new Ludo()};\n for (Visitable v : games){\n v.accept(visitor);\n }\n }\n}\n</code></pre>\n\n<p>Explanation:</p>\n\n<ol>\n<li><code>Visitable</code> (<code>Element</code>) is an interface and this interface method has to be added to a set of classes. </li>\n<li><code>Visitor</code> is an interface, which contains methods to perform an operation on <code>Visitable</code> elements.</li>\n<li><code>GameVisitor</code> is a class, which implements <code>Visitor</code> interface ( <code>ConcreteVisitor</code>).</li>\n<li>Each <code>Visitable</code> element accept <code>Visitor</code> and invoke a relevant method of <code>Visitor</code> interface.</li>\n<li>You can treat <code>Game</code> as <code>Element</code> and concrete games like <code>Chess,Checkers and Ludo</code> as <code>ConcreteElements</code>.</li>\n</ol>\n\n<p>In above example, <code>Chess, Checkers and Ludo</code> are three different games ( and <code>Visitable</code> classes). On one fine day, I have encountered with a scenario to log statistics of each game. So without modifying individual class to implement statistics functionality, you can centralise that responsibility in <code>GameVisitor</code> class, which does the trick for you without modifying the structure of each game.</p>\n\n<p>output:</p>\n\n<pre><code>Logging Chess statistics: Game Completion duration, number of moves etc..\nLogging Checkers statistics: Game Completion duration, remaining coins of loser\nLogging Ludo statistics: Game Completion duration, remaining coins of loser\n</code></pre>\n\n<p>Refer to </p>\n\n<p><a href=\"http://www.oodesign.com/visitor-pattern.html\" rel=\"nofollow noreferrer\">oodesign article</a></p>\n\n<p><a href=\"https://sourcemaking.com/design_patterns/visitor\" rel=\"nofollow noreferrer\">sourcemaking</a> article</p>\n\n<p>for more details</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"nofollow noreferrer\">Decorator</a> </p>\n\n<blockquote>\n <p>pattern allows behaviour to be added to an individual object, either statically or dynamically, without affecting the behaviour of other objects from the same class</p>\n</blockquote>\n\n<p>Related posts:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/6366385/decorator-pattern-for-io/37482635#37482635\">Decorator Pattern for IO</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1549743/when-to-use-the-decorator-pattern/37504043#37504043\">When to Use the Decorator Pattern?</a></p>\n"
},
{
"answer_id": 36273106,
"author": "Tomás Escamez",
"author_id": 1582225,
"author_profile": "https://Stackoverflow.com/users/1582225",
"pm_score": 2,
"selected": false,
"text": "<p>Based on the excellent answer of @Federico A. Ramponi.</p>\n\n<p>Just imagine you have this hierarchy:</p>\n\n<pre><code>public interface IAnimal\n{\n void DoSound();\n}\n\npublic class Dog : IAnimal\n{\n public void DoSound()\n {\n Console.WriteLine(\"Woof\");\n }\n}\n\npublic class Cat : IAnimal\n{\n public void DoSound(IOperation o)\n {\n Console.WriteLine(\"Meaw\");\n }\n}\n</code></pre>\n\n<p>What happen if you need to add a \"Walk\" method here? That will be painful to the whole design.</p>\n\n<p>At the same time, adding the \"Walk\" method generate new questions. What about \"Eat\" or \"Sleep\"? Must we really add a new method to the Animal hierarchy for every new action or operation that we want to add? That's ugly and most important, we will never be able to close the Animal interface. So, with the visitor pattern, we can add new method to the hierarchy without modifying the hierarchy!</p>\n\n<p>So, just check and run this C# example:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nnamespace VisitorPattern\n{\n class Program\n {\n static void Main(string[] args)\n {\n var animals = new List<IAnimal>\n {\n new Cat(), new Cat(), new Dog(), new Cat(), \n new Dog(), new Dog(), new Cat(), new Dog()\n };\n\n foreach (var animal in animals)\n {\n animal.DoOperation(new Walk());\n animal.DoOperation(new Sound());\n }\n\n Console.ReadLine();\n }\n }\n\n public interface IOperation\n {\n void PerformOperation(Dog dog);\n void PerformOperation(Cat cat);\n }\n\n public class Walk : IOperation\n {\n public void PerformOperation(Dog dog)\n {\n Console.WriteLine(\"Dog walking\");\n }\n\n public void PerformOperation(Cat cat)\n {\n Console.WriteLine(\"Cat Walking\");\n }\n }\n\n public class Sound : IOperation\n {\n public void PerformOperation(Dog dog)\n {\n Console.WriteLine(\"Woof\");\n }\n\n public void PerformOperation(Cat cat)\n {\n Console.WriteLine(\"Meaw\");\n }\n }\n\n public interface IAnimal\n {\n void DoOperation(IOperation o);\n }\n\n public class Dog : IAnimal\n {\n public void DoOperation(IOperation o)\n {\n o.PerformOperation(this);\n }\n }\n\n public class Cat : IAnimal\n {\n public void DoOperation(IOperation o)\n {\n o.PerformOperation(this);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 38341948,
"author": "Kapoor",
"author_id": 5252960,
"author_profile": "https://Stackoverflow.com/users/5252960",
"pm_score": 4,
"selected": false,
"text": "<p>As Konrad Rudolph already pointed out, it is suitable for cases where we need <strong>double dispatch</strong></p>\n\n<p>Here is an example to show a situation where we need double dispatch & how visitor helps us in doing so. </p>\n\n<p><strong>Example :</strong> </p>\n\n<p>Lets say I have 3 types of mobile devices - iPhone, Android, Windows Mobile.</p>\n\n<p>All these three devices have a Bluetooth radio installed in them. </p>\n\n<p>Lets assume that the blue tooth radio can be from 2 separate OEMs – Intel & Broadcom. </p>\n\n<p>Just to make the example relevant for our discussion, lets also assume that the APIs exposes by Intel radio are different from the ones exposed by Broadcom radio. </p>\n\n<p>This is how my classes look – </p>\n\n<p><a href=\"https://i.stack.imgur.com/AMvXJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/AMvXJ.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/4s7KS.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4s7KS.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now, I would like to introduce an operation – Switching On the Bluetooth on mobile device. </p>\n\n<p>Its function signature should like something like this – </p>\n\n<pre><code> void SwitchOnBlueTooth(IMobileDevice mobileDevice, IBlueToothRadio blueToothRadio)\n</code></pre>\n\n<p>So depending upon <strong>Right type of device</strong> and <strong>Depending upon right type of Bluetooth radio</strong>, it can be switched on by <strong>calling appropriate steps or algorithm</strong>. </p>\n\n<p>In principal, it becomes a 3 x 2 matrix, where-in I’m trying to vector the right operation depending upon the right type of objects involved. </p>\n\n<p>A polymorphic behaviour depending upon the type of both the arguments.</p>\n\n<p><a href=\"https://i.stack.imgur.com/A1422.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/A1422.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now, Visitor pattern can be applied to this problem. Inspiration comes from the Wikipedia page stating – <em>“In essence, the visitor allows one to add new virtual functions to a family of classes without modifying the classes themselves; instead, one creates a visitor class that implements all of the appropriate specializations of the virtual function. The visitor takes the instance reference as input, and implements the goal through double dispatch.”</em></p>\n\n<p><strong>Double dispatch is a necessity here due to the 3x2 matrix</strong></p>\n\n<p>Here is how the set up will look like - \n<a href=\"https://i.stack.imgur.com/8mjd2.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/8mjd2.png\" alt=\"enter image description here\"></a></p>\n\n<p>I wrote the example to answer another question, the code & its explanation is mentioned <a href=\"https://stackoverflow.com/questions/33456948/when-should-you-really-use-the-visitor-pattern/33460652#33460652\">here</a>. </p>\n"
},
{
"answer_id": 40426542,
"author": "wojcikstefan",
"author_id": 1579058,
"author_profile": "https://Stackoverflow.com/users/1579058",
"pm_score": 2,
"selected": false,
"text": "<p>I really like the description and the example from <a href=\"http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Visitor.html\" rel=\"nofollow noreferrer\">http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Visitor.html</a>.</p>\n\n<blockquote>\n <p>The assumption is that you have a primary class hierarchy that is fixed; perhaps it’s from another vendor and you can’t make changes to that hierarchy. However, your intent is that you’d like to add new polymorphic methods to that hierarchy, which means that normally you’d have to add something to the base class interface. So the dilemma is that you need to add methods to the base class, but you can’t touch the base class. How do you get around this?</p>\n \n <p>The design pattern that solves this kind of problem is called a “visitor” (the final one in the Design Patterns book), and it builds on the double dispatching scheme shown in the last section.</p>\n \n <p>The visitor pattern allows you to extend the interface of the primary type by creating a separate class hierarchy of type Visitor to virtualize the operations performed upon the primary type. The objects of the primary type simply “accept” the visitor, then call the visitor’s dynamically-bound member function.</p>\n</blockquote>\n"
},
{
"answer_id": 47968789,
"author": "davidxxx",
"author_id": 270371,
"author_profile": "https://Stackoverflow.com/users/270371",
"pm_score": 4,
"selected": false,
"text": "<p>Double dispatch is just <strong>one reason among others to use this pattern</strong>.<br>\nBut note that it is the single way to implement double or more dispatch in languages that uses a single dispatch paradigm.</p>\n\n<p>Here are reasons to use the pattern :</p>\n\n<p>1) <strong>We want to define new operations without changing the model at each time</strong> because the model doesn’t change often wile operations change frequently.<br></p>\n\n<p>2) <strong>We don't want to couple model and behavior</strong> because <strong>we want to have a reusable model</strong> in multiple applications or <strong>we want to have an extensible model</strong> that allow client classes to define their behaviors with their own classes.<br></p>\n\n<p>3) We have common operations that depend on the concrete type of the model but <strong>we don’t want to implement the logic in each subclass as that would explode common logic in multiple classes and so in multiple places</strong>.<br></p>\n\n<p>4) We are using a domain model design and <strong>model classes of the same hierarchy perform too many distinct things that could be gathered somewhere else</strong>.<br></p>\n\n<p>5) <strong>We need a double dispatch</strong>.<br>\nWe have variables declared with interface types and we want to be able to process them according their runtime type … of course without using <code>if (myObj instanceof Foo) {}</code> or any trick.<br>\nThe idea is for example to pass these variables to methods that declares a concrete type of the interface as parameter to apply a specific processing. \nThis way of doing is not possible out of the box with languages relies on a single-dispatch because the chosen invoked at runtime depends only on the runtime type of the receiver.<br>\nNote that in Java, the method (signature) to call is chosen at compile time and it depends on the declared type of the parameters, not their runtime type.<br></p>\n\n<p>The last point that is a reason to use the visitor is also a consequence because as you implement the visitor (of course for languages that doesn’t support multiple dispatch), you necessarily need to introduce a double dispatch implementation.<br></p>\n\n<p>Note that the traversal of elements (iteration) to apply the visitor on each one is not a reason to use the pattern.<br>\nYou use the pattern because you split model and processing.<br>\nAnd by using the pattern, you benefit in addition from an iterator ability.<br>\nThis ability is very powerful and goes beyond iteration on common type with a specific method as <code>accept()</code> is a generic method.<br>\nIt is a special use case. So I will put that to one side.</p>\n\n<hr>\n\n<p><strong>Example in Java</strong></p>\n\n<p>I will illustrate the added value of the pattern with a chess example where we would like to define processing as player requests a piece moving.<br></p>\n\n<p>Without the visitor pattern use, we could define piece moving behaviors directly in the pieces subclasses.<br>\nWe could have for example a <code>Piece</code> interface such as : <br></p>\n\n<pre><code>public interface Piece{\n\n boolean checkMoveValidity(Coordinates coord);\n\n void performMove(Coordinates coord);\n\n Piece computeIfKingCheck();\n\n}\n</code></pre>\n\n<p>Each Piece subclass would implement it such as : <br></p>\n\n<pre><code>public class Pawn implements Piece{\n\n @Override\n public boolean checkMoveValidity(Coordinates coord) {\n ...\n }\n\n @Override\n public void performMove(Coordinates coord) {\n ...\n }\n\n @Override\n public Piece computeIfKingCheck() {\n ...\n }\n\n}\n</code></pre>\n\n<p>And the same thing for all Piece subclasses. <br>\nHere is a diagram class that illustrates this design : <br></p>\n\n<p><a href=\"https://i.stack.imgur.com/5pQTS.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/5pQTS.jpg\" alt=\"[model class diagram\"></a></p>\n\n<p>This approach presents three important drawbacks :<br></p>\n\n<p>– behaviors such as <code>performMove()</code> or <code>computeIfKingCheck()</code> will very probably use common logic.<br>\nFor example whatever the concrete <code>Piece</code>, <code>performMove()</code> will finally set the current piece to a specific location and potentially takes the opponent piece.<br>\nSplitting related behaviors in multiple classes instead of gathering them defeats in a some way the single responsibility pattern. Making their maintainability harder.</p>\n\n<p>– processing as <code>checkMoveValidity()</code> should not be something that the <code>Piece</code> subclasses may see or change.<br>\nIt is check that goes beyond human or computer actions. This check is performed at each action requested by a player to ensure that the requested piece move is valid.<br>\nSo we even don’t want to provide that in the <code>Piece</code> interface. </p>\n\n<p>– In chess games challenging for bot developers, generally the application provides a standard API (<code>Piece</code> interfaces, subclasses, Board, common behaviors, etc…) and let developers enrich their bot strategy.<br>\nTo be able to do that, we have to propose a model where data and behaviors are not tightly coupled in the <code>Piece</code> implementations.</p>\n\n<p>So let’s go to use the visitor pattern !<br></p>\n\n<p>We have two kinds of structure :</p>\n\n<p>– the model classes that accept to be visited (the pieces)</p>\n\n<p>– the visitors that visit them (moving operations)</p>\n\n<p>Here is a class diagram that illustrates the pattern : <br></p>\n\n<p><a href=\"https://i.stack.imgur.com/2GtFI.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/2GtFI.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>In the upper part we have the visitors and in the lower part we have the model classes. <br></p>\n\n<p>Here is the <code>PieceMovingVisitor</code> interface (behavior specified for each kind of <code>Piece</code>) :</p>\n\n<pre><code>public interface PieceMovingVisitor {\n\n void visitPawn(Pawn pawn);\n\n void visitKing(King king);\n\n void visitQueen(Queen queen);\n\n void visitKnight(Knight knight);\n\n void visitRook(Rook rook);\n\n void visitBishop(Bishop bishop);\n\n}\n</code></pre>\n\n<p>The Piece is defined now :</p>\n\n<pre><code>public interface Piece {\n\n void accept(PieceMovingVisitor pieceVisitor);\n\n Coordinates getCoordinates();\n\n void setCoordinates(Coordinates coordinates);\n\n}\n</code></pre>\n\n<p>Its key method is :</p>\n\n<pre><code>void accept(PieceMovingVisitor pieceVisitor);\n</code></pre>\n\n<p>It provides the first dispatch : a invocation based on the <code>Piece</code> receiver. <br>\nAt compile time, the method is bound to the <code>accept()</code> method of the Piece interface and at runtime, the bounded method will be invoked on the runtime <code>Piece</code> class. <br>\nAnd it is the <code>accept()</code> method implementation that will perform a second dispatch. <br></p>\n\n<p>Indeed, each <code>Piece</code> subclass that wants to be visited by a <code>PieceMovingVisitor</code> object invokes the <code>PieceMovingVisitor.visit()</code> method by passing as argument itself.<br>\nIn this way, the compiler bounds as soon as the compile time, the type of the declared parameter with the concrete type.<br>\nThere is the second dispatch.<br>\nHere is the <code>Bishop</code> subclass that illustrates that :</p>\n\n<pre><code>public class Bishop implements Piece {\n\n private Coordinates coord;\n\n public Bishop(Coordinates coord) {\n super(coord);\n }\n\n @Override\n public void accept(PieceMovingVisitor pieceVisitor) {\n pieceVisitor.visitBishop(this);\n }\n\n @Override\n public Coordinates getCoordinates() {\n return coordinates;\n }\n\n @Override\n public void setCoordinates(Coordinates coordinates) {\n this.coordinates = coordinates;\n }\n\n}\n</code></pre>\n\n<p>And here an usage example :</p>\n\n<pre><code>// 1. Player requests a move for a specific piece\nPiece piece = selectPiece();\nCoordinates coord = selectCoordinates();\n\n// 2. We check with MoveCheckingVisitor that the request is valid\nfinal MoveCheckingVisitor moveCheckingVisitor = new MoveCheckingVisitor(coord);\npiece.accept(moveCheckingVisitor);\n\n// 3. If the move is valid, MovePerformingVisitor performs the move\nif (moveCheckingVisitor.isValid()) {\n piece.accept(new MovePerformingVisitor(coord));\n}\n</code></pre>\n\n<p><strong>Visitor drawbacks</strong> <br></p>\n\n<p>The Visitor pattern is a very powerful pattern but it also has some important limitations that you should consider before using it.<br></p>\n\n<p><strong>1) Risk to reduce/break the encapsulation</strong></p>\n\n<p>In some kinds of operation, the visitor pattern may reduce or break the encapsulation of domain objects.<br></p>\n\n<p>For example, as the <code>MovePerformingVisitor</code> class needs to set the coordinates of the actual piece, the <code>Piece</code> interface has to provide a way to do that :</p>\n\n<pre><code>void setCoordinates(Coordinates coordinates);\n</code></pre>\n\n<p>The responsibility of <code>Piece</code> coordinates changes is now open to other classes than <code>Piece</code> subclasses.<br>\nMoving the processing performed by the visitor in the <code>Piece</code> subclasses is not an option either.<br>\nIt will indeed create another issue as the <code>Piece.accept()</code> accepts any visitor implementation. It doesn't know what the visitor performs and so no idea about whether and how to change the Piece state.<br>\nA way to identify the visitor would be to perform a post processing in <code>Piece.accept()</code> according to the visitor implementation. It would be a very bad idea as it would create a high coupling between Visitor implementations and Piece subclasses and besides it would probably require to use trick as <code>getClass()</code>, <code>instanceof</code> or any marker identifying the Visitor implementation.</p>\n\n<p><strong>2) Requirement to change the model</strong></p>\n\n<p>Contrary to some other behavioral design patterns as <code>Decorator</code> for example, the visitor pattern is intrusive.<br>\nWe indeed need to modify the initial receiver class to provide an <code>accept()</code> method to accept to be visited.<br>\nWe didn't have any issue for <code>Piece</code> and its subclasses as these are <strong>our classes</strong>.<br>\nIn built-in or third party classes, things are not so easy.<br>\nWe need to wrap or inherit (if we can) them to add the <code>accept()</code> method.<br></p>\n\n<p><strong>3) Indirections</strong></p>\n\n<p>The pattern creates multiples indirections.<br>\nThe double dispatch means two invocations instead of a single one : </p>\n\n<pre><code>call the visited (piece) -> that calls the visitor (pieceMovingVisitor)\n</code></pre>\n\n<p>And we could have additional indirections as the visitor changes the visited object state.<br> \nIt may look like a cycle :</p>\n\n<pre><code>call the visited (piece) -> that calls the visitor (pieceMovingVisitor) -> that calls the visited (piece)\n</code></pre>\n"
},
{
"answer_id": 48853812,
"author": "andrew pate",
"author_id": 2668869,
"author_profile": "https://Stackoverflow.com/users/2668869",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Quick description of the visitor pattern.</strong> The classes that require modification must all implement the 'accept' method. Clients call this accept method to perform some new action on that family of classes thereby extending their functionality. Clients are able to use this one accept method to perform a wide range of new actions by passing in a different visitor class for each specific action. A visitor class contains multiple overridden visit methods defining how to achieve that same specific action for every class within the family. These visit methods get passed an instance on which to work.</p>\n\n<p><strong>When you might consider using it</strong></p>\n\n<ol>\n<li>When you have a family of classes you know your going to have to add many new actions them all, but for some reason you are not able to alter or recompile the family of classes in the future.</li>\n<li>When you want to add a new action and have that new action entirely defined within one the visitor class rather than spread out across multiple classes.</li>\n<li>When your boss says you must produce a range of classes which must do something <strong>right now</strong>!... but nobody actually knows exactly what that something is yet.</li>\n</ol>\n"
},
{
"answer_id": 50575946,
"author": "Hearen",
"author_id": 2361308,
"author_profile": "https://Stackoverflow.com/users/2361308",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for the awesome explanation of <a href=\"https://stackoverflow.com/questions/255214/when-should-i-use-the-visitor-design-pattern/50575946#50575946#answer-255300\">@Federico A. Ramponi</a>, I just made this in <strong>java</strong> version. Hope it might be helpful. </p>\n\n<p>Also just as <a href=\"https://stackoverflow.com/questions/255214/when-should-i-use-the-visitor-design-pattern/50575946#50575946#answer-255224\">@Konrad Rudolph</a> pointed out, it's actually a <strong>double dispatch</strong> using <strong>two</strong> concrete instances together to determine the run-time methods. </p>\n\n<p>So actually there is no need to create a <strong>common</strong> interface for the <em>operation</em> executor as long as we have the <em>operation</em> interface properly defined. </p>\n\n<pre><code>import static java.lang.System.out;\npublic class Visitor_2 {\n public static void main(String...args) {\n Hearen hearen = new Hearen();\n FoodImpl food = new FoodImpl();\n hearen.showTheHobby(food);\n Katherine katherine = new Katherine();\n katherine.presentHobby(food);\n }\n}\n\ninterface Hobby {\n void insert(Hearen hearen);\n void embed(Katherine katherine);\n}\n\n\nclass Hearen {\n String name = \"Hearen\";\n void showTheHobby(Hobby hobby) {\n hobby.insert(this);\n }\n}\n\nclass Katherine {\n String name = \"Katherine\";\n void presentHobby(Hobby hobby) {\n hobby.embed(this);\n }\n}\n\nclass FoodImpl implements Hobby {\n public void insert(Hearen hearen) {\n out.println(hearen.name + \" start to eat bread\");\n }\n public void embed(Katherine katherine) {\n out.println(katherine.name + \" start to eat mango\");\n }\n}\n</code></pre>\n\n<p>As you expect, a <strong>common</strong> interface will bring us more clarity though it's actually not the <em>essential</em> part in this pattern. </p>\n\n<pre><code>import static java.lang.System.out;\npublic class Visitor_2 {\n public static void main(String...args) {\n Hearen hearen = new Hearen();\n FoodImpl food = new FoodImpl();\n hearen.showHobby(food);\n Katherine katherine = new Katherine();\n katherine.showHobby(food);\n }\n}\n\ninterface Hobby {\n void insert(Hearen hearen);\n void insert(Katherine katherine);\n}\n\nabstract class Person {\n String name;\n protected Person(String n) {\n this.name = n;\n }\n abstract void showHobby(Hobby hobby);\n}\n\nclass Hearen extends Person {\n public Hearen() {\n super(\"Hearen\");\n }\n @Override\n void showHobby(Hobby hobby) {\n hobby.insert(this);\n }\n}\n\nclass Katherine extends Person {\n public Katherine() {\n super(\"Katherine\");\n }\n\n @Override\n void showHobby(Hobby hobby) {\n hobby.insert(this);\n }\n}\n\nclass FoodImpl implements Hobby {\n public void insert(Hearen hearen) {\n out.println(hearen.name + \" start to eat bread\");\n }\n public void insert(Katherine katherine) {\n out.println(katherine.name + \" start to eat mango\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 51015854,
"author": "j2emanue",
"author_id": 835883,
"author_profile": "https://Stackoverflow.com/users/835883",
"pm_score": 0,
"selected": false,
"text": "<p>your question is when to know:</p>\n\n<p>i do not first code with visitor pattern. i code standard and wait for the need to occur & then refactor. so lets say you have multiple payment systems that you installed one at a time. At checkout time you could have many if conditions (or instanceOf) , for example :</p>\n\n<pre><code>//psuedo code\n if(payPal) \n do paypal checkout \n if(stripe)\n do strip stuff checkout\n if(payoneer)\n do payoneer checkout\n</code></pre>\n\n<p>now imagine i had 10 payment methods, it gets kind of ugly. So when you see that kind of pattern occuring visitor comes in handly to seperate all that out and you end up calling something like this afterwards:</p>\n\n<pre><code>new PaymentCheckoutVistor(paymentType).visit()\n</code></pre>\n\n<p>You can see how to implement it from the number of examples here, im just showing you a usecase. </p>\n"
},
{
"answer_id": 53315503,
"author": "Access Denied",
"author_id": 1099716,
"author_profile": "https://Stackoverflow.com/users/1099716",
"pm_score": 2,
"selected": false,
"text": "<p>I didn't understand this pattern until I came across with <a href=\"http://butunclebob.com/ArticleS.UncleBob.IuseVisitor\" rel=\"nofollow noreferrer\">uncle bob article</a> and read comments.\nConsider the following code:</p>\n\n<pre><code>public class Employee\n{\n}\n\npublic class SalariedEmployee : Employee\n{\n}\n\npublic class HourlyEmployee : Employee\n{\n}\n\npublic class QtdHoursAndPayReport\n{\n public void PrintReport()\n {\n var employees = new List<Employee>\n {\n new SalariedEmployee(),\n new HourlyEmployee()\n };\n foreach (Employee e in employees)\n {\n if (e is HourlyEmployee he)\n PrintReportLine(he);\n if (e is SalariedEmployee se)\n PrintReportLine(se);\n }\n }\n\n public void PrintReportLine(HourlyEmployee he)\n {\n System.Diagnostics.Debug.WriteLine(\"hours\");\n }\n public void PrintReportLine(SalariedEmployee se)\n {\n System.Diagnostics.Debug.WriteLine(\"fix\");\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n new QtdHoursAndPayReport().PrintReport();\n }\n}\n</code></pre>\n\n<p>While it may look good since it confirms to <a href=\"https://docs.google.com/open?id=0ByOwmqah_nuGNHEtcU5OekdDMkk\" rel=\"nofollow noreferrer\">Single Responsibility</a> it violates <a href=\"http://docs.google.com/a/cleancoder.com/viewer?a=v&pid=explorer&chrome=true&srcid=0BwhCYaYDn8EgN2M5MTkwM2EtNWFkZC00ZTI3LWFjZTUtNTFhZGZiYmUzODc1&hl=en\" rel=\"nofollow noreferrer\">Open/Closed</a> principle. Each time you have new Employee type you will have to add if with type check. And if you won't you'll never know that at compile time.</p>\n\n<p>With visitor pattern you can make your code cleaner since it does not violate open/closed principle and does not violate Single responsibility. And if you forget to implement visit it won't compile:</p>\n\n<pre><code>public abstract class Employee\n{\n public abstract void Accept(EmployeeVisitor v);\n}\n\npublic class SalariedEmployee : Employee\n{\n public override void Accept(EmployeeVisitor v)\n {\n v.Visit(this);\n }\n}\n\npublic class HourlyEmployee:Employee\n{\n public override void Accept(EmployeeVisitor v)\n {\n v.Visit(this);\n }\n}\n\npublic interface EmployeeVisitor\n{\n void Visit(HourlyEmployee he);\n void Visit(SalariedEmployee se);\n}\n\npublic class QtdHoursAndPayReport : EmployeeVisitor\n{\n public void Visit(HourlyEmployee he)\n {\n System.Diagnostics.Debug.WriteLine(\"hourly\");\n // generate the line of the report.\n }\n public void Visit(SalariedEmployee se)\n {\n System.Diagnostics.Debug.WriteLine(\"fix\");\n } // do nothing\n\n public void PrintReport()\n {\n var employees = new List<Employee>\n {\n new SalariedEmployee(),\n new HourlyEmployee()\n };\n QtdHoursAndPayReport v = new QtdHoursAndPayReport();\n foreach (var emp in employees)\n {\n emp.Accept(v);\n }\n }\n}\n\nclass Program\n{\n\n public static void Main(string[] args)\n {\n new QtdHoursAndPayReport().PrintReport();\n } \n} \n}\n</code></pre>\n\n<p>The magic is that while <code>v.Visit(this)</code> looks the same it's in fact different since it call different overloads of visitor.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
I keep seeing references to the visitor pattern in blogs but I've got to admit, I just don't get it. I read the [wikipedia article for the pattern](http://en.wikipedia.org/wiki/Visitor_pattern) and I understand its mechanics but I'm still confused as to when I'd use it.
As someone who just recently really **got** the decorator pattern and is now seeing uses for it absolutely everywhere I'd like to be able to really understand intuitively this seemingly handy pattern as well.
|
I'm not very familiar with the Visitor pattern. Let's see if I got it right. Suppose you have a hierarchy of animals
```cpp
class Animal { };
class Dog: public Animal { };
class Cat: public Animal { };
```
(Suppose it is a complex hierarchy with a well-established interface.)
Now we want to add a new operation to the hierarchy, namely we want each animal to make its sound. As far as the hierarchy is this simple, you can do it with straight polymorphism:
```cpp
class Animal
{ public: virtual void makeSound() = 0; };
class Dog : public Animal
{ public: void makeSound(); };
void Dog::makeSound()
{ std::cout << "woof!\n"; }
class Cat : public Animal
{ public: void makeSound(); };
void Cat::makeSound()
{ std::cout << "meow!\n"; }
```
But proceeding in this way, each time you want to add an operation you must modify the interface to every single class of the hierarchy. Now, suppose instead that you are satisfied with the original interface, and that you want to make the fewest possible modifications to it.
The Visitor pattern allows you to move each new operation in a suitable class, and you need to extend the hierarchy's interface only once. Let's do it. First, we define an abstract operation (the "Visitor" class in [GoF](https://en.wikipedia.org/wiki/Design_Patterns)) which has a method for every class in the hierarchy:
```cpp
class Operation
{
public:
virtual void hereIsADog(Dog *d) = 0;
virtual void hereIsACat(Cat *c) = 0;
};
```
Then, we modify the hierarchy in order to accept new operations:
```cpp
class Animal
{ public: virtual void letsDo(Operation *v) = 0; };
class Dog : public Animal
{ public: void letsDo(Operation *v); };
void Dog::letsDo(Operation *v)
{ v->hereIsADog(this); }
class Cat : public Animal
{ public: void letsDo(Operation *v); };
void Cat::letsDo(Operation *v)
{ v->hereIsACat(this); }
```
Finally, we implement the actual operation, *without modifying neither Cat nor Dog*:
```cpp
class Sound : public Operation
{
public:
void hereIsADog(Dog *d);
void hereIsACat(Cat *c);
};
void Sound::hereIsADog(Dog *d)
{ std::cout << "woof!\n"; }
void Sound::hereIsACat(Cat *c)
{ std::cout << "meow!\n"; }
```
Now you have a way to add operations without modifying the hierarchy anymore.
Here is how it works:
```cpp
int main()
{
Cat c;
Sound theSound;
c.letsDo(&theSound);
}
```
|
255,216 |
<p>So far, I've only been passing javascript strings to my web methods, which get parsed, usually as Guids. but now i have a method that accepts an IList... on the client, i build this array of objects and then attempt to pass it like: </p>
<pre><code>$.ajax({
type: 'POST',
url: 'personalization.aspx/SetPersonalization',
data: "{'backerEntries':" + backerEntries + "}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: postcardManager.SetPersonalizationComplete
});
</code></pre>
<p>The post: </p>
<pre><code>{'backerEntries':[object Object],[object Object],[object Object]}
</code></pre>
<p>The error response: </p>
<pre><code>Invalid JSON primitive: object.
</code></pre>
<p>For some reason, jquery doesn't seem to convert my array into a json string? Any ideas why? I tried putting [] around the backerEntries, and {}, as well as {[]} just in sheer desperation. Am I missing something obvious here? </p>
|
[
{
"answer_id": 255261,
"author": "Duncan",
"author_id": 25035,
"author_profile": "https://Stackoverflow.com/users/25035",
"pm_score": 2,
"selected": false,
"text": "<p>The data you are passing you are trying to pass it as a string already. If you want jQuery to transform it leave the whole thing as an object, e.g.</p>\n\n<pre><code>data:{backerEntries: backerEntries }\n</code></pre>\n\n<p>Assuming of course backerEntries is an array. jQuery should transform this and will append it to the querystring as that is its default behaviour. Your current code is relying on default JavaScript behaviour which won't by default convert an array into its string representation.</p>\n"
},
{
"answer_id": 255269,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "<blockquote>\n <p>data: \"{'backerEntries':\" + backerEntries + \"}\",</p>\n</blockquote>\n\n<p>..is the same as </p>\n\n<pre><code>data: \"{'backerEntries':\" + backerEntries.toString() + \"}\",\n</code></pre>\n\n<p>...which is pretty much useless. Use <a href=\"https://stackoverflow.com/questions/255216/why-doesnt-jquery-turn-my-array-into-a-json-string-before-sending-to-aspnet-web#255261\">Duncan</a>'s suggestion if you just want to pass an encoded list of values with the name \"backerEntries\" in your querystring. If you want to JSON-encode the data, then get <a href=\"https://raw.github.com/douglascrockford/JSON-js/master/json2.js\" rel=\"nofollow noreferrer\">a JSON library</a> and call <code>JSON.stringify()</code>.</p>\n"
},
{
"answer_id": 255754,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 2,
"selected": false,
"text": "<p>Since you're using ASP.NET, you can use the built-in ASP.NET AJAX serialization library:</p>\n\n<pre><code>var backerEntriesJson = Sys.Serialization.JavaScriptSerializer.serialize(backerEntries);\n</code></pre>\n\n<p>then pass that directly in your jQuery ajax call:</p>\n\n<pre><code>...\ndata: backerEntriesJson,\n...\n</code></pre>\n"
},
{
"answer_id": 1280221,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>This is NOT valid JSON: { 'foo': 'bar' }</p>\n\n<p>Isn't, wasn't ever, never will be. JSON processors are often very forgiving, which of course is a false convenience. </p>\n\n<p>Read the specification. A string is defined to be enclosed in double quotes, not single quotes, not smiley face characters, not pieces of metal bent at right angles, not bricks. There's no mention of single quotes, period. </p>\n\n<p>Now, property names are JSON strings. By definition, they MUST are enclosed in double quotes. </p>\n\n<p>Valid: { \"foo\": \"bar\" } \nvalid\" { \"foo\": 100 }\nvalid: { \"foo\": true }\nvalid: { \"foo\": [ \"one\", \"two\" ], \"bar\": false }</p>\n\n<p>see www.json.org</p>\n\n<p>see www.jsonlint.com</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6350/"
] |
So far, I've only been passing javascript strings to my web methods, which get parsed, usually as Guids. but now i have a method that accepts an IList... on the client, i build this array of objects and then attempt to pass it like:
```
$.ajax({
type: 'POST',
url: 'personalization.aspx/SetPersonalization',
data: "{'backerEntries':" + backerEntries + "}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: postcardManager.SetPersonalizationComplete
});
```
The post:
```
{'backerEntries':[object Object],[object Object],[object Object]}
```
The error response:
```
Invalid JSON primitive: object.
```
For some reason, jquery doesn't seem to convert my array into a json string? Any ideas why? I tried putting [] around the backerEntries, and {}, as well as {[]} just in sheer desperation. Am I missing something obvious here?
|
>
> data: "{'backerEntries':" + backerEntries + "}",
>
>
>
..is the same as
```
data: "{'backerEntries':" + backerEntries.toString() + "}",
```
...which is pretty much useless. Use [Duncan](https://stackoverflow.com/questions/255216/why-doesnt-jquery-turn-my-array-into-a-json-string-before-sending-to-aspnet-web#255261)'s suggestion if you just want to pass an encoded list of values with the name "backerEntries" in your querystring. If you want to JSON-encode the data, then get [a JSON library](https://raw.github.com/douglascrockford/JSON-js/master/json2.js) and call `JSON.stringify()`.
|
255,278 |
<p>What would be the best way to determine if an object equals number zero (0) or string.empty in C#?</p>
<p><b>EDIT:</b> The object can equal any built-in System.Value type or reference type.</p>
<p>Source Code:</p>
<pre><code>public void MyMethod(object input1, object input2)
{
bool result = false;
object compare = new object();
if(input != null && input2 != null)
{
if(input1 is IComparable && input2 is IComparable)
{
//do check for zero or string.empty
//if input1 equals to zero or string.empty
result = object.Equals(input2);
//if input1 not equals to zero or string.empty
result = object.Equals(input1) && object.Equals(input2); //yes not valid, but this is what I want to accomplish
}
}
}
</code></pre>
|
[
{
"answer_id": 255281,
"author": "x0n",
"author_id": 6920,
"author_profile": "https://Stackoverflow.com/users/6920",
"pm_score": 0,
"selected": false,
"text": "<p>Do you mean null or string.empty, if you're talking about strings?</p>\n\n<p>if (String.IsNullOrEmpty(obj as string)) { ... do something }</p>\n\n<ul>\n<li>Oisin</li>\n</ul>\n"
},
{
"answer_id": 255283,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 0,
"selected": false,
"text": "<p>In the first case by testing if it is null. In the second case by testing if it is string.empty (you answered your own question).</p>\n\n<p>I should add that an object can never be equal to 0. An object variable can have a null reference though (in reality that means the variable has the value of 0; there is no object in this case though)</p>\n"
},
{
"answer_id": 255292,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 1,
"selected": false,
"text": "<p>Michael, you need to provide a little bit more information here.</p>\n\n<p>strings can be compared to null or string.Empty by using the method</p>\n\n<pre><code>string x = \"Some String\"\nif( string.IsNullOrEmpty(string input) ) { ... }\n</code></pre>\n\n<p>int, decimals, doubles (and other numeric value-types) can be compared to 0 (zero) with a simple == test</p>\n\n<pre><code>int x = 0;\nif(x == 0) { ... }\n</code></pre>\n\n<p>You can also have nullable value-types also by using the ? operator when you instantiate them. This allows you to set a value type as null.</p>\n\n<pre><code>int? x = null;\nif( !x.HasValue ) { }\n</code></pre>\n\n<p>For any other object, a simple == null test will tell you if its null or not</p>\n\n<pre><code>object o = new object();\nif( o != null ) { ... } \n</code></pre>\n\n<p>Hope that sheds some light on things.</p>\n"
},
{
"answer_id": 255339,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>Not quite sure the reasoning behind this, because .Equals is reference equality on reference types, and value equality on value types. </p>\n\n<p>This seems to work, but I doubt its what you want:</p>\n\n<pre><code> static bool IsZeroOrEmpty(object o1)\n {\n if (o1 == null)\n return false;\n if (o1.GetType().IsValueType)\n { \n return (o1 as System.ValueType).Equals(0);\n }\n else\n {\n if (o1.GetType() == typeof(String))\n {\n return o1.Equals(String.Empty);\n }\n\n return o1.Equals(0);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 255384,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 0,
"selected": false,
"text": "<pre><code>obj => obj is int && (int)obj == 0 || obj is string && (string)obj == string.Empty\n</code></pre>\n"
},
{
"answer_id": 255399,
"author": "Cybis",
"author_id": 32998,
"author_profile": "https://Stackoverflow.com/users/32998",
"pm_score": 2,
"selected": false,
"text": "<p>What's wrong with this?</p>\n\n<pre><code>public static bool IsZeroOrEmptyString(object obj)\n{\n if (obj == null)\n return false;\n else if (obj.Equals(0) || obj.Equals(\"\"))\n return true;\n else\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 266173,
"author": "Michael Kniskern",
"author_id": 26327,
"author_profile": "https://Stackoverflow.com/users/26327",
"pm_score": 3,
"selected": true,
"text": "<p>Using Jonathan Holland code sample with a minor modification, here is the solution that worked:</p>\n\n<pre><code>static bool IsZeroOrEmpty(object o1)\n{\n bool Passed = false;\n object ZeroValue = 0;\n\n if(o1 != null)\n {\n if(o1.GetType().IsValueType)\n {\n Passed = (o1 as System.ValueType).Equals(Convert.ChangeType(ZeroValue, o1.GetType()))\n }\n else\n {\n if (o1.GetType() == typeof(String))\n {\n Passed = o1.Equals(String.Empty);\n }\n }\n }\n\n return Passed;\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/255278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
What would be the best way to determine if an object equals number zero (0) or string.empty in C#?
**EDIT:** The object can equal any built-in System.Value type or reference type.
Source Code:
```
public void MyMethod(object input1, object input2)
{
bool result = false;
object compare = new object();
if(input != null && input2 != null)
{
if(input1 is IComparable && input2 is IComparable)
{
//do check for zero or string.empty
//if input1 equals to zero or string.empty
result = object.Equals(input2);
//if input1 not equals to zero or string.empty
result = object.Equals(input1) && object.Equals(input2); //yes not valid, but this is what I want to accomplish
}
}
}
```
|
Using Jonathan Holland code sample with a minor modification, here is the solution that worked:
```
static bool IsZeroOrEmpty(object o1)
{
bool Passed = false;
object ZeroValue = 0;
if(o1 != null)
{
if(o1.GetType().IsValueType)
{
Passed = (o1 as System.ValueType).Equals(Convert.ChangeType(ZeroValue, o1.GetType()))
}
else
{
if (o1.GetType() == typeof(String))
{
Passed = o1.Equals(String.Empty);
}
}
}
return Passed;
}
```
|
255,302 |
<p>Hoping some of you TinyXML++ people can help me out. Really, since you recomended to me before I think you owe me ;)</p>
<p>I have the following code:</p>
<pre><code> //ticpp::Iterator< ticpp::Element > child( "SetPiece" );
ticpp::Iterator< ticpp::Node > child("SetPiece");
GLuint lc_SPieces = 0;
for(child = child.begin( this ); child != child.end(); child++ )
{
lc_SPieces++;
}
</code></pre>
<p>If I use the top declaration for child I get the error:</p>
<blockquote>
<p>Unhandled exception at 0x7c812aeb in
Drawing.exe: Microsoft C++ exception:
__non_rtti_object @ 0x0012f7b4.</p>
</blockquote>
<p>And I get it in dbgheap.c at this line:</p>
<pre><code>pvBlk = _heap_alloc_dbg(nSize, nBlockUse, szFileName, nLine);
</code></pre>
<p>What's weird is it works with Node, and I know that there are elements in there(I checked using the TinyXML iteration methods).</p>
<p>Has anyone run into this before?</p>
|
[
{
"answer_id": 256996,
"author": "tabdamage",
"author_id": 28022,
"author_profile": "https://Stackoverflow.com/users/28022",
"pm_score": 1,
"selected": false,
"text": "<p>just poking in the dark, i don't know tinyxml, but it seems that a dynamic_cast went wrong. \nIf you dynamic_cast<> a pointer, you get a NULL-pointer on failure. However, if you cast to a reference type, there is no concept of a NULL-reference, so the runtime throws this exception (or bad_type). <a href=\"http://msdn.microsoft.com/en-us/library/cby9kycs(VS.71).aspx\" rel=\"nofollow noreferrer\">MSDN on dynamic_cast, and why it can go wrong</a></p>\n\n<p>The line you pasted for the exception to occur does not help to clear up the situation, since it identifies the symptom rather than the cause.</p>\n\n<p>Try to identify the cast that went wrong, you should be able to find it if you walk up the stack and find the last method in tinyxml libs or headers. Then you can decide whether tinyxml is worng, or you just applied it the wrong way.</p>\n\n<p>good luck!</p>\n"
},
{
"answer_id": 257014,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 0,
"selected": false,
"text": "<p>Project -> Properties -> C/C++ -> Language -> Enable Run-Time Type Info</p>\n"
},
{
"answer_id": 285834,
"author": "paavo256",
"author_id": 34911,
"author_profile": "https://Stackoverflow.com/users/34911",
"pm_score": 1,
"selected": false,
"text": "<p><code>__non_rtti_object</code> is generated by the dynamic_cast operator if the passed pointer or reference does not point to a polymorphic object, but to some garbage instead. Maybe the object had been deleted earlier. </p>\n\n<p>Step through the code in the debugger and check where the dynamic_cast is used and what is passed to it.</p>\n\n<p>hth\nPaavo</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23829/"
] |
Hoping some of you TinyXML++ people can help me out. Really, since you recomended to me before I think you owe me ;)
I have the following code:
```
//ticpp::Iterator< ticpp::Element > child( "SetPiece" );
ticpp::Iterator< ticpp::Node > child("SetPiece");
GLuint lc_SPieces = 0;
for(child = child.begin( this ); child != child.end(); child++ )
{
lc_SPieces++;
}
```
If I use the top declaration for child I get the error:
>
> Unhandled exception at 0x7c812aeb in
> Drawing.exe: Microsoft C++ exception:
> \_\_non\_rtti\_object @ 0x0012f7b4.
>
>
>
And I get it in dbgheap.c at this line:
```
pvBlk = _heap_alloc_dbg(nSize, nBlockUse, szFileName, nLine);
```
What's weird is it works with Node, and I know that there are elements in there(I checked using the TinyXML iteration methods).
Has anyone run into this before?
|
just poking in the dark, i don't know tinyxml, but it seems that a dynamic\_cast went wrong.
If you dynamic\_cast<> a pointer, you get a NULL-pointer on failure. However, if you cast to a reference type, there is no concept of a NULL-reference, so the runtime throws this exception (or bad\_type). [MSDN on dynamic\_cast, and why it can go wrong](http://msdn.microsoft.com/en-us/library/cby9kycs(VS.71).aspx)
The line you pasted for the exception to occur does not help to clear up the situation, since it identifies the symptom rather than the cause.
Try to identify the cast that went wrong, you should be able to find it if you walk up the stack and find the last method in tinyxml libs or headers. Then you can decide whether tinyxml is worng, or you just applied it the wrong way.
good luck!
|
255,312 |
<p>Say i have this PHP code:</p>
<pre><code>$FooBar = "a string";
</code></pre>
<p>i then need a function like this:</p>
<pre><code>print_var_name($FooBar);
</code></pre>
<p>which prints:</p>
<pre><code>FooBar
</code></pre>
<p>Any Ideas how to achieve this? Is this even possible in PHP?</p>
|
[
{
"answer_id": 255319,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": -1,
"selected": false,
"text": "<p>I really fail to see the use case... If you will type print_var_name($foobar) what's so hard (and different) about typing print(\"foobar\") instead? </p>\n\n<p>Because even if you were to use this in a function, you'd get the local name of the variable...</p>\n\n<p>In any case, here's the <a href=\"http://www.php.net/oop5.reflection\" rel=\"nofollow noreferrer\">reflection manual</a> in case there's something you need in there.</p>\n"
},
{
"answer_id": 255335,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 7,
"selected": true,
"text": "<p>You could use <a href=\"http://php.net/get_defined_vars\" rel=\"noreferrer\">get_defined_vars()</a> to find the name of a variable that has the same value as the one you're trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it's the only way I can think of to do this.</p>\n\n<p>Edit: get_defined_vars() doesn't seem to be working correctly, it returns 'var' because $var is used in the function itself. $GLOBALS seems to work so I've changed it to that.</p>\n\n<pre><code>function print_var_name($var) {\n foreach($GLOBALS as $var_name => $value) {\n if ($value === $var) {\n return $var_name;\n }\n }\n\n return false;\n}\n</code></pre>\n\n<p>Edit: to be clear, there is no good way to do this in PHP, which is probably because you shouldn't have to do it. There are probably better ways of doing what you're trying to do.</p>\n"
},
{
"answer_id": 255498,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 1,
"selected": false,
"text": "<p>If the variable is interchangable, you must have logic <em>somewhere</em> that's determining which variable gets used. All you need to do is put the variable name in <code>$variable</code> within that logic while you're doing everything else.</p>\n\n<p>I think we're all having a hard time understanding what you're needing this for. Sample code or an explanation of what you're actually trying to <em>do</em> might help, but I suspect you're way, <strong>way</strong> overthinking this.</p>\n"
},
{
"answer_id": 404562,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>You might consider changing your approach and using a variable variable name?</p>\n\n<pre><code>$var_name = \"FooBar\";\n$$var_name = \"a string\";\n</code></pre>\n\n<p>then you could just </p>\n\n<pre><code>print($var_name);\n</code></pre>\n\n<p>to get </p>\n\n<pre><code>FooBar\n</code></pre>\n\n<p>Here's the link to the <a href=\"http://us3.php.net/variables.variable\" rel=\"noreferrer\">PHP manual on Variable variables</a></p>\n"
},
{
"answer_id": 404637,
"author": "Nick Presta",
"author_id": 40906,
"author_profile": "https://Stackoverflow.com/users/40906",
"pm_score": 6,
"selected": false,
"text": "<p>I couldn't think of a way to do this efficiently either but I came up with this. It works, for the limited uses below. </p>\n\n<p><em>shrug</em></p>\n\n<pre><code><?php\n\nfunction varName( $v ) {\n $trace = debug_backtrace();\n $vLine = file( __FILE__ );\n $fLine = $vLine[ $trace[0]['line'] - 1 ];\n preg_match( \"#\\\\$(\\w+)#\", $fLine, $match );\n print_r( $match );\n}\n\n$foo = \"knight\";\n$bar = array( 1, 2, 3 );\n$baz = 12345;\n\nvarName( $foo );\nvarName( $bar );\nvarName( $baz );\n\n?>\n\n// Returns\nArray\n(\n [0] => $foo\n [1] => foo\n)\nArray\n(\n [0] => $bar\n [1] => bar\n)\nArray\n(\n [0] => $baz\n [1] => baz\n)\n</code></pre>\n\n<p>It works based on the line that called the function, where it finds the argument you passed in. I suppose it could be expanded to work with multiple arguments but, like others have said, if you could explain the situation better, another solution would probably work better.</p>\n"
},
{
"answer_id": 1232338,
"author": "Xyz",
"author_id": 150926,
"author_profile": "https://Stackoverflow.com/users/150926",
"pm_score": 1,
"selected": false,
"text": "<p>I actually have a valid use case for this.</p>\n\n<p>I have a function cacheVariable($var) (ok, I have a function cache($key, $value), but I'd like to have a function as mentioned).</p>\n\n<p>The purpose is to do:</p>\n\n<pre><code>$colour = 'blue';\ncacheVariable($colour);\n</code></pre>\n\n<p>...</p>\n\n<pre><code>// another session\n</code></pre>\n\n<p>...</p>\n\n<pre><code>$myColour = getCachedVariable('colour');\n</code></pre>\n\n<p>I have tried with </p>\n\n<pre><code>function cacheVariable($variable) {\n $key = ${$variable}; // This doesn't help! It only gives 'variable'.\n // do some caching using suitable backend such as apc, memcache or ramdisk\n}\n</code></pre>\n\n<p>I have also tried with</p>\n\n<pre><code>function varName(&$var) {\n $definedVariables = get_defined_vars();\n $copyOfDefinedVariables = array();\n foreach ($definedVariables as $variable=>$value) {\n $copyOfDefinedVariables[$variable] = $value;\n }\n $oldVar = $var;\n $var = !$var;\n $difference = array_diff_assoc($definedVariables, $copyOfDefinedVariables);\n $var = $oldVar;\n return key(array_slice($difference, 0, 1, true));\n}\n</code></pre>\n\n<p>But this fails as well... :(</p>\n\n<p>Sure, I could continue to do cache('colour', $colour), but I'm lazy, you know... ;)</p>\n\n<p>So, what I want is a function that gets the ORIGINAL name of a variable, as it was passed to a function. Inside the function there is no way I'm able to know that, as it seems. Passing get_defined_vars() by reference in the second example above helped me (Thanks to Jean-Jacques Guegan for that idea) somewhat. The latter function started working, but it still only kept returning the local variable ('variable', not 'colour'). </p>\n\n<p>I haven't tried yet to use get_func_args() and get_func_arg(), ${}-constructs and key() combined, but I presume it will fail as well.</p>\n"
},
{
"answer_id": 2414745,
"author": "Sebastián Grignoli",
"author_id": 290221,
"author_profile": "https://Stackoverflow.com/users/290221",
"pm_score": 4,
"selected": false,
"text": "<p>I made an inspection function for debugging reasons. It's like print_r() on steroids, much like Krumo but a little more effective on objects. I wanted to add the var name detection and came out with this, inspired by Nick Presta's post on this page. It detects any expression passed as an argument, not only variable names. </p>\n\n<p>This is only the wrapper function that detects the passed expression.\nWorks on most of the cases. \nIt will not work if you call the function more than once in the same line of code.</p>\n\n<p>This works fine:\n die(<strong>inspect(<em></strong>$this->getUser()->hasCredential(\"delete\")<strong></em>)</strong>);</p>\n\n<p>inspect() is the function that will detect the passed expression.</p>\n\n<p>We get: <em>$this->getUser()->hasCredential(\"delete\")</em></p>\n\n<pre><code>function inspect($label, $value = \"__undefin_e_d__\")\n{\n if($value == \"__undefin_e_d__\") {\n\n /* The first argument is not the label but the \n variable to inspect itself, so we need a label.\n Let's try to find out it's name by peeking at \n the source code. \n */\n\n /* The reason for using an exotic string like \n \"__undefin_e_d__\" instead of NULL here is that \n inspected variables can also be NULL and I want \n to inspect them anyway.\n */\n\n $value = $label;\n\n $bt = debug_backtrace();\n $src = file($bt[0][\"file\"]);\n $line = $src[ $bt[0]['line'] - 1 ];\n\n // let's match the function call and the last closing bracket\n preg_match( \"#inspect\\((.+)\\)#\", $line, $match );\n\n /* let's count brackets to see how many of them actually belongs \n to the var name\n Eg: die(inspect($this->getUser()->hasCredential(\"delete\")));\n We want: $this->getUser()->hasCredential(\"delete\")\n */\n $max = strlen($match[1]);\n $varname = \"\";\n $c = 0;\n for($i = 0; $i < $max; $i++){\n if( $match[1]{$i} == \"(\" ) $c++;\n elseif( $match[1]{$i} == \")\" ) $c--;\n if($c < 0) break;\n $varname .= $match[1]{$i};\n }\n $label = $varname;\n }\n\n // $label now holds the name of the passed variable ($ included)\n // Eg: inspect($hello) \n // => $label = \"$hello\"\n // or the whole expression evaluated\n // Eg: inspect($this->getUser()->hasCredential(\"delete\"))\n // => $label = \"$this->getUser()->hasCredential(\\\"delete\\\")\"\n\n // now the actual function call to the inspector method, \n // passing the var name as the label:\n\n // return dInspect::dump($label, $val);\n // UPDATE: I commented this line because people got confused about \n // the dInspect class, wich has nothing to do with the issue here.\n\n echo(\"The label is: \".$label);\n echo(\"The value is: \".$value);\n\n}\n</code></pre>\n\n<p>Here's an example of the inspector function (and my dInspect class) in action:</p>\n\n<p><a href=\"http://inspect.ip1.cc\" rel=\"nofollow noreferrer\">http://inspect.ip1.cc</a></p>\n\n<p>Texts are in spanish in that page, but code is concise and really easy to understand.</p>\n"
},
{
"answer_id": 3046038,
"author": "Will Fastie",
"author_id": 330377,
"author_profile": "https://Stackoverflow.com/users/330377",
"pm_score": 1,
"selected": false,
"text": "<p>I have this:</p>\n\n<pre><code> debug_echo(array('$query'=>$query, '$nrUsers'=>$nrUsers, '$hdr'=>$hdr));\n</code></pre>\n\n<p>I would prefer this:</p>\n\n<pre><code> debug_echo($query, $nrUsers, $hdr);\n</code></pre>\n\n<p>The existing function displays a yellow box with a red outline and shows each variable by name and value. The array solution works but is a little convoluted to type when it is needed.</p>\n\n<p>That's my use case and yes, it does have to do with debugging. I agree with those who question its use otherwise.</p>\n"
},
{
"answer_id": 4034225,
"author": "Workman",
"author_id": 488909,
"author_profile": "https://Stackoverflow.com/users/488909",
"pm_score": 4,
"selected": false,
"text": "<p>Lucas on PHP.net provided a reliable way to check if a variable exists. In his example, he iterates through a copy of the global variable array (or a scoped array) of variables, changes the value to a randomly generated value, and checks for the generated value in the copied array. </p>\n\n<pre><code>function variable_name( &$var, $scope=false, $prefix='UNIQUE', $suffix='VARIABLE' ){\n if($scope) {\n $vals = $scope;\n } else {\n $vals = $GLOBALS;\n }\n $old = $var;\n $var = $new = $prefix.rand().$suffix;\n $vname = FALSE;\n foreach($vals as $key => $val) {\n if($val === $new) $vname = $key;\n }\n $var = $old;\n return $vname;\n}\n</code></pre>\n\n<p>Then try:</p>\n\n<pre><code>$a = 'asdf';\n$b = 'asdf';\n$c = FALSE;\n$d = FALSE;\n\necho variable_name($a); // a\necho variable_name($b); // b\necho variable_name($c); // c\necho variable_name($d); // d\n</code></pre>\n\n<p>Be sure to check his post on PHP.net: <a href=\"http://php.net/manual/en/language.variables.php\" rel=\"noreferrer\">http://php.net/manual/en/language.variables.php</a></p>\n"
},
{
"answer_id": 6403889,
"author": "AnOldMan",
"author_id": 805562,
"author_profile": "https://Stackoverflow.com/users/805562",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you just build a simple function and TELL it?</p>\n\n<pre><code>/**\n * Prints out $obj for debug\n *\n * @param any_type $obj\n * @param (string) $title\n */\nfunction print_all( $obj, $title = false )\n{\n print \"\\n<div style=\\\"font-family:Arial;\\\">\\n\";\n if( $title ) print \"<div style=\\\"background-color:red; color:white; font-size:16px; font-weight:bold; margin:0; padding:10px; text-align:center;\\\">$title</div>\\n\";\n print \"<pre style=\\\"background-color:yellow; border:2px solid red; color:black; margin:0; padding:10px;\\\">\\n\\n\";\n var_export( $obj );\n print \"\\n\\n</pre>\\n</div>\\n\";\n}\n\nprint_all( $aUser, '$aUser' );\n</code></pre>\n"
},
{
"answer_id": 7049999,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>From <a href=\"http://www.php.net/manual/en/language.variables.php#49997\" rel=\"noreferrer\" title=\"php.net\">php.net</a></p>\n\n<p>@Alexandre - short solution</p>\n\n<pre><code><?php\nfunction vname(&$var, $scope=0)\n{\n $old = $var;\n if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key; \n}\n?>\n</code></pre>\n\n<p>@Lucas - usage</p>\n\n<pre><code><?php\n//1. Use of a variable contained in the global scope (default):\n $my_global_variable = \"My global string.\";\n echo vname($my_global_variable); // Outputs: my_global_variable\n\n//2. Use of a local variable:\n function my_local_func()\n {\n $my_local_variable = \"My local string.\";\n return vname($my_local_variable, get_defined_vars());\n }\n echo my_local_func(); // Outputs: my_local_variable\n\n//3. Use of an object property:\n class myclass\n {\n public function __constructor()\n {\n $this->my_object_property = \"My object property string.\";\n }\n }\n $obj = new myclass;\n echo vname($obj->my_object_property, $obj); // Outputs: my_object_property\n?>\n</code></pre>\n"
},
{
"answer_id": 9614338,
"author": "dakiquang",
"author_id": 931877,
"author_profile": "https://Stackoverflow.com/users/931877",
"pm_score": 1,
"selected": false,
"text": "<p>Here's my solution based on <code>Jeremy Ruten</code></p>\n\n<pre><code>class DebugHelper {\n\n function printVarNames($systemDefinedVars, $varNames) {\n foreach ($systemDefinedVars as $var=>$value) {\n if (in_array($var, $varNames )) {\n var_dump($var);\n var_dump($value);\n }\n }\n }\n}\n</code></pre>\n\n<p>using it</p>\n\n<pre><code>DebugHelper::printVarNames(\n $systemDefinedVars = get_defined_vars(),\n $varNames=array('yourVar00', 'yourVar01')\n);\n</code></pre>\n"
},
{
"answer_id": 9730533,
"author": "K. Brunner",
"author_id": 1272978,
"author_profile": "https://Stackoverflow.com/users/1272978",
"pm_score": 3,
"selected": false,
"text": "<p>Many replies question the usefulness of this. However, getting a reference for a variable can be very useful. Especially in cases with objects and <em>$this</em>. My solution works with objects, and as property defined objects as well:</p>\n\n<pre><code>function getReference(&$var)\n{\n if(is_object($var))\n $var->___uniqid = uniqid();\n else\n $var = serialize($var);\n $name = getReference_traverse($var,$GLOBALS);\n if(is_object($var))\n unset($var->___uniqid);\n else\n $var = unserialize($var);\n return \"\\${$name}\"; \n}\n\nfunction getReference_traverse(&$var,$arr)\n{\n if($name = array_search($var,$arr,true))\n return \"{$name}\";\n foreach($arr as $key=>$value)\n if(is_object($value))\n if($name = getReference_traverse($var,get_object_vars($value)))\n return \"{$key}->{$name}\";\n}\n</code></pre>\n\n<p>Example for the above:</p>\n\n<pre><code>class A\n{\n public function whatIs()\n {\n echo getReference($this);\n }\n}\n\n$B = 12;\n$C = 12;\n$D = new A;\n\necho getReference($B).\"<br/>\"; //$B\necho getReference($C).\"<br/>\"; //$C\n$D->whatIs(); //$D\n</code></pre>\n"
},
{
"answer_id": 10435829,
"author": "Ajaxmint",
"author_id": 1373122,
"author_profile": "https://Stackoverflow.com/users/1373122",
"pm_score": -1,
"selected": false,
"text": "<p>why we have to use globals to get variable name... we can use simply like below.</p>\n\n<pre><code> $variableName = \"ajaxmint\";\n\n echo getVarName('$variableName');\n\n function getVarName($name) {\n return str_replace('$','',$name);\n }\n</code></pre>\n"
},
{
"answer_id": 10959842,
"author": "user1446000",
"author_id": 1446000,
"author_profile": "https://Stackoverflow.com/users/1446000",
"pm_score": -1,
"selected": false,
"text": "<p>Use this to detach user variables from global to check variable at the moment. </p>\n\n<pre><code>function get_user_var_defined () \n{\n return array_slice($GLOBALS,8,count($GLOBALS)-8); \n}\n\nfunction get_var_name ($var) \n{\n $vuser = get_user_var_defined(); \n foreach($vuser as $key=>$value) \n {\n if($var===$value) return $key ; \n }\n}\n</code></pre>\n"
},
{
"answer_id": 13391688,
"author": "Kieron Axten",
"author_id": 1825667,
"author_profile": "https://Stackoverflow.com/users/1825667",
"pm_score": 0,
"selected": false,
"text": "<p>I was looking for this but just decided to pass the name in, I usually have the name in the clipboard anyway.</p>\n\n<pre><code>function VarTest($my_var,$my_var_name){\n echo '$'.$my_var_name.': '.$my_var.'<br />';\n}\n\n$fruit='apple';\nVarTest($fruit,'fruit');\n</code></pre>\n"
},
{
"answer_id": 14062672,
"author": "user1933288",
"author_id": 1933288,
"author_profile": "https://Stackoverflow.com/users/1933288",
"pm_score": 2,
"selected": false,
"text": "<p>Adapted from answers above for many variables, with good performance, just one $GLOBALS scan for many</p>\n\n<pre><code>function compact_assoc(&$v1='__undefined__', &$v2='__undefined__',&$v3='__undefined__',&$v4='__undefined__',&$v5='__undefined__',&$v6='__undefined__',&$v7='__undefined__',&$v8='__undefined__',&$v9='__undefined__',&$v10='__undefined__',&$v11='__undefined__',&$v12='__undefined__',&$v13='__undefined__',&$v14='__undefined__',&$v15='__undefined__',&$v16='__undefined__',&$v17='__undefined__',&$v18='__undefined__',&$v19='__undefined__'\n) {\n $defined_vars=get_defined_vars();\n\n $result=Array();\n $reverse_key=Array();\n $original_value=Array();\n foreach( $defined_vars as $source_key => $source_value){\n if($source_value==='__undefined__') break;\n $original_value[$source_key]=$$source_key;\n $new_test_value=\"PREFIX\".rand().\"SUFIX\";\n $reverse_key[$new_test_value]=$source_key;\n $$source_key=$new_test_value;\n\n }\n foreach($GLOBALS as $key => &$value){\n if( is_string($value) && isset($reverse_key[$value]) ) {\n $result[$key]=&$value;\n }\n }\n foreach( $original_value as $source_key => $original_value){\n $$source_key=$original_value;\n }\n return $result;\n}\n\n\n$a = 'A';\n$b = 'B';\n$c = '999';\n$myArray=Array ('id'=>'id123','name'=>'Foo');\nprint_r(compact_assoc($a,$b,$c,$myArray) );\n\n//print\nArray\n(\n [a] => A\n [b] => B\n [c] => 999\n [myArray] => Array\n (\n [id] => id123\n [name] => Foo\n )\n\n)\n</code></pre>\n"
},
{
"answer_id": 15936154,
"author": "IMSoP",
"author_id": 157957,
"author_profile": "https://Stackoverflow.com/users/157957",
"pm_score": 5,
"selected": false,
"text": "<p>No-one seems to have mentioned the fundamental reasons <em>why</em> this is a) hard and b) unwise:</p>\n\n<ul>\n<li>A \"variable\" is just a symbol pointing at something else. In PHP, it internally points to something called a \"zval\", which can actually be used for multiple variables simultaneously, either because they have the same value (PHP implements something called \"copy-on-write\" so that <code>$foo = $bar</code> doesn't need to allocate extra memory straight away) or because they have been assigned (or passed to a function) by reference (e.g. <code>$foo =& $bar</code>). So a zval has no name.</li>\n<li>When you pass a parameter to a function you are creating a <em>new</em> variable (even if it's a reference). You could pass something anonymous, like <code>\"hello\"</code>, but once inside your function, it's whatever variable you name it as. This is fairly fundamental to code separation: if a function relied on what a variable <em>used</em> to be called, it would be more like a <code>goto</code> than a properly separate function.</li>\n<li>Global variables are generally considered a bad idea. A lot of the examples here assume that the variable you want to \"reflect\" can be found in <code>$GLOBALS</code>, but this will only be true if you've structured your code badly and variables aren't scoped to some function or object.</li>\n<li>Variable names are there to help programmers read their code. Renaming variables to better suit their purpose is a very common refactoring practice, and the whole point is that it doesn't make any difference.</li>\n</ul>\n\n<p>Now, I understand the desire for this for debugging (although some of the proposed usages go far beyond that), but as a generalised solution it's not actually as helpful as you might think: if your debug function says your variable is called \"$file\", that could still be any one of dozens of \"$file\" variables in your code, or a variable which you have called \"$filename\" but are passing to a function whose parameter is called \"$file\".</p>\n\n<p>A far more useful piece of information is where in your code the debug function was called from. Since you can quickly find this in your editor, you can see which variable you were outputting for yourself, and can even pass whole expressions into it in one go (e.g. <code>debug('$foo + $bar = ' . ($foo + $bar))</code>).</p>\n\n<p>For that, you can use this snippet at the top of your debug function:</p>\n\n<pre><code>$backtrace = debug_backtrace();\necho '# Debug function called from ' . $backtrace[0]['file'] . ' at line ' . $backtrace[0]['line'];\n</code></pre>\n"
},
{
"answer_id": 21973770,
"author": "user3344253",
"author_id": 3344253,
"author_profile": "https://Stackoverflow.com/users/3344253",
"pm_score": -1,
"selected": false,
"text": "<p>It may be considered quick and dirty, but my own personal preference is to use a function/method like this:</p>\n\n<pre><code>public function getVarName($var) { \n $tmp = array($var => '');\n $keys = array_keys($tmp);\n return trim($keys[0]);\n}\n</code></pre>\n\n<p>basically it just creates an associative array containing one null/empty element, using as a key the variable for which you want the name.</p>\n\n<p>we then get the value of that key using array_keys and return it.</p>\n\n<p>obviously this gets messy quick and wouldn't be desirable in a production environment, but it works for the problem presented.</p>\n"
},
{
"answer_id": 26045008,
"author": "Budove",
"author_id": 1628741,
"author_profile": "https://Stackoverflow.com/users/1628741",
"pm_score": 1,
"selected": false,
"text": "<p>You could use compact() to achieve this.</p>\n\n<pre><code>$FooBar = \"a string\";\n\n$newArray = compact('FooBar');\n</code></pre>\n\n<p>This would create an associative array with the variable name as the key. You could then loop through the array using the key name where you needed it.</p>\n\n<pre><code>foreach($newarray as $key => $value) {\n echo $key;\n}\n</code></pre>\n"
},
{
"answer_id": 29436177,
"author": "Janaka R Rajapaksha",
"author_id": 2020193,
"author_profile": "https://Stackoverflow.com/users/2020193",
"pm_score": 1,
"selected": false,
"text": "<p>I think you want to know variable name with it's value. You can use an associative array to achieve this.</p>\n\n<p>use variable names for array keys:</p>\n\n<pre><code>$vars = array('FooBar' => 'a string');\n</code></pre>\n\n<p>When you want to get variable names, use <code>array_keys($vars)</code>, it will return an array of those variable names that used in your <code>$vars</code> array as it's keys.</p>\n"
},
{
"answer_id": 36921487,
"author": "adilbo",
"author_id": 5201919,
"author_profile": "https://Stackoverflow.com/users/5201919",
"pm_score": 5,
"selected": false,
"text": "<p>This is exactly what you want - its a ready to use "copy and drop in" function that echo the name of a given var:</p>\n<pre><code>function print_var_name(){\n // read backtrace\n $bt = debug_backtrace();\n // read file\n $file = file($bt[0]['file']);\n // select exact print_var_name($varname) line\n $src = $file[$bt[0]['line']-1];\n // search pattern\n $pat = '#(.*)'.__FUNCTION__.' *?\\( *?(.*) *?\\)(.*)#i';\n // extract $varname from match no 2\n $var = preg_replace($pat, '$2', $src);\n // print to browser\n echo '<pre>' . trim($var) . ' = ' . print_r(current(func_get_args()), true) . '</pre>';\n}\n</code></pre>\n<p>USAGE: print_var_name($FooBar)</p>\n<p>PRINT: FooBar</p>\n<blockquote>\n<p><strong>HINT</strong><br>\nNow you can rename the function and it will still work and also use the function several times in one line! Thanks to @Cliffordlife<br>\nAnd I add a nicer output! Thanks to @Blue-Water</p>\n</blockquote>\n"
},
{
"answer_id": 60701076,
"author": "Stuperfied",
"author_id": 5411736,
"author_profile": "https://Stackoverflow.com/users/5411736",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is old and already answered but I was actually looking for this. I am posting this answer to save people a little time refining some of the answers. </p>\n\n<p>Option 1: </p>\n\n<pre><code>$data = array('$FooBar'); \n\n$vars = []; \n$vars = preg_replace('/^\\\\$/', '', $data); \n\n$varname = key(compact($vars)); \necho $varname;\n</code></pre>\n\n<p>Prints:</p>\n\n<blockquote>\n <p>FooBar</p>\n</blockquote>\n\n<p>For whatever reason you would find yourself in a situation like this, it does actually work. </p>\n\n<p>.<br>\nOption 2: </p>\n\n<pre><code>$FooBar = \"a string\"; \n\n$varname = trim(array_search($FooBar, $GLOBALS), \" \\t.\"); \necho $varname;\n</code></pre>\n\n<p>If <code>$FooBar</code> holds a unique value, it will print 'FooBar'. If <code>$FooBar</code> is empty or null it will print the name of the first empty or null string it finds.</p>\n\n<p>It could be used as such: </p>\n\n<pre><code>if (isset($FooBar) && !is_null($FooBar) && !empty($FooBar)) {\n $FooBar = \"a string\";\n $varname = trim(array_search($FooBar, $GLOBALS), \" \\t.\");\n}\n</code></pre>\n"
},
{
"answer_id": 61442261,
"author": "Rain",
"author_id": 5999372,
"author_profile": "https://Stackoverflow.com/users/5999372",
"pm_score": 1,
"selected": false,
"text": "<p>This is the way I did it</p>\n\n<pre><code>function getVar(&$var) {\n $tmp = $var; // store the variable value\n $var = '_$_%&33xc$%^*7_r4'; // give the variable a new unique value\n $name = array_search($var, $GLOBALS); // search $GLOBALS for that unique value and return the key(variable)\n $var = $tmp; // restore the variable old value\n return $name;\n}\n</code></pre>\n\n<p><strong>Usage</strong></p>\n\n<pre><code>$city = \"San Francisco\";\necho getVar($city); // city\n</code></pre>\n\n<p><strong>Note:</strong> some PHP 7 versions will not work properly due to a bug in <code>array_search</code> with <code>$GLOBALS</code>, however all other versions will work.</p>\n\n<p>See this <a href=\"https://3v4l.org/UMW7V\" rel=\"nofollow noreferrer\">https://3v4l.org/UMW7V</a></p>\n"
},
{
"answer_id": 65645016,
"author": "thomas",
"author_id": 12903396,
"author_profile": "https://Stackoverflow.com/users/12903396",
"pm_score": 1,
"selected": false,
"text": "<p>There is no predefined function in PHP that can output the name of a variable. However, you can use the result of <code>get_defined_vars()</code>, which returns all the variables defined in the scope, including name and value. Here is an example:</p>\n<pre><code><?php\n // Function for determining the name of a variable\n function getVarName(&$var, $definedVars=null) {\n $definedVars = (!is_array($definedVars) ? $GLOBALS : $definedVars);\n $val = $var;\n $rand = 1;\n while (in_array($rand, $definedVars, true)) {\n $rand = md5(mt_rand(10000, 1000000));\n }\n $var = $rand;\n \n foreach ($definedVars as $dvName=>$dvVal) {\n if ($dvVal === $rand) {\n $var = $val;\n return $dvName;\n }\n }\n \n return null;\n }\n \n // the name of $a is to be determined. \n $a = 1;\n \n // Determine the name of $a\n echo getVarName($a);\n?>\n</code></pre>\n<p>Read more in <a href=\"https://stackhowto.com/how-to-get-a-variable-name-as-a-string-in-php/\" rel=\"nofollow noreferrer\">How to get a variable name as a string in PHP?</a></p>\n"
},
{
"answer_id": 69171251,
"author": "Juan Carlos Constantine",
"author_id": 3083631,
"author_profile": "https://Stackoverflow.com/users/3083631",
"pm_score": 0,
"selected": false,
"text": "<p>other use:</p>\n<p>shrug</p>\n<pre><code>function varsToArrayAssoc(...$arguments){\n \n $bt = debug_backtrace();\n $file = file($bt[0]['file']);\n $src = $file[$bt[0]['line']-1];\n $pat = '#(.*)'.__FUNCTION__.' *?\\( *?(.*) *?\\)(.*)#i';\n $vars =explode(',',substr_replace(trim(preg_replace($pat, '$2', $src)) ,"", -1));\n $result=[];\n foreach(func_get_args() as $key=>$v){\n $index=trim(explode('$',$vars[$key])[1]);\n $result[$index]=$v;\n }\n return $result;\n}\n\n$a=12;\n$b=13;\n$c=123;\n$d='aa';\n\nvar_dump(varsToArrayAssoc($a,$b,$c,$d));\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] |
Say i have this PHP code:
```
$FooBar = "a string";
```
i then need a function like this:
```
print_var_name($FooBar);
```
which prints:
```
FooBar
```
Any Ideas how to achieve this? Is this even possible in PHP?
|
You could use [get\_defined\_vars()](http://php.net/get_defined_vars) to find the name of a variable that has the same value as the one you're trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it's the only way I can think of to do this.
Edit: get\_defined\_vars() doesn't seem to be working correctly, it returns 'var' because $var is used in the function itself. $GLOBALS seems to work so I've changed it to that.
```
function print_var_name($var) {
foreach($GLOBALS as $var_name => $value) {
if ($value === $var) {
return $var_name;
}
}
return false;
}
```
Edit: to be clear, there is no good way to do this in PHP, which is probably because you shouldn't have to do it. There are probably better ways of doing what you're trying to do.
|
255,317 |
<p>I have an asp.net page with a button. This button generates and inserts a user control into the page, so many controls could exist on one page. I need to validate that a certain dynamically generated control inside the generated control exists. </p>
<p>So..Page has 0 to N Control1’s. Each Control 1 can have 0 to N Control2’s. When SaveButton is clicked on Page, I need to make sure there are at least 1 Control2’s inside every Control1. </p>
<p>I’m currently between two options:</p>
<p>• Dynamically insert CustomValidators for each control that is generated, each of which would validate one Control1.</p>
<p>• Do the validation manually (with jQuery), calling a validation function from SaveButton.OnClientClick.</p>
<p>Both are sloppy in their own way – which is why I’m sharing this with you all. Am I missing the easy solution?</p>
<p>Thanks in advance.. (btw – anything up to and including .NET 3.5 SP1 is fair game)</p>
|
[
{
"answer_id": 255933,
"author": "tbreffni",
"author_id": 637,
"author_profile": "https://Stackoverflow.com/users/637",
"pm_score": 0,
"selected": false,
"text": "<p>One method you could try is creating and maintaining a simple xml structure that represents your custom control hierarchy. Insert or delete from this structure any time you create or destroy a custom user control. Upon save, validate that the control hierarchy represented in the xml structure is correct. You could save the xml in the Session object to persist it across postbacks.</p>\n"
},
{
"answer_id": 255957,
"author": "digiguru",
"author_id": 5055,
"author_profile": "https://Stackoverflow.com/users/5055",
"pm_score": 2,
"selected": false,
"text": "<p>If you are adding user controls on the fly, you could make each control implement the same interface with a Validate function. That way you can load the controls into a placeholder in each parent control on the page. When the page is submitted, simply loop through the controls in the placeholder, cast them to the interface class and then call the validate function. I doesn't use custom validators, but you can build up a list of validation errors using the object returned from the validate function, you can render this collection of validation errors whichever way you like.</p>\n"
},
{
"answer_id": 256251,
"author": "SecretDeveloper",
"author_id": 2720,
"author_profile": "https://Stackoverflow.com/users/2720",
"pm_score": 4,
"selected": true,
"text": "<p>Hmm i like the Interface idea suggested by digiguru but i would use the interface on the container Control1 instead of the sub controls as it seems like the more logical place for the code to live. Heres my take on it:</p>\n\n<pre><code>public interface IValidatableControl\n{\n bool IsValidControl(); \n}\n</code></pre>\n\n<p>then implement this on your Control1</p>\n\n<pre><code>public class Control1 : IValidatableControl\n{\n... Other methods\n public bool IsValidControl()\n {\n\n foreach(object c in this.Controls)\n {\n if(c.GetType() == \"Control2\")\n return true;\n }\n return false;\n }\n\n}\n</code></pre>\n\n<p>There are probably better ways to write this but it should give you enough of an idea to get started.</p>\n"
},
{
"answer_id": 309401,
"author": "Kelly Adams",
"author_id": 12734,
"author_profile": "https://Stackoverflow.com/users/12734",
"pm_score": 1,
"selected": false,
"text": "<p>I think you could do it by assigning a public property in Control1 that references the existence of Control2's ID, and then decorate Control1's class with ValidationProperty. I'm thinking something along these lines:</p>\n\n<pre><code>[ValidationProperty(\"Control2Ref\")]\npublic partial class Control1 : UserControl\n{\n public string Control2Ref\n {\n get { return FindControl(\"Control2\"); }\n }\n // rest of control 1 class\n}\n</code></pre>\n\n<p>And then you should be able to point a RequiredFieldValidator at an instance of Control1.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33253/"
] |
I have an asp.net page with a button. This button generates and inserts a user control into the page, so many controls could exist on one page. I need to validate that a certain dynamically generated control inside the generated control exists.
So..Page has 0 to N Control1’s. Each Control 1 can have 0 to N Control2’s. When SaveButton is clicked on Page, I need to make sure there are at least 1 Control2’s inside every Control1.
I’m currently between two options:
• Dynamically insert CustomValidators for each control that is generated, each of which would validate one Control1.
• Do the validation manually (with jQuery), calling a validation function from SaveButton.OnClientClick.
Both are sloppy in their own way – which is why I’m sharing this with you all. Am I missing the easy solution?
Thanks in advance.. (btw – anything up to and including .NET 3.5 SP1 is fair game)
|
Hmm i like the Interface idea suggested by digiguru but i would use the interface on the container Control1 instead of the sub controls as it seems like the more logical place for the code to live. Heres my take on it:
```
public interface IValidatableControl
{
bool IsValidControl();
}
```
then implement this on your Control1
```
public class Control1 : IValidatableControl
{
... Other methods
public bool IsValidControl()
{
foreach(object c in this.Controls)
{
if(c.GetType() == "Control2")
return true;
}
return false;
}
}
```
There are probably better ways to write this but it should give you enough of an idea to get started.
|
255,337 |
<p>I want to read and write from serial using events/interrupts.
Currently, I have it in a while loop and it continuously reads and writes through the serial. I want it to only read when something comes from the serial port. How do I implement this in C++?</p>
<p>This is my current code:</p>
<pre>
while(true)
{
//read
if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
//error occurred. Report to user.
}
//write
if(!WriteFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
//error occurred. Report to user.
}
//print what you are reading
printf("%s\n", szBuff);
}
</pre>
|
[
{
"answer_id": 255933,
"author": "tbreffni",
"author_id": 637,
"author_profile": "https://Stackoverflow.com/users/637",
"pm_score": 0,
"selected": false,
"text": "<p>One method you could try is creating and maintaining a simple xml structure that represents your custom control hierarchy. Insert or delete from this structure any time you create or destroy a custom user control. Upon save, validate that the control hierarchy represented in the xml structure is correct. You could save the xml in the Session object to persist it across postbacks.</p>\n"
},
{
"answer_id": 255957,
"author": "digiguru",
"author_id": 5055,
"author_profile": "https://Stackoverflow.com/users/5055",
"pm_score": 2,
"selected": false,
"text": "<p>If you are adding user controls on the fly, you could make each control implement the same interface with a Validate function. That way you can load the controls into a placeholder in each parent control on the page. When the page is submitted, simply loop through the controls in the placeholder, cast them to the interface class and then call the validate function. I doesn't use custom validators, but you can build up a list of validation errors using the object returned from the validate function, you can render this collection of validation errors whichever way you like.</p>\n"
},
{
"answer_id": 256251,
"author": "SecretDeveloper",
"author_id": 2720,
"author_profile": "https://Stackoverflow.com/users/2720",
"pm_score": 4,
"selected": true,
"text": "<p>Hmm i like the Interface idea suggested by digiguru but i would use the interface on the container Control1 instead of the sub controls as it seems like the more logical place for the code to live. Heres my take on it:</p>\n\n<pre><code>public interface IValidatableControl\n{\n bool IsValidControl(); \n}\n</code></pre>\n\n<p>then implement this on your Control1</p>\n\n<pre><code>public class Control1 : IValidatableControl\n{\n... Other methods\n public bool IsValidControl()\n {\n\n foreach(object c in this.Controls)\n {\n if(c.GetType() == \"Control2\")\n return true;\n }\n return false;\n }\n\n}\n</code></pre>\n\n<p>There are probably better ways to write this but it should give you enough of an idea to get started.</p>\n"
},
{
"answer_id": 309401,
"author": "Kelly Adams",
"author_id": 12734,
"author_profile": "https://Stackoverflow.com/users/12734",
"pm_score": 1,
"selected": false,
"text": "<p>I think you could do it by assigning a public property in Control1 that references the existence of Control2's ID, and then decorate Control1's class with ValidationProperty. I'm thinking something along these lines:</p>\n\n<pre><code>[ValidationProperty(\"Control2Ref\")]\npublic partial class Control1 : UserControl\n{\n public string Control2Ref\n {\n get { return FindControl(\"Control2\"); }\n }\n // rest of control 1 class\n}\n</code></pre>\n\n<p>And then you should be able to point a RequiredFieldValidator at an instance of Control1.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28462/"
] |
I want to read and write from serial using events/interrupts.
Currently, I have it in a while loop and it continuously reads and writes through the serial. I want it to only read when something comes from the serial port. How do I implement this in C++?
This is my current code:
```
while(true)
{
//read
if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
//error occurred. Report to user.
}
//write
if(!WriteFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
//error occurred. Report to user.
}
//print what you are reading
printf("%s\n", szBuff);
}
```
|
Hmm i like the Interface idea suggested by digiguru but i would use the interface on the container Control1 instead of the sub controls as it seems like the more logical place for the code to live. Heres my take on it:
```
public interface IValidatableControl
{
bool IsValidControl();
}
```
then implement this on your Control1
```
public class Control1 : IValidatableControl
{
... Other methods
public bool IsValidControl()
{
foreach(object c in this.Controls)
{
if(c.GetType() == "Control2")
return true;
}
return false;
}
}
```
There are probably better ways to write this but it should give you enough of an idea to get started.
|
255,341 |
<p>It's easy to get the value of a key from a .NET generic Dictionary:</p>
<pre><code>Dictionary<int, string> greek = new Dictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
string secondGreek = greek[2]; // Beta
</code></pre>
<p>But trying to get the keys given a value is not as straightforward because there could be multiple keys:</p>
<pre><code>int[] betaKeys = greek.WhatDoIPutHere("Beta"); // expecting single 2
</code></pre>
|
[
{
"answer_id": 255348,
"author": "dove",
"author_id": 30913,
"author_profile": "https://Stackoverflow.com/users/30913",
"pm_score": 2,
"selected": false,
"text": "<p>revised: okay to have some kind of find you would need something other than dictionary, since if you think about it dictionary are one way keys. that is, the values might not be unique</p>\n\n<p>that said it looks like you're using c#3.0 so you might not have to resort to looping and could use something like:</p>\n\n<pre><code>var key = (from k in yourDictionary where string.Compare(k.Value, \"yourValue\", true) == 0 select k.Key).FirstOrDefault();\n</code></pre>\n"
},
{
"answer_id": 255352,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 5,
"selected": false,
"text": "<p>Dictionaries aren't really meant to work like this, because while uniqueness of keys is guaranteed, uniqueness of values isn't. So e.g. if you had</p>\n\n<pre><code>var greek = new Dictionary<int, string> { { 1, \"Alpha\" }, { 2, \"Alpha\" } };\n</code></pre>\n\n<p>What would you expect to get for <code>greek.WhatDoIPutHere(\"Alpha\")</code>?</p>\n\n<p>Therefore you can't expect something like this to be rolled into the framework. You'd need your own method for your own unique uses---do you want to return an array (or <code>IEnumerable<T></code>)? Do you want to throw an exception if there are multiple keys with the given value? What about if there are none?</p>\n\n<p>Personally I'd go for an enumerable, like so:</p>\n\n<pre><code>IEnumerable<TKey> KeysFromValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TValue val)\n{\n if (dict == null)\n {\n throw new ArgumentNullException(\"dict\");\n }\n return dict.Keys.Where(k => dict[k] == val);\n}\n\nvar keys = greek.KeysFromValue(\"Beta\");\nint exceptionIfNotExactlyOne = greek.KeysFromValue(\"Beta\").Single();\n</code></pre>\n"
},
{
"answer_id": 255354,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 5,
"selected": false,
"text": "<p>Maybe the easiest way to do it, without Linq, can be to loop over the pairs:</p>\n\n<pre><code>int betaKey; \nforeach (KeyValuePair<int, string> pair in lookup)\n{\n if (pair.Value == value)\n {\n betaKey = pair.Key; // Found\n break;\n }\n}\nbetaKey = -1; // Not found\n</code></pre>\n\n<p>If you had Linq, it could have done easily this way:</p>\n\n<pre><code>int betaKey = greek.SingleOrDefault(x => x.Value == \"Beta\").Key;\n</code></pre>\n"
},
{
"answer_id": 255364,
"author": "Cybis",
"author_id": 32998,
"author_profile": "https://Stackoverflow.com/users/32998",
"pm_score": 1,
"selected": false,
"text": "<p>Can't you create a subclass of Dictionary which has that functionality?</p>\n\n<pre>\n<code>\n public class MyDict < TKey, TValue > : Dictionary < TKey, TValue >\n {\n private Dictionary < TValue, TKey > _keys;\n\n public TValue this[TKey key]\n {\n get\n {\n return base[key];\n }\n set \n { \n base[key] = value;\n _keys[value] = key;\n }\n }\n\n public MyDict()\n {\n _keys = new Dictionary < TValue, TKey >();\n }\n\n public TKey GetKeyFromValue(TValue value)\n {\n return _keys[value];\n }\n }\n</code>\n</pre>\n\n<p>EDIT: Sorry, didn't get code right first time.</p>\n"
},
{
"answer_id": 255391,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>A dictionary doesn't keep an hash of the values, only the keys, so any search over it using a value is going to take at least linear time. Your best bet is to simply iterate over the elements in the dictionary and keep track of the matching keys or switch to a different data structure, perhaps maintain two dictionary mapping key->value and value->List_of_keys. If you do the latter you will trade storage for look up speed. It wouldn't take much to turn @Cybis example into such a data structure.</p>\n"
},
{
"answer_id": 255630,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>As everyone else has said, there's no mapping within a dictionary from value to key.</p>\n\n<p><strong>I've just noticed you wanted to map to from value to multiple keys - I'm leaving this solution here for the single value version, but I'll then add another answer for a multi-entry bidirectional map.</strong></p>\n\n<p>The normal approach to take here is to have two dictionaries - one mapping one way and one the other. Encapsulate them in a separate class, and work out what you want to do when you have duplicate key or value (e.g. throw an exception, overwrite the existing entry, or ignore the new entry). Personally I'd probably go for throwing an exception - it makes the success behaviour easier to define. Something like this:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nclass BiDictionary<TFirst, TSecond>\n{\n IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();\n IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();\n\n public void Add(TFirst first, TSecond second)\n {\n if (firstToSecond.ContainsKey(first) ||\n secondToFirst.ContainsKey(second))\n {\n throw new ArgumentException(\"Duplicate first or second\");\n }\n firstToSecond.Add(first, second);\n secondToFirst.Add(second, first);\n }\n\n public bool TryGetByFirst(TFirst first, out TSecond second)\n {\n return firstToSecond.TryGetValue(first, out second);\n }\n\n public bool TryGetBySecond(TSecond second, out TFirst first)\n {\n return secondToFirst.TryGetValue(second, out first);\n }\n}\n\nclass Test\n{\n static void Main()\n {\n BiDictionary<int, string> greek = new BiDictionary<int, string>();\n greek.Add(1, \"Alpha\");\n greek.Add(2, \"Beta\");\n int x;\n greek.TryGetBySecond(\"Beta\", out x);\n Console.WriteLine(x);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 255638,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": true,
"text": "<p>Okay, here's the multiple bidirectional version:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\n\nclass BiDictionary<TFirst, TSecond>\n{\n IDictionary<TFirst, IList<TSecond>> firstToSecond = new Dictionary<TFirst, IList<TSecond>>();\n IDictionary<TSecond, IList<TFirst>> secondToFirst = new Dictionary<TSecond, IList<TFirst>>();\n\n private static IList<TFirst> EmptyFirstList = new TFirst[0];\n private static IList<TSecond> EmptySecondList = new TSecond[0];\n\n public void Add(TFirst first, TSecond second)\n {\n IList<TFirst> firsts;\n IList<TSecond> seconds;\n if (!firstToSecond.TryGetValue(first, out seconds))\n {\n seconds = new List<TSecond>();\n firstToSecond[first] = seconds;\n }\n if (!secondToFirst.TryGetValue(second, out firsts))\n {\n firsts = new List<TFirst>();\n secondToFirst[second] = firsts;\n }\n seconds.Add(second);\n firsts.Add(first);\n }\n\n // Note potential ambiguity using indexers (e.g. mapping from int to int)\n // Hence the methods as well...\n public IList<TSecond> this[TFirst first]\n {\n get { return GetByFirst(first); }\n }\n\n public IList<TFirst> this[TSecond second]\n {\n get { return GetBySecond(second); }\n }\n\n public IList<TSecond> GetByFirst(TFirst first)\n {\n IList<TSecond> list;\n if (!firstToSecond.TryGetValue(first, out list))\n {\n return EmptySecondList;\n }\n return new List<TSecond>(list); // Create a copy for sanity\n }\n\n public IList<TFirst> GetBySecond(TSecond second)\n {\n IList<TFirst> list;\n if (!secondToFirst.TryGetValue(second, out list))\n {\n return EmptyFirstList;\n }\n return new List<TFirst>(list); // Create a copy for sanity\n }\n}\n\nclass Test\n{\n static void Main()\n {\n BiDictionary<int, string> greek = new BiDictionary<int, string>();\n greek.Add(1, \"Alpha\");\n greek.Add(2, \"Beta\");\n greek.Add(5, \"Beta\");\n ShowEntries(greek, \"Alpha\");\n ShowEntries(greek, \"Beta\");\n ShowEntries(greek, \"Gamma\");\n }\n\n static void ShowEntries(BiDictionary<int, string> dict, string key)\n {\n IList<int> values = dict[key];\n StringBuilder builder = new StringBuilder();\n foreach (int value in values)\n {\n if (builder.Length != 0)\n {\n builder.Append(\", \");\n }\n builder.Append(value);\n }\n Console.WriteLine(\"{0}: [{1}]\", key, builder);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 255643,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 2,
"selected": false,
"text": "<p>Dictionary class is not optimized for this case, but if you really wanted to do it (in C# 2.0), you can do:</p>\n\n<pre><code>public List<TKey> GetKeysFromValue<TKey, TVal>(Dictionary<TKey, TVal> dict, TVal val)\n{\n List<TKey> ks = new List<TKey>();\n foreach(TKey k in dict.Keys)\n {\n if (dict[k] == val) { ks.Add(k); }\n }\n return ks;\n}\n</code></pre>\n\n<p>I prefer the LINQ solution for elegance, but this is the 2.0 way.</p>\n"
},
{
"answer_id": 11853278,
"author": "Loay",
"author_id": 1161506,
"author_profile": "https://Stackoverflow.com/users/1161506",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Dictionary<string, string> dic = new Dictionary<string, string>();\ndic[\"A\"] = \"Ahmed\";\ndic[\"B\"] = \"Boys\";\n\nforeach (string mk in dic.Keys)\n{\n if(dic[mk] == \"Ahmed\")\n {\n Console.WriteLine(\"The key that contains \\\"Ahmed\\\" is \" + mk);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 16198782,
"author": "Max Hodges",
"author_id": 861010,
"author_profile": "https://Stackoverflow.com/users/861010",
"pm_score": 1,
"selected": false,
"text": "<p>The \"simple\" bidirectional dictionary solution proposed here is complex and may be be difficult to understand, maintain or extend. Also the original question asked for \"the key for a value\", but clearly there could be multiple keys (I've since edited the question). The whole approach is rather suspicious. </p>\n\n<p>Software changes. Writing code that is easy to maintain should be given priority other \"clever\" complex workarounds. The way to get keys back from values in a dictionary is to loop. A dictionary isn't designed to be bidirectional. </p>\n"
},
{
"answer_id": 22230811,
"author": "DavidRR",
"author_id": 1497596,
"author_profile": "https://Stackoverflow.com/users/1497596",
"pm_score": 1,
"selected": false,
"text": "<p>Use <strong>LINQ</strong> to do a reverse <code>Dictionary<K, V></code> lookup. But keep in mind that the values in your <code>Dictionary<K, V></code> values may not be distinct.</p>\n\n<p><strong>Demonstration:</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass ReverseDictionaryLookupDemo\n{\n static void Main()\n {\n var dict = new Dictionary<int, string>();\n dict.Add(4, \"Four\");\n dict.Add(5, \"Five\");\n dict.Add(1, \"One\");\n dict.Add(11, \"One\"); // duplicate!\n dict.Add(3, \"Three\");\n dict.Add(2, \"Two\");\n dict.Add(44, \"Four\"); // duplicate!\n\n Console.WriteLine(\"\\n== Enumerating Distinct Values ==\");\n foreach (string value in dict.Values.Distinct())\n {\n string valueString =\n String.Join(\", \", GetKeysFromValue(dict, value));\n\n Console.WriteLine(\"{0} => [{1}]\", value, valueString);\n }\n }\n\n static List<int> GetKeysFromValue(Dictionary<int, string> dict, string value)\n {\n // Use LINQ to do a reverse dictionary lookup.\n // Returns a 'List<T>' to account for the possibility\n // of duplicate values.\n return\n (from item in dict\n where item.Value.Equals(value)\n select item.Key).ToList();\n }\n}\n</code></pre>\n\n<p><strong>Expected Output:</strong></p>\n\n<pre class=\"lang-none prettyprint-override\"><code>== Enumerating Distinct Values ==\nFour => [4, 44]\nFive => [5]\nOne => [1, 11]\nThree => [3]\nTwo => [2]\n</code></pre>\n"
},
{
"answer_id": 26724048,
"author": "Michail Michailidis",
"author_id": 986160,
"author_profile": "https://Stackoverflow.com/users/986160",
"pm_score": 0,
"selected": false,
"text": "<p>As a twist of the accepted answer (<a href=\"https://stackoverflow.com/a/255638/986160\">https://stackoverflow.com/a/255638/986160</a>) assuming that the keys will be associated with signle values in the dictionary. Similar to (<a href=\"https://stackoverflow.com/a/255630/986160\">https://stackoverflow.com/a/255630/986160</a>) but a bit more elegant. The novelty is in that the consuming class can be used as an enumeration alternative (but for strings too) and that the dictionary implements IEnumerable.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Collections;\n\nnamespace MyApp.Dictionaries\n{\n\n class BiDictionary<TFirst, TSecond> : IEnumerable\n {\n IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();\n IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();\n\n public void Add(TFirst first, TSecond second)\n {\n firstToSecond.Add(first, second);\n secondToFirst.Add(second, first);\n }\n\n public TSecond this[TFirst first]\n {\n get { return GetByFirst(first); }\n }\n\n public TFirst this[TSecond second]\n {\n get { return GetBySecond(second); }\n }\n\n public TSecond GetByFirst(TFirst first)\n {\n return firstToSecond[first];\n }\n\n public TFirst GetBySecond(TSecond second)\n {\n return secondToFirst[second];\n }\n\n public IEnumerator GetEnumerator()\n {\n return GetFirstEnumerator();\n }\n\n public IEnumerator GetFirstEnumerator()\n {\n return firstToSecond.GetEnumerator();\n }\n\n public IEnumerator GetSecondEnumerator()\n {\n return secondToFirst.GetEnumerator();\n }\n }\n}\n</code></pre>\n\n<p>And as a consuming class you could have </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace MyApp.Dictionaries\n{\n class Greek\n {\n\n public static readonly string Alpha = \"Alpha\";\n public static readonly string Beta = \"Beta\";\n public static readonly string Gamma = \"Gamma\";\n public static readonly string Delta = \"Delta\";\n\n\n private static readonly BiDictionary<int, string> Dictionary = new BiDictionary<int, string>();\n\n\n static Greek() {\n Dictionary.Add(1, Alpha);\n Dictionary.Add(2, Beta);\n Dictionary.Add(3, Gamma);\n Dictionary.Add(4, Delta);\n }\n\n public static string getById(int id){\n return Dictionary.GetByFirst(id);\n }\n\n public static int getByValue(string value)\n {\n return Dictionary.GetBySecond(value);\n }\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 40020615,
"author": "DW.com",
"author_id": 6406263,
"author_profile": "https://Stackoverflow.com/users/6406263",
"pm_score": 2,
"selected": false,
"text": "<p>As I wanted a full fledged BiDirectional Dictionary (and not only a Map), I added the missing functions to make it an IDictionary compatible class. This is based on the version with unique Key-Value Pairs. Here's the file if desired (Most work was the XMLDoc through):</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Common\n{\n /// <summary>Represents a bidirectional collection of keys and values.</summary>\n /// <typeparam name=\"TFirst\">The type of the keys in the dictionary</typeparam>\n /// <typeparam name=\"TSecond\">The type of the values in the dictionary</typeparam>\n [System.Runtime.InteropServices.ComVisible(false)]\n [System.Diagnostics.DebuggerDisplay(\"Count = {Count}\")]\n //[System.Diagnostics.DebuggerTypeProxy(typeof(System.Collections.Generic.Mscorlib_DictionaryDebugView<,>))]\n //[System.Reflection.DefaultMember(\"Item\")]\n public class BiDictionary<TFirst, TSecond> : Dictionary<TFirst, TSecond>\n {\n IDictionary<TSecond, TFirst> _ValueKey = new Dictionary<TSecond, TFirst>();\n /// <summary> PropertyAccessor for Iterator over KeyValue-Relation </summary>\n public IDictionary<TFirst, TSecond> KeyValue => this;\n /// <summary> PropertyAccessor for Iterator over ValueKey-Relation </summary>\n public IDictionary<TSecond, TFirst> ValueKey => _ValueKey;\n\n #region Implemented members\n\n /// <Summary>Gets or sets the value associated with the specified key.</Summary>\n /// <param name=\"key\">The key of the value to get or set.</param>\n /// <Returns>The value associated with the specified key. If the specified key is not found,\n /// a get operation throws a <see cref=\"KeyNotFoundException\"/>, and\n /// a set operation creates a new element with the specified key.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"key\"/> is null.</exception>\n /// <exception cref=\"T:System.Collections.Generic.KeyNotFoundException\">\n /// The property is retrieved and <paramref name=\"key\"/> does not exist in the collection.</exception>\n /// <exception cref=\"T:System.ArgumentException\"> An element with the same key already\n /// exists in the <see cref=\"ValueKey\"/> <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</exception>\n public new TSecond this[TFirst key]\n {\n get { return base[key]; }\n set { _ValueKey.Remove(base[key]); base[key] = value; _ValueKey.Add(value, key); }\n }\n\n /// <Summary>Gets or sets the key associated with the specified value.</Summary>\n /// <param name=\"val\">The value of the key to get or set.</param>\n /// <Returns>The key associated with the specified value. If the specified value is not found,\n /// a get operation throws a <see cref=\"KeyNotFoundException\"/>, and\n /// a set operation creates a new element with the specified value.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"val\"/> is null.</exception>\n /// <exception cref=\"T:System.Collections.Generic.KeyNotFoundException\">\n /// The property is retrieved and <paramref name=\"val\"/> does not exist in the collection.</exception>\n /// <exception cref=\"T:System.ArgumentException\"> An element with the same value already\n /// exists in the <see cref=\"KeyValue\"/> <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</exception>\n public TFirst this[TSecond val]\n {\n get { return _ValueKey[val]; }\n set { base.Remove(_ValueKey[val]); _ValueKey[val] = value; base.Add(value, val); }\n }\n\n /// <Summary>Adds the specified key and value to the dictionary.</Summary>\n /// <param name=\"key\">The key of the element to add.</param>\n /// <param name=\"value\">The value of the element to add.</param>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"key\"/> or <paramref name=\"value\"/> is null.</exception>\n /// <exception cref=\"T:System.ArgumentException\">An element with the same key or value already exists in the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</exception>\n public new void Add(TFirst key, TSecond value) {\n base.Add(key, value);\n _ValueKey.Add(value, key);\n }\n\n /// <Summary>Removes all keys and values from the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</Summary>\n public new void Clear() { base.Clear(); _ValueKey.Clear(); }\n\n /// <Summary>Determines whether the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/> contains the specified\n /// KeyValuePair.</Summary>\n /// <param name=\"item\">The KeyValuePair to locate in the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</param>\n /// <Returns>true if the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/> contains an element with\n /// the specified key which links to the specified value; otherwise, false.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"item\"/> is null.</exception>\n public bool Contains(KeyValuePair<TFirst, TSecond> item) => base.ContainsKey(item.Key) & _ValueKey.ContainsKey(item.Value);\n\n /// <Summary>Removes the specified KeyValuePair from the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</Summary>\n /// <param name=\"item\">The KeyValuePair to remove.</param>\n /// <Returns>true if the KeyValuePair is successfully found and removed; otherwise, false. This\n /// method returns false if <paramref name=\"item\"/> is not found in the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"item\"/> is null.</exception>\n public bool Remove(KeyValuePair<TFirst, TSecond> item) => base.Remove(item.Key) & _ValueKey.Remove(item.Value);\n\n /// <Summary>Removes the value with the specified key from the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</Summary>\n /// <param name=\"key\">The key of the element to remove.</param>\n /// <Returns>true if the element is successfully found and removed; otherwise, false. This\n /// method returns false if <paramref name=\"key\"/> is not found in the <see cref=\"Dictionary&lt;TFirst,TSecond&gt;\"/>.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"key\"/> is null.</exception>\n public new bool Remove(TFirst key) => _ValueKey.Remove(base[key]) & base.Remove(key);\n\n /// <Summary>Gets the key associated with the specified value.</Summary>\n /// <param name=\"value\">The value of the key to get.</param>\n /// <param name=\"key\">When this method returns, contains the key associated with the specified value,\n /// if the value is found; otherwise, the default value for the type of the key parameter.\n /// This parameter is passed uninitialized.</param>\n /// <Returns>true if <see cref=\"ValueKey\"/> contains an element with the specified value; \n /// otherwise, false.</Returns>\n /// <exception cref=\"T:System.ArgumentNullException\"><paramref name=\"value\"/> is null.</exception>\n public bool TryGetValue(TSecond value, out TFirst key) => _ValueKey.TryGetValue(value, out key);\n #endregion\n }\n}\n</code></pre>\n"
},
{
"answer_id": 50731776,
"author": "beppe9000",
"author_id": 3389585,
"author_profile": "https://Stackoverflow.com/users/3389585",
"pm_score": 0,
"selected": false,
"text": "<h2>Then layman's solution</h2>\n<p>A function similar to the one below could be written to make such a dictionary:</p>\n<pre><code> public Dictionary<TValue, TKey> Invert(Dictionary<TKey, TValue> dict) {\n Dictionary<TValue, TKey> ret = new Dictionary<TValue, TKey>();\n foreach (var kvp in dict) {ret[kvp.value] = kvp.key;} return ret; }\n</code></pre>\n"
},
{
"answer_id": 63500438,
"author": "Jessica",
"author_id": 5151441,
"author_profile": "https://Stackoverflow.com/users/5151441",
"pm_score": 1,
"selected": false,
"text": "<p><em>Many of these answers are now outdated, here is a modern C# approach, using LINQ</em></p>\n<p>Since values aren't necessarily unique, you may get multiple results. You can return an <code>IEnumerable<KeyValuePair<int, string>></code>:</p>\n<pre><code>var betaKeys = greek.Where(x => x.Value == "beta");\n</code></pre>\n<p>To transform this into an <code>IEnumerable<int></code> type, just use <code>.Select()</code>:</p>\n<pre><code>var betaKeys = greek.Where(x => x.Value == "beta").Select(x => x.Key);\n</code></pre>\n"
},
{
"answer_id": 73478394,
"author": "iiKuzmychov",
"author_id": 10846531,
"author_profile": "https://Stackoverflow.com/users/10846531",
"pm_score": 0,
"selected": false,
"text": "<p>Probably, you need a bidirectional dictionary. In my mind, <a href=\"https://github.com/iiKuzmychov/BidirectionalDictionary\" rel=\"nofollow noreferrer\">BidirectionalDictionary</a> is the best realization of a bidirectional dictionary. It just provides access to an inverse <code>O(1)</code> dictionary.</p>\n<pre><code>var biDictionary = new BidirectionalDictionary<T1,T2> { ... };\n</code></pre>\n<p>This realization, for example, has no indexations problems when <code>TKey</code> equals <code>TValue</code>:</p>\n<pre><code>var capital = countryCapitalDictionary["Italy"]; // "Rome"\nvar country = countryCapitalDictionary.Inverse["Rome"]; // "Italy"\n</code></pre>\n<p>Changing the dictionary causes the reverse dictionary to be changed safely (as well as vice versa):</p>\n<pre><code>countryCapitalDictionary.Clear(); // equals countryCapitalDictionary.Inverse.Clear();\n\nvar containsCapital = countryCapitalDictionary.ContainsKey("Italy"); // false\nvar containsCountry = countryCapitalDictionary.Inverse.ContainsKey("Rome"); // false\n</code></pre>\n<p>Also, this library supports a read-only bidirectional dictionary:</p>\n<pre><code>var readOnlyBiDictionary = new ReadOnlyBidurectionalDictionary<T1, T2>(biDictionary);\n</code></pre>\n<p>You can use it via the <a href=\"https://www.nuget.org/packages/BidirectionalDictionary/\" rel=\"nofollow noreferrer\"><img src=\"https://img.shields.io/nuget/v/BidirectionalDictionary\" alt=\"Nuget\" /></a> package.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22437/"
] |
It's easy to get the value of a key from a .NET generic Dictionary:
```
Dictionary<int, string> greek = new Dictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
string secondGreek = greek[2]; // Beta
```
But trying to get the keys given a value is not as straightforward because there could be multiple keys:
```
int[] betaKeys = greek.WhatDoIPutHere("Beta"); // expecting single 2
```
|
Okay, here's the multiple bidirectional version:
```
using System;
using System.Collections.Generic;
using System.Text;
class BiDictionary<TFirst, TSecond>
{
IDictionary<TFirst, IList<TSecond>> firstToSecond = new Dictionary<TFirst, IList<TSecond>>();
IDictionary<TSecond, IList<TFirst>> secondToFirst = new Dictionary<TSecond, IList<TFirst>>();
private static IList<TFirst> EmptyFirstList = new TFirst[0];
private static IList<TSecond> EmptySecondList = new TSecond[0];
public void Add(TFirst first, TSecond second)
{
IList<TFirst> firsts;
IList<TSecond> seconds;
if (!firstToSecond.TryGetValue(first, out seconds))
{
seconds = new List<TSecond>();
firstToSecond[first] = seconds;
}
if (!secondToFirst.TryGetValue(second, out firsts))
{
firsts = new List<TFirst>();
secondToFirst[second] = firsts;
}
seconds.Add(second);
firsts.Add(first);
}
// Note potential ambiguity using indexers (e.g. mapping from int to int)
// Hence the methods as well...
public IList<TSecond> this[TFirst first]
{
get { return GetByFirst(first); }
}
public IList<TFirst> this[TSecond second]
{
get { return GetBySecond(second); }
}
public IList<TSecond> GetByFirst(TFirst first)
{
IList<TSecond> list;
if (!firstToSecond.TryGetValue(first, out list))
{
return EmptySecondList;
}
return new List<TSecond>(list); // Create a copy for sanity
}
public IList<TFirst> GetBySecond(TSecond second)
{
IList<TFirst> list;
if (!secondToFirst.TryGetValue(second, out list))
{
return EmptyFirstList;
}
return new List<TFirst>(list); // Create a copy for sanity
}
}
class Test
{
static void Main()
{
BiDictionary<int, string> greek = new BiDictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
greek.Add(5, "Beta");
ShowEntries(greek, "Alpha");
ShowEntries(greek, "Beta");
ShowEntries(greek, "Gamma");
}
static void ShowEntries(BiDictionary<int, string> dict, string key)
{
IList<int> values = dict[key];
StringBuilder builder = new StringBuilder();
foreach (int value in values)
{
if (builder.Length != 0)
{
builder.Append(", ");
}
builder.Append(value);
}
Console.WriteLine("{0}: [{1}]", key, builder);
}
}
```
|
255,370 |
<p>I am developing Eclipse plugins, and I need to be able to automate the building and execution of the test suite for each plugin. (Using Junit)</p>
<p>Test are working within Eclipse, and I can break the plugins into the actual plugin and a fragment plugin for unit testing as described <a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.test/testframework.html?view=co" rel="nofollow noreferrer">here</a>, <a href="http://rcpquickstart.com/2007/08/06/running-automated-tests-with-pde-build/" rel="nofollow noreferrer">here</a> and in a couple places <a href="http://eclipsenuggets.blogspot.com/2007/09/6-great-links-for-eclipse-build.html" rel="nofollow noreferrer">here</a>.</p>
<p>However, each of the approaches above results in the same issue: The java ant task/commandline command that issues the build or should trigger the test, generates no observable side effects, and returns the value "13". I've tried everything I can find, and I've learned a fair bit about how Eclipse starts up (eg: since v3.3 you can no longer use startup.jar -- it doesn't exist -- but you should use <a href="http://blog.ciscavate.org/2008/11/treat-your-mailing-lists-like-reference-documents-please.html" rel="nofollow noreferrer">org.eclipse.equinox.launcher</a>). Unfortunately, while that is apparently necessary information, it is far from sufficient.</p>
<p>I am working with Eclipse 3.4, Junit 4.3.1 (the org.junit4 bundle, but I would much rather use JUnit 4.4. See <a href="https://stackoverflow.com/questions/251791">here</a>.)</p>
<p>So, my question is: How exactly do you automate the build and testing of Eclipse plugins? </p>
<p><em>Edit:</em> To clarify, I <em>want</em> to use something like ant + cruise control, but I can't even get the unit tests to run <em>at all</em> outside of Eclipse. I say "something like" because there are other technologies that accomplish the same thing, and I am not so picky as to discard a solution that works just because it's using say, Maven or Buckminster, if those technologies make this substantially easier.</p>
<p><em>Edit2:</em> The 'Java Result 13' mentioned above seems to be caused by the inability to find the coretestrunner. From the log:</p>
<pre><code>java.lang.RuntimeException: Application "org.eclipse.test.coretestapplication" could not be found in the registry. The applications available are: org.eclipse.equinox.app.error, com.rcpquickstart.helloworld.application.
at org.eclipse.equinox.internal.app.EclipseAppContainer.startDefaultApp(EclipseAppContainer.java:242)
at org.eclipse.equinox.internal.app.MainApplicationLauncher.run(MainApplicationLauncher.java:29)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:382)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504)
at org.eclipse.equinox.launcher.Main.run(Main.java:1236)
at org.eclipse.equinox.launcher.Main.main(Main.java:1212)
at org.eclipse.core.launcher.Main.main(Main.java:30)
!ENTRY org.eclipse.osgi 2 0 2008-11-04 21:02:10.514
!MESSAGE The following is a complete list of bundles which are not resolved, see the prior log entry for the root cause if it exists:
!SUBENTRY 1 org.eclipse.osgi 2 0 2008-11-04 21:02:10.515
!MESSAGE Bundle update@plugins/org.eclipse.test_3.2.0/ [34] was not resolved.
!SUBENTRY 2 org.eclipse.test 2 0 2008-11-04 21:02:10.516
!MESSAGE Missing required bundle org.apache.ant_0.0.0.
!SUBENTRY 2 org.eclipse.test 2 0 2008-11-04 21:02:10.516
!MESSAGE Missing required bundle org.eclipse.ui.ide.application_0.0.0.
!SUBENTRY 1 org.eclipse.osgi 2 0 2008-11-04 21:02:10.518
!MESSAGE Bundle update@plugins/org.eclipse.ant.optional.junit_3.2.100.jar [60] was not resolved.
!SUBENTRY 2 org.eclipse.ant.optional.junit 2 0 2008-11-04 21:02:10.519
!MESSAGE Missing host org.apache.ant_[1.6.5,2.0.0).
!SUBENTRY 2 org.eclipse.ant.optional.junit 2 0 2008-11-04 21:02:10.519
!MESSAGE Missing required bundle org.eclipse.core.runtime.compatibility_0.0.0.
</code></pre>
|
[
{
"answer_id": 255620,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 0,
"selected": false,
"text": "<p>We're using the PDE build scripts (see <a href=\"https://stackoverflow.com/questions/133234/building-eclipse-plugins-and-features-on-the-command-line\">this question</a>), and we export ant build files for our unit-test plugins. These ant build scripts are then invoked from the PDE build scripts (customTargets.xml) using the \"ant\" ant-task. Unfortunately, this only works with JUnit3. There's supposed to be a JUnit4-adapter for JUnit3 so you can run JUnit4 tests from a JUnit3 test-runner.</p>\n\n<p>We'll probably move to something like Maven; the PDE build scripts aren't really cut out for what we need to do with them.</p>\n"
},
{
"answer_id": 258547,
"author": "Fred",
"author_id": 33630,
"author_profile": "https://Stackoverflow.com/users/33630",
"pm_score": -1,
"selected": false,
"text": "<p>Here is a Tool which I can recommand if someone is interrested by TDD : \n<a href=\"http://www.junit.org/node/343\" rel=\"nofollow noreferrer\">Infinitest</a></p>\n\n<p>Short description extracted from the Infinitest site:</p>\n\n<blockquote>\n <p>What is Infinitest?</p>\n \n <p>Infinitest is a continuous test runner\n designed to facilitate Test Driven\n Development. Infinitest helps you\n learn TDD by providing feedback as you\n work, and helps you master TDD by\n reducing your feedback cycle from\n minutes to mere seconds.</p>\n \n <p>Whenever you change a class,\n Infinitest runs your tests for you.\n It's smart about what tests to run,\n and only runs the ones you need. If\n any errors occur, it reports them\n clearly and concisely. This gives you\n instant feedback about the semantic\n correctness of your code, just as\n modern IDE's give you instant feedback\n about syntax errors.</p>\n</blockquote>\n"
},
{
"answer_id": 263073,
"author": "silverbugg",
"author_id": 29650,
"author_profile": "https://Stackoverflow.com/users/29650",
"pm_score": -1,
"selected": false,
"text": "<p>Use <a href=\"http://ant.apache.org/\" rel=\"nofollow noreferrer\">Ant</a> and <a href=\"http://cruisecontrol.sourceforge.net/\" rel=\"nofollow noreferrer\">CruiseControl</a> - you call the unit tests in the <a href=\"http://ant.apache.org/\" rel=\"nofollow noreferrer\">Ant</a> script as well as the rest of your build logic and can run them with each build iteration - then <a href=\"http://cruisecontrol.sourceforge.net/\" rel=\"nofollow noreferrer\">CruiseControl</a> can automate your build calls and run these tests each time.</p>\n"
},
{
"answer_id": 288064,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 4,
"selected": false,
"text": "<p>I have just got JUnit testing working as part of the headless build for our RCP application. </p>\n\n<p>I found this article - <a href=\"http://www.eclipse.org/articles/article.php?file=Article-PDEJUnitAntAutomation/index.html\" rel=\"noreferrer\">Automating Eclipse PDE Unit Tests using Ant</a> incredibly helpful. It provides code and approach to get you started. However, a number of things that I discovered:</p>\n\n<h2>About the article's code</h2>\n\n<ul>\n<li>there was only one bundle under tests (we have separated out our build process from the code, using <a href=\"http://wiki.eclipse.org/Buckminster_Project\" rel=\"noreferrer\">Buckminster</a>)</li>\n<li>there was only one test class. </li>\n<li>these were both effectively hardcoded into the build script</li>\n</ul>\n\n<h2>About Eclipse PDE</h2>\n\n<ul>\n<li>the <code>uitestapplication</code> requires another <code>testApplication</code>. Using <code>coretestapplication</code> does not. </li>\n<li>as these applications are both in bundles that have dependencies on SWT. This is a deal killer in most circumstances, though not if your build machine is a Windows box. I would love to see these split into non-UI bundles.</li>\n</ul>\n\n<p>I found that the code provided was a good starting point, but had a number of the above assumptions implicit in their implementation.</p>\n\n<p>Having discovered these assumptions, doing the work was relatively straight forward.</p>\n\n<h2>Our new and shiny setup</h2>\n\n<ul>\n<li>buckminster builds the bundles. </li>\n<li>target copies the bundles from the target platform, the org.eclipse.pde.runtime and org.eclipse.jdt.junit into a \"tester-eclipse-install\". This should take care of your <code>Java Result 13</code> problem.</li>\n<li>find the test fragments from looking at the workspace</li>\n<li>find the fragment host from looking at the manifest</li>\n<li>find the test classes from looking at the project in the workspace.</li>\n<li>register a <code>PDETestListener</code> modified to handle multiple test classes</li>\n<li>invoke the tester-eclipse-install with the multiple test classes.</li>\n</ul>\n\n<p>I also read <a href=\"http://www.eclipse.org/articles/Article-PDE-Automation/automation.html\" rel=\"noreferrer\">Build and Test Automation for plug-ins and features</a> but we are not using PDE-Build directly. </p>\n"
},
{
"answer_id": 963808,
"author": "liangzan",
"author_id": 11927,
"author_profile": "https://Stackoverflow.com/users/11927",
"pm_score": 2,
"selected": false,
"text": "<p>Looking at your exception, it says that the coretestapplication is missing. The ant target could be found at plugins/org.eclipse.test_3.1.0/library.xml:10</p>\n\n<p>This is actually a dependency issue. Eclipse needs to have all the plugins in order to build.</p>\n\n<p>To configure it correctly, there're 2 files to look at. </p>\n\n<ol>\n<li>The product file</li>\n<li>The feature.xml</li>\n</ol>\n\n<p><strong>Product</strong></p>\n\n<p>Make sure you the product file contains all the plugins you need. </p>\n\n<p>After that, add the org.eclipse.rcp and org.eclipse.test features</p>\n\n<p>...\nplugins are above\n...</p>\n\n<pre><code><features>\n <feature id=\"mock_feature\" version=\"1.0.0\"/>\n <feature id=\"mock_feature_test\" version=\"1.0.0\"/>\n <feature id=\"org.eclipse.rcp\" version=\"3.2.0.v20060609m-SVDNgVrNoh-MeGG\"/>\n <feature id=\"org.eclipse.test\" version=\"3.2.0.v20060220------0842282442\"/>\n </features>\n</code></pre>\n\n<p>You need org.eclipse.test to run the tests, and org.eclipse.rcp to launch eclipse in order to run the tests.</p>\n\n<p>Don't forget to set useFeatures to 'true'</p>\n\n<pre><code><product name=\"mock\" id=\"com.example.mock\" application=\"com.example.mock.application\" useFeatures=\"true\">\n</code></pre>\n\n<p><strong>feature.xml</strong></p>\n\n<p>Assuming you have a feature for testing, you must add 2 additional plugins.</p>\n\n<p>...\nother plugins above\n...</p>\n\n<pre><code><plugin\n id=\"org.apache.ant\"\n download-size=\"0\"\n install-size=\"0\"\n version=\"0.0.0\"/>\n\n <plugin\n id=\"org.eclipse.core.runtime.compatibility\"\n download-size=\"0\"\n install-size=\"0\"\n version=\"0.0.0\"\n unpack=\"false\"/>\n</code></pre>\n\n<p>THe tests need org.apache.ant to run the tests and org.eclipse.core.runtime.compatibility to launch.</p>\n\n<p><strong>Another gotcha</strong></p>\n\n<p>Ensure that in your target eclipse(the copy of eclipse that you use to build against), there's only 1 copy of each plugin. For example if there're 2 versions of com.ibm.icu plugins in the plugin folder, eclipse would use the newer one. As the pde build plugin is configured to use a specific version, eclipse would complain that it cannot find the particular plugin even when it is there.</p>\n\n<p><strong>Some thoughts</strong></p>\n\n<p>The whole process of building eclipse could be a lot better. In fact I got the process mostly by trial and error. The documentation is outdated and sparse. The error messages doesn't help. It only leaves you feeling helpless and frustrated. Let's hope this post helps a fellow programmer save some time!</p>\n"
},
{
"answer_id": 1373682,
"author": "AMilassin",
"author_id": 167915,
"author_profile": "https://Stackoverflow.com/users/167915",
"pm_score": 0,
"selected": false,
"text": "<p>As an alternative to Ant, I've had good experience in using the brand new Maven+Tycho with Hudson. Tycho provides complete support for Osgi and Eclipse development in Maven. It's currently under heavy development, but most of the features I've needed worked. It needs only very little configuration from your side, because it can parse MANIFEST.MF files.</p>\n\n<p>If you have some experience with Maven it's not very hard to start working with it. Hudson is a bit more problematic because of missing Maven 3 support. (the development version of Maven 3 is used by Tycho)</p>\n\n<p>Links for start:</p>\n\n<ul>\n<li><a href=\"https://docs.codehaus.org/display/M2ECLIPSE/Tycho+user+docs\" rel=\"nofollow noreferrer\">uncomplete user docs</a></li>\n</ul>\n"
},
{
"answer_id": 27933127,
"author": "Gunjan Aggarwal",
"author_id": 2888308,
"author_profile": "https://Stackoverflow.com/users/2888308",
"pm_score": 2,
"selected": false,
"text": "<p>For any one still looking for a way to execute Eclipse plugin tests outside Eclipse, the following command works for me:</p>\n\n<pre><code>java -Xms40m -Xmx1024m -XX:MaxPermSize=512m -Dorg.eclipse.swt.browser.DefaultType=mozilla -Declipse.pde.launch=true -classpath C:\\eclipse\\eclipse-standard-luna-M2-win32-x86_64\\eclipse\\plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar org.eclipse.equinox.launcher.Main -port 22 -testLoaderClass org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader -loaderpluginname org.eclipse.jdt.junit4.runtime -classNames testpackage.testClass -application org.eclipse.pde.junit.runtime.uitestapplication -data C:\\temp\\log.temp -dev bin -consoleLog -testpluginname PluginName\n</code></pre>\n\n<p><code>-classpath</code> should be set to Eclipse launcher jar. You can get exact version for your Eclipse from <code>eclipse.ini</code> file. </p>\n\n<p><code>-className</code> is the junit plugin test file name</p>\n\n<p><code>-data</code> is set to a temp file.</p>\n\n<p><code>-testpluginname</code> is the name of plugin you want to test.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446/"
] |
I am developing Eclipse plugins, and I need to be able to automate the building and execution of the test suite for each plugin. (Using Junit)
Test are working within Eclipse, and I can break the plugins into the actual plugin and a fragment plugin for unit testing as described [here](http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.test/testframework.html?view=co), [here](http://rcpquickstart.com/2007/08/06/running-automated-tests-with-pde-build/) and in a couple places [here](http://eclipsenuggets.blogspot.com/2007/09/6-great-links-for-eclipse-build.html).
However, each of the approaches above results in the same issue: The java ant task/commandline command that issues the build or should trigger the test, generates no observable side effects, and returns the value "13". I've tried everything I can find, and I've learned a fair bit about how Eclipse starts up (eg: since v3.3 you can no longer use startup.jar -- it doesn't exist -- but you should use [org.eclipse.equinox.launcher](http://blog.ciscavate.org/2008/11/treat-your-mailing-lists-like-reference-documents-please.html)). Unfortunately, while that is apparently necessary information, it is far from sufficient.
I am working with Eclipse 3.4, Junit 4.3.1 (the org.junit4 bundle, but I would much rather use JUnit 4.4. See [here](https://stackoverflow.com/questions/251791).)
So, my question is: How exactly do you automate the build and testing of Eclipse plugins?
*Edit:* To clarify, I *want* to use something like ant + cruise control, but I can't even get the unit tests to run *at all* outside of Eclipse. I say "something like" because there are other technologies that accomplish the same thing, and I am not so picky as to discard a solution that works just because it's using say, Maven or Buckminster, if those technologies make this substantially easier.
*Edit2:* The 'Java Result 13' mentioned above seems to be caused by the inability to find the coretestrunner. From the log:
```
java.lang.RuntimeException: Application "org.eclipse.test.coretestapplication" could not be found in the registry. The applications available are: org.eclipse.equinox.app.error, com.rcpquickstart.helloworld.application.
at org.eclipse.equinox.internal.app.EclipseAppContainer.startDefaultApp(EclipseAppContainer.java:242)
at org.eclipse.equinox.internal.app.MainApplicationLauncher.run(MainApplicationLauncher.java:29)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:382)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504)
at org.eclipse.equinox.launcher.Main.run(Main.java:1236)
at org.eclipse.equinox.launcher.Main.main(Main.java:1212)
at org.eclipse.core.launcher.Main.main(Main.java:30)
!ENTRY org.eclipse.osgi 2 0 2008-11-04 21:02:10.514
!MESSAGE The following is a complete list of bundles which are not resolved, see the prior log entry for the root cause if it exists:
!SUBENTRY 1 org.eclipse.osgi 2 0 2008-11-04 21:02:10.515
!MESSAGE Bundle update@plugins/org.eclipse.test_3.2.0/ [34] was not resolved.
!SUBENTRY 2 org.eclipse.test 2 0 2008-11-04 21:02:10.516
!MESSAGE Missing required bundle org.apache.ant_0.0.0.
!SUBENTRY 2 org.eclipse.test 2 0 2008-11-04 21:02:10.516
!MESSAGE Missing required bundle org.eclipse.ui.ide.application_0.0.0.
!SUBENTRY 1 org.eclipse.osgi 2 0 2008-11-04 21:02:10.518
!MESSAGE Bundle update@plugins/org.eclipse.ant.optional.junit_3.2.100.jar [60] was not resolved.
!SUBENTRY 2 org.eclipse.ant.optional.junit 2 0 2008-11-04 21:02:10.519
!MESSAGE Missing host org.apache.ant_[1.6.5,2.0.0).
!SUBENTRY 2 org.eclipse.ant.optional.junit 2 0 2008-11-04 21:02:10.519
!MESSAGE Missing required bundle org.eclipse.core.runtime.compatibility_0.0.0.
```
|
I have just got JUnit testing working as part of the headless build for our RCP application.
I found this article - [Automating Eclipse PDE Unit Tests using Ant](http://www.eclipse.org/articles/article.php?file=Article-PDEJUnitAntAutomation/index.html) incredibly helpful. It provides code and approach to get you started. However, a number of things that I discovered:
About the article's code
------------------------
* there was only one bundle under tests (we have separated out our build process from the code, using [Buckminster](http://wiki.eclipse.org/Buckminster_Project))
* there was only one test class.
* these were both effectively hardcoded into the build script
About Eclipse PDE
-----------------
* the `uitestapplication` requires another `testApplication`. Using `coretestapplication` does not.
* as these applications are both in bundles that have dependencies on SWT. This is a deal killer in most circumstances, though not if your build machine is a Windows box. I would love to see these split into non-UI bundles.
I found that the code provided was a good starting point, but had a number of the above assumptions implicit in their implementation.
Having discovered these assumptions, doing the work was relatively straight forward.
Our new and shiny setup
-----------------------
* buckminster builds the bundles.
* target copies the bundles from the target platform, the org.eclipse.pde.runtime and org.eclipse.jdt.junit into a "tester-eclipse-install". This should take care of your `Java Result 13` problem.
* find the test fragments from looking at the workspace
* find the fragment host from looking at the manifest
* find the test classes from looking at the project in the workspace.
* register a `PDETestListener` modified to handle multiple test classes
* invoke the tester-eclipse-install with the multiple test classes.
I also read [Build and Test Automation for plug-ins and features](http://www.eclipse.org/articles/Article-PDE-Automation/automation.html) but we are not using PDE-Build directly.
|
255,393 |
<p>I'm trying to make a page in php that takes rows from a database, displays them, and then give the viewer a chance to upvote or downvote a specific entry. Here is a snippet:</p>
<pre><code>echo("<form action=\"vote.php\" method=\"post\"> \n");
echo("<INPUT type=\"hidden\" name=\"idnum\" value=\"".$row[0]."\">");
echo("<INPUT type=\"submit\" name=\"up\" value=\"Upvote.\"> \n");
echo("<INPUT type=\"submit\" name=\"down\" value=\"Downvote\"> ");
echo("<form/>\n");
</code></pre>
<p>The problem is when I hit a submit button, the value for idnum that gets sent is based on the one farthest down it seems. So my questions is, when a submit button is pressed, are the values for all inputs on a page sent?</p>
|
[
{
"answer_id": 255396,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>Your form is not closed properly. Use <code></form></code> instead of <code><form/></code>.</p>\n"
},
{
"answer_id": 255397,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "<p>The problem with your html is that you should have <code></form></code>, not <code><form/></code>.</p>\n"
},
{
"answer_id": 255398,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 4,
"selected": true,
"text": "<p>Your form tag isn't closed properly. You have <code><form/></code>, but it should be <code></form></code>.</p>\n\n<p>This makes the entire page a form so it sends all the inputs. With a form that is closed properly though, it will only send the inputs within the form tags that the pressed button was in.</p>\n"
},
{
"answer_id": 255432,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "<p>While this wouldn't have helped with this particular issue, I would recommend not mixing your markup with your logic wherever possible. This is quite a lot more readable, and quite a lot more editable as well:</p>\n\n<pre><code><form action=\"vote.php\" method=\"post\">\n <input type=\"hidden\" name=\"idnum\" value=\"<?php echo $row[0]; ?>\">\n <input type=\"submit\" name=\"up\" value=\"Upvote.\">\n <input type=\"submit\" name=\"down\" value=\"Downvote\">\n</form>\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25680/"
] |
I'm trying to make a page in php that takes rows from a database, displays them, and then give the viewer a chance to upvote or downvote a specific entry. Here is a snippet:
```
echo("<form action=\"vote.php\" method=\"post\"> \n");
echo("<INPUT type=\"hidden\" name=\"idnum\" value=\"".$row[0]."\">");
echo("<INPUT type=\"submit\" name=\"up\" value=\"Upvote.\"> \n");
echo("<INPUT type=\"submit\" name=\"down\" value=\"Downvote\"> ");
echo("<form/>\n");
```
The problem is when I hit a submit button, the value for idnum that gets sent is based on the one farthest down it seems. So my questions is, when a submit button is pressed, are the values for all inputs on a page sent?
|
Your form tag isn't closed properly. You have `<form/>`, but it should be `</form>`.
This makes the entire page a form so it sends all the inputs. With a form that is closed properly though, it will only send the inputs within the form tags that the pressed button was in.
|
255,400 |
<p>This is a very complicated question concerning how to serialize data via a web service call, when the data is not-strongly typed. I'll try to lay it out as best possible.</p>
<p><strong>Sample Storage Object:</strong></p>
<pre><code>[Serializable]
public class StorageObject {
public string Name { get; set; }
public string Birthday { get; set; }
public List<NameValuePairs> OtherInfo { get; set; }
}
[Serializable]
public class NameValuePairs {
public string Name { get; set; }
public string Value { get; set; }
}
</code></pre>
<p><strong>Sample Use:</strong></p>
<pre><code>[WebMethod]
public List<StorageObject> GetStorageObjects() {
List<StorageObject> o = new List<StorageObject>() {
new StorageObject() {
Name = "Matthew",
Birthday = "Jan 1st, 2008",
OtherInfo = new List<NameValuePairs>() {
new NameValuePairs() { Name = "Hobbies", Value = "Programming" },
new NameValuePairs() { Name = "Website", Value = "Stackoverflow.com" }
}
},
new StorageObject() {
Name = "Joe",
Birthday = "Jan 10th, 2008",
OtherInfo = new List<NameValuePairs>() {
new NameValuePairs() { Name = "Hobbies", Value = "Programming" },
new NameValuePairs() { Name = "Website", Value = "Stackoverflow.com" }
}
}
};
return o;
}
</code></pre>
<p><strong>Return Value from Web Service:</strong></p>
<pre><code><StorageObject>
<Name>Matthew</Name>
<Birthday>Jan 1st, 2008</Birthday>
<OtherInfo>
<NameValuePairs>
<Name>Hobbies</Name>
<Value>Programming</Value>
</NameValuePairs>
<NameValuePairs>
<Name>Website</Name>
<Value>Stackoverflow.com</Value>
</NameValuePairs>
</OtherInfo>
</StorageObject>
</code></pre>
<p><strong>What I want:</strong></p>
<pre><code><OtherInfo>
<Hobbies>Programming</Hobbies>
<Website>Stackoverflow.com</Website>
</OtherInfo>
</code></pre>
<p><strong>The Reason & Other Stuff:</strong></p>
<p>First, I'm sorry for the length of the post, but I wanted to give reproducible code as well. </p>
<p>I want it in this format, because I'm consuming the web services from PHP. I want to easily go:</p>
<p>// THIS IS IMPORANT</p>
<pre><code>In PHP => "$Result["StorageObject"]["OtherInfo"]["Hobbies"]".
</code></pre>
<p>If it's in the other format, then there would be no way for me to accomplish that, at all. Additionally, in C# if I am consuming the service, I would also like to be able to do the following:</p>
<p>// THIS IS IMPORANT</p>
<pre><code>In C# => var m = ServiceResult[0].OtherInfo["Hobbies"];
</code></pre>
<p>Unfortunately, I'm not sure how to accomplish this. I was able to get it this way, by building a custom Dictionary that implemented IXmlSerializer (see <a href="https://stackoverflow.com/questions/67959/c-xml-serialization-gotchas">StackOverflow: IXmlSerializer Dictionary</a>), however, it blew the WSDL schema out of the water. It's also much too complicated, and produced horrible results in my WinFormsTester application!</p>
<p>Is there any way to accomplish this ? What type of objects do I need to create ? Is there any way to do this /other than by making a strongly typed collection/ ? Obviously, if I make it strongly typed like this:</p>
<pre><code>public class OtherInfo {
public string Hobbies { get; set; }
public string FavoriteWebsite { get; set; }
}
</code></pre>
<p>Then it would work perfectly, I would have no WSDL issues, I would be able to easily access it from PHP, and C# (.OtherInfo.Hobbies). </p>
<p>However, I would completely lose the point of NVP's, in that I would have to know in advance what the list is, and it would be unchangeable.. say, from a Database.</p>
<p>Thanks everyone!! I hope we're able to come up with some sort of solution to this. Here's are the requirements again:</p>
<ol>
<li>WSDL schema should not break</li>
<li>Name value pairs (NVP's) should be serialized into attribute format</li>
<li>Should be easy to access NVP's in PHP by name ["Hobbies"]</li>
<li>Should be easy to access in C# (and be compatible with it's Proxy generator)</li>
<li>Be easily serializable</li>
<li>Not require me to strongly type the data</li>
</ol>
<p>Now, I am /completely/ open to input on a better/different way to do this. I'm storing some relatively "static" information (like Name), and a bunch of pieces of data. If there's a better way, I'd love to hear it.</p>
|
[
{
"answer_id": 255411,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": -1,
"selected": false,
"text": "<p>I'm not sure this would solve your problem (it would in C#, but maybe not in PHP), but try using <code>Dictionary<string,List<string>> OtherInfo</code> instead of <code>List<NameValuePairs></code>. Then \"Hobbies\" and \"Websites\" would be your keys and the values would be the list of hobbies or web sites. I'm not sure how it would serialize, though.</p>\n\n<p>You would be able to reference the lists of hobbies as:</p>\n\n<pre><code>List<string> hobbies = storageObject.OtherInfo[\"Hobbies\"];\n</code></pre>\n\n<p>[EDIT] See <a href=\"http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx\" rel=\"nofollow noreferrer\">here</a> for a generic XML serializable dictionary. This derived class is the one you would need to use instead of generic Dictionary.</p>\n"
},
{
"answer_id": 255413,
"author": "x0n",
"author_id": 6920,
"author_profile": "https://Stackoverflow.com/users/6920",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look into the System.Xml.Serialization.XmlSerializerAssemblyAttribute attribute. This lets you specify a custom class-level serializer. You'll be able to spit out whatever XML you like. </p>\n\n<p>A quick way to get up to speed on these is to use sgen.exe to generate one and have a peek at it with Reflector.</p>\n\n<p>-Oisin</p>\n"
},
{
"answer_id": 255424,
"author": "Ray Lu",
"author_id": 11413,
"author_profile": "https://Stackoverflow.com/users/11413",
"pm_score": 4,
"selected": true,
"text": "<p>This is like dynamic properties for a object. \nC# is not quite a dynamic language unlike javascript or maybe PHP can parse the object properties on the fly. The following two methods are what I can think of. The second one might fit into your requirements.</p>\n\n<p><strong>The KISS Way</strong> </p>\n\n<p>The Keep It Simple Stupid way </p>\n\n<pre><code>public class StorageObject {\n public string Name { get; set; }\n public string Birthday { get; set; }\n public List<string> OtherInfo { get; set; } \n}\n</code></pre>\n\n<p>You can have name value pairs which is separated by '|'</p>\n\n<pre><code>OtherInfo = {\"Hobbies|Programming\", \"Website|Stackoverflow.com\"}\n</code></pre>\n\n<p>Serialized forms</p>\n\n<pre><code><StorageObject>\n <Name>Matthew</Name>\n <Birthday>Jan 1st, 2008</Birthday>\n <OtherInfo>\n <string>Hobbies|Programming</string>\n <string>Website|Stackoverflow.com</string>\n </OtherInfo>\n</StorageObject>\n</code></pre>\n\n<p><strong>The Dynamic Way in C#</strong></p>\n\n<p>Make the name value pair part become an XML element so that you can build it dynamically.</p>\n\n<pre><code>public class StorageObject {\n public string Name { get; set; }\n public string Birthday { get; set; }\n public XElement OtherInfo { get; set; } // XmlElement for dot net 2\n}\n</code></pre>\n\n<p>You can easily build up OtherInfo object as element centric\ne.g. </p>\n\n<pre><code>XElement OtherInfo = new XElement(\"OtherInfo\");\nOtherInfo.Add( ..Hobbies xelement & text value..);\nOtherInfo.Add( ..WebSite xelement & text value..);\n</code></pre>\n\n<p>The serialized form will be</p>\n\n<pre><code><OtherInfo>\n <Hobbies>Programming</Hobbies>\n <Website>Stackoverflow.com</Website>\n</OtherInfo>\n</code></pre>\n\n<p>or build it as attribute centric</p>\n\n<pre><code>XElement OtherInfo = new XElement(\"OtherInfo\");\nOtherInfo.Add( ..nvp xattribute Hobbies & value..);\nOtherInfo.Add( ..nvp xattribute WebSite & value..);\n\n<OtherInfo>\n <nvp n=\"Hobbies\" v=\"Programming\" />\n <nvp n=\"Website\" v=\"Stackoverflow.com\" />\n</OtherInfo>\n</code></pre>\n\n<p>For any dynamic language, it can access to the properties directly. \nFor the rest, they can access the value by read the XML. Reading XML is well supported by most of framework.</p>\n"
},
{
"answer_id": 255455,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>As a completely different take on this, why not think about doing it completely differently. Have one web service method to return the serialized storage object, minus the <code>OtherInfo</code> and another method to return the list of properties (keys) for <code>OtherInfo</code>, and a third to return the list of values for any key. Granted, it will take more round trips to the web service if you want all of the data, but the solution will be much simpler and more flexible.</p>\n\n<pre><code>[Serializable]\npublic class StorageObject {\n public string Name { get; set; }\n public string Birthday { get; set; }\n\n [Nonserializable]\n public Dictionary<string,List<string>> OtherInfo { get; set; } \n}\n\n[WebMethod]\npublic List<StorageObject> GetStorageObjects() {\n // returns list of storage objects from persistent storage or cache\n}\n\n[WebMethod]\npublic List<string> GetStorageObjectAttributes( string name )\n{\n // find storage object, sObj\n return sObj.Keys.ToList();\n}\n\n[WebMethod]\npublic List<string> GetStorageObjectAtributeValues( sting name, string attribute )\n{\n // find storage object, sObj\n return sObj[attribute];\n}\n</code></pre>\n"
},
{
"answer_id": 255469,
"author": "Matthew M.",
"author_id": 27472,
"author_profile": "https://Stackoverflow.com/users/27472",
"pm_score": 2,
"selected": false,
"text": "<p>This is what I've settled on.</p>\n\n<p>Class Structure:</p>\n\n<pre><code>public class StorageObject {\n public string Name { get; set; }\n public string Birthday { get; set; }\n [XmlAnyElement(\"Info\")] // this prevents double-nodes in the XML\n public XElement OtherInfo { get; set; }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>StorageObject o = new StorageObject();\no.OtherInfo.Add(new XElement(\"Hobbies\",\"Programming\");\no.OtherInfo.Add(new XElement(\"Website\",\"Stackoverflow.com\");\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code><Info>\n <Hobbies>Programming</Hobbies>\n <Website>Stackoverflow.com</Website>\n</Info>\n</code></pre>\n\n<p>I would like to thank everyone for their assistance, I really appreciate the help and ideas.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27472/"
] |
This is a very complicated question concerning how to serialize data via a web service call, when the data is not-strongly typed. I'll try to lay it out as best possible.
**Sample Storage Object:**
```
[Serializable]
public class StorageObject {
public string Name { get; set; }
public string Birthday { get; set; }
public List<NameValuePairs> OtherInfo { get; set; }
}
[Serializable]
public class NameValuePairs {
public string Name { get; set; }
public string Value { get; set; }
}
```
**Sample Use:**
```
[WebMethod]
public List<StorageObject> GetStorageObjects() {
List<StorageObject> o = new List<StorageObject>() {
new StorageObject() {
Name = "Matthew",
Birthday = "Jan 1st, 2008",
OtherInfo = new List<NameValuePairs>() {
new NameValuePairs() { Name = "Hobbies", Value = "Programming" },
new NameValuePairs() { Name = "Website", Value = "Stackoverflow.com" }
}
},
new StorageObject() {
Name = "Joe",
Birthday = "Jan 10th, 2008",
OtherInfo = new List<NameValuePairs>() {
new NameValuePairs() { Name = "Hobbies", Value = "Programming" },
new NameValuePairs() { Name = "Website", Value = "Stackoverflow.com" }
}
}
};
return o;
}
```
**Return Value from Web Service:**
```
<StorageObject>
<Name>Matthew</Name>
<Birthday>Jan 1st, 2008</Birthday>
<OtherInfo>
<NameValuePairs>
<Name>Hobbies</Name>
<Value>Programming</Value>
</NameValuePairs>
<NameValuePairs>
<Name>Website</Name>
<Value>Stackoverflow.com</Value>
</NameValuePairs>
</OtherInfo>
</StorageObject>
```
**What I want:**
```
<OtherInfo>
<Hobbies>Programming</Hobbies>
<Website>Stackoverflow.com</Website>
</OtherInfo>
```
**The Reason & Other Stuff:**
First, I'm sorry for the length of the post, but I wanted to give reproducible code as well.
I want it in this format, because I'm consuming the web services from PHP. I want to easily go:
// THIS IS IMPORANT
```
In PHP => "$Result["StorageObject"]["OtherInfo"]["Hobbies"]".
```
If it's in the other format, then there would be no way for me to accomplish that, at all. Additionally, in C# if I am consuming the service, I would also like to be able to do the following:
// THIS IS IMPORANT
```
In C# => var m = ServiceResult[0].OtherInfo["Hobbies"];
```
Unfortunately, I'm not sure how to accomplish this. I was able to get it this way, by building a custom Dictionary that implemented IXmlSerializer (see [StackOverflow: IXmlSerializer Dictionary](https://stackoverflow.com/questions/67959/c-xml-serialization-gotchas)), however, it blew the WSDL schema out of the water. It's also much too complicated, and produced horrible results in my WinFormsTester application!
Is there any way to accomplish this ? What type of objects do I need to create ? Is there any way to do this /other than by making a strongly typed collection/ ? Obviously, if I make it strongly typed like this:
```
public class OtherInfo {
public string Hobbies { get; set; }
public string FavoriteWebsite { get; set; }
}
```
Then it would work perfectly, I would have no WSDL issues, I would be able to easily access it from PHP, and C# (.OtherInfo.Hobbies).
However, I would completely lose the point of NVP's, in that I would have to know in advance what the list is, and it would be unchangeable.. say, from a Database.
Thanks everyone!! I hope we're able to come up with some sort of solution to this. Here's are the requirements again:
1. WSDL schema should not break
2. Name value pairs (NVP's) should be serialized into attribute format
3. Should be easy to access NVP's in PHP by name ["Hobbies"]
4. Should be easy to access in C# (and be compatible with it's Proxy generator)
5. Be easily serializable
6. Not require me to strongly type the data
Now, I am /completely/ open to input on a better/different way to do this. I'm storing some relatively "static" information (like Name), and a bunch of pieces of data. If there's a better way, I'd love to hear it.
|
This is like dynamic properties for a object.
C# is not quite a dynamic language unlike javascript or maybe PHP can parse the object properties on the fly. The following two methods are what I can think of. The second one might fit into your requirements.
**The KISS Way**
The Keep It Simple Stupid way
```
public class StorageObject {
public string Name { get; set; }
public string Birthday { get; set; }
public List<string> OtherInfo { get; set; }
}
```
You can have name value pairs which is separated by '|'
```
OtherInfo = {"Hobbies|Programming", "Website|Stackoverflow.com"}
```
Serialized forms
```
<StorageObject>
<Name>Matthew</Name>
<Birthday>Jan 1st, 2008</Birthday>
<OtherInfo>
<string>Hobbies|Programming</string>
<string>Website|Stackoverflow.com</string>
</OtherInfo>
</StorageObject>
```
**The Dynamic Way in C#**
Make the name value pair part become an XML element so that you can build it dynamically.
```
public class StorageObject {
public string Name { get; set; }
public string Birthday { get; set; }
public XElement OtherInfo { get; set; } // XmlElement for dot net 2
}
```
You can easily build up OtherInfo object as element centric
e.g.
```
XElement OtherInfo = new XElement("OtherInfo");
OtherInfo.Add( ..Hobbies xelement & text value..);
OtherInfo.Add( ..WebSite xelement & text value..);
```
The serialized form will be
```
<OtherInfo>
<Hobbies>Programming</Hobbies>
<Website>Stackoverflow.com</Website>
</OtherInfo>
```
or build it as attribute centric
```
XElement OtherInfo = new XElement("OtherInfo");
OtherInfo.Add( ..nvp xattribute Hobbies & value..);
OtherInfo.Add( ..nvp xattribute WebSite & value..);
<OtherInfo>
<nvp n="Hobbies" v="Programming" />
<nvp n="Website" v="Stackoverflow.com" />
</OtherInfo>
```
For any dynamic language, it can access to the properties directly.
For the rest, they can access the value by read the XML. Reading XML is well supported by most of framework.
|
255,414 |
<p>I'm trying to write a small script to change the current directory to my project directory:</p>
<pre><code>#!/bin/bash
cd /home/tree/projects/java
</code></pre>
<p>I saved this file as proj, added execute permission with <code>chmod</code>, and copied it to <code>/usr/bin</code>. When I call it by:
<code>proj</code>, it does nothing. What am I doing wrong?</p>
|
[
{
"answer_id": 255415,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 10,
"selected": true,
"text": "<p>Shell scripts are run inside a subshell, and each subshell has its own concept of what the current directory is. The <code>cd</code> succeeds, but as soon as the subshell exits, you're back in the interactive shell and nothing ever changed there.</p>\n\n<p>One way to get around this is to use an alias instead:</p>\n\n<pre><code>alias proj=\"cd /home/tree/projects/java\"\n</code></pre>\n"
},
{
"answer_id": 255416,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 9,
"selected": false,
"text": "<p>You're doing nothing wrong! You've changed the directory, but only within the subshell that runs the script.</p>\n\n<p>You can run the script in your current process with the \"dot\" command:</p>\n\n<pre><code>. proj\n</code></pre>\n\n<p>But I'd prefer Greg's suggestion to use an alias in this simple case.</p>\n"
},
{
"answer_id": 255417,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 4,
"selected": false,
"text": "<p>When you fire a shell script, it runs a <em>new</em> instance of that shell (<code>/bin/bash</code>). Thus, your script just fires up a shell, changes the directory and exits. Put another way, <code>cd</code> (and other such commands) within a shell script do not affect nor have access to the shell from which they were launched.</p>\n"
},
{
"answer_id": 255418,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>It only changes the directory for the script itself, while your current directory stays the same.</p>\n\n<p>You might want to use a <a href=\"http://en.wikipedia.org/wiki/Symbolic_link\" rel=\"noreferrer\">symbolic link</a> instead. It allows you to make a \"shortcut\" to a file or directory, so you'd only have to type something like <code>cd my-project</code>.</p>\n"
},
{
"answer_id": 255439,
"author": "Thevs",
"author_id": 8559,
"author_profile": "https://Stackoverflow.com/users/8559",
"pm_score": 4,
"selected": false,
"text": "<p>You can do following:</p>\n\n<pre><code>#!/bin/bash\ncd /your/project/directory\n# start another shell and replacing the current\nexec /bin/bash\n</code></pre>\n\n<p>EDIT: This could be 'dotted' as well, to prevent creation of subsequent shells.</p>\n\n<p>Example:</p>\n\n<pre><code>. ./previous_script (with or without the first line)\n</code></pre>\n"
},
{
"answer_id": 255526,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": false,
"text": "<p>Jeremy Ruten's idea of using a symlink triggered a thought that hasn't crossed any other answer. Use:</p>\n\n<pre><code>CDPATH=:$HOME/projects\n</code></pre>\n\n<p>The leading colon is important; it means that if there is a directory 'dir' in the current directory, then '<code>cd dir</code>' will change to that, rather than hopping off somewhere else. With the value set as shown, you can do:</p>\n\n<pre><code>cd java\n</code></pre>\n\n<p>and, if there is no sub-directory called java in the current directory, then it will take you directly to $HOME/projects/java - no aliases, no scripts, no dubious execs or dot commands.</p>\n\n<p>My $HOME is /Users/jleffler; my $CDPATH is:</p>\n\n<pre><code>:/Users/jleffler:/Users/jleffler/mail:/Users/jleffler/src:/Users/jleffler/src/perl:/Users/jleffler/src/sqltools:/Users/jleffler/lib:/Users/jleffler/doc:/Users/jleffler/work\n</code></pre>\n"
},
{
"answer_id": 256866,
"author": "Gene T",
"author_id": 413049,
"author_profile": "https://Stackoverflow.com/users/413049",
"pm_score": 3,
"selected": false,
"text": "<p>to navigate directories quicky, there's $CDPATH, cdargs, and ways to generate aliases automatically</p>\n\n<p><a href=\"http://jackndempsey.blogspot.com/2008/07/cdargs.html\" rel=\"nofollow noreferrer\">http://jackndempsey.blogspot.com/2008/07/cdargs.html</a></p>\n\n<p><a href=\"http://muness.blogspot.com/2008/06/lazy-bash-cd-aliaes.html\" rel=\"nofollow noreferrer\">http://muness.blogspot.com/2008/06/lazy-bash-cd-aliaes.html</a></p>\n\n<p><a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5827311.html\" rel=\"nofollow noreferrer\">https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5827311.html</a></p>\n"
},
{
"answer_id": 259349,
"author": "J. A. Faucett",
"author_id": 18503,
"author_profile": "https://Stackoverflow.com/users/18503",
"pm_score": 3,
"selected": false,
"text": "<p>You can combine an alias and a script,</p>\n\n<pre><code>alias proj=\"cd \\`/usr/bin/proj !*\\`\"\n</code></pre>\n\n<p>provided that the script echos the destination path. Note that those are backticks surrounding the script name. </p>\n\n<p>For example, your script could be</p>\n\n<pre><code>#!/bin/bash\necho /home/askgelal/projects/java/$1\n</code></pre>\n\n<p>The advantage with this technique is that the script could take any number of command line parameters and emit different destinations calculated by possibly complex logic.</p>\n"
},
{
"answer_id": 2236614,
"author": "Tzachi.e",
"author_id": 270251,
"author_profile": "https://Stackoverflow.com/users/270251",
"pm_score": 7,
"selected": false,
"text": "<p>The <code>cd</code> is done within the script's shell. When the script ends, that shell exits, and then you are left in the directory you were. \"Source\" the script, don't run it. Instead of:</p>\n\n<pre><code>./myscript.sh\n</code></pre>\n\n<p>do</p>\n\n<pre><code>. ./myscript.sh\n</code></pre>\n\n<p>(Notice the dot and space before the script name.)</p>\n"
},
{
"answer_id": 2778286,
"author": "Matt Thomas",
"author_id": 332033,
"author_profile": "https://Stackoverflow.com/users/332033",
"pm_score": 7,
"selected": false,
"text": "<h3>To make a bash script that will cd to a select directory :</h3>\n\n<p>Create the script file</p>\n\n<pre>\n#!/bin/sh\n# file : /scripts/cdjava\n#\ncd /home/askgelal/projects/java\n</pre>\n\n<p>Then create an alias in your startup file.</p>\n\n<pre>\n#!/bin/sh\n# file /scripts/mastercode.sh\n#\nalias cdjava='. /scripts/cdjava'\n</pre>\n\n<hr>\n\n<ul>\n<li>I created a startup file where I dump all my aliases and custom functions.\n<li>Then I source this file into my .bashrc to have it set on each boot.\n</ul>\n\n<p>\nFor example, create a master aliases/functions file: <b>/scripts/mastercode.sh</b><br>\n<i>(Put the alias in this file.)</i>\n</p>\n\n<p>Then at the end of your <b>.bashrc</b> file:</p>\n\n<pre>\nsource /scripts/mastercode.sh\n</pre>\n\n<p><br></p>\n\n<hr>\n\n<p>Now its easy to cd to your java directory, just type cdjava and you are there.</p>\n"
},
{
"answer_id": 5627915,
"author": "chris",
"author_id": 702998,
"author_profile": "https://Stackoverflow.com/users/702998",
"pm_score": 2,
"selected": false,
"text": "<p>I did the following:</p>\n<p>create a file called case</p>\n<p>paste the following in the file:</p>\n<pre><code>#!/bin/sh\n\ncd /home/"$1"\n</code></pre>\n<p>save it and then:</p>\n<pre><code>chmod +x case\n</code></pre>\n<p>I also created an alias in my <code>.bashrc</code>:</p>\n<pre><code>alias disk='cd /home/; . case'\n</code></pre>\n<p>now when I type:</p>\n<pre><code>case 12345\n</code></pre>\n<p>essentially I am typing:</p>\n<pre><code>cd /home/12345\n</code></pre>\n<p>You can type any folder after 'case':</p>\n<pre><code>case 12\n\ncase 15\n\ncase 17\n</code></pre>\n<p>which is like typing:</p>\n<pre><code>cd /home/12\n\ncd /home/15\n\ncd /home/17\n</code></pre>\n<p>respectively</p>\n<p>In my case the path is much longer - these guys summed it up with the ~ info earlier.</p>\n"
},
{
"answer_id": 7020787,
"author": "DigitalRoss",
"author_id": 140740,
"author_profile": "https://Stackoverflow.com/users/140740",
"pm_score": 8,
"selected": false,
"text": "<p>The <code>cd</code> in your script technically <em>worked</em> as it changed the directory of the shell that ran the script, but that was a separate process forked from your interactive shell.</p>\n\n<p>A Posix-compatible way to solve this problem is to define a <em>shell procedure</em> rather than a shell-invoked <em>command script</em>.</p>\n\n<pre><code>jhome () {\n cd /home/tree/projects/java\n}\n</code></pre>\n\n<p>You can just type this in or put it in one of the various shell startup files.</p>\n"
},
{
"answer_id": 9207009,
"author": "rjmoggach",
"author_id": 586932,
"author_profile": "https://Stackoverflow.com/users/586932",
"pm_score": 3,
"selected": false,
"text": "<p>You can combine Adam & Greg's alias and dot approaches to make something that can be more dynamic—</p>\n\n<pre><code>alias project=\". project\"\n</code></pre>\n\n<p>Now running the project alias will execute the project script in the current shell as opposed to the subshell. </p>\n"
},
{
"answer_id": 12423064,
"author": "workdreamer",
"author_id": 855668,
"author_profile": "https://Stackoverflow.com/users/855668",
"pm_score": 4,
"selected": false,
"text": "<p>On my particular case i needed too many times to change for the same directory. \nSo on my .bashrc (I use ubuntu) i've added the </p>\n\n<p>1 -</p>\n\n<blockquote>\n <p>$ nano ~./bashrc</p>\n</blockquote>\n\n<pre><code> function switchp\n {\n cd /home/tree/projects/$1\n }\n</code></pre>\n\n<p>2- </p>\n\n<blockquote>\n <p>$ source ~/.bashrc</p>\n</blockquote>\n\n<p>3 - </p>\n\n<blockquote>\n <p>$ switchp java</p>\n</blockquote>\n\n<p>Directly it will do: cd /home/tree/projects/java</p>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 13112324,
"author": "kaelhop",
"author_id": 1781341,
"author_profile": "https://Stackoverflow.com/users/1781341",
"pm_score": 5,
"selected": false,
"text": "<p>I got my code to work by using<code>. <your file name></code></p>\n\n<p><code>./<your file name></code> dose not work because it doesn't change your directory in the terminal it just changes the directory specific to that script. </p>\n\n<p>Here is my program</p>\n\n<pre><code>#!/bin/bash \necho \"Taking you to eclipse's workspace.\"\ncd /Developer/Java/workspace\n</code></pre>\n\n<p>Here is my terminal </p>\n\n<pre><code>nova:~ Kael$ \nnova:~ Kael$ . workspace.sh\nTaking you to eclipe's workspace.\nnova:workspace Kael$ \n</code></pre>\n"
},
{
"answer_id": 13844527,
"author": "Lane Roathe",
"author_id": 812716,
"author_profile": "https://Stackoverflow.com/users/812716",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using <a href=\"http://ridiculousfish.com/shell/\" rel=\"nofollow\">fish</a> as your shell, the best solution is to create a function. As an example, given the original question, you could copy the 4 lines below and paste them into your fish command line:</p>\n\n<pre><code>function proj\n cd /home/tree/projects/java\nend\nfuncsave proj\n</code></pre>\n\n<p>This will create the function and save it for use later. If your project changes, just repeat the process using the new path.</p>\n\n<p>If you prefer, you can manually add the function file by doing the following:</p>\n\n<pre><code>nano ~/.config/fish/functions/proj.fish\n</code></pre>\n\n<p>and enter the text:</p>\n\n<pre><code>function proj\n cd /home/tree/projects/java\nend\n</code></pre>\n\n<p>and finally press ctrl+x to exit and y followed by return to save your changes.</p>\n\n<p>(<em>NOTE: the first method of using funcsave creates the proj.fish file for you</em>).</p>\n"
},
{
"answer_id": 15601283,
"author": "Jack Bauer",
"author_id": 2204999,
"author_profile": "https://Stackoverflow.com/users/2204999",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the operator && :</p>\n\n<p>cd myDirectory && ls</p>\n"
},
{
"answer_id": 15849531,
"author": "Max",
"author_id": 2251927,
"author_profile": "https://Stackoverflow.com/users/2251927",
"pm_score": -1,
"selected": false,
"text": "<p>You can execute some lines in the same subshell if you end lines with backslash.</p>\n\n<pre><code>cd somedir; \\\npwd\n</code></pre>\n"
},
{
"answer_id": 18306584,
"author": "mihai.ciorobea",
"author_id": 2071602,
"author_profile": "https://Stackoverflow.com/users/2071602",
"pm_score": 3,
"selected": false,
"text": "<p>In your ~/.bash_profile file. add the next function</p>\n\n<pre><code>move_me() {\n cd ~/path/to/dest\n}\n</code></pre>\n\n<p>Restart terminal and you can type</p>\n\n<pre><code>move_me \n</code></pre>\n\n<p>and you will be moved to the destination folder.</p>\n"
},
{
"answer_id": 19135116,
"author": "godzilla",
"author_id": 1054503,
"author_profile": "https://Stackoverflow.com/users/1054503",
"pm_score": -1,
"selected": false,
"text": "<p>I have a simple bash script called p to manage directory changing on<br><a href=\"https://github.com/godzilla/bash-stuff\" rel=\"nofollow\" title=\"github\">github.com/godzilla/bash-stuff</a><br>\njust put the script in your local bin directory (/usr/local/bin)<br> \nand put<br></p>\n\n<pre><code>alias p='. p'\n</code></pre>\n\n<p>in your .bashrc </p>\n"
},
{
"answer_id": 21498174,
"author": "thomasd",
"author_id": 468828,
"author_profile": "https://Stackoverflow.com/users/468828",
"pm_score": 2,
"selected": false,
"text": "<p>While sourcing the script you want to run is one solution, you should be aware that this script then can directly modify the environment of your current shell. Also it is not possible to pass arguments anymore.</p>\n\n<p>Another way to do, is to implement your script as a function in bash.</p>\n\n<pre><code>function cdbm() {\n cd whereever_you_want_to_go\n echo \"Arguments to the functions were $1, $2, ...\"\n}\n</code></pre>\n\n<p>This technique is used by autojump: <a href=\"http://github.com/joelthelion/autojump/wiki\" rel=\"nofollow\">http://github.com/joelthelion/autojump/wiki</a> to provide you with learning shell directory bookmarks.</p>\n"
},
{
"answer_id": 21676651,
"author": "Sagar",
"author_id": 1483186,
"author_profile": "https://Stackoverflow.com/users/1483186",
"pm_score": 6,
"selected": false,
"text": "<p>You can use <code>.</code> to execute a script in the current shell environment:</p>\n\n<pre><code>. script_name\n</code></pre>\n\n<p>or alternatively, its more readable but shell specific alias <code>source</code>:</p>\n\n<pre><code>source script_name\n</code></pre>\n\n<p>This avoids the subshell, and allows any variables or builtins (including <code>cd</code>) to affect the current shell instead.</p>\n"
},
{
"answer_id": 36768357,
"author": "Serge Stroobandt",
"author_id": 2192488,
"author_profile": "https://Stackoverflow.com/users/2192488",
"pm_score": 5,
"selected": false,
"text": "<h1>Use <code>exec bash</code> at the end</h1>\n<blockquote>\n<p>A bash script operates on its current environment or on that of its\nchildren, but never on its parent environment.</p>\n</blockquote>\n<p>However, this question often gets asked because one wants <strong>to be left at a (new) bash prompt in a certain directory after execution</strong> of a bash script from within another directory.</p>\n<p>If this is the case, simply <strong>execute a child bash instance</strong> at the end of the script:</p>\n<pre><code>#!/usr/bin/env bash\ncd /home/tree/projects/java\necho -e '\\nHit [Ctrl]+[D] to exit this child shell.'\nexec bash\n</code></pre>\n<p>To return to the previous, parental <code>bash</code> instance, use <kbd>Ctrl</kbd>+<kbd>D</kbd>.</p>\n<h2>Update</h2>\n<p>At least with newer versions of <code>bash</code>, the <code>exec</code> on the last line is no longer required. Furthermore, the script could be made to work with whatever preferred shell by using the <code>$SHELL</code> environment variable. This then gives:</p>\n<pre><code>#!/usr/bin/env bash\ncd desired/directory\necho -e '\\nHit [Ctrl]+[D] to exit this child shell.'\n$SHELL\n</code></pre>\n"
},
{
"answer_id": 38771044,
"author": "Krish",
"author_id": 2018627,
"author_profile": "https://Stackoverflow.com/users/2018627",
"pm_score": 2,
"selected": false,
"text": "<p>You can create a function like below in your <code>.bash_profile</code> and it will work smoothly.</p>\n\n<p>The following function takes an optional parameter which is a project.\nFor example, you can just run</p>\n\n<pre><code>cdproj\n</code></pre>\n\n<p>or</p>\n\n<pre><code>cdproj project_name\n</code></pre>\n\n<p>Here is the function definition.</p>\n\n<pre><code>cdproj(){\n dir=/Users/yourname/projects\n if [ \"$1\" ]; then\n cd \"${dir}/${1}\"\n else\n cd \"${dir}\"\n fi\n}\n</code></pre>\n\n<p>Dont forget to source your <code>.bash_profile</code></p>\n"
},
{
"answer_id": 39406080,
"author": "Gauthier",
"author_id": 108802,
"author_profile": "https://Stackoverflow.com/users/108802",
"pm_score": 0,
"selected": false,
"text": "<p>You need no script, only set the correct option and create an environment variable.</p>\n\n<pre><code>shopt -s cdable_vars\n</code></pre>\n\n<p>in your <code>~/.bashrc</code> allows to <code>cd</code> to the content of environment variables.</p>\n\n<p>Create such an environment variable:</p>\n\n<pre><code>export myjava=\"/home/tree/projects/java\"\n</code></pre>\n\n<p>and you can use:</p>\n\n<pre><code>cd myjava\n</code></pre>\n\n<p><a href=\"https://askubuntu.com/a/481733/4246\">Other alternatives</a>.</p>\n"
},
{
"answer_id": 42720845,
"author": "warhansen",
"author_id": 5497373,
"author_profile": "https://Stackoverflow.com/users/5497373",
"pm_score": 4,
"selected": false,
"text": "<p>simply run:</p>\n\n<pre><code>cd /home/xxx/yyy && command_you_want\n</code></pre>\n"
},
{
"answer_id": 49748187,
"author": "intika",
"author_id": 4877948,
"author_profile": "https://Stackoverflow.com/users/4877948",
"pm_score": 1,
"selected": false,
"text": "<p>As explained on the other answers, you have changed the directory, but only within the <strong>sub-shell that runs the script</strong>. this does not impact the parent shell. </p>\n\n<p>One solution is to use <strong>bash functions</strong> instead of a bash script (<code>sh</code>); by placing your bash script code into a function. That makes the function available as a command and then, this will be executed without a child process and thus any <code>cd</code> command will impact the caller shell.</p>\n\n<p><strong>Bash functions :</strong></p>\n\n<p>One feature of the bash profile is to store custom functions that can be run in the terminal or in bash scripts the same way you run application/commands this also could be used as a shortcut for long commands. </p>\n\n<p>To make your function efficient system widely you will need to copy your function at the end of several files</p>\n\n<pre><code>/home/user/.bashrc\n/home/user/.bash_profile\n/root/.bashrc\n/root/.bash_profile\n</code></pre>\n\n<p>You can <code>sudo kwrite /home/user/.bashrc /home/user/.bash_profile /root/.bashrc /root/.bash_profile</code> to edit/create those files quickly</p>\n\n<p><strong>Howto :</strong></p>\n\n<p>Copy your bash script code inside a new function at the end of your bash's profile file and restart your terminal, you can then run <code>cdd</code> or whatever the function you wrote.</p>\n\n<p><strong>Script Example</strong></p>\n\n<p>Making shortcut to <code>cd ..</code> with <code>cdd</code></p>\n\n<pre><code>cdd() {\n cd ..\n}\n</code></pre>\n\n<p>ls shortcut</p>\n\n<pre><code>ll() {\n ls -l -h\n}\n</code></pre>\n\n<p>ls shortcut</p>\n\n<pre><code>lll() {\n ls -l -h -a\n}\n</code></pre>\n"
},
{
"answer_id": 50145087,
"author": "jithu83",
"author_id": 2950979,
"author_profile": "https://Stackoverflow.com/users/2950979",
"pm_score": 2,
"selected": false,
"text": "<p>This should do what you want. Change to the directory of interest (from within the script), and then spawn a new bash shell.</p>\n\n<pre><code>#!/bin/bash\n\n# saved as mov_dir.sh\ncd ~/mt/v3/rt_linux-rt-tools/\nbash\n</code></pre>\n\n<p>If you run this, it will take you to the directory of interest and when you exit it it will bring you back to the original place.</p>\n\n<pre><code>root@intel-corei7-64:~# ./mov_dir.sh\n\nroot@intel-corei7-64:~/mt/v3/rt_linux-rt-tools# exit\nroot@intel-corei7-64:~#\n</code></pre>\n\n<p>This will even take you to back to your original directory when you exit (<kbd>CTRL</kbd>+<kbd>d</kbd>)</p>\n"
},
{
"answer_id": 51986175,
"author": "18446744073709551615",
"author_id": 755804,
"author_profile": "https://Stackoverflow.com/users/755804",
"pm_score": 0,
"selected": false,
"text": "<p>Note the discussion <a href=\"https://stackoverflow.com/questions/2375003/how-do-i-set-the-working-directory-of-the-parent-process/\">How do I set the working directory of the parent process?</a></p>\n\n<p>It contains some hackish answers, e.g.\n<a href=\"https://stackoverflow.com/a/2375174/755804\">https://stackoverflow.com/a/2375174/755804</a> (changing the parent process directory via gdb, don't do this) and <a href=\"https://stackoverflow.com/a/51985735/755804\">https://stackoverflow.com/a/51985735/755804</a> (the command <code>tailcd</code> that injects <em>cd dirname</em> to the input stream of the parent process; well, ideally it should be a part of bash rather than a hack)</p>\n"
},
{
"answer_id": 60427463,
"author": "Yuri Nudelman",
"author_id": 5528355,
"author_profile": "https://Stackoverflow.com/users/5528355",
"pm_score": 0,
"selected": false,
"text": "<p>It is an old question, but I am really surprised I don't see this trick here</p>\n\n<p>Instead of using <strong>cd</strong> you can use</p>\n\n<pre><code>export PWD=the/path/you/want\n</code></pre>\n\n<p>No need to create subshells or use aliases.</p>\n\n<p>Note that it is your responsibility to make sure the/path/you/want exists.</p>\n"
},
{
"answer_id": 63926954,
"author": "ZakS",
"author_id": 8270512,
"author_profile": "https://Stackoverflow.com/users/8270512",
"pm_score": 0,
"selected": false,
"text": "<p>I have to work in tcsh, and I know this is not an elegant solution, but for example, if I had to change folders to a path where one word is different, the whole thing can be done in the alias</p>\n<pre><code>a alias_name 'set a = `pwd`; set b = `echo $a | replace "Trees" "Tests"` ; cd $b'\n</code></pre>\n<p>If the path is always fixed, the just</p>\n<pre><code>a alias_name2 'cd path/you/always/need'\n</code></pre>\n<p>should work\nIn the line above, the new folder path is set</p>\n"
},
{
"answer_id": 64529986,
"author": "Asclepius",
"author_id": 832230,
"author_profile": "https://Stackoverflow.com/users/832230",
"pm_score": 0,
"selected": false,
"text": "<p>This combines the <a href=\"https://stackoverflow.com/a/36768357/\">answer by Serge</a> with an <a href=\"https://unix.stackexchange.com/a/352430/\">unrelated answer by David</a>. It changes the directory, and then instead of forcing a bash shell, it <strong>launches the user's default shell</strong>. It however requires both <code>getent</code> and <code>/etc/passwd</code> to detect the default shell.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/usr/bin/env bash\ncd desired/directory\nUSER_SHELL=$(getent passwd <USER> | cut -d : -f 7)\n$USER_SHELL\n</code></pre>\n<p>Of course this still has the same deficiency of creating a nested shell.</p>\n"
},
{
"answer_id": 71812788,
"author": "zyfyy",
"author_id": 1857269,
"author_profile": "https://Stackoverflow.com/users/1857269",
"pm_score": 0,
"selected": false,
"text": "<p>instead of excute a script file and cd to the certain folder,</p>\n<p>we can make it by:</p>\n<ul>\n<li><code>source</code> or <code>.</code> certain shell script</li>\n<li><code>alias</code> the cd command</li>\n<li>define a function ant cd to folder</li>\n</ul>\n<p>examples:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>. script\n# or\nsource script\n</code></pre>\n<pre class=\"lang-sh prettyprint-override\"><code>alias ghqc='cd $(ghq root)/$(ghq list | fzf)'\n</code></pre>\n<pre class=\"lang-sh prettyprint-override\"><code>ghqc() {\n cd $(ghq root)/$1\n}\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33203/"
] |
I'm trying to write a small script to change the current directory to my project directory:
```
#!/bin/bash
cd /home/tree/projects/java
```
I saved this file as proj, added execute permission with `chmod`, and copied it to `/usr/bin`. When I call it by:
`proj`, it does nothing. What am I doing wrong?
|
Shell scripts are run inside a subshell, and each subshell has its own concept of what the current directory is. The `cd` succeeds, but as soon as the subshell exits, you're back in the interactive shell and nothing ever changed there.
One way to get around this is to use an alias instead:
```
alias proj="cd /home/tree/projects/java"
```
|
255,422 |
<p>I would like to create an HTML table with row colors changing based on position and content. But instead of alternating every row, I'd like to be able to group rows together, so that I can have some XML like this:</p>
<pre><code><itemlist>
<item group="0">Conent...blah blah</item>
<item group="0">Content...who cares</item>
<item group="1">Content</item>
<item group="2">Content</item>
<item group="2">Content</item>
</itemlist>
</code></pre>
<p>And all of the items with group=0 are one color, and items with group=1 are another, and group=2 are either toggled back to the first color, or are their own color.</p>
<p>All I can seem to find out there is ways to alternate every row, but I can't seem to "get it" when it comes to actually using the node data to help me make the decision.</p>
|
[
{
"answer_id": 255457,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 1,
"selected": false,
"text": "<p>The first two groups are simple as you can parse them based on their group number.</p>\n\n<p>To handle group 2, consider using the <a href=\"http://www.zvon.org/xxl/XSLTreference/Output/axis_preceding.html\" rel=\"nofollow noreferrer\">preceding</a> function to get a list of proir notes, and use <a href=\"http://www.zvon.org/xxl/XSLTreference/Output/function_count.html\" rel=\"nofollow noreferrer\">count</a> to determine how many there are. You can can then alternate values based on whether the count is even or odd.</p>\n"
},
{
"answer_id": 255467,
"author": "jmcdowell",
"author_id": 2421,
"author_profile": "https://Stackoverflow.com/users/2421",
"pm_score": 3,
"selected": true,
"text": "<p>Here's an example of using \"choose\" to apply a different class value based on the group value. Something similar to this would work if you want to treat each group in a specific way. If your decision logic for handling group 2 is more complex, then you could place additional decision logic inside the \"when\" statement testing for group 2.</p>\n\n<p></p>\n\n<pre><code><xsl:template match=\"/\">\n <ul>\n <xsl:apply-templates select=\"itemlist/item\"/>\n </ul>\n</xsl:template>\n\n<xsl:template match=\"item\">\n <li>\n <xsl:attribute name=\"class\">\n <xsl:choose>\n <xsl:when test=\"@group = 0\">\n red\n </xsl:when>\n <xsl:when test=\"@group = 1\">\n green\n </xsl:when>\n <xsl:when test=\"@group = 2\">\n blue\n </xsl:when>\n <xsl:otherwise>\n black\n </xsl:otherwise>\n </xsl:choose>\n </xsl:attribute>\n <xsl:value-of select=\".\"/>\n </li>\n</xsl:template>\n</code></pre>\n\n<p> </p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33263/"
] |
I would like to create an HTML table with row colors changing based on position and content. But instead of alternating every row, I'd like to be able to group rows together, so that I can have some XML like this:
```
<itemlist>
<item group="0">Conent...blah blah</item>
<item group="0">Content...who cares</item>
<item group="1">Content</item>
<item group="2">Content</item>
<item group="2">Content</item>
</itemlist>
```
And all of the items with group=0 are one color, and items with group=1 are another, and group=2 are either toggled back to the first color, or are their own color.
All I can seem to find out there is ways to alternate every row, but I can't seem to "get it" when it comes to actually using the node data to help me make the decision.
|
Here's an example of using "choose" to apply a different class value based on the group value. Something similar to this would work if you want to treat each group in a specific way. If your decision logic for handling group 2 is more complex, then you could place additional decision logic inside the "when" statement testing for group 2.
```
<xsl:template match="/">
<ul>
<xsl:apply-templates select="itemlist/item"/>
</ul>
</xsl:template>
<xsl:template match="item">
<li>
<xsl:attribute name="class">
<xsl:choose>
<xsl:when test="@group = 0">
red
</xsl:when>
<xsl:when test="@group = 1">
green
</xsl:when>
<xsl:when test="@group = 2">
blue
</xsl:when>
<xsl:otherwise>
black
</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:value-of select="."/>
</li>
</xsl:template>
```
|
255,423 |
<p>I seem to remember being able to print out (or locate) the specific switches that each -O<num> option turns on. Can you remind?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 255434,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "<p>You may also try the good ol' manual</p>\n\n<pre><code>$ man gcc\n</code></pre>\n\n<p>at the subsection \"Options That Control Optimization\".</p>\n"
},
{
"answer_id": 255440,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": true,
"text": "<p>The <a href=\"http://gcc.gnu.org/gcc-4.3/changes.html\" rel=\"nofollow noreferrer\">list of new features on gcc 4.3</a> shows a way to do it, via an extension to the <code>--help</code> command line option:</p>\n\n<pre><code>gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts\ngcc -c -Q -O2 --help=optimizers > /tmp/O2-opts\ndiff /tmp/O2-opts /tmp/O3-opts | grep enabled\n</code></pre>\n\n<p>Note, however that I never tried that, only read about it. The documentation about this command line option is at <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#Overall-Options\" rel=\"nofollow noreferrer\">http://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#Overall-Options</a></p>\n\n<p>If you ever read the list of new features on gcc 4.3, perhaps this was what you were recalling.</p>\n"
},
{
"answer_id": 255530,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>On many machines, '<code>info gcc</code>' will produce a wealth of information. Using '<code>gcc -v --help</code>' produced a very long listing of options from sub-processes (actually, 1001 lines on stdout, and 14 on stderr) on my Mac (PPC G4 and MacOS X 10.4.11).</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30636/"
] |
I seem to remember being able to print out (or locate) the specific switches that each -O<num> option turns on. Can you remind?
Thanks!
|
The [list of new features on gcc 4.3](http://gcc.gnu.org/gcc-4.3/changes.html) shows a way to do it, via an extension to the `--help` command line option:
```
gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts
gcc -c -Q -O2 --help=optimizers > /tmp/O2-opts
diff /tmp/O2-opts /tmp/O3-opts | grep enabled
```
Note, however that I never tried that, only read about it. The documentation about this command line option is at <http://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#Overall-Options>
If you ever read the list of new features on gcc 4.3, perhaps this was what you were recalling.
|
255,429 |
<p>I would like to know if it is possible to determine if a function parameter with a default value was passed in Python.
For example, how does dict.pop work?</p>
<pre><code>>>> {}.pop('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pop(): dictionary is empty'
>>> {}.pop('test',None)
>>> {}.pop('test',3)
3
>>> {}.pop('test',NotImplemented)
NotImplemented
</code></pre>
<p>How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?</p>
<p>Thanks</p>
|
[
{
"answer_id": 255433,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it like this:</p>\n\n<pre><code>def isdefarg(*args):\n if len(args) > 0:\n print len(args), \"arguments\"\n else:\n print \"no arguments\"\n\nisdefarg()\nisdefarg(None)\nisdefarg(5, 7)\n</code></pre>\n\n<p>See the Python documentation on <a href=\"http://python.org/doc/2.5/ref/calls.html\" rel=\"nofollow noreferrer\">calls</a> for full information.</p>\n"
},
{
"answer_id": 255438,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 5,
"selected": true,
"text": "<p>I guess you mean \"keyword argument\", when you say \"named parameter\". <code>dict.pop()</code> does not accept keyword argument, so this part of the question is moot.</p>\n\n<pre><code>>>> {}.pop('test', d=None)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: pop() takes no keyword arguments\n</code></pre>\n\n<p>That said, the way to detect whether an argument was provided is to use the <code>*args</code> or <code>**kwargs</code> syntax. For example:</p>\n\n<pre><code>def foo(first, *rest):\n if len(rest) > 1:\n raise TypeError(\"foo() expected at most 2 arguments, got %d\"\n % (len(rest) + 1))\n print 'first =', first\n if rest:\n print 'second =', rest[0]\n</code></pre>\n\n<p>With some work, and using the <code>**kwargs</code> syntax too it is possible to completely emulate the python calling convention, where arguments can be either provided by position or by name, and arguments provided multiple times (by position and name) cause an error.</p>\n"
},
{
"answer_id": 255446,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 1,
"selected": false,
"text": "<pre><code>def f(one, two=2):\n print \"I wonder if\", two, \"has been passed or not...\"\n\nf(1, 2)\n</code></pre>\n\n<p>If this is the exact meaning of your question, I think that there is no way to distinguish between a 2 that was in the default value and a 2 that has been passed. I didn't find how to accomplish such distinction even in the <a href=\"http://www.python.org/doc/2.5.2/lib/module-inspect.html\" rel=\"nofollow noreferrer\">inspect</a> module.</p>\n"
},
{
"answer_id": 255472,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>I am not certain if I fully understand what is it you want; however:</p>\n\n<pre><code>def fun(arg=Ellipsis):\n if arg is Ellipsis:\n print \"No arg provided\"\n else:\n print \"arg provided:\", repr(arg)\n</code></pre>\n\n<p>does that do what you want? If not, then as others have suggested, you should declare your function with the <code>*args, **kwargs</code> syntax and check in the kwargs dict for the parameter existence.</p>\n"
},
{
"answer_id": 255580,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 4,
"selected": false,
"text": "<p>The convention is often to use <code>arg=None</code> and use</p>\n\n<pre><code>def foo(arg=None):\n if arg is None:\n arg = \"default value\"\n # other stuff\n # ...\n</code></pre>\n\n<p>to check if it was passed or not. Allowing the user to pass <code>None</code>, which would be interpreted as if the argument was <em>not</em> passed.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24730/"
] |
I would like to know if it is possible to determine if a function parameter with a default value was passed in Python.
For example, how does dict.pop work?
```
>>> {}.pop('test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'pop(): dictionary is empty'
>>> {}.pop('test',None)
>>> {}.pop('test',3)
3
>>> {}.pop('test',NotImplemented)
NotImplemented
```
How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?
Thanks
|
I guess you mean "keyword argument", when you say "named parameter". `dict.pop()` does not accept keyword argument, so this part of the question is moot.
```
>>> {}.pop('test', d=None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pop() takes no keyword arguments
```
That said, the way to detect whether an argument was provided is to use the `*args` or `**kwargs` syntax. For example:
```
def foo(first, *rest):
if len(rest) > 1:
raise TypeError("foo() expected at most 2 arguments, got %d"
% (len(rest) + 1))
print 'first =', first
if rest:
print 'second =', rest[0]
```
With some work, and using the `**kwargs` syntax too it is possible to completely emulate the python calling convention, where arguments can be either provided by position or by name, and arguments provided multiple times (by position and name) cause an error.
|
255,470 |
<p>As the title describes, what are the different doctypes available and what do they mean? I notice that the layout looks a little different in IE7 when I switch from </p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
</code></pre>
<p>to</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code></pre>
<p>Are there any others and what are the effects or ramifications?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 255473,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the official explanation of the various DTD's from the W3C:</p>\n\n<p><a href=\"http://www.w3.org/QA/2002/04/valid-dtd-list.html\" rel=\"nofollow noreferrer\"><a href=\"http://www.w3.org/QA/2002/04/valid-dtd-list.html\" rel=\"nofollow noreferrer\">http://www.w3.org/QA/2002/04/valid-dtd-list.html</a></a></p>\n\n<p>You might also find the following beneficial:</p>\n\n<p><a href=\"http://www.freedivs.com/tutorials/Choosing%20a%20DOCTYPE/\" rel=\"nofollow noreferrer\"><a href=\"http://www.freedivs.com/tutorials/Choosing%20a%20DOCTYPE/\" rel=\"nofollow noreferrer\">http://www.freedivs.com/tutorials/Choosing%20a%20DOCTYPE/</a></a></p>\n"
},
{
"answer_id": 255474,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 7,
"selected": true,
"text": "<p>Traditionally, a <strong>Doctype</strong>, or <strong>Document Type Declaration</strong> associates the document with a <strong>Document Type Definition</strong>.</p>\n<p>The <strong>Document Type Definition</strong> is a standard for a specific XML or SGML document. XML and SGML themselves doesn't have much of a schema or a very specific set of rules aside from how tags and attributes work in general. You can think of a DTD a description of the rules for a particular kind of document (like HTML, SVG or MathML). They say what tags are allowed where (e.g. that an <code>html</code> element must contain exactly one <code>head</code> element followed by exactly one <code>body</code> element).</p>\n<p>There are alternatives to DTDs such as XML Schemas that are more commonly used today.</p>\n<p>Browsers, however, do not use DTDs at all. They read the Doctype to determine the <em>rendering mode</em>, but the rules for parsing the document are entirely baked into the browser.</p>\n<p>This is why HTML 5 has a Doctype (to determine the rendering mode) but not DTD.</p>\n<p><strong>Rendering Modes</strong></p>\n<p>Early web browsers were very buggy. When new versions were released they had to maintain compatibility with their predecessors and rivals. This made it very hard to fix bugs because websites were built that depended on them.</p>\n<p>To resolve this, modern browsers have different rendering modes (<strong>standards mode</strong>, for rendering your document and css according to standards, and <strong>quirks mode</strong>, wherein the browser emulates the bugs of earlier browsers, and <strong>almost standards mode</strong> which sits between the two).</p>\n<p><strong>Choosing a Doctype</strong></p>\n<p>There are two factors to consider when selecting a Doctype:</p>\n<ul>\n<li>Does it trigger standards mode? (For new pages it <em>should</em>, times when you need to be compatible with browsers which don't support standards mode are very rare today).</li>\n<li>Does it support the features I need?</li>\n</ul>\n<p>Generally this means you should use HTML 5. It is the current standard and best reflects how browsers actually work:</p>\n<pre><code><!DOCTYPE html>\n</code></pre>\n<p>Failing that. Strict doctypes avoid most features that should be handled with CSS.</p>\n<p>When writing in <strong>XHTML 1.0</strong>, this Doctype is common:</p>\n<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n</code></pre>\n<p>More obsolete features are available via:</p>\n<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\n"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"\n"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">\n</code></pre>\n<p>When writing in <strong>HTML 4.01</strong>, this one is common instead:</p>\n<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"\n"http://www.w3.org/TR/html4/strict.dtd">\n</code></pre>\n<p>With the obsolete features being in</p>\n<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"\n"http://www.w3.org/TR/html4/loose.dtd">\n</code></pre>\n<p>and</p>\n<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"\n"http://www.w3.org/TR/html4/frameset.dtd">\n</code></pre>\n<p>Note that most of the above have variations (e.g. you can omit the URL and rely on the public identifier) which have implications for the support of standards mode. <a href=\"https://hsivonen.fi/doctype/\" rel=\"nofollow noreferrer\">This article includes an extensive list</a>.</p>\n<p><strong>Debate on Strict versus Transitional Doctypes</strong></p>\n<p>(Note that the following is much, <strong>must</strong> less true in 2021 than it was in 2008)</p>\n<p>Standards evangelists have called for web developers to stop using the Transitional Doctype on new pages and instead use Strict. Again, this is a case where the theory and the practice have some difficulties being reconciled. The original hope of the transitional Doctype was to provide a halfway house for transitioning legacy websites toward standards-compliance. With transitional doctypes, the restriction on elements and attributes is literally "less strict", so developers would be able to get their work running under standards mode sooner, and phase out the outstanding differences over time.</p>\n<p>Controversy exists because it isn't always quite so simple for a developer change the Doctype in an enterprise environment. Freelance developers and makers of small- or medium- sized websites may often have an easier time determining their Doctype and making this transition. In an enterprise production environment for a highly-demanded web-based service, there are inherently more complicated dependencies on legacy systems and 3rd party code products, which themselves may be on a roadmap for removal or redesign, but the execution of such changes must be done methodically and incrementally.</p>\n<p><strong>Helpful Tools</strong></p>\n<p>The W3C (<a href=\"http://en.wikipedia.org/wiki/W3C\" rel=\"nofollow noreferrer\"><strong>World Wide Web Consortium</strong></a>) is a group which plays an active role in defining these kinds of standards. They maintain a helpful online tool at <a href=\"http://validator.w3.org/\" rel=\"nofollow noreferrer\"><strong>http://validator.w3.org/</strong></a> for verifying and validating documents against their standards. There are many other 3rd party tools and <a href=\"http://addons.mozilla.org/en-US/firefox/search?q=validator&cat=all\" rel=\"nofollow noreferrer\"><strong>browser extensions</strong></a> with similar functionality.</p>\n"
},
{
"answer_id": 255747,
"author": "cic",
"author_id": 4771,
"author_profile": "https://Stackoverflow.com/users/4771",
"pm_score": 3,
"selected": false,
"text": "<p>Browsers <a href=\"http://wiki.whatwg.org/wiki/FAQ#Syntax_issues\" rel=\"nofollow noreferrer\">don't care</a> what doctype you use (well, almost true), they use it for one thing and one thing only: to decide which <em>render mode</em> to use. See e.g. the <a href=\"https://developer.mozilla.org/en/Mozilla%27s_DOCTYPE_sniffing\" rel=\"nofollow noreferrer\">Fx</a> or <a href=\"http://www.opera.com/docs/specs/doctype/\" rel=\"nofollow noreferrer\">Opera documentation</a> for real-world examples on what algorithms is used to decide which mode to use (I guess there is some documentation for IE buried somewhere in MSDN too ... [This may be the correct page](<a href=\"http://msdn.microsoft.com/en-us/library/ms535242(VS.85).aspx)\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms535242(VS.85).aspx)</a>, I don't know, sorry).</p>\n\n<p>There are however two major modes in most browsers (some browsers have an <a href=\"https://developer.mozilla.org/en/Gecko%27s_%22Almost_Standards%22_Mode\" rel=\"nofollow noreferrer\">almost standards mode</a> too):</p>\n\n<ul>\n<li><strong>quirks mode</strong> (used when no \"correct\" doctype is found, \"correct\" from the browsers point of view): try to render the document as some old version of IE would do (one of the most important differences, i.e. affects rendering the most, is that some browsers exploits the <a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug\" rel=\"nofollow noreferrer\">IE box model bug</a> in this mode),</li>\n<li>and <strong>standard mode</strong> (used when the browser found a doctype it considers correct): try to do as the standards says.</li>\n</ul>\n\n<p>You can use (the non-standard) <a href=\"https://developer.mozilla.org/En/DOM/Document.compatMode\" rel=\"nofollow noreferrer\"><code>document.compatMode</code></a> property in previous mentioned browsers to check which mode that was used to render the current document.</p>\n\n<p>(Note on XHTML: I assumed that you serve you documents as HTML (<code>text/html</code>), if you serve you document as XHTML (probably <code>application/xhtml+xml</code>) most browser jumps into standard mode directly and don't care about the doctype at all AFAIK.)</p>\n\n<p>BTW: the recommendation (or, what looked like a recommendation) in the other answer is broken, the <a href=\"http://dictionary.reference.com/search?q=transitional\" rel=\"nofollow noreferrer\">transitional</a> DTD should not be used on new documents. Always use strict (the term \"strict\" is kind of misleading, should be \"default\" or something else non-scary), period:</p>\n\n<blockquote>\n <p>Authors should use the Strict DTD when possible, but may use the Transitional DTD when support for presentation attribute and elements is required. -- <a href=\"http://www.w3.org/TR/REC-html40/sgml/loosedtd.html\" rel=\"nofollow noreferrer\">HTML 4.01: 22 Transitional Document Type Definition</a>.</p>\n \n <p>We recommend that authors write documents that conform to the strict DTD rather than the other DTDs defined by this specification. -- <a href=\"http://www.w3.org/TR/REC-html40/conform.html#h-4.1\" rel=\"nofollow noreferrer\">HTML 4.01: 4 Conformance: requirements and recommendations</a></p>\n</blockquote>\n\n<p>And there are many blog post about this, e.g. <a href=\"http://www.456bereastreet.com/archive/200609/no_more_transitional_doctypes_please/\" rel=\"nofollow noreferrer\">no more Transitional DOCTYPEs, please</a> (from 2006, but <em>some</em>, obviously, still have problems with this :).</p>\n\n<p>This post started out with pointing out that browsers don't care what you choose, and then developed into a rant about how to choose the correct DTD, interesting ... But if you are going to spend(/waste?) time and energy to choose a DTD you might as well choose the correct one (from a HTML 4.01 standard perspective that is).</p>\n\n<p><em>Or</em>, you can ignore all this and use the following instead, <a href=\"http://blog.whatwg.org/two-thousand-twenty-two\" rel=\"nofollow noreferrer\">soon</a> <a href=\"http://ishtml5readyyet.com\" rel=\"nofollow noreferrer\">anyway</a>:</p>\n\n<pre><code><!doctype html>\n</code></pre>\n\n<p>(<a href=\"https://stackoverflow.com/questions/5629/any-reason-not-to-start-using-the-html-5-doctype#14192\">This answer</a> to \"any reason not to start using the HTML 5 doctype?\" was kind of related to the last part.)</p>\n"
},
{
"answer_id": 256184,
"author": "dicroce",
"author_id": 3886,
"author_profile": "https://Stackoverflow.com/users/3886",
"pm_score": 0,
"selected": false,
"text": "<p>Basically, the doctype determines how crazy IE is going to be. </p>\n\n<p>If you don't set it to XHTML, or \"strict\" you'll be living in a world of hurt when it comes to IE (even if you set it, you'll still be hating on IE, but it does make it a lot better).</p>\n"
},
{
"answer_id": 256674,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 2,
"selected": false,
"text": "<p>There is a lot of misinformation around doctypes. The confusion stems from the fact that doctypes originally was intended for one purpose (to identify the DTD, ie. the HTML version used), but in real-world browsers are used for a completely unrelated purpose.</p>\n\n<p>Doctype declarations are only used for <strong>one thing</strong> in todays browsers, that is switching between <em>quirks</em> rendering mode and <em>standards</em> rendering mode for CSS. So basically it is a CSS-thing, not a HTML-thing.</p>\n\n<p>Quirks mode rendering is backwards compatible with some old rendering bugs in older browsers, and is mostly useful for legacy content you dont want to fix. New content should always use standards mode, since it renders more correct and consistently among browsers. (There is still rendering differences between browsers when using standards mode, but there are much worse in quirks mode.)</p>\n\n<p>It does <strong>not</strong> make any difference whether you choose a HTML or XHTML docytype, neither will it make any difference if you choose strict or transitional doctype. The rendering mode is basically selected like this:</p>\n\n<ul>\n<li>If the document don't have any doctype, <em>quirks</em> mode is selected.</li>\n<li>If the document have an <em>unrecognized</em> doctype, <em>standards</em> mode is selected. This means you can write a random doctype like <code><!DOCTYPE Chris></code> and it will work perfectly fine.</li>\n<li>Official W3C doctypes <em>without</em> the correct url (the second string in the tag) selects <em>quirks</em> mode. All other doctypes selects standards mode. (Edit: of course it is more complex than that, and it even differs between browsers which of the recognized doctypes triggers quirks mode. Se <a href=\"http://hsivonen.iki.fi/doctype/\" rel=\"nofollow noreferrer\">hsivonens overview</a>, linked from another answer.)</li>\n</ul>\n\n<p>Historically doctypes were intended to declare which version and subset of HTML were used. HTML4 defines several versions, where \"transitional\" allows a number of elements ans attributes that (like FONT) is not allowed in \"strict\". A browser could theoretically process \"strict\" documents different than \"transitional\"-document. However <em>no browser actually does this</em>. </p>\n\n<p>Edit: scunliffe points out that IE8 will have yet another rendering mode, \"IE8 standards\" mode. However AFAIK this mode is not triggered by a doctype but by a meta-tag.</p>\n"
},
{
"answer_id": 257365,
"author": "hsivonen",
"author_id": 18721,
"author_profile": "https://Stackoverflow.com/users/18721",
"pm_score": 2,
"selected": false,
"text": "<p>I've written an <a href=\"http://hsivonen.iki.fi/doctype/\" rel=\"nofollow noreferrer\">article that explains how doctypes are involved in rendering mode selection</a>.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2849/"
] |
As the title describes, what are the different doctypes available and what do they mean? I notice that the layout looks a little different in IE7 when I switch from
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
```
to
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
```
Are there any others and what are the effects or ramifications?
Thanks!
|
Traditionally, a **Doctype**, or **Document Type Declaration** associates the document with a **Document Type Definition**.
The **Document Type Definition** is a standard for a specific XML or SGML document. XML and SGML themselves doesn't have much of a schema or a very specific set of rules aside from how tags and attributes work in general. You can think of a DTD a description of the rules for a particular kind of document (like HTML, SVG or MathML). They say what tags are allowed where (e.g. that an `html` element must contain exactly one `head` element followed by exactly one `body` element).
There are alternatives to DTDs such as XML Schemas that are more commonly used today.
Browsers, however, do not use DTDs at all. They read the Doctype to determine the *rendering mode*, but the rules for parsing the document are entirely baked into the browser.
This is why HTML 5 has a Doctype (to determine the rendering mode) but not DTD.
**Rendering Modes**
Early web browsers were very buggy. When new versions were released they had to maintain compatibility with their predecessors and rivals. This made it very hard to fix bugs because websites were built that depended on them.
To resolve this, modern browsers have different rendering modes (**standards mode**, for rendering your document and css according to standards, and **quirks mode**, wherein the browser emulates the bugs of earlier browsers, and **almost standards mode** which sits between the two).
**Choosing a Doctype**
There are two factors to consider when selecting a Doctype:
* Does it trigger standards mode? (For new pages it *should*, times when you need to be compatible with browsers which don't support standards mode are very rare today).
* Does it support the features I need?
Generally this means you should use HTML 5. It is the current standard and best reflects how browsers actually work:
```
<!DOCTYPE html>
```
Failing that. Strict doctypes avoid most features that should be handled with CSS.
When writing in **XHTML 1.0**, this Doctype is common:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
```
More obsolete features are available via:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
```
When writing in **HTML 4.01**, this one is common instead:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
```
With the obsolete features being in
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
```
and
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
```
Note that most of the above have variations (e.g. you can omit the URL and rely on the public identifier) which have implications for the support of standards mode. [This article includes an extensive list](https://hsivonen.fi/doctype/).
**Debate on Strict versus Transitional Doctypes**
(Note that the following is much, **must** less true in 2021 than it was in 2008)
Standards evangelists have called for web developers to stop using the Transitional Doctype on new pages and instead use Strict. Again, this is a case where the theory and the practice have some difficulties being reconciled. The original hope of the transitional Doctype was to provide a halfway house for transitioning legacy websites toward standards-compliance. With transitional doctypes, the restriction on elements and attributes is literally "less strict", so developers would be able to get their work running under standards mode sooner, and phase out the outstanding differences over time.
Controversy exists because it isn't always quite so simple for a developer change the Doctype in an enterprise environment. Freelance developers and makers of small- or medium- sized websites may often have an easier time determining their Doctype and making this transition. In an enterprise production environment for a highly-demanded web-based service, there are inherently more complicated dependencies on legacy systems and 3rd party code products, which themselves may be on a roadmap for removal or redesign, but the execution of such changes must be done methodically and incrementally.
**Helpful Tools**
The W3C ([**World Wide Web Consortium**](http://en.wikipedia.org/wiki/W3C)) is a group which plays an active role in defining these kinds of standards. They maintain a helpful online tool at [**http://validator.w3.org/**](http://validator.w3.org/) for verifying and validating documents against their standards. There are many other 3rd party tools and [**browser extensions**](http://addons.mozilla.org/en-US/firefox/search?q=validator&cat=all) with similar functionality.
|
255,516 |
<p>I used the method</p>
<pre><code>$("#dvTheatres a").hover(function (){
$(this).css("text-decoration", "underline");
},function(){
$(this).css("text-decoration", "none");
}
);
</code></pre>
<p>Is there a more elegant method?(single line)</p>
|
[
{
"answer_id": 255519,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 4,
"selected": false,
"text": "<p>Why not just use CSS?</p>\n\n<pre><code>#dvTheatres a {\n text-decoration: none;\n}\n\n#dvTheatres a:hover {\n text-decoration: underline;\n}\n</code></pre>\n"
},
{
"answer_id": 255539,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>No good answer, but maybe you're just looking for alternatives. One is to use named function (and CSS) instead to express intent rather than in-lining raw instructions.</p>\n\n<p>Script</p>\n\n<pre><code>function toggleUnderline() { $(this).toggleClass('underline') };\n$(\"#dvTheatres a\").hover(toggleUnderline, toggleUnderline);\n</code></pre>\n\n<p>CSS</p>\n\n<pre><code>.underline { text-decoration: underline; }\n</code></pre>\n"
},
{
"answer_id": 255561,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": true,
"text": "<p>You might be having issues with other CSS rules overriding the one you want. Even if it is declared last in the file, other declarations might have more importance and hence your will be ignored. eg:</p>\n\n<pre><code>#myDiv .myClass a {\n color: red;\n}\n#myDiv a {\n color: blue;\n}\n</code></pre>\n\n<p>Because the first rule is <strong>more specific</strong> it takes precedence. Here's a page explaining CSS Specificity: <a href=\"http://www.htmldog.com/guides/cssadvanced/specificity/\" rel=\"noreferrer\">http://www.htmldog.com/guides/cssadvanced/specificity/</a></p>\n\n<p>The reason your jQuery solution works is because applying a style via the <code>style=\"\"</code> parameter has very high specificity.</p>\n\n<p>The best way to find which rules are being applied and which are being overruled by others is to use the Firebug extension for Firefox. Inspect the element in that and click on the CSS tab: it will show you every single CSS declaration which is being applied, and put a strike-through on ones which are being overruled.</p>\n\n<p>If you want a really quick and easy way to solve your problem though, try this:</p>\n\n<pre><code>#dvTheatres a:hover {\n text-decoration: underline !important;\n}\n</code></pre>\n\n<hr>\n\n<p>if you really want to stick to using jQuery, your method is fine and probably the most elegant way to do it (using jQuery).</p>\n"
},
{
"answer_id": 48724078,
"author": "Rick",
"author_id": 1827424,
"author_profile": "https://Stackoverflow.com/users/1827424",
"pm_score": 0,
"selected": false,
"text": "<p>Give this a try</p>\n\n<pre><code>$('.my-awesome div a').hover().css('text-decoration', 'none');\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17447/"
] |
I used the method
```
$("#dvTheatres a").hover(function (){
$(this).css("text-decoration", "underline");
},function(){
$(this).css("text-decoration", "none");
}
);
```
Is there a more elegant method?(single line)
|
You might be having issues with other CSS rules overriding the one you want. Even if it is declared last in the file, other declarations might have more importance and hence your will be ignored. eg:
```
#myDiv .myClass a {
color: red;
}
#myDiv a {
color: blue;
}
```
Because the first rule is **more specific** it takes precedence. Here's a page explaining CSS Specificity: <http://www.htmldog.com/guides/cssadvanced/specificity/>
The reason your jQuery solution works is because applying a style via the `style=""` parameter has very high specificity.
The best way to find which rules are being applied and which are being overruled by others is to use the Firebug extension for Firefox. Inspect the element in that and click on the CSS tab: it will show you every single CSS declaration which is being applied, and put a strike-through on ones which are being overruled.
If you want a really quick and easy way to solve your problem though, try this:
```
#dvTheatres a:hover {
text-decoration: underline !important;
}
```
---
if you really want to stick to using jQuery, your method is fine and probably the most elegant way to do it (using jQuery).
|
255,517 |
<p>I would like to construct a query that displays all the results in a table, but is offset by 5 from the start of the table. As far as I can tell, MySQL's <code>LIMIT</code> requires a limit as well as an offset. Is there any way to do this?</p>
|
[
{
"answer_id": 271648,
"author": "Czimi",
"author_id": 3906,
"author_profile": "https://Stackoverflow.com/users/3906",
"pm_score": 5,
"selected": false,
"text": "<p>As you mentioned it LIMIT is required, so you need to use the biggest limit possible, which is 18446744073709551615 (maximum of unsigned BIGINT)</p>\n\n<pre><code>SELECT * FROM somewhere LIMIT 18446744073709551610 OFFSET 5\n</code></pre>\n"
},
{
"answer_id": 271650,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 8,
"selected": true,
"text": "<p>From the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select.html#id4651990\" rel=\"noreferrer\">MySQL Manual on LIMIT</a>:</p>\n\n<blockquote>\n <p>To retrieve all rows from a certain\n offset up to the end of the result\n set, you can use some large number for\n the second parameter. This statement\n retrieves all rows from the 96th row\n to the last:</p>\n</blockquote>\n\n<pre><code>SELECT * FROM tbl LIMIT 95, 18446744073709551615;\n</code></pre>\n"
},
{
"answer_id": 271673,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 3,
"selected": false,
"text": "<p>Another approach would be to select an autoimcremented column and then filter it using HAVING.</p>\n\n<pre><code>SET @a := 0; \nselect @a:=@a + 1 AS counter, table.* FROM table \nHAVING counter > 4\n</code></pre>\n\n<p>But I would probably stick with the high limit approach.</p>\n"
},
{
"answer_id": 10105941,
"author": "fed",
"author_id": 403099,
"author_profile": "https://Stackoverflow.com/users/403099",
"pm_score": -1,
"selected": false,
"text": "<p>Just today I was reading about the best way to get huge amounts of data (more than a million rows) from a mysql table. One way is, as suggested, using <code>LIMIT x,y</code> where <code>x</code> is the offset and <code>y</code> the last row you want returned. However, as I found out, it isn't the most efficient way to do so. If you have an autoincrement column, you can as easily use a <code>SELECT</code> statement with a <code>WHERE</code> clause saying from which record you'd like to start.</p>\n\n<p>For example,\n <code>SELECT * FROM table_name WHERE id > x;</code></p>\n\n<p>It seems that mysql gets all results when you use <code>LIMIT</code> and then only shows you the records that fit in the offset: not the best for performance.</p>\n\n<p>Source: Answer to this question <a href=\"http://forums.mysql.com/read.php?24,112440,112440\" rel=\"nofollow\">MySQL Forums</a>. Just take note, the question is about 6 years old.</p>\n"
},
{
"answer_id": 21438563,
"author": "Baron Von Sparklefarts",
"author_id": 3250001,
"author_profile": "https://Stackoverflow.com/users/3250001",
"pm_score": -1,
"selected": false,
"text": "<p>I know that this is old but I didnt see a similar response so this is the solution I would use.</p>\n\n<p>First, I would execute a count query on the table to see how many records exist. This query is fast and normally the execution time is negligible. Something like:</p>\n\n<pre><code>SELECT COUNT(*) FROM table_name;\n</code></pre>\n\n<p>Then I would build my query using the result I got from count as my limit (since that is the maximum number of rows the table could possibly return). Something like:</p>\n\n<pre><code>SELECT * FROM table_name LIMIT count_result OFFSET desired_offset;\n</code></pre>\n\n<p>Or possibly something like:</p>\n\n<pre><code>SELECT * FROM table_name LIMIT desired_offset, count_result;\n</code></pre>\n\n<p>Of course, if necessary, you could subtract desired_offset from count_result to get an actual, accurate value to supply as the limit. Passing the \"18446744073709551610\" value just doesnt make sense if I can actually determine an appropriate limit to provide. </p>\n"
},
{
"answer_id": 21690378,
"author": "user3131125",
"author_id": 3131125,
"author_profile": "https://Stackoverflow.com/users/3131125",
"pm_score": -1,
"selected": false,
"text": "<pre><code>WHERE .... AND id > <YOUROFFSET>\n</code></pre>\n\n<p>id can be any autoincremented or unique numerical column you have...</p>\n"
},
{
"answer_id": 37754209,
"author": "sissi_luaty",
"author_id": 2097703,
"author_profile": "https://Stackoverflow.com/users/2097703",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a MySQL statement with LIMIT:</p>\n\n<pre><code>START TRANSACTION;\nSET @my_offset = 5;\nSET @rows = (SELECT COUNT(*) FROM my_table);\nPREPARE statement FROM 'SELECT * FROM my_table LIMIT ? OFFSET ?';\nEXECUTE statement USING @rows, @my_offset;\nCOMMIT;\n</code></pre>\n\n<p>Tested in MySQL 5.5.44. Thus, we can avoid the insertion of the number 18446744073709551615.</p>\n\n<p>note: the transaction makes sure that the variable @rows is in agreement to the table considered in the execution of statement.</p>\n"
},
{
"answer_id": 38618872,
"author": "cesoid",
"author_id": 289324,
"author_profile": "https://Stackoverflow.com/users/289324",
"pm_score": 4,
"selected": false,
"text": "<p>As noted in other answers, MySQL suggests using 18446744073709551615 as the number of records in the limit, but consider this: What would you do if you got 18,446,744,073,709,551,615 records back? In fact, what would you do if you got 1,000,000,000 records?</p>\n\n<p>Maybe you do want more than one billion records, but my point is that there is some limit on the number you <em>want</em>, and it is less than 18 quintillion. For the sake of stability, optimization, and possibly usability, I would suggest putting some meaningful limit on the query. This would also reduce confusion for anyone who has never seen that magical looking number, and have the added benefit of communicating at least how many records you are willing to handle at once.</p>\n\n<p>If you really must get all 18 quintillion records from your database, maybe what you really want is to grab them in increments of 100 million and loop 184 billion times.</p>\n"
},
{
"answer_id": 58806110,
"author": "Bruno.S",
"author_id": 9041942,
"author_profile": "https://Stackoverflow.com/users/9041942",
"pm_score": 3,
"selected": false,
"text": "<p>As others mentioned, from the MySQL manual. In order to achieve that, you can use the maximum value of an unsigned big int, that is this awful number (18446744073709551615). But to make it a little bit less messy you can the tilde \"~\" bitwise operator.</p>\n\n<pre><code> LIMIT 95, ~0\n</code></pre>\n\n<p>it works as a bitwise negation. The result of \"~0\" is 18446744073709551615.</p>\n"
},
{
"answer_id": 67593830,
"author": "fishstick",
"author_id": 6648533,
"author_profile": "https://Stackoverflow.com/users/6648533",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into a very similar issue when practicing <a href=\"https://leetcode.com/problems/restaurant-growth/\" rel=\"nofollow noreferrer\">LC#1321</a>, in which I have to select all the dates but the first 6 dates are skipped.</p>\n<p>I achieved this in MySQL with the help of <code>ROW_NUMBER()</code> window function and subquery. For example, the following query returns all the results with the first five rows skipped:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT\n fieldname1,\n fieldname2\nFROM(\n SELECT\n *,\n ROW_NUMBER() OVER() row_num\n FROM\n mytable\n) tmp\nWHERE\n row_num > 5;\n</code></pre>\n<p>You may need to add some more logics in the subquery, especially in <code>OVER()</code> to fit your need. In addition, <code>RANK()</code>/<code>DENSE_RANK()</code> window functions may be used instead of <code>ROW_NUMBER()</code> depending on your real offset logic.</p>\n<p>Reference:</p>\n<p><a href=\"https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html#function_row-number\" rel=\"nofollow noreferrer\">MySQL 8.0 Reference Manual - ROW_NUMBER()</a></p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23335/"
] |
I would like to construct a query that displays all the results in a table, but is offset by 5 from the start of the table. As far as I can tell, MySQL's `LIMIT` requires a limit as well as an offset. Is there any way to do this?
|
From the [MySQL Manual on LIMIT](http://dev.mysql.com/doc/refman/5.0/en/select.html#id4651990):
>
> To retrieve all rows from a certain
> offset up to the end of the result
> set, you can use some large number for
> the second parameter. This statement
> retrieves all rows from the 96th row
> to the last:
>
>
>
```
SELECT * FROM tbl LIMIT 95, 18446744073709551615;
```
|
255,527 |
<p>Is there a practical algorithm that gives "multiplication chains"</p>
<p>To clarify, the goal is to produce a multiplication change of an <b>arbitrary and exact </b> length<br>
Multiplication chains of length 1 are trivial.</p>
<p>A "multiplication chain" would be defined as 2 numbers, {start} and {multiplier}, used in code:</p>
<pre><code> Given a pointer to array of size [{count}] // count is a parameter
a = start;
do
{
a = a * multiplier; // Really: a = (a * multiplier) MOD (power of 2
*(pointer++) = a;
}
while (a != {constant} )
// Postcondition: all {count} entries are filled.
</code></pre>
<p>I'd like to find a routine that takes three parameters<br>
1. Power of 2<br>
2. Stopping {constant}<br>
3. {count} - Number of times the loop will iterate </p>
<p>The routine would return {start} and {multiplier}. </p>
<p>Ideally, a {Constant} value of 0 should be valid.</p>
<p>Trivial example:</p>
<pre><code>power of 2 = 256
stopping constant = 7
number of times for the loop = 1
returns {7,1}
</code></pre>
<p>Nontrivial example: </p>
<pre><code>power of 2 = 256
stopping constant = 1
number of times for the loop = 49
returns {25, 19}
</code></pre>
<p>The maximum {count} for a given power of 2 can be fairly small.<br>
For example, 2^4 (16) seems to be limited to a count of 4 </p>
|
[
{
"answer_id": 255537,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>Why wouldn't this satisfy the requirements?</p>\n\n<pre><code>start = constant;\nmultiplier = 1;\n</code></pre>\n\n<p>Update: I see now that the number of loops is one of the input parameters. It sounds like this problem is a special case of, or at least related to, the <a href=\"http://mathworld.wolfram.com/DiscreteLogarithm.html\" rel=\"nofollow noreferrer\">discrete logarithm</a> problem.</p>\n"
},
{
"answer_id": 255558,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 3,
"selected": false,
"text": "<p>You are asking for nontrivial solutions to the following modular equation:</p>\n\n<pre><code>s * m^N = C (mod 2^D)</code></pre>\n\n<p>where</p>\n\n<ul>\n<li>s is the starting constant</li>\n<li>m is the multiplier</li>\n<li>N is the number of iterations (given by the problem)</li>\n<li>C is the final constant (given by the problem)</li>\n<li>D is the exponent of the power of 2 (given by the problem)</li>\n</ul>\n\n<p>Have a look at <a href=\"http://en.wikipedia.org/wiki/Euler%27s_theorem\" rel=\"nofollow noreferrer\">Euler's theorem</a> in number theory.</p>\n\n<p>For an arbitrary <em>odd</em> m (which is prime with 2^D), you have</p>\n\n<pre><code>m^phi(2^D) = 1 (mod 2^D)</code></pre>\n\n<p>thus</p>\n\n<pre><code>C * m^phi(2^D) = C (mod 2^D)</code></pre>\n\n<p>and finally</p>\n\n<pre><code>C * m^(phi(2^D)-N) * m^N = C (mod 2^D)</code></pre>\n\n<p>Take</p>\n\n<pre><code>s = C * m^(phi(2^D)-N)</code></pre>\n\n<p>and you're done. The <a href=\"http://en.wikipedia.org/wiki/Euler%27s_totient_function\" rel=\"nofollow noreferrer\">Euler's phi function</a> of a power of 2 is <em>half</em> that power of 2, i.e.:</p>\n\n<pre><code>phi(2^D) = 2^(D-1)</code></pre>\n\n<p><strong>Example</strong>. Let</p>\n\n<ul>\n<li>N = 5</li>\n<li>C = 3</li>\n<li>2^D = 16</li>\n<li>phi(16) = 8</li>\n</ul>\n\n<p>Choose arbitrarily m = 7 (odd), and compute</p>\n\n<pre><code>3 * 7^(8-5) = 1029\ns = 1029 mod 16 = 5\n</code></pre>\n\n<p>Now</p>\n\n<pre><code>s * m^N = 5 * 7^5 = 84035\n84035 mod 16 = 3 == C\n</code></pre>\n"
},
{
"answer_id": 255900,
"author": "mattiast",
"author_id": 8272,
"author_profile": "https://Stackoverflow.com/users/8272",
"pm_score": 3,
"selected": true,
"text": "<p>Here is a method for computing the values for start and multiplier for the case when constant is odd:</p>\n\n<ol>\n<li><p>Find such odd m (m = multiplier) that order of m modulo 2^D is at least count, meaning that smallest n such that m^n = 1 (mod 2^D) is at least count. I don't know any other way to find such m than to make a random guess, but from a little experimenting it seems that half of odd numbers between 1 and 2^D have order 2^(D-2) which is maximal. (I tried for D at most 12.)</p></li>\n<li><p>Compute x such that x * m^count = 1 (mod 2^D) and set start = x * constant (mod 2^D). </p></li>\n</ol>\n\n<p>Such x can be found with \"extended euclidean algorithm\": Given a and b with no common divisor, it gives you x and y such that a * x + b * y = 1. Here a=m^count mod 2^D and b = 2^D.</p>\n\n<p><strong>edit:</strong> If constant happens to be even, you can divide it with a power of 2, say 2^k, to make in odd, then do the above for input {constant/2^k, count, 2^(D-k)} and finally return {start*2^k,multiplier}. </p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24404/"
] |
Is there a practical algorithm that gives "multiplication chains"
To clarify, the goal is to produce a multiplication change of an **arbitrary and exact** length
Multiplication chains of length 1 are trivial.
A "multiplication chain" would be defined as 2 numbers, {start} and {multiplier}, used in code:
```
Given a pointer to array of size [{count}] // count is a parameter
a = start;
do
{
a = a * multiplier; // Really: a = (a * multiplier) MOD (power of 2
*(pointer++) = a;
}
while (a != {constant} )
// Postcondition: all {count} entries are filled.
```
I'd like to find a routine that takes three parameters
1. Power of 2
2. Stopping {constant}
3. {count} - Number of times the loop will iterate
The routine would return {start} and {multiplier}.
Ideally, a {Constant} value of 0 should be valid.
Trivial example:
```
power of 2 = 256
stopping constant = 7
number of times for the loop = 1
returns {7,1}
```
Nontrivial example:
```
power of 2 = 256
stopping constant = 1
number of times for the loop = 49
returns {25, 19}
```
The maximum {count} for a given power of 2 can be fairly small.
For example, 2^4 (16) seems to be limited to a count of 4
|
Here is a method for computing the values for start and multiplier for the case when constant is odd:
1. Find such odd m (m = multiplier) that order of m modulo 2^D is at least count, meaning that smallest n such that m^n = 1 (mod 2^D) is at least count. I don't know any other way to find such m than to make a random guess, but from a little experimenting it seems that half of odd numbers between 1 and 2^D have order 2^(D-2) which is maximal. (I tried for D at most 12.)
2. Compute x such that x \* m^count = 1 (mod 2^D) and set start = x \* constant (mod 2^D).
Such x can be found with "extended euclidean algorithm": Given a and b with no common divisor, it gives you x and y such that a \* x + b \* y = 1. Here a=m^count mod 2^D and b = 2^D.
**edit:** If constant happens to be even, you can divide it with a power of 2, say 2^k, to make in odd, then do the above for input {constant/2^k, count, 2^(D-k)} and finally return {start\*2^k,multiplier}.
|
255,553 |
<p>I've heard that it's possible with extension methods, but I can't quite figure it out myself. I'd like to see a specific example if possible.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 255621,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": false,
"text": "<p>It really depends on what you mean by \"mixin\" - everyone seems to have a slightly different idea. The kind of mixin I'd <em>like</em> to see (but which isn't available in C#) is making implementation-through-composition simple:</p>\n\n<pre><code>public class Mixin : ISomeInterface\n{\n private SomeImplementation impl implements ISomeInterface;\n\n public void OneMethod()\n {\n // Specialise just this method\n }\n}\n</code></pre>\n\n<p>The compiler would implement ISomeInterface just by proxying every member to \"impl\" unless there was another implementation in the class directly.</p>\n\n<p>None of this is possible at the moment though :)</p>\n"
},
{
"answer_id": 255690,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://code.google.com/p/linfu/\" rel=\"nofollow noreferrer\">LinFu</a> and <a href=\"https://github.com/castleproject/Core/tree/master/src/Castle.Core.Tests/Mixins\" rel=\"nofollow noreferrer\">Castle's DynamicProxy</a> implement mixins. COP (Composite Oriented Programming) could be considered as making a whole paradigm out of mixins. <a href=\"http://web.archive.org/web/20081228224052/http://andersnoras.com/blogs/anoras/archive/2008/08/27/cop-c-4-0-and-doing-open-source-stuff.aspx\" rel=\"nofollow noreferrer\">This post from Anders Noras</a> has useful informations and links.</p>\n\n<p>EDIT: This is all possible with C# 2.0, without extension methods</p>\n"
},
{
"answer_id": 4667069,
"author": "Stefan Papp",
"author_id": 453623,
"author_profile": "https://Stackoverflow.com/users/453623",
"pm_score": 3,
"selected": false,
"text": "<p>There is an open source framework that enables you to implement mixins via C#. Have a look on <a href=\"http://remix.codeplex.com/\" rel=\"noreferrer\">http://remix.codeplex.com/</a>.</p>\n\n<p>It is very easy to implement mixins with this framework. Just have a look on the samples and the \"Additional Information\" links given on the page.</p>\n"
},
{
"answer_id": 7753579,
"author": "3dGrabber",
"author_id": 141397,
"author_profile": "https://Stackoverflow.com/users/141397",
"pm_score": 4,
"selected": false,
"text": "<p>I usually employ this pattern:</p>\n\n<pre><code>public interface IColor\n{\n byte Red {get;}\n byte Green {get;}\n byte Blue {get;}\n}\n\npublic static class ColorExtensions\n{\n public static byte Luminance(this IColor c)\n {\n return (byte)(c.Red*0.3 + c.Green*0.59+ c.Blue*0.11);\n }\n}\n</code></pre>\n\n<p>I have the two definitions in the same source file/namespace.\nThat way the extensions are always available when the interface is used (with 'using').</p>\n\n<p>This gives you a <em>limited mixin</em> as described in CMS' first link.</p>\n\n<p>Limitations:</p>\n\n<ul>\n<li>no data fields </li>\n<li>no properties (you'll have to call myColor.Luminance() with parentheses, <a href=\"https://stackoverflow.com/questions/619033/c-extension-properties\">extension properties</a> anyone?) </li>\n</ul>\n\n<p>It's still sufficient for many situations.</p>\n\n<p>It would be nice if they (MS) could add some compiler magic to auto-generate the extension class:</p>\n\n<pre><code>public interface IColor\n{\n byte Red {get;}\n byte Green {get;}\n byte Blue {get;}\n\n // compiler generates anonymous extension class\n public static byte Luminance(this IColor c) \n {\n return (byte)(c.Red*0.3 + c.Green*0.59+ c.Blue*0.11);\n }\n}\n</code></pre>\n\n<p>Although Jon's proposed compiler trick would be even nicer.</p>\n"
},
{
"answer_id": 11799305,
"author": "staafl",
"author_id": 1527706,
"author_profile": "https://Stackoverflow.com/users/1527706",
"pm_score": 2,
"selected": false,
"text": "<p>You could also augment the extension method approach to incorporate state, in a pattern not unlike WPF's attached properties. </p>\n\n<p>Here is an example with minimum boilerplate. Note that no modification are required on the target classes, including adding interfaces, unless you need to deal with the target class polymorphically - in which case you end up with something very close to actual Multiple Inheritance.</p>\n\n<pre><code>// Mixin class: mixin infrastructure and mixin component definitions\npublic static class Mixin\n{ \n // =====================================\n // ComponentFoo: Sample mixin component\n // =====================================\n\n // ComponentFooState: ComponentFoo contents\n class ComponentFooState\n {\n public ComponentFooState() {\n // initialize as you like\n this.Name = \"default name\";\n }\n\n public string Name { get; set; }\n }\n\n // ComponentFoo methods\n\n // if you like, replace T with some interface \n // implemented by your target class(es)\n\n public static void \n SetName<T>(this T obj, string name) {\n var state = GetState(component_foo_states, obj);\n\n // do something with \"obj\" and \"state\"\n // for example: \n\n state.Name = name + \" the \" + obj.GetType();\n\n\n }\n public static string\n GetName<T>(this T obj) {\n var state = GetState(component_foo_states, obj);\n\n return state.Name; \n }\n\n // =====================================\n // boilerplate\n // =====================================\n\n // instances of ComponentFoo's state container class,\n // indexed by target object\n static readonly Dictionary<object, ComponentFooState>\n component_foo_states = new Dictionary<object, ComponentFooState>();\n\n // get a target class object's associated state\n // note lazy instantiation\n static TState\n GetState<TState>(Dictionary<object, TState> dict, object obj) \n where TState : new() {\n TState ret;\n if(!dict.TryGet(obj, out ret))\n dict[obj] = ret = new TState();\n\n return ret;\n }\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>var some_obj = new SomeClass();\nsome_obj.SetName(\"Johny\");\nConsole.WriteLine(some_obj.GetName()); // \"Johny the SomeClass\"\n</code></pre>\n\n<p>Note that it also works with null instances, since extension methods naturally do.</p>\n\n<p>You might also consider using a WeakDictionary implementation to avoid memory leaks caused by the collection's holding on to target class references as keys.</p>\n"
},
{
"answer_id": 28652400,
"author": "mll5",
"author_id": 2699865,
"author_profile": "https://Stackoverflow.com/users/2699865",
"pm_score": 2,
"selected": false,
"text": "<p>I needed something similar so I came up with the following using Reflection.Emit. In the following code a new type is dynamically generated which has a private member of type 'mixin'. All the calls to methods of 'mixin' interface are forwarded to this private member. A single parameter constructor is defined that takes an instance which implements the 'mixin' interface. Basically, it is equal to writing the following code for a given concrete type T and interface I:</p>\n\n<pre><code>class Z : T, I\n{\n I impl;\n\n public Z(I impl)\n {\n this.impl = impl;\n }\n\n // Implement all methods of I by proxying them through this.impl\n // as follows: \n //\n // I.Foo()\n // {\n // return this.impl.Foo();\n // }\n}\n</code></pre>\n\n<p>This is the class:</p>\n\n<pre><code>public class MixinGenerator\n{\n public static Type CreateMixin(Type @base, Type mixin)\n {\n // Mixin must be an interface\n if (!mixin.IsInterface)\n throw new ArgumentException(\"mixin not an interface\");\n\n TypeBuilder typeBuilder = DefineType(@base, new Type[]{mixin});\n\n FieldBuilder fb = typeBuilder.DefineField(\"impl\", mixin, FieldAttributes.Private);\n\n DefineConstructor(typeBuilder, fb);\n\n DefineInterfaceMethods(typeBuilder, mixin, fb);\n\n Type t = typeBuilder.CreateType();\n\n return t;\n }\n\n static AssemblyBuilder assemblyBuilder;\n private static TypeBuilder DefineType(Type @base, Type [] interfaces)\n {\n assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(\n new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.RunAndSave);\n\n ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(Guid.NewGuid().ToString());\n\n TypeBuilder b = moduleBuilder.DefineType(Guid.NewGuid().ToString(),\n @base.Attributes,\n @base,\n interfaces);\n\n return b;\n }\n private static void DefineConstructor(TypeBuilder typeBuilder, FieldBuilder fieldBuilder)\n {\n ConstructorBuilder ctor = typeBuilder.DefineConstructor(\n MethodAttributes.Public, CallingConventions.Standard, new Type[] { fieldBuilder.FieldType });\n\n ILGenerator il = ctor.GetILGenerator();\n\n // Call base constructor\n ConstructorInfo baseCtorInfo = typeBuilder.BaseType.GetConstructor(new Type[]{});\n il.Emit(OpCodes.Ldarg_0);\n il.Emit(OpCodes.Call, typeBuilder.BaseType.GetConstructor(new Type[0]));\n\n // Store type parameter in private field\n il.Emit(OpCodes.Ldarg_0);\n il.Emit(OpCodes.Ldarg_1);\n il.Emit(OpCodes.Stfld, fieldBuilder);\n il.Emit(OpCodes.Ret);\n }\n\n private static void DefineInterfaceMethods(TypeBuilder typeBuilder, Type mixin, FieldInfo instanceField)\n {\n MethodInfo[] methods = mixin.GetMethods();\n\n foreach (MethodInfo method in methods)\n {\n MethodInfo fwdMethod = instanceField.FieldType.GetMethod(method.Name,\n method.GetParameters().Select((pi) => { return pi.ParameterType; }).ToArray<Type>());\n\n MethodBuilder methodBuilder = typeBuilder.DefineMethod(\n fwdMethod.Name,\n // Could not call absract method, so remove flag\n fwdMethod.Attributes & (~MethodAttributes.Abstract),\n fwdMethod.ReturnType,\n fwdMethod.GetParameters().Select(p => p.ParameterType).ToArray());\n\n methodBuilder.SetReturnType(method.ReturnType);\n typeBuilder.DefineMethodOverride(methodBuilder, method);\n\n // Emit method body\n ILGenerator il = methodBuilder.GetILGenerator();\n il.Emit(OpCodes.Ldarg_0);\n il.Emit(OpCodes.Ldfld, instanceField);\n\n // Call with same parameters\n for (int i = 0; i < method.GetParameters().Length; i++)\n {\n il.Emit(OpCodes.Ldarg, i + 1);\n }\n il.Emit(OpCodes.Call, fwdMethod);\n il.Emit(OpCodes.Ret);\n }\n }\n}\n</code></pre>\n\n<p>This is the usage:</p>\n\n<pre><code>public interface ISum\n{\n int Sum(int x, int y);\n}\n\npublic class SumImpl : ISum\n{\n public int Sum(int x, int y)\n {\n return x + y;\n }\n}\n\npublic class Multiply\n{ \n public int Mul(int x, int y)\n {\n return x * y;\n }\n}\n\n// Generate a type that does multiply and sum\nType newType = MixinGenerator.CreateMixin(typeof(Multiply), typeof(ISum));\n\nobject instance = Activator.CreateInstance(newType, new object[] { new SumImpl() });\n\nint res = ((Multiply)instance).Mul(2, 4);\nConsole.WriteLine(res);\nres = ((ISum)instance).Sum(1, 4);\nConsole.WriteLine(res);\n</code></pre>\n"
},
{
"answer_id": 30503470,
"author": "regisbsb",
"author_id": 434919,
"author_profile": "https://Stackoverflow.com/users/434919",
"pm_score": 1,
"selected": false,
"text": "<p>If you have a base class that can store data you can enforce compiler safety and use marker interfaces.\nThat's more or less what \"Mixins in C# 3.0\" from the accepted answer proposes. </p>\n\n<pre><code>public static class ModelBaseMixins\n{\n public interface IHasStuff{ }\n\n public static void AddStuff<TObjectBase>(this TObjectBase objectBase, Stuff stuff) where TObjectBase: ObjectBase, IHasStuff\n {\n var stuffStore = objectBase.Get<IList<Stuff>>(\"stuffStore\");\n stuffStore.Add(stuff);\n }\n}\n</code></pre>\n\n<p>The ObjectBase:</p>\n\n<pre><code>public abstract class ObjectBase\n{\n protected ModelBase()\n {\n _objects = new Dictionary<string, object>();\n }\n\n private readonly Dictionary<string, object> _objects;\n\n internal void Add<T>(T thing, string name)\n {\n _objects[name] = thing;\n }\n\n internal T Get<T>(string name)\n {\n T thing = null;\n _objects.TryGetValue(name, out thing);\n\n return (T) thing;\n }\n</code></pre>\n\n<p>So if you have a Class you can inherit from 'ObjectBase' and decorate with IHasStuff you can add sutff now</p>\n"
},
{
"answer_id": 36253410,
"author": "GregRos",
"author_id": 1333004,
"author_profile": "https://Stackoverflow.com/users/1333004",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a mixin implementation I've just come up with. I'll probably use it with <a href=\"https://github.com/Imms/Imms\" rel=\"nofollow\">a library of mine</a>.</p>\n\n<p>It's probably been done before, somewhere.</p>\n\n<p>It's all statically typed, with no dictionaries or something. It requires a little bit of extra code per type, you don't need any storage per instance. On the other hand, it also gives you the flexibility of changing the mixin implementation on the fly, if you so desire. No post-build, pre-build, mid-build tools.</p>\n\n<p>It has some limitations, but it does allow things like overriding and so on.</p>\n\n<p>We begin by defining a marker interface. Perhaps something will be added to it later:</p>\n\n<pre><code>public interface Mixin {}\n</code></pre>\n\n<p>This interface is implemented by mixins. Mixins are regular classes. Types do not inherit or implement mixins directly. They instead just expose an instance of the mixin using the interface:</p>\n\n<pre><code>public interface HasMixins {}\n\npublic interface Has<TMixin> : HasMixins\n where TMixin : Mixin {\n TMixin Mixin { get; }\n}\n</code></pre>\n\n<p>Implementing this interface means supporting the mixin. It's important that it's implemented explicitly, since we're going to have several of these per type.</p>\n\n<p>Now for a little trick using extension methods. We define:</p>\n\n<pre><code>public static class MixinUtils {\n public static TMixin Mixout<TMixin>(this Has<TMixin> what)\n where TMixin : Mixin {\n return what.Mixin;\n }\n}\n</code></pre>\n\n<p><code>Mixout</code> exposes the mixin of the appropriate type. Now, to test this out, let's define:</p>\n\n<pre><code>public abstract class Mixin1 : Mixin {}\n\npublic abstract class Mixin2 : Mixin {}\n\npublic abstract class Mixin3 : Mixin {}\n\npublic class Test : Has<Mixin1>, Has<Mixin2> {\n\n private class Mixin1Impl : Mixin1 {\n public static readonly Mixin1Impl Instance = new Mixin1Impl();\n }\n\n private class Mixin2Impl : Mixin2 {\n public static readonly Mixin2Impl Instance = new Mixin2Impl();\n }\n\n Mixin1 Has<Mixin1>.Mixin => Mixin1Impl.Instance;\n\n Mixin2 Has<Mixin2>.Mixin => Mixin2Impl.Instance;\n}\n\nstatic class TestThis {\n public static void run() {\n var t = new Test();\n var a = t.Mixout<Mixin1>();\n var b = t.Mixout<Mixin2>();\n }\n}\n</code></pre>\n\n<p>Rather amusingly (though in retrospect, it does make sense), IntelliSense does not detect that the extension method <code>Mixout</code> applies to <code>Test</code>, but the compiler does accept it, as long as <code>Test</code> actually has the mixin. If you try,</p>\n\n<pre><code>t.Mixout<Mixin3>();\n</code></pre>\n\n<p>It gives you a compilation error.</p>\n\n<p>You can go a bit fancy, and define the following method too:</p>\n\n<pre><code>[Obsolete(\"The object does not have this mixin.\", true)]\npublic static TSome Mixout<TSome>(this HasMixins something) where TSome : Mixin {\n return default(TSome);\n}\n</code></pre>\n\n<p>What this does is, a) display a method called <code>Mixout</code> in IntelliSense, reminding you of its existence, and b) provide a somewhat more descriptive error message (generated by the <code>Obsolete</code> attribute).</p>\n"
},
{
"answer_id": 52643008,
"author": "BartoszKP",
"author_id": 2642204,
"author_profile": "https://Stackoverflow.com/users/2642204",
"pm_score": 2,
"selected": false,
"text": "<p>I've found a workaround <a href=\"https://www.c-sharpcorner.com/UploadFile/b942f9/how-to-create-mixin-using-C-Sharp-4-0/\" rel=\"nofollow noreferrer\">here</a>, which while not entirely elegant, allows you to achieve fully observable mixin behavior. Additionally, IntelliSense still works!</p>\n\n<pre><code>using System;\nusing System.Runtime.CompilerServices; //needed for ConditionalWeakTable\npublic interface MAgeProvider // use 'M' prefix to indicate mixin interface\n{\n // nothing needed in here, it's just a 'marker' interface\n}\npublic static class AgeProvider // implements the mixin using extensions methods\n{\n static ConditionalWeakTable<MAgeProvider, Fields> table;\n static AgeProvider()\n {\n table = new ConditionalWeakTable<MAgeProvider, Fields>();\n }\n private sealed class Fields // mixin's fields held in private nested class\n {\n internal DateTime BirthDate = DateTime.UtcNow;\n }\n public static int GetAge(this MAgeProvider map)\n {\n DateTime dtNow = DateTime.UtcNow;\n DateTime dtBorn = table.GetOrCreateValue(map).BirthDate;\n int age = ((dtNow.Year - dtBorn.Year) * 372\n + (dtNow.Month - dtBorn.Month) * 31\n + (dtNow.Day - dtBorn.Day)) / 372;\n return age;\n }\n public static void SetBirthDate(this MAgeProvider map, DateTime birthDate)\n {\n table.GetOrCreateValue(map).BirthDate = birthDate;\n }\n}\n\npublic abstract class Animal\n{\n // contents unimportant\n}\npublic class Human : Animal, MAgeProvider\n{\n public string Name;\n public Human(string name)\n {\n Name = name;\n }\n // nothing needed in here to implement MAgeProvider\n}\nstatic class Test\n{\n static void Main()\n {\n Human h = new Human(\"Jim\");\n h.SetBirthDate(new DateTime(1980, 1, 1));\n Console.WriteLine(\"Name {0}, Age = {1}\", h.Name, h.GetAge());\n Human h2 = new Human(\"Fred\");\n h2.SetBirthDate(new DateTime(1960, 6, 1));\n Console.WriteLine(\"Name {0}, Age = {1}\", h2.Name, h2.GetAge());\n Console.ReadKey();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 71689898,
"author": "Dmitri Nesteruk",
"author_id": 9476,
"author_profile": "https://Stackoverflow.com/users/9476",
"pm_score": 0,
"selected": false,
"text": "<p>There are, fundamentally, several techniques to getting Mixin behavior in your classes:</p>\n<ul>\n<li>Behavioral mixins that hold no state are easily done using extension methods</li>\n<li>Behavioral mixins for interfaces that use duck typing (currently, <code>IEnumerable</code> and <code>IDisposable</code>) <a href=\"https://www.youtube.com/watch?v=R8WbqTFlAeM\" rel=\"nofollow noreferrer\">can use</a> default interface members with explicit implementation of said interface. Then, then new interface behaves as a mixin where concrete behavior can be added and leveraged without using extension methods, and can support constructs such as <code>using</code> and <code>foreach</code>.</li>\n<li>Mixins that need state can be implemented very roughly by using extension methods and a static <code>ConditionalWeakTable</code> to hold data.</li>\n<li>Multiple inheritance mechanics can be crudely synthesized at compile-time (T4, source generators) or runtime (Reflection.Emit).</li>\n</ul>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6408/"
] |
I've heard that it's possible with extension methods, but I can't quite figure it out myself. I'd like to see a specific example if possible.
Thanks!
|
It really depends on what you mean by "mixin" - everyone seems to have a slightly different idea. The kind of mixin I'd *like* to see (but which isn't available in C#) is making implementation-through-composition simple:
```
public class Mixin : ISomeInterface
{
private SomeImplementation impl implements ISomeInterface;
public void OneMethod()
{
// Specialise just this method
}
}
```
The compiler would implement ISomeInterface just by proxying every member to "impl" unless there was another implementation in the class directly.
None of this is possible at the moment though :)
|
255,571 |
<p>I am having some trouble manipulating images using CodeIgniter 1.7. With the following code, the image is uploaded correctly. Alas, instead of a new image being made, and then modified; the existing image is modified. Any help?</p>
<pre><code>//Upload image first
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|bmp';
$this->load->library('upload', $config);
$this->upload->do_upload();
//Now fix the image
$picloc = $this->upload->data();
$picloc = $picloc['file_name'];
$thumbnail = "thumb_".$picloc;
$imagemanip['image_library'] = 'gd2';
$imagemanip['source_image'] = './uploads/'.$picloc;
$imagemanip['new_img'] = './uploads/'.$thumbnail;
$imagemanip['maintain_ratio'] = TRUE;
$imagemanip['width'] = 250;
$imagemanip['height'] = 250;
$this->load->library('image_lib', $imagemanip);
$this->image_lib->resize();
</code></pre>
|
[
{
"answer_id": 255628,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is simple, you have a typo in the line:</p>\n\n<pre><code>$imagemanip['new_img'] = './uploads/'.$thumbnail;\n</code></pre>\n\n<p>The the index should be \"new_image\", not \"new_img\", so the line becomes..</p>\n\n<pre><code>$imagemanip['new_image'] = './uploads/'.$thumbnail;\n</code></pre>\n"
},
{
"answer_id": 29937507,
"author": "Abdulla Nilam",
"author_id": 4595675,
"author_profile": "https://Stackoverflow.com/users/4595675",
"pm_score": 0,
"selected": false,
"text": "<pre><code>//Upload image first\n$config['upload_path'] = './uploads/';\n$config['allowed_types'] = 'gif|jpg|png|bmp';\n\n$this->load->library('upload', $config); \n$this->upload->do_upload();\n\n//Now fix the image\n$picloc = $this->upload->data();\n$picloc = $picloc['file_name'];\n\n$thumbnail = \"thumb_\".$picloc;\n\n$imagemanip['image_library'] = 'gd2';\n$imagemanip['source_image'] = './uploads/'.$picloc;\n$imagemanip['new_image'] = './uploads/'.$thumbnail;// this will get change in new code.\n$imagemanip['maintain_ratio'] = TRUE;\n$imagemanip['width'] = 250;\n$imagemanip['height'] = 250;\n\n$this->load->library('image_lib', $imagemanip);\n\n$this->image_lib->resize();\n</code></pre>\n\n<p>now this will do your work</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am having some trouble manipulating images using CodeIgniter 1.7. With the following code, the image is uploaded correctly. Alas, instead of a new image being made, and then modified; the existing image is modified. Any help?
```
//Upload image first
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|bmp';
$this->load->library('upload', $config);
$this->upload->do_upload();
//Now fix the image
$picloc = $this->upload->data();
$picloc = $picloc['file_name'];
$thumbnail = "thumb_".$picloc;
$imagemanip['image_library'] = 'gd2';
$imagemanip['source_image'] = './uploads/'.$picloc;
$imagemanip['new_img'] = './uploads/'.$thumbnail;
$imagemanip['maintain_ratio'] = TRUE;
$imagemanip['width'] = 250;
$imagemanip['height'] = 250;
$this->load->library('image_lib', $imagemanip);
$this->image_lib->resize();
```
|
The problem is simple, you have a typo in the line:
```
$imagemanip['new_img'] = './uploads/'.$thumbnail;
```
The the index should be "new\_image", not "new\_img", so the line becomes..
```
$imagemanip['new_image'] = './uploads/'.$thumbnail;
```
|
255,605 |
<p>There are several application systems that pass messages to each other as part of their work process. Due to technical constraints revolving transactional integrity, the application data and message delivery are all committed into a single mainframe DB2 database. The messages are not directly passed to BizTalk server (2006 R2); it is up to BTS to pull the message out from the DB2 database later.</p>
<p>The message-queue table in the DB2 database has several fields. The key field is the MESSAGE_DATA column - the actual message; it is XML content itself. When one uses the DB2 adapter to query out records from the table the incoming schema would be like</p>
<p>CORRECTION UPDATE: the DB2Message schema is attribute based; I mistook it previously to be element based.</p>
<pre><code><DB2Message MESSAGE_DATA="&lt;InternalXML&gt; ........ &lt;/InternalXML&gt;"
MESSAGE_DATE="2008-1-1 00:00:00" MESSAGE_ID="GUID" TXN_ID="GUID" .... other attrib />
</code></pre>
<p>The orchestration consumes the schema</p>
<pre><code><EAIMessage>
<Header>
<ServiceID>
<MessageID>
....
<Mode>
</Header>
<Body>
<RawXML>
</Body>
</EAIMessage>
</code></pre>
<p>The orchestration will use several promoted fields in the Header to make routing and processing decisions. The thing is, those header fields are actually coming from the inner-XML content stored into DB2Message's MESSAGE_DATA.</p>
<p>At this single level, the Mapper has no knowledge of this underyling XML schema inside MESSAGE_DATA when pitting the two schemas together. There should probably be some XPath functoid that can further drill down the MESSAGET_DATA element to conduct the proper mapping of values, but having not dealt with extensive XML and XSLT applications before, I am unable to see the features available that can help me perform this task.</p>
<p>Has anybody done such data extraction and mapping before?</p>
<p>UPDATE. As requested, in the MESSAGE_DATA inner XML may look like</p>
<pre><code><Message>
<Id>e86970f4-0455-4535-8e65-a06eb7aaef8a</Id>
<SenderApp>999</SenderApp>
<ReceiverApp>2000</ReceiverApp>
<ServiceId>8798973454</ServiceId>
<Mode>P</Mode>
<MuxId></MuxId>
<ExceptionCode></ExceptionCode>
<ExceptionMessage></ExceptionMessage>
<Body>
<WorkItem xmlns="http://tempuri.org/WorkItem.xsd">
<ServiceHeader xmlns="http://tempuri.org/Service.xsd">
<ID_UPDATED_BY>username</ID_UPDATED_BY>
<ID_HISTORY_REF>xxxxxxx</ID_HISTORY_REF>
<SESSION_ID>sessionID</SESSION_ID>
<DT_LAST_UPDATE>timestamp</DT_LAST_UPDATE>
<TM_LAST_UPDATE>time</TM_LAST_UPDATE>
</ServiceHeader>
</WorkItem>
</Body>
</Message>
</code></pre>
|
[
{
"answer_id": 342897,
"author": "Christian Loris",
"author_id": 2574178,
"author_profile": "https://Stackoverflow.com/users/2574178",
"pm_score": 0,
"selected": false,
"text": "<p>I would suggest looking into envelope schemas to 'unwrap' the interior message from the outer message. I believe the envelope can promote properties from the envelope into the inner message's context as it moves through the receive pipeline. The inner message will then have to map to a schema of its own type. You will then be able to route or make decisions based on the schema type and use XPath to pick out whatever you need. Have not tried all of these things, but I am certain the functionality exists to do do this. </p>\n"
},
{
"answer_id": 346317,
"author": "Yossi Dahan",
"author_id": 43541,
"author_profile": "https://Stackoverflow.com/users/43541",
"pm_score": 1,
"selected": false,
"text": "<p>Chris is correct - it seems it's only the inner part of the message you actually care about, the outer part is just an envelope.</p>\n\n<p>As such I would suggest you create a disassembler which, in the receive pipeline, will strip out the envelope (you can keep it in it's entirety as a context property and/or extract some bits from it as individual properties, if you need to act on them), and extract the inner part which would become the message published into the Message Box. </p>\n\n<p>Now the real message is the one get's processed, but the rest of the send port and any subscriber, and whatever information you require from the envelope flows with it through its context.</p>\n\n<p>Now you have full access to the message and it's properties; if applicable you can deploy a schema for this message, which could have distinguished properties which would give you quick access to some (simple type) nodes. alternatively you can use xlang/s xpath to extract the information.</p>\n\n<p>If your embedded message was inside an element in the envelope you could certainly use the built in XmlDisassembler to do all of this (you would just need to deploy your schemas correctly and configure the component accordingly; I'm not sure how well this works with a message contained within an attribute, but it's probably worth a try. </p>\n\n<p>Worst case you are looking at writing a custom disassembler that would strip the envelope and then call the built-in disassembler to process the internal message, but that should not be too much effort as well.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2663/"
] |
There are several application systems that pass messages to each other as part of their work process. Due to technical constraints revolving transactional integrity, the application data and message delivery are all committed into a single mainframe DB2 database. The messages are not directly passed to BizTalk server (2006 R2); it is up to BTS to pull the message out from the DB2 database later.
The message-queue table in the DB2 database has several fields. The key field is the MESSAGE\_DATA column - the actual message; it is XML content itself. When one uses the DB2 adapter to query out records from the table the incoming schema would be like
CORRECTION UPDATE: the DB2Message schema is attribute based; I mistook it previously to be element based.
```
<DB2Message MESSAGE_DATA="<InternalXML> ........ </InternalXML>"
MESSAGE_DATE="2008-1-1 00:00:00" MESSAGE_ID="GUID" TXN_ID="GUID" .... other attrib />
```
The orchestration consumes the schema
```
<EAIMessage>
<Header>
<ServiceID>
<MessageID>
....
<Mode>
</Header>
<Body>
<RawXML>
</Body>
</EAIMessage>
```
The orchestration will use several promoted fields in the Header to make routing and processing decisions. The thing is, those header fields are actually coming from the inner-XML content stored into DB2Message's MESSAGE\_DATA.
At this single level, the Mapper has no knowledge of this underyling XML schema inside MESSAGE\_DATA when pitting the two schemas together. There should probably be some XPath functoid that can further drill down the MESSAGET\_DATA element to conduct the proper mapping of values, but having not dealt with extensive XML and XSLT applications before, I am unable to see the features available that can help me perform this task.
Has anybody done such data extraction and mapping before?
UPDATE. As requested, in the MESSAGE\_DATA inner XML may look like
```
<Message>
<Id>e86970f4-0455-4535-8e65-a06eb7aaef8a</Id>
<SenderApp>999</SenderApp>
<ReceiverApp>2000</ReceiverApp>
<ServiceId>8798973454</ServiceId>
<Mode>P</Mode>
<MuxId></MuxId>
<ExceptionCode></ExceptionCode>
<ExceptionMessage></ExceptionMessage>
<Body>
<WorkItem xmlns="http://tempuri.org/WorkItem.xsd">
<ServiceHeader xmlns="http://tempuri.org/Service.xsd">
<ID_UPDATED_BY>username</ID_UPDATED_BY>
<ID_HISTORY_REF>xxxxxxx</ID_HISTORY_REF>
<SESSION_ID>sessionID</SESSION_ID>
<DT_LAST_UPDATE>timestamp</DT_LAST_UPDATE>
<TM_LAST_UPDATE>time</TM_LAST_UPDATE>
</ServiceHeader>
</WorkItem>
</Body>
</Message>
```
|
Chris is correct - it seems it's only the inner part of the message you actually care about, the outer part is just an envelope.
As such I would suggest you create a disassembler which, in the receive pipeline, will strip out the envelope (you can keep it in it's entirety as a context property and/or extract some bits from it as individual properties, if you need to act on them), and extract the inner part which would become the message published into the Message Box.
Now the real message is the one get's processed, but the rest of the send port and any subscriber, and whatever information you require from the envelope flows with it through its context.
Now you have full access to the message and it's properties; if applicable you can deploy a schema for this message, which could have distinguished properties which would give you quick access to some (simple type) nodes. alternatively you can use xlang/s xpath to extract the information.
If your embedded message was inside an element in the envelope you could certainly use the built in XmlDisassembler to do all of this (you would just need to deploy your schemas correctly and configure the component accordingly; I'm not sure how well this works with a message contained within an attribute, but it's probably worth a try.
Worst case you are looking at writing a custom disassembler that would strip the envelope and then call the built-in disassembler to process the internal message, but that should not be too much effort as well.
|
255,612 |
<p>I have a class that contains a dynamically allocated array, say</p>
<pre><code>class A
{
int* myArray;
A()
{
myArray = 0;
}
A(int size)
{
myArray = new int[size];
}
~A()
{
// Note that as per MikeB's helpful style critique, no need to check against 0.
delete [] myArray;
}
}
</code></pre>
<p>But now I want to create a dynamically allocated array of these classes. Here's my current code:</p>
<pre><code>A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
arrayOfAs[i] = A(3);
}
</code></pre>
<p>But this blows up terribly. Because the new <code>A</code> object created (with the <code>A(3)</code> call) gets destructed when the <code>for</code> loop iteration finishes, and this means that the internal <code>myArray</code> of that <code>A</code> instance gets <code>delete []</code>-ed.</p>
<p>So I think my syntax must be terribly wrong? I guess there are a few fixes that seem like overkill, which I'm hoping to avoid:</p>
<ul>
<li>Creating a copy constructor for <code>A</code>.</li>
<li>Using <code>vector<int></code> and <code>vector<A></code> so I don't have to worry about all this.</li>
<li>Instead of having <code>arrayOfAs</code> be an array of <code>A</code> objects, have it be an array of <code>A*</code> pointers.</li>
</ul>
<p>I would think this is just some beginners thing where there's a syntax that actually works when attempting to dynamically allocate an array of things that have internal dynamic allocation.</p>
<p>(Also, style critiques appreciated, since it's been a while since I did C++.)</p>
<p><strong>Update for future viewers</strong>: All of the answers below are really helpful. Martin's is accepted because of the example code and the useful "rule of 4," but I really suggest reading them all. Some are good, succinct statements of what's wrong, and some point out correctly how and why <code>vector</code>s are a good way to go.</p>
|
[
{
"answer_id": 255625,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li><p>Use array or common container for objects only if they have default and copy constructors. </p></li>\n<li><p>Store pointers otherwise (or smart pointers, but may meet some issues in this case).</p></li>\n</ol>\n\n<p>PS: Always define own default and copy constructors otherwise auto-generated will be used</p>\n"
},
{
"answer_id": 255649,
"author": "IMil",
"author_id": 11185,
"author_profile": "https://Stackoverflow.com/users/11185",
"pm_score": 4,
"selected": false,
"text": "<p>I'd recommend using std::vector: something like</p>\n\n<pre><code>typedef std::vector<int> A;\ntypedef std::vector<A> AS;\n</code></pre>\n\n<p>There's nothing wrong with the slight overkill of STL, and you'll be able to spend more time implementing the specific features of your app instead of reinventing the bicycle.</p>\n"
},
{
"answer_id": 255681,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 2,
"selected": false,
"text": "<p>You need an assignment operator so that:</p>\n\n<pre><code>arrayOfAs[i] = A(3);\n</code></pre>\n\n<p>works as it should.</p>\n"
},
{
"answer_id": 255730,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": "<p>The constructor of your A object allocates another object dynamically and stores a pointer to that dynamically allocated object in a raw pointer.</p>\n\n<p>For that scenario, you <em>must</em> define your own copy constructor , assignment operator and destructor. The compiler generated ones will not work correctly. (This is a corollary to the \"Law of the Big Three\": A class with any of destructor, assignment operator, copy constructor generally needs all 3).</p>\n\n<p>You have defined your own destructor (and you mentioned creating a copy constructor), but you need to define both of the other 2 of the big three.</p>\n\n<p>An alternative is to store the pointer to your dynamically allocated <code>int[]</code> in some other object that will take care of these things for you. Something like a <code>vector<int></code> (as you mentioned) or a <code>boost::shared_array<></code>.</p>\n\n<p>To boil this down - to take advantage of RAII to the full extent, you should avoid dealing with raw pointers to the extent possible.</p>\n\n<p>And since you asked for other style critiques, a minor one is that when you are deleting raw pointers you do not need to check for 0 before calling <code>delete</code> - <code>delete</code> handles that case by doing nothing so you don't have to clutter you code with the checks.</p>\n"
},
{
"answer_id": 255744,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 8,
"selected": true,
"text": "<p>For building containers you obviously want to use one of the standard containers (such as a std::vector). But this is a perfect example of the things you need to consider when your object contains RAW pointers.</p>\n\n<p>If your object has a RAW pointer then you need to remember the rule of 3 (now the rule of 5 in C++11).</p>\n\n<ul>\n<li>Constructor</li>\n<li>Destructor</li>\n<li>Copy Constructor</li>\n<li>Assignment Operator</li>\n<li>Move Constructor (C++11)</li>\n<li>Move Assignment (C++11)</li>\n</ul>\n\n<p>This is because if not defined the compiler will generate its own version of these methods (see below). The compiler generated versions are not always useful when dealing with RAW pointers.</p>\n\n<p>The copy constructor is the hard one to get correct (it's non trivial if you want to provide the strong exception guarantee). The Assignment operator can be defined in terms of the Copy Constructor as you can use the copy and swap idiom internally.</p>\n\n<p>See below for full details on the absolute minimum for a class containing a pointer to an array of integers.</p>\n\n<p>Knowing that it is non trivial to get it correct you should consider using std::vector rather than a pointer to an array of integers. The vector is easy to use (and expand) and covers all the problems associated with exceptions. Compare the following class with the definition of A below.</p>\n\n<pre><code>class A\n{ \n std::vector<int> mArray;\n public:\n A(){}\n A(size_t s) :mArray(s) {}\n};\n</code></pre>\n\n<p>Looking at your problem:</p>\n\n<pre><code>A* arrayOfAs = new A[5];\nfor (int i = 0; i < 5; ++i)\n{\n // As you surmised the problem is on this line.\n arrayOfAs[i] = A(3);\n\n // What is happening:\n // 1) A(3) Build your A object (fine)\n // 2) A::operator=(A const&) is called to assign the value\n // onto the result of the array access. Because you did\n // not define this operator the compiler generated one is\n // used.\n}\n</code></pre>\n\n<p>The compiler generated assignment operator is fine for nearly all situations, but when RAW pointers are in play you need to pay attention. In your case it is causing a problem because of the <b>shallow copy</b> problem. You have ended up with two objects that contain pointers to the same piece of memory. When the A(3) goes out of scope at the end of the loop it calls delete [] on its pointer. Thus the other object (in the array) now contains a pointer to memory that has been returned to the system.</p>\n\n<p><b>The compiler generated copy constructor</b>; copies each member variable by using that members copy constructor. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).</p>\n\n<p><b>The compiler generated assignment operator</b>; copies each member variable by using that members assignment operator. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).</p>\n\n<p>So the minimum for a class that contains a pointer:</p>\n\n<pre><code>class A\n{\n size_t mSize;\n int* mArray;\n public:\n // Simple constructor/destructor are obvious.\n A(size_t s = 0) {mSize=s;mArray = new int[mSize];}\n ~A() {delete [] mArray;}\n\n // Copy constructor needs more work\n A(A const& copy)\n {\n mSize = copy.mSize;\n mArray = new int[copy.mSize];\n\n // Don't need to worry about copying integers.\n // But if the object has a copy constructor then\n // it would also need to worry about throws from the copy constructor.\n std::copy(&copy.mArray[0],&copy.mArray[c.mSize],mArray);\n\n }\n\n // Define assignment operator in terms of the copy constructor\n // Modified: There is a slight twist to the copy swap idiom, that you can\n // Remove the manual copy made by passing the rhs by value thus\n // providing an implicit copy generated by the compiler.\n A& operator=(A rhs) // Pass by value (thus generating a copy)\n {\n rhs.swap(*this); // Now swap data with the copy.\n // The rhs parameter will delete the array when it\n // goes out of scope at the end of the function\n return *this;\n }\n void swap(A& s) noexcept\n {\n using std::swap;\n swap(this.mArray,s.mArray);\n swap(this.mSize ,s.mSize);\n }\n\n // C++11\n A(A&& src) noexcept\n : mSize(0)\n , mArray(NULL)\n {\n src.swap(*this);\n }\n A& operator=(A&& src) noexcept\n {\n src.swap(*this); // You are moving the state of the src object\n // into this one. The state of the src object\n // after the move must be valid but indeterminate.\n //\n // The easiest way to do this is to swap the states\n // of the two objects.\n //\n // Note: Doing any operation on src after a move \n // is risky (apart from destroy) until you put it \n // into a specific state. Your object should have\n // appropriate methods for this.\n // \n // Example: Assignment (operator = should work).\n // std::vector() has clear() which sets\n // a specific state without needing to\n // know the current state.\n return *this;\n } \n }\n</code></pre>\n"
},
{
"answer_id": 255859,
"author": "baash05",
"author_id": 31325,
"author_profile": "https://Stackoverflow.com/users/31325",
"pm_score": 2,
"selected": false,
"text": "<p>Why not have a setSize method. </p>\n\n<pre><code>A* arrayOfAs = new A[5];\nfor (int i = 0; i < 5; ++i)\n{\n arrayOfAs[i].SetSize(3);\n}\n</code></pre>\n\n<p>I like the \"copy\" but in this case the default constructor isn't really doing anything. \nThe SetSize could copy the data out of the original m_array (if it exists).. You'd have to store the size of the array within the class to do that. <br>\nOR <br>\nThe SetSize could delete the original m_array. </p>\n\n<pre><code>void SetSize(unsigned int p_newSize)\n{\n //I don't care if it's null because delete is smart enough to deal with that.\n delete myArray;\n myArray = new int[p_newSize];\n ASSERT(myArray);\n}\n</code></pre>\n"
},
{
"answer_id": 36799794,
"author": "Saman Barghi",
"author_id": 620409,
"author_profile": "https://Stackoverflow.com/users/620409",
"pm_score": 2,
"selected": false,
"text": "<p>Using the placement feature of <code>new</code> operator, you can create the object in place and avoid copying: </p>\n\n<blockquote>\n <p>placement (3) :void* operator new (std::size_t size, void* ptr) noexcept;</p>\n \n <p>Simply returns ptr (no storage is allocated).\n Notice though that, if the function is called by a new-expression, the proper initialization will be performed (for class objects, this includes calling its default constructor).</p>\n</blockquote>\n\n<p>I suggest the following:</p>\n\n<pre><code>A* arrayOfAs = new A[5]; //Allocate a block of memory for 5 objects\nfor (int i = 0; i < 5; ++i)\n{\n //Do not allocate memory,\n //initialize an object in memory address provided by the pointer\n new (&arrayOfAs[i]) A(3);\n}\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
] |
I have a class that contains a dynamically allocated array, say
```
class A
{
int* myArray;
A()
{
myArray = 0;
}
A(int size)
{
myArray = new int[size];
}
~A()
{
// Note that as per MikeB's helpful style critique, no need to check against 0.
delete [] myArray;
}
}
```
But now I want to create a dynamically allocated array of these classes. Here's my current code:
```
A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
arrayOfAs[i] = A(3);
}
```
But this blows up terribly. Because the new `A` object created (with the `A(3)` call) gets destructed when the `for` loop iteration finishes, and this means that the internal `myArray` of that `A` instance gets `delete []`-ed.
So I think my syntax must be terribly wrong? I guess there are a few fixes that seem like overkill, which I'm hoping to avoid:
* Creating a copy constructor for `A`.
* Using `vector<int>` and `vector<A>` so I don't have to worry about all this.
* Instead of having `arrayOfAs` be an array of `A` objects, have it be an array of `A*` pointers.
I would think this is just some beginners thing where there's a syntax that actually works when attempting to dynamically allocate an array of things that have internal dynamic allocation.
(Also, style critiques appreciated, since it's been a while since I did C++.)
**Update for future viewers**: All of the answers below are really helpful. Martin's is accepted because of the example code and the useful "rule of 4," but I really suggest reading them all. Some are good, succinct statements of what's wrong, and some point out correctly how and why `vector`s are a good way to go.
|
For building containers you obviously want to use one of the standard containers (such as a std::vector). But this is a perfect example of the things you need to consider when your object contains RAW pointers.
If your object has a RAW pointer then you need to remember the rule of 3 (now the rule of 5 in C++11).
* Constructor
* Destructor
* Copy Constructor
* Assignment Operator
* Move Constructor (C++11)
* Move Assignment (C++11)
This is because if not defined the compiler will generate its own version of these methods (see below). The compiler generated versions are not always useful when dealing with RAW pointers.
The copy constructor is the hard one to get correct (it's non trivial if you want to provide the strong exception guarantee). The Assignment operator can be defined in terms of the Copy Constructor as you can use the copy and swap idiom internally.
See below for full details on the absolute minimum for a class containing a pointer to an array of integers.
Knowing that it is non trivial to get it correct you should consider using std::vector rather than a pointer to an array of integers. The vector is easy to use (and expand) and covers all the problems associated with exceptions. Compare the following class with the definition of A below.
```
class A
{
std::vector<int> mArray;
public:
A(){}
A(size_t s) :mArray(s) {}
};
```
Looking at your problem:
```
A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
// As you surmised the problem is on this line.
arrayOfAs[i] = A(3);
// What is happening:
// 1) A(3) Build your A object (fine)
// 2) A::operator=(A const&) is called to assign the value
// onto the result of the array access. Because you did
// not define this operator the compiler generated one is
// used.
}
```
The compiler generated assignment operator is fine for nearly all situations, but when RAW pointers are in play you need to pay attention. In your case it is causing a problem because of the **shallow copy** problem. You have ended up with two objects that contain pointers to the same piece of memory. When the A(3) goes out of scope at the end of the loop it calls delete [] on its pointer. Thus the other object (in the array) now contains a pointer to memory that has been returned to the system.
**The compiler generated copy constructor**; copies each member variable by using that members copy constructor. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).
**The compiler generated assignment operator**; copies each member variable by using that members assignment operator. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).
So the minimum for a class that contains a pointer:
```
class A
{
size_t mSize;
int* mArray;
public:
// Simple constructor/destructor are obvious.
A(size_t s = 0) {mSize=s;mArray = new int[mSize];}
~A() {delete [] mArray;}
// Copy constructor needs more work
A(A const& copy)
{
mSize = copy.mSize;
mArray = new int[copy.mSize];
// Don't need to worry about copying integers.
// But if the object has a copy constructor then
// it would also need to worry about throws from the copy constructor.
std::copy(©.mArray[0],©.mArray[c.mSize],mArray);
}
// Define assignment operator in terms of the copy constructor
// Modified: There is a slight twist to the copy swap idiom, that you can
// Remove the manual copy made by passing the rhs by value thus
// providing an implicit copy generated by the compiler.
A& operator=(A rhs) // Pass by value (thus generating a copy)
{
rhs.swap(*this); // Now swap data with the copy.
// The rhs parameter will delete the array when it
// goes out of scope at the end of the function
return *this;
}
void swap(A& s) noexcept
{
using std::swap;
swap(this.mArray,s.mArray);
swap(this.mSize ,s.mSize);
}
// C++11
A(A&& src) noexcept
: mSize(0)
, mArray(NULL)
{
src.swap(*this);
}
A& operator=(A&& src) noexcept
{
src.swap(*this); // You are moving the state of the src object
// into this one. The state of the src object
// after the move must be valid but indeterminate.
//
// The easiest way to do this is to swap the states
// of the two objects.
//
// Note: Doing any operation on src after a move
// is risky (apart from destroy) until you put it
// into a specific state. Your object should have
// appropriate methods for this.
//
// Example: Assignment (operator = should work).
// std::vector() has clear() which sets
// a specific state without needing to
// know the current state.
return *this;
}
}
```
|
255,642 |
<p>I have a database table named call with columns call_time, location, emergency_type and there are three types of emergency: paramedics, police and firefighters. In the windows form I created CheckBoxes 'paramedics', 'police', 'firefighters' and I want to retrieve all table columns which meet user's selection.</p>
<p>I created a function:</p>
<pre><code>public static DataTable GetHistory(DateTime from, DateTime to, bool paramedics, bool police, bool firefighters)
{
string select =
"SELECT call_time, location, emergency_type where call_time between @from AND @to AND";
if(paramedics)
{
select += " emergency_type = 'paramedics' ";
}
if(paramedics && police)
{
select +=" emergency_type = 'paramedics' OR emergency_type = 'police';
}
...
}
</code></pre>
<p>This code however seems very dirty because if there were 30 kinds of emergency there would be 30! combinations and I would get old before writing all if statements.</p>
<p>I would appreciate if you shared your practice for retrieving data that meet the selected search conditions if there are many options you can chosse.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 255657,
"author": "Ady",
"author_id": 31395,
"author_profile": "https://Stackoverflow.com/users/31395",
"pm_score": 0,
"selected": false,
"text": "<p>This is a dirty way of doing this.</p>\n\n<pre><code>string select = \"SELECT call_time, location, emergency_type where call_time between @from AND @to AND (1=0\";\n\nif(paramedics) { select += \" OR emergency_type = 'paramedics' \"; }\nif(police) { select += \" OR emergency_type = 'police'\"; }\nif(xyz) { select += \" OR emergency_type = 'xyz'\"; }\n\nselect += \")\";\n</code></pre>\n"
},
{
"answer_id": 255660,
"author": "TheCodeJunkie",
"author_id": 25319,
"author_profile": "https://Stackoverflow.com/users/25319",
"pm_score": 4,
"selected": true,
"text": "<p>Well if you have to use emergency_type as a string then instead of passing in bools you could send in a List containing the text representation of the emergency type. For example to adjust the above code you could change the method signature to</p>\n\n<pre><code>public static DataTable GetHistory(DateTime from, DateTime to, List<string> types)\n{\n ..\n}\n</code></pre>\n\n<p>and then pass in a list that looked like these (for example)</p>\n\n<pre><code>List<string> types = \n new List<string> { \"paramedics\" };\n\nor \n\nList<string> types = \n new List<string> { \"paramedics\", \"police\" };\n</code></pre>\n\n<p>Then you could adapt your query to use the SQL IN statement in your where clause. Next convert the list of strings into a comma separated string like</p>\n\n<pre><code>string values = \"'paramedics', 'police'\"\n</code></pre>\n\n<p>A simple way to create the values variable is to use</p>\n\n<pre><code>string values = string.Empty;\n types.ForEach(s =>\n {\n if (!string.IsNullOrEmpty(values))\n values += \",\";\n values += string.Format(\"'{0}'\", s);\n\n });\n</code></pre>\n\n<p>By the way you could use a parameterized command to avoid SQL injection. Once you have the string you can simply do</p>\n\n<pre><code>string select =\n \"SELECT call_time, location, emergency_type where call_time between @from AND @to AND emergency_type IN \" + values\n</code></pre>\n"
},
{
"answer_id": 255777,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>String concatenation should be avoided, as it can contribute to some nasty vulnerabilities.\nIf you're looking for best practices in terms of programmatic access, then the best practice here is to use a parameterized query.</p>\n\n<p>If you want to be cheap, then make the in clause take a parameter, and concatenate that string together from the list of checked checkboxes, and pass that as the value of the parameter for the in clause. it would look like this:</p>\n\n<pre><code>where ... and emergency_type in (?)\n</code></pre>\n\n<p>The other way to do it is to count the number of checkboxes that are checked, and build the list of parameters to the in clause, so that it looks more like this:</p>\n\n<pre><code>where ... and emergency_type in(?,?...) -- as many params as there are checked checkboxes.\n</code></pre>\n\n<p>Either of these will do just fine.\nWith these types of queries, i've gone so far as to build my own SQL constructor methods, I keep an internal count of parameters, and their datatypes, and dynamically build the sql, then do the prepare with the known list of good parameters.</p>\n\n<p>You might look at learning Linq.</p>\n"
},
{
"answer_id": 255803,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 0,
"selected": false,
"text": "<p>Build the user's list of compare values (@EmergencyList) and use SQL with a parameterized query using the Contains operator. </p>\n\n<pre><code>SELECT call_time, \n location, \n emergency_type \nwhere call_time between @from AND @to \n AND CONTAINS( Emegency_Type, @EmergencyList )\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22996/"
] |
I have a database table named call with columns call\_time, location, emergency\_type and there are three types of emergency: paramedics, police and firefighters. In the windows form I created CheckBoxes 'paramedics', 'police', 'firefighters' and I want to retrieve all table columns which meet user's selection.
I created a function:
```
public static DataTable GetHistory(DateTime from, DateTime to, bool paramedics, bool police, bool firefighters)
{
string select =
"SELECT call_time, location, emergency_type where call_time between @from AND @to AND";
if(paramedics)
{
select += " emergency_type = 'paramedics' ";
}
if(paramedics && police)
{
select +=" emergency_type = 'paramedics' OR emergency_type = 'police';
}
...
}
```
This code however seems very dirty because if there were 30 kinds of emergency there would be 30! combinations and I would get old before writing all if statements.
I would appreciate if you shared your practice for retrieving data that meet the selected search conditions if there are many options you can chosse.
Thanks!
|
Well if you have to use emergency\_type as a string then instead of passing in bools you could send in a List containing the text representation of the emergency type. For example to adjust the above code you could change the method signature to
```
public static DataTable GetHistory(DateTime from, DateTime to, List<string> types)
{
..
}
```
and then pass in a list that looked like these (for example)
```
List<string> types =
new List<string> { "paramedics" };
or
List<string> types =
new List<string> { "paramedics", "police" };
```
Then you could adapt your query to use the SQL IN statement in your where clause. Next convert the list of strings into a comma separated string like
```
string values = "'paramedics', 'police'"
```
A simple way to create the values variable is to use
```
string values = string.Empty;
types.ForEach(s =>
{
if (!string.IsNullOrEmpty(values))
values += ",";
values += string.Format("'{0}'", s);
});
```
By the way you could use a parameterized command to avoid SQL injection. Once you have the string you can simply do
```
string select =
"SELECT call_time, location, emergency_type where call_time between @from AND @to AND emergency_type IN " + values
```
|
255,669 |
<p>How do I enable assembly bind failure logging (Fusion) in .NET?</p>
|
[
{
"answer_id": 255670,
"author": "user32736",
"author_id": 32736,
"author_profile": "https://Stackoverflow.com/users/32736",
"pm_score": 7,
"selected": false,
"text": "<p>Set the following registry value:</p>\n\n<p>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Fusion!EnableLog] (DWORD) to 1</p>\n\n<p>To disable, set to 0 or delete the value.</p>\n\n<p>[edit ]:Save the following text to a file, e.g FusionEnableLog.reg, in\nWindows Registry Editor Format:</p>\n\n<pre><code>Windows Registry Editor Version 5.00\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Fusion]\n\"EnableLog\"=dword:00000001\n</code></pre>\n\n<p>Then run the file from windows explorer and ignore the warning about possible damage.</p>\n"
},
{
"answer_id": 1527249,
"author": "Gary Kindel",
"author_id": 44597,
"author_profile": "https://Stackoverflow.com/users/44597",
"pm_score": 10,
"selected": false,
"text": "<p>Add the following values to</p>\n\n<pre>\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Fusion\nAdd:\nDWORD ForceLog set value to 1\nDWORD LogFailures set value to 1\nDWORD LogResourceBinds set value to 1\nDWORD EnableLog set value to 1\nString LogPath set value to folder for logs (e.g. C:\\FusionLog\\)\n</pre>\n\n<p>Make sure you <strong>include the backslash</strong> after the folder name and that the <strong>Folder exists</strong>. </p>\n\n<p>You need to restart the program that you're running to force it to read those registry settings.</p>\n\n<p>By the way, don't forget to turn off fusion logging when not needed.</p>\n\n<p><a href=\"https://i.stack.imgur.com/hcled.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/hcled.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 2863911,
"author": "Samuel Jack",
"author_id": 1727,
"author_profile": "https://Stackoverflow.com/users/1727",
"pm_score": 8,
"selected": false,
"text": "<p>If you have the Windows SDK installed on your machine, you'll find the \"Fusion Log Viewer\" under Microsoft SDK\\Tools (just type \"Fusion\" in the start menu on Vista or Windows 7/8). Launch it, click the Settings button, and select \"Log bind failure\" or \"Log all binds\".</p>\n\n<p>If these buttons are disabled, go back to the start menu, right-click the Log Viewer, and select \"Run as Administrator\".</p>\n"
},
{
"answer_id": 3256753,
"author": "Mike Goatly",
"author_id": 266104,
"author_profile": "https://Stackoverflow.com/users/266104",
"pm_score": 8,
"selected": false,
"text": "<p>I usually use the Fusion Log Viewer (<a href=\"https://learn.microsoft.com/en-us/dotnet/framework/tools/fuslogvw-exe-assembly-binding-log-viewer\" rel=\"noreferrer\">Fuslogvw.exe</a> from a <a href=\"https://learn.microsoft.com/en-us/dotnet/framework/tools/developer-command-prompt-for-vs\" rel=\"noreferrer\">Visual Studio command prompt</a> or Fusion Log Viewer from the start menu) - my standard setup is:</p>\n\n<ul>\n<li>Open Fusion Log Viewer as administrator</li>\n<li>Click <strong>settings</strong></li>\n<li>Check the <strong>Enable custom log path</strong> checkbox</li>\n<li>Enter the location you want logs to get written to, for example, <code>c:\\FusionLogs</code> (<strong>Important:</strong> make sure that you have actually created this folder in the file system.)</li>\n<li>Make sure that the right level of logging is on (I sometimes just select <strong>Log all binds to disk</strong> just to make sure things are working right)</li>\n<li>Click <strong>OK</strong></li>\n<li>Set the log location option to <strong>Custom</strong></li>\n</ul>\n\n<p>Remember to turn of logging off once you're done! </p>\n\n<p>(I just posted this on a similar question - I think it's relevant here too.)</p>\n"
},
{
"answer_id": 7845375,
"author": "Adam Tuliper",
"author_id": 371637,
"author_profile": "https://Stackoverflow.com/users/371637",
"pm_score": 4,
"selected": false,
"text": "<p>The <a href=\"http://www.paraesthesia.com/archive/2004/10/20/fusion-log-viewer-settings-changer.aspx\" rel=\"noreferrer\">Fusion Log Settings Viewer changer script</a> is bar none the best way to do this. </p>\n\n<p>In <a href=\"http://en.wikipedia.org/wiki/ASP.NET\" rel=\"noreferrer\">ASP.NET</a>, it has been tricky at times to get this to work correctly. This script works great and was listed on <a href=\"http://www.hanselman.com/blog/ScottHanselmans2011UltimateDeveloperAndPowerUsersToolListForWindows.aspx\" rel=\"noreferrer\">Scott Hanselman's Power Tool list</a> as well. I've personally used it for years and its never let me down.</p>\n"
},
{
"answer_id": 10200818,
"author": "Adam Mendoza",
"author_id": 464313,
"author_profile": "https://Stackoverflow.com/users/464313",
"pm_score": 2,
"selected": false,
"text": "<p>If you already have logging enabled and you still get this error on Windows 7 64 bit, try this in IIS 7.5:</p>\n\n<ol>\n<li><p>Create a new application pool</p></li>\n<li><p>Go to the Advanced Settings of this application pool</p></li>\n<li><p>Set the <em>Enable 32-Bit Application</em> to <em>True</em></p></li>\n<li><p>Point your web application to use this new pool</p></li>\n</ol>\n"
},
{
"answer_id": 17727149,
"author": "andrerav",
"author_id": 393716,
"author_profile": "https://Stackoverflow.com/users/393716",
"pm_score": 2,
"selected": false,
"text": "<p>Just a tiny bit of info that might help others; if you do something along the lines of searching all assemblies in some directory for classes that inherit/implement classes/interfaces, then make sure you clean out stale assemblies if you get this error pertaining to one of your own assemblies.</p>\n\n<p>The scenario would be something like:</p>\n\n<ol>\n<li>Assembly A loads all assemblies in some folder </li>\n<li>Assembly B in this folder is stale, but references assembly C </li>\n<li>Assembly C exists, but namespaces, class names or some other detail might have changed in the time that has passed since assembly B became stale (in my case a namespace was changed through a refactoring process)</li>\n</ol>\n\n<p>In short: A ---loads--> B (stale) ---references---> C</p>\n\n<p>If this happens, the only telltale sign is the namespace and classname in the error message. Examine it closely. If you can't find it anywhere in your solution, you are likely trying to load a stale assembly.</p>\n"
},
{
"answer_id": 29374658,
"author": "magicandre1981",
"author_id": 1466046,
"author_profile": "https://Stackoverflow.com/users/1466046",
"pm_score": 4,
"selected": false,
"text": "<p>Instead of using a ugly log file, you can also activate Fusion log via <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/hh448186.aspx\" rel=\"noreferrer\">ETW/xperf</a> by turning on the DotnetRuntime Private provider (<code>Microsoft-Windows-DotNETRuntimePrivate</code>) with GUID <code>763FD754-7086-4DFE-95EB-C01A46FAF4CA</code> and the <code>FusionKeyword</code> keyword (0x4) on.</p>\n\n<pre><code>@echo off\necho Press a key when ready to start...\npause\necho .\necho ...Capturing...\necho .\n\n\"C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\xperf.exe\" -on PROC_THREAD+LOADER+PROFILE -stackwalk Profile -buffersize 1024 -MaxFile 2048 -FileMode Circular -f Kernel.etl\n\"C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\xperf.exe\" -start ClrSession -on Microsoft-Windows-DotNETRuntime:0x8118:0x5:'stack'+763FD754-7086-4DFE-95EB-C01A46FAF4CA:0x4:0x5 -f clr.etl -buffersize 1024\n\necho Press a key when you want to stop...\npause\npause\necho .\necho ...Stopping...\necho .\n\n\"C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\xperf.exe\" -start ClrRundownSession -on Microsoft-Windows-DotNETRuntime:0x8118:0x5:'stack'+Microsoft-Windows-DotNETRuntimeRundown:0x118:0x5:'stack' -f clr_DCend.etl -buffersize 1024 \n\ntimeout /t 15\n\nset XPERF_CreateNGenPdbs=1\n\n\"C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\xperf.exe\" -stop ClrSession ClrRundownSession \n\"C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\xperf.exe\" -stop\n\"C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\xperf.exe\" -merge kernel.etl clr.etl clr_DCend.etl Result.etl -compress\ndel kernel.etl\ndel clr.etl\ndel clr_DCend.etl\n</code></pre>\n\n<p>When you now open the ETL file in <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=28567\" rel=\"noreferrer\">PerfView</a> and look under the Events table, you can find the Fusion data:</p>\n\n<p><a href=\"https://i.stack.imgur.com/eccjZ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eccjZ.png\" alt=\"Fusion events in PerfView\"></a></p>\n"
},
{
"answer_id": 33013110,
"author": "Tereza Tomcova",
"author_id": 99237,
"author_profile": "https://Stackoverflow.com/users/99237",
"pm_score": 7,
"selected": false,
"text": "<p>You can run this Powershell script as administrator to enable FL:</p>\n\n<pre><code>Set-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name ForceLog -Value 1 -Type DWord\nSet-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name LogFailures -Value 1 -Type DWord\nSet-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name LogResourceBinds -Value 1 -Type DWord\nSet-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name LogPath -Value 'C:\\FusionLog\\' -Type String\nmkdir C:\\FusionLog -Force\n</code></pre>\n\n<p>and this one to disable:</p>\n\n<pre><code>Remove-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name ForceLog\nRemove-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name LogFailures\nRemove-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name LogResourceBinds\nRemove-ItemProperty -Path HKLM:\\Software\\Microsoft\\Fusion -Name LogPath\n</code></pre>\n"
},
{
"answer_id": 53023482,
"author": "Dikshit Kathuria",
"author_id": 10296144,
"author_profile": "https://Stackoverflow.com/users/10296144",
"pm_score": 2,
"selected": false,
"text": "<p>Just in case you're wondering about the location of FusionLog.exe -\nYou know you have it, but you cannot find it? I was looking for FUSLOVW in last few years over and over again. After move to .NET 4.5 number of version of FUSION LOG has exploded. \nHer are places where it can be found on your disk, depending on software which you have installed:</p>\n\n<p>C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.0A\\bin\\NETFX 4.0 Tools\\x64 </p>\n\n<p>C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Bin\\x64 </p>\n\n<p>C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.1A\\bin\\NETFX 4.5.1 Tools\\x64 </p>\n\n<p>C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.0A\\bin\\NETFX 4.0 Tools </p>\n\n<p>C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.1A\\bin\\NETFX 4.5.1 Tools </p>\n\n<p>C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Bin</p>\n"
},
{
"answer_id": 54287180,
"author": "Vlad",
"author_id": 4683817,
"author_profile": "https://Stackoverflow.com/users/4683817",
"pm_score": -1,
"selected": false,
"text": "<p>In my case helped type disk name in lower case</p>\n\n<p><strong>Wrong</strong> - C:\\someFolder</p>\n\n<p><strong>Correct</strong> - c:\\someFolder</p>\n"
},
{
"answer_id": 56044491,
"author": "Igor Meszaros",
"author_id": 946889,
"author_profile": "https://Stackoverflow.com/users/946889",
"pm_score": 3,
"selected": false,
"text": "<p>For those who are a bit lazy, I recommend running this as a bat file for when ever you want to enable it:</p>\n\n<pre><code>reg add \"HKLM\\Software\\Microsoft\\Fusion\" /v EnableLog /t REG_DWORD /d 1 /f\nreg add \"HKLM\\Software\\Microsoft\\Fusion\" /v ForceLog /t REG_DWORD /d 1 /f\nreg add \"HKLM\\Software\\Microsoft\\Fusion\" /v LogFailures /t REG_DWORD /d 1 /f\nreg add \"HKLM\\Software\\Microsoft\\Fusion\" /v LogResourceBinds /t REG_DWORD /d 1 /f\nreg add \"HKLM\\Software\\Microsoft\\Fusion\" /v LogPath /t REG_SZ /d C:\\FusionLog\\\n\nif not exist \"C:\\FusionLog\\\" mkdir C:\\FusionLog\n</code></pre>\n"
},
{
"answer_id": 56067961,
"author": "Waescher",
"author_id": 704281,
"author_profile": "https://Stackoverflow.com/users/704281",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/61012329/704281\">There's so much wrong</a> with the Assembly Binding Log Viewer (FUSLOGVW.exe) that I decided to write an alternative viewer named <a href=\"https://github.com/awaescher/Fusion\" rel=\"noreferrer\">Fusion++ and put it on GitHub</a>. <strong>It uses the same mechanics internally</strong> but parses the logs for you. You don't have to care for any settings at all, not even log paths </p>\n<p>You can get the latest release from <a href=\"https://github.com/awaescher/Fusion/releases\" rel=\"noreferrer\">here</a> or via chocolatey (<code>choco install fusionplusplus</code>).</p>\n<p>I hope you and some of the visitors in here can save some worthy lifetime minutes with it.</p>\n<p><a href=\"https://i.stack.imgur.com/2uOEO.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/2uOEO.png\" alt=\"Fusion++\" /></a></p>\n"
},
{
"answer_id": 74081168,
"author": "Igor Levicki",
"author_id": 1778190,
"author_profile": "https://Stackoverflow.com/users/1778190",
"pm_score": 0,
"selected": false,
"text": "<p>This is not an answer but a word of warning:</p>\n<ul>\n<li>If you ever enable this logging, <strong>DO NOT FORGET TO DISABLE IT</strong> or you will regret it later.</li>\n</ul>\n<p>I did forget, and I ended up with several GB of small log files with <code>HTM</code> extension in <code>C:\\Windows\\System32\\config\\systemprofile\\AppData\\Local\\Microsoft\\Windows\\INetCache\\IE</code> folder — it was apparently logging all assembly bindings from applications running under <code>NT AUTHORITY\\SYSTEM</code> account.</p>\n<p>The number of files was greater than 3 million and neither Total Commander nor Windows Explorer could display the contents or folder size without hanging.</p>\n<p>After disabling logging and a reboot for good measure, I ran the deletion from command prompt.</p>\n<p>It took more than 15 minutes to delete all the files on a Samsung 970 Pro SSD which was showing 100% disk usage all the time — my high-end PC workstation was brought down to its knees by this delete operation and remained only partially responsive until it finished.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32736/"
] |
How do I enable assembly bind failure logging (Fusion) in .NET?
|
Add the following values to
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion
Add:
DWORD ForceLog set value to 1
DWORD LogFailures set value to 1
DWORD LogResourceBinds set value to 1
DWORD EnableLog set value to 1
String LogPath set value to folder for logs (e.g. C:\FusionLog\)
```
Make sure you **include the backslash** after the folder name and that the **Folder exists**.
You need to restart the program that you're running to force it to read those registry settings.
By the way, don't forget to turn off fusion logging when not needed.
[](https://i.stack.imgur.com/hcled.jpg)
|
255,700 |
<p>In my website, users have the possibility to store links.</p>
<p>During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar.</p>
<p>Example:</p>
<p>User is typing as URL:</p>
<pre><code>http://www.sta
</code></pre>
<p>Suggestions which would be displayed:</p>
<pre><code>http://www.staples.com
http://www.starbucks.com
http://www.stackoverflow.com
</code></pre>
<p>How can I achieve this while not reinventing the wheel? :)</p>
|
[
{
"answer_id": 255705,
"author": "Pesto D",
"author_id": 21746,
"author_profile": "https://Stackoverflow.com/users/21746",
"pm_score": 4,
"selected": true,
"text": "<p>You could try with\n<a href=\"http://google.com/complete/search?output=toolbar&q=keyword\" rel=\"noreferrer\">http://google.com/complete/search?output=toolbar&q=keyword</a></p>\n\n<p>and then parse the xml result.</p>\n"
},
{
"answer_id": 255962,
"author": "albertb",
"author_id": 26715,
"author_profile": "https://Stackoverflow.com/users/26715",
"pm_score": 0,
"selected": false,
"text": "<p>If you want the auto-complete to use date from your own database, you'll need to do the search yourself and update the suggestions using AJAX as users type. For the search part, you might want to look at <a href=\"http://lucene.apache.org/java/docs/\" rel=\"nofollow noreferrer\">Lucene</a>.</p>\n"
},
{
"answer_id": 256099,
"author": "lacker",
"author_id": 2652,
"author_profile": "https://Stackoverflow.com/users/2652",
"pm_score": 2,
"selected": false,
"text": "<p>I did this once before in a Django server. There's two parts - client-side and server-side.</p>\n\n<p>Client side you will have to send out XmlHttpRequests to the server as the user is typing, and then when the information comes back, display it. This part will require a decent amount of javascript, including some tricky parts like callbacks and keypress handlers.</p>\n\n<p>Server side you will have to handle the XmlHttpRequests which will be something that contains what the user has typed so far. Like a url of</p>\n\n<pre><code>www.yoursite.com/suggest?typed=www.sta\n</code></pre>\n\n<p>and then respond with the suggestions encoded in some way. (I'd recommend JSON-encoding the suggestions.) You also have to actually get the suggestions from your database, this could be just a simple SQL call or something else depending on your framework.</p>\n\n<p>But the server-side part is pretty simple. The client-side part is trickier, I think. I found this <a href=\"http://www.phpriot.com/articles/google-suggest-ajaxac\" rel=\"nofollow noreferrer\">article</a> helpful</p>\n\n<p>He's writing things in php, but the client side work is pretty much the same. In particular you might find his CSS helpful.</p>\n"
},
{
"answer_id": 656122,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 1,
"selected": false,
"text": "<p>Yahoo has a good <a href=\"http://developer.yahoo.com/yui/autocomplete/\" rel=\"nofollow noreferrer\">autocomplete control</a>.</p>\n\n<p>They have a <a href=\"http://developer.yahoo.com/yui/examples/autocomplete/ac_basic_array.html\" rel=\"nofollow noreferrer\">sample here.</a>.</p>\n\n<p>Obviously this does nothing to help you out in getting the data - but it looks like you have your own source and arent actually looking to get data from Google.</p>\n"
},
{
"answer_id": 656223,
"author": "Justin R.",
"author_id": 4593,
"author_profile": "https://Stackoverflow.com/users/4593",
"pm_score": 0,
"selected": false,
"text": "<p>That control is often called a word wheel. MSDN has a recent <a href=\"http://msdn.microsoft.com/en-us/magazine/cc721610.aspx\" rel=\"nofollow noreferrer\">walkthrough</a> on writing one with <code>LINQ</code>. There are two critical aspects: deferred execution and lazy evaluation. The article has source code too. </p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26763/"
] |
In my website, users have the possibility to store links.
During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar.
Example:
User is typing as URL:
```
http://www.sta
```
Suggestions which would be displayed:
```
http://www.staples.com
http://www.starbucks.com
http://www.stackoverflow.com
```
How can I achieve this while not reinventing the wheel? :)
|
You could try with
<http://google.com/complete/search?output=toolbar&q=keyword>
and then parse the xml result.
|
255,714 |
<p>So I've got a Ruby method like this:</p>
<pre><code>def something(variable, &block)
....
end
</code></pre>
<p>And I want to call it like this:</p>
<pre><code>something 'hello' { do_it }
</code></pre>
<p>Except that isn't working for me, I'm getting a syntax error. If I do this instead, it works:</p>
<pre><code>something 'hello' do
do_it
end
</code></pre>
<p>Except there I'm kind of missing the nice look of it being on one line.</p>
<p>I can see why this is happening, as it could look like it's a hash being passed as a second variable, but without a comma in between the variables...but I assume that there must be a way to deal with this that I'm missing. Is there?</p>
|
[
{
"answer_id": 255732,
"author": "seanbehan",
"author_id": 155970,
"author_profile": "https://Stackoverflow.com/users/155970",
"pm_score": 2,
"selected": false,
"text": "<p>If you want \"def something\" to to accept a block, you need to yield data to that block. For example: </p>\n\n<pre><code>#to uppercase string\ndef something(my_input)\n yield my_input.upcase\nend\n\n# => \"HELLO WORLD\"\nsomething(\"hello world\") { |i| puts i}\n</code></pre>\n"
},
{
"answer_id": 255791,
"author": "Rômulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 7,
"selected": true,
"text": "<p>You need to parenthesize your argument:</p>\n\n<pre><code>something('hello') { do_it }\n</code></pre>\n\n<p>That should work.</p>\n"
},
{
"answer_id": 256607,
"author": "Ryan Bigg",
"author_id": 15245,
"author_profile": "https://Stackoverflow.com/users/15245",
"pm_score": 0,
"selected": false,
"text": "<p>Uh, what about:</p>\n\n<pre><code>>> def something(arg1 , &block)\n>> yield block\n>> end\n=> nil\n>> def do_it\n>> puts \"Doing it!\"\n>> end\n=> nil\n>> something('hello') { do_it }\n\"Doing it!\"\n=> nil\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14873/"
] |
So I've got a Ruby method like this:
```
def something(variable, &block)
....
end
```
And I want to call it like this:
```
something 'hello' { do_it }
```
Except that isn't working for me, I'm getting a syntax error. If I do this instead, it works:
```
something 'hello' do
do_it
end
```
Except there I'm kind of missing the nice look of it being on one line.
I can see why this is happening, as it could look like it's a hash being passed as a second variable, but without a comma in between the variables...but I assume that there must be a way to deal with this that I'm missing. Is there?
|
You need to parenthesize your argument:
```
something('hello') { do_it }
```
That should work.
|
255,723 |
<p>I'm looking to write a html sanitiser, and obviously to test/prove that it works properly, I need a set of XSS examples to pitch against it to see how it performs. Here's a <a href="http://www.codinghorror.com/blog/archives/001167.html" rel="noreferrer">nice example from Coding Horror</a></p>
<pre><code><img src=""http://www.a.com/a.jpg<script type=text/javascript
src="http://1.2.3.4:81/xss.js">" /><<img
src=""http://www.a.com/a.jpg</script>"
</code></pre>
<p>I know there's a <a href="http://sourceforge.net/project/showfiles.php?group_id=32721&package_id=98949" rel="noreferrer">Mime Torture Test</a> which comprises of several nested emails with attachments that's used to test Mime decoders (if they can decode it properly, then they've been proven to work). I'm basically looking for an equivilent for XSS, i.e. a list of examples of dodgy html that I can throw at my sanitiser just to make sure it works OK.</p>
<p>If anyone also has any good resources on how to write the sanitiser (i.e. what common exploits people try to use, etc) they'd be gratefully received too.</p>
<p>Thanks in advance :-)</p>
<p>Edit: Sorry if this wasn't clear before, but I was after a set of torture tests so I can write unit tests for the sanitiser, not test it in the browser, etc. The source data in theory may have come from anywhere - not just a browser.</p>
|
[
{
"answer_id": 255739,
"author": "RealHowTo",
"author_id": 25122,
"author_profile": "https://Stackoverflow.com/users/25122",
"pm_score": 5,
"selected": true,
"text": "<p>Take a look at this XSS Cheat List : <a href=\"https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet\" rel=\"nofollow noreferrer\">https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet</a></p>\n"
},
{
"answer_id": 255746,
"author": "Maxam",
"author_id": 15310,
"author_profile": "https://Stackoverflow.com/users/15310",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://addons.mozilla.org/en-US/firefox/addon/7598\" rel=\"nofollow noreferrer\">XSS Me</a> is a great Firefox plugin you can run against your sanitizer.</p>\n"
},
{
"answer_id": 255750,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "<p>Check out <a href=\"http://www.owasp.org/index.php/Main_Page\" rel=\"nofollow noreferrer\">OWASP</a>. They have good guidance on how XSS works, what to look for, and even the <a href=\"http://www.owasp.org/index.php/Category:OWASP_WebGoat_Project\" rel=\"nofollow noreferrer\">WebGoat</a> project, where you can try your hand on a vulnerable site.</p>\n"
},
{
"answer_id": 255751,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 2,
"selected": false,
"text": "<p>You might try Jesse Ruderman's jsfunfuzz (<a href=\"http://www.squarefree.com/2007/08/02/introducing-jsfunfuzz/\" rel=\"nofollow noreferrer\">http://www.squarefree.com/2007/08/02/introducing-jsfunfuzz/</a>) that throws random data at your Javascript trying to break it. It seems the Firefox team has used this with great success.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11905/"
] |
I'm looking to write a html sanitiser, and obviously to test/prove that it works properly, I need a set of XSS examples to pitch against it to see how it performs. Here's a [nice example from Coding Horror](http://www.codinghorror.com/blog/archives/001167.html)
```
<img src=""http://www.a.com/a.jpg<script type=text/javascript
src="http://1.2.3.4:81/xss.js">" /><<img
src=""http://www.a.com/a.jpg</script>"
```
I know there's a [Mime Torture Test](http://sourceforge.net/project/showfiles.php?group_id=32721&package_id=98949) which comprises of several nested emails with attachments that's used to test Mime decoders (if they can decode it properly, then they've been proven to work). I'm basically looking for an equivilent for XSS, i.e. a list of examples of dodgy html that I can throw at my sanitiser just to make sure it works OK.
If anyone also has any good resources on how to write the sanitiser (i.e. what common exploits people try to use, etc) they'd be gratefully received too.
Thanks in advance :-)
Edit: Sorry if this wasn't clear before, but I was after a set of torture tests so I can write unit tests for the sanitiser, not test it in the browser, etc. The source data in theory may have come from anywhere - not just a browser.
|
Take a look at this XSS Cheat List : <https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet>
|
255,771 |
<p>I need a modal dialog to gather some user input. I then need the same data to be consumed by the application MainFrame.</p>
<p>Usually my Modal Dialog would have a pointer to some DataType able to store what I need, and I'd be passing this object by reference from the MainFrame in order to be able to recover data once the modal dialog is closed by the user. </p>
<p>Is this the best way of passing around data?</p>
<p>It doesn't feel right!</p>
|
[
{
"answer_id": 255778,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 0,
"selected": false,
"text": "<p>Normally you can use a single class or other datatype to transfer data. So the dialog is used to change the properties of the class. Why doesn't this feel right?</p>\n\n<p>[humor]\nWith mainframe, I assume you don't mean the big old (althoug still alive and kicking) computers. Else, I think TCP/IP will be a good choise.\n[/humor]</p>\n"
},
{
"answer_id": 255782,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 0,
"selected": false,
"text": "<p>The very best way of doing this is to package the data into an event and send it out on an event bus.</p>\n\n<p>This decouples the dialog from the mainframe - and if you design the event properly it doesn't limit you to just using a dialog.</p>\n\n<p>Depending on the language and environment this event system can be implemented easily and cheaply. I call my version class based interobject communication.</p>\n"
},
{
"answer_id": 255790,
"author": "Samuel",
"author_id": 32465,
"author_profile": "https://Stackoverflow.com/users/32465",
"pm_score": 3,
"selected": true,
"text": "<p>Since you are passing data once the user has closed the dialog (presumably on DialogResult.OK), you can easily do this without having a MainFrame reference.</p>\n\n<p>So say you have a TextBox on your dialog, called userNameTextBox and a button that ends the dialog with the OK result. You can either make the userNameTextBox public (not recommended) or add a property to return the text.</p>\n\n<pre><code>public string UserName\n{\n get { return userNameTextBox.Text; }\n}\n</code></pre>\n\n<p>And to get this value after the dialog has ended, you just do:</p>\n\n<pre><code>Dialog dialog = new Dialog();\nif (dialog.ShowDialog() == DialogResult.OK)\n{\n string username = dialog.UserName;\n}\n</code></pre>\n"
},
{
"answer_id": 255952,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 1,
"selected": false,
"text": "<p>@Samuel's suggestion is perfectly adequate when collecting one or two values from the user. </p>\n\n<p>If you're getting many values then the solution in your question is fine as well.</p>\n\n<p>Don't fall prey to premature optimization and over-engineer a decoupled solution. By boundary object I assume you're referring to the datastructure instance referenced by the mainframe and dialog. What's the problem with the dialog and mainframe both referencing this object? What is the benefit of decoupling the boundary/transfer object in this scenario?</p>\n\n<p>The only decoupling payoff I could see here would be decoupling the mainframe from the specific implementation that delivers the data to it. So rather than the mainframe instantiating Dialog and calling Dialog.ShowModal, dependency injection would provide the mainframe with an IDataYouNeedGetter (which would happen to be the same modal dialog) and at the appropriate time the mainframe would do </p>\n\n<pre><code>myGetter.SetTransferObject(dataStructInstance)\nmyGetter.GoGetTheData()\n// do stuff with dataStructInstance now that myGetter set it up.\n</code></pre>\n\n<p>BUT, there is no reason to add a layer of indirection unless you already know of a specific need for the decoupling.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1311500/"
] |
I need a modal dialog to gather some user input. I then need the same data to be consumed by the application MainFrame.
Usually my Modal Dialog would have a pointer to some DataType able to store what I need, and I'd be passing this object by reference from the MainFrame in order to be able to recover data once the modal dialog is closed by the user.
Is this the best way of passing around data?
It doesn't feel right!
|
Since you are passing data once the user has closed the dialog (presumably on DialogResult.OK), you can easily do this without having a MainFrame reference.
So say you have a TextBox on your dialog, called userNameTextBox and a button that ends the dialog with the OK result. You can either make the userNameTextBox public (not recommended) or add a property to return the text.
```
public string UserName
{
get { return userNameTextBox.Text; }
}
```
And to get this value after the dialog has ended, you just do:
```
Dialog dialog = new Dialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
string username = dialog.UserName;
}
```
|
255,797 |
<p>In what areas of programming would I use state machines ? Why ? How could I implement one ?</p>
<p><strong>EDIT:</strong> please provide a practical example , if it's not too much to ask .</p>
|
[
{
"answer_id": 255808,
"author": "Maxam",
"author_id": 15310,
"author_profile": "https://Stackoverflow.com/users/15310",
"pm_score": 3,
"selected": false,
"text": "<p>Most workflows can be implemented as state machines. For example, processing leave applications or orders.</p>\n\n<p>If you're using .NET, try Windows Workflow Foundation. You can implement a state machine workflow quite quickly with it.</p>\n"
},
{
"answer_id": 255823,
"author": "Nate",
"author_id": 11760,
"author_profile": "https://Stackoverflow.com/users/11760",
"pm_score": 2,
"selected": false,
"text": "<p>State machines are everywhere. State machines are key in communications interfaces where a message needs to be parsed as it is received. Also, there have been many times in embedded systems development that I've needed to separate a task into multiple tasks because of strict timing constraints.</p>\n"
},
{
"answer_id": 255826,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 2,
"selected": false,
"text": "<p>QA infrastructure, intended to screen-scrape or otherwise run through a process under test. (This is my particular area of experience; I built a state machine framework in Python for my last employer with support for pushing the current state onto a stack and using various methods of state handler selection for use in all our TTY-based screen scrapers). The conceptual model fits well, as running through a TTY application, it goes through a limited number of known states, and can be moved back into old ones (think about using a nested menu). This has been released (with said employer's permission); use <A HREF=\"http://bazaar-vcs.org/\" rel=\"nofollow noreferrer\">Bazaar</A> to check out <code>http://web.dyfis.net/bzr/isg_state_machine_framework/</code> if you want to see the code.</p>\n\n<p>Ticket-, process-management and workflow systems -- if your ticket has a set of rules determining its movement between NEW, TRIAGED, IN-PROGRESS, NEEDS-QA, FAILED-QA and VERIFIED (for example), you've got a simple state machine.</p>\n\n<p>Building small, readily provable embedded systems -- traffic light signaling is a key example where the list of all possible states <em>has</em> to be fully enumerated and known.</p>\n\n<p>Parsers and lexers are heavily state-machine based, because the way something streaming in is determined is based on where you're at at the time.</p>\n"
},
{
"answer_id": 255837,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using C#, any time you write an iterator block you're asking the compiler to build a state machine for you (keeping track of where you are in the iterator etc).</p>\n"
},
{
"answer_id": 255881,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://en.wikipedia.org/wiki/State_pattern\" rel=\"noreferrer\">State</a> design pattern is an object-oriented way to represent the state of an object by means of a finite state machine. It usually helps to reduce the logical complexity of that object's implementation (nested if's, many flags, etc.)</p>\n"
},
{
"answer_id": 255885,
"author": "Robert Elwell",
"author_id": 23102,
"author_profile": "https://Stackoverflow.com/users/23102",
"pm_score": 1,
"selected": false,
"text": "<p>Finite state machines can be used for morphological parsing in any natural language.</p>\n\n<p>Theoretically, this means that morphology and syntax are split up between computational levels, one being at most finite-state, and the other being at most mildly context sensitive (thus the need for other theoretical models to account for word-to-word rather than morpheme-to-morpheme relationships).</p>\n\n<p>This can be useful in the area of machine translation and word glossing. Ostensibly, they're low-cost features to extract for less trivial machine learning applications in NLP, such as syntactic or dependency parsing. </p>\n\n<p>If you're interested in learning more, you can check out <em>Finite State Morphology</em> by Beesley and Karttunen, and the Xerox Finite State Toolkit they designed at PARC. </p>\n"
},
{
"answer_id": 255886,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 4,
"selected": false,
"text": "<p><strong>What sort of task?</strong></p>\n\n<p>Any task but from what I have seen, Parsing of any sort is frequently implemented as a state machine.</p>\n\n<p><strong>Why?</strong></p>\n\n<p>Parsing a grammar is generally not a straightforward task. During the design phase it is fairly common that a state diagram is drawn to test the parsing algorithm. Translating that to a state machine implementation is a fairly simple task.</p>\n\n<p><strong>How?</strong></p>\n\n<p>Well, you are limited only by your imagination.</p>\n\n<p>I have seen it done with <a href=\"http://www.kirit.com/Implementing%20a%20state%20engine%20using%20instance%20behaviour\" rel=\"noreferrer\">case statements and loops</a>.</p>\n\n<p>I have seen it done with <a href=\"http://backpan.perl.org/authors/id/D/DW/DWHEELER/FSA-Rules-0.05.readme\" rel=\"noreferrer\">labels and goto</a> statements</p>\n\n<p>I have even seen it done with structures of function pointers which represent the current state. When the state changes, one or more <a href=\"http://www.gamedev.net/reference/articles/article2116.asp\" rel=\"noreferrer\">function pointer</a> is updated.</p>\n\n<p>I have seen it done in code only, where a change of state simply means that you are running in a different section of code. (no state variables, and redundent code where necessary. This can be demonstrated as a very simply sort, which is useful for only very small sets of data.</p>\n\n<pre><code>int a[10] = {some unsorted integers};\n\nnot_sorted_state:;\n z = -1;\n while (z < (sizeof(a) / sizeof(a[0]) - 1)\n {\n z = z + 1\n if (a[z] > a[z + 1])\n {\n // ASSERT The array is not in order\n swap(a[z], a[z + 1]; // make the array more sorted\n goto not_sorted_state; // change state to sort the array\n }\n }\n // ASSERT the array is in order\n</code></pre>\n\n<p>There are no state variables, but the code itself represents the state</p>\n"
},
{
"answer_id": 255908,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Regular_expression\" rel=\"nofollow noreferrer\">Regular expressions</a> are another example of where finite state machines (or \"finite state automata\") come into play. </p>\n\n<p>A compiled regexp is a finite state machine, and\nthe sets of strings that regular expressions can match are exactly the languages that finite state automata can accept (called \"regular languages\").</p>\n"
},
{
"answer_id": 255920,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 2,
"selected": false,
"text": "<p>A lot of digital hardware design involves creating state machines to specify the behaviour of your circuits. It comes up quite a bit if you're writing VHDL.</p>\n"
},
{
"answer_id": 255929,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 2,
"selected": false,
"text": "<p>A FSM is used everywhere you have multiple states and need to transition to a different state on stimulus. </p>\n\n<p>(turns out that this encompasses most problems, at least theoretically)</p>\n"
},
{
"answer_id": 255970,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 0,
"selected": false,
"text": "<p>State driven code is a good way to implement certain types of logic (parsers being an example). It can be done in several ways, for example:</p>\n\n<ul>\n<li><p>State driving which bit of code is actually being executed at a given point (i.e. the state is implicit in the piece of code you are writing). <a href=\"http://en.wikipedia.org/wiki/Recursive_descent_parser\" rel=\"nofollow noreferrer\">Recursive descent parsers</a> are a good example of this type of code.</p></li>\n<li><p>State driving what to do in a conditional such as a switch statement.</p></li>\n<li><p>Explicit state machines such as those generated by parser generating tools such as <a href=\"http://en.wikipedia.org/wiki/Lex_programming_tool\" rel=\"nofollow noreferrer\">Lex</a> and <a href=\"http://en.wikipedia.org/wiki/Yacc\" rel=\"nofollow noreferrer\">Yacc</a>.</p></li>\n</ul>\n\n<p>Not all state driven code is used for parsing. A general state machine generator is <a href=\"http://smc.sourceforge.net/\" rel=\"nofollow noreferrer\">smc</a>. It inhales a definition of a state machine (in its language) and it will spit out code for the state machine in a variety of languages.</p>\n"
},
{
"answer_id": 256001,
"author": "dviljoen",
"author_id": 29021,
"author_profile": "https://Stackoverflow.com/users/29021",
"pm_score": 2,
"selected": false,
"text": "<p>I have an example from a current system I'm working on. I'm in the process of building a stock trading system. The process of tracking the state of an order can be complex, but if you build a state diagram for the life cycle of an order it makes applying new incoming transactions to the existing order much simpler. There are many fewer comparisons necessary in applying that transaction if you know from its current state that the new transaction can only be one of three things rather than one of 20 things. It makes the code much more efficient.</p>\n"
},
{
"answer_id": 256011,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 8,
"selected": true,
"text": "<h2>In what areas of programming would I use a state machine?</h2>\n\n<p>Use a state machine to represent a (real or logical) object that can exist in a limited number of conditions (\"<em>states</em>\") and progresses from one state to the next according to a fixed set of rules.</p>\n\n<h2>Why would I use a state machine?</h2>\n\n<p>A state machine is often a <em>very</em> compact way to represent a set of complex rules and conditions, and to process various inputs. You'll see state machines in embedded devices that have limited memory. Implemented well, a state machine is self-documenting because each logical state represents a physical condition. A state machine can be embodied in a <em>tiny</em> amount of code in comparison to its procedural equivalent and runs extremely efficiently. Moreover, the rules that govern state changes can often be stored as data in a table, providing a compact representation that can be easily maintained.</p>\n\n<h2>How can I implement one?</h2>\n\n<p>Trivial example:</p>\n\n<pre><code>enum states { // Define the states in the state machine.\n NO_PIZZA, // Exit state machine.\n COUNT_PEOPLE, // Ask user for # of people.\n COUNT_SLICES, // Ask user for # slices.\n SERVE_PIZZA, // Validate and serve.\n EAT_PIZZA // Task is complete.\n} STATE;\n\nSTATE state = COUNT_PEOPLE;\nint nPeople, nSlices, nSlicesPerPerson;\n\n// Serve slices of pizza to people, so that each person gets\n/// the same number of slices. \nwhile (state != NO_PIZZA) {\n switch (state) {\n case COUNT_PEOPLE: \n if (promptForPeople(&nPeople)) // If input is valid..\n state = COUNT_SLICES; // .. go to next state..\n break; // .. else remain in this state.\n case COUNT_SLICES: \n if (promptForSlices(&nSlices))\n state = SERVE_PIZZA;\n break;\n case SERVE_PIZZA:\n if (nSlices % nPeople != 0) // Can't divide the pizza evenly.\n { \n getMorePizzaOrFriends(); // Do something about it.\n state = COUNT_PEOPLE; // Start over.\n }\n else\n {\n nSlicesPerPerson = nSlices/nPeople;\n state = EAT_PIZZA;\n }\n break;\n case EAT_PIZZA:\n // etc...\n state = NO_PIZZA; // Exit the state machine.\n break;\n } // switch\n} // while\n</code></pre>\n\n<p></p>\n\n<p><strong>Notes:</strong></p>\n\n<ul>\n<li><p>The example uses a <code>switch()</code> with explicit <code>case</code>/<code>break</code> states for simplicity. In practice, a <code>case</code> will often \"fall through\" to the next state.</p></li>\n<li><p>For ease of maintaining a large state machine, the work done in each <code>case</code> can be encapsulated in a \"worker\" function. Get any input at the top of the <code>while()</code>, pass it to the worker function, and check the return value of the worker to compute the next state.</p></li>\n<li><p>For compactness, the entire <code>switch()</code> can be replaced with an array of function pointers. Each state is embodied by a function whose return value is a pointer to the next state. <em>Warning:</em> This can either simplify the state machine or render it totally unmaintainable, so consider the implementation carefully!</p></li>\n<li><p>An embedded device may be implemented as a state machine that exits only on a catastrophic error, after which it performs a hard reset and re-enters the state machine.</p></li>\n</ul>\n"
},
{
"answer_id": 256030,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<p>Some great answers already. For a slightly different perspective, consider searching a text in a larger string. Someone has already mentioned regular expressions and this is really just a special case, albeit an important one.</p>\n\n<p>Consider the following method call:</p>\n\n<pre><code>very_long_text = \"Bereshit bara Elohim et hashamayim ve'et ha'arets.\" …\nword = \"Elohim\"\nposition = find_in_string(very_long_text, word)\n</code></pre>\n\n<p>How would you implement <code>find_in_string</code>? The easy approach would use a nested loop, something like this:</p>\n\n<pre><code>for i in 0 … length(very_long_text) - length(word):\n found = true\n for j in 0 … length(word):\n if (very_long_text[i] != word[j]):\n found = false\n break\n if found: return i\nreturn -1\n</code></pre>\n\n<p>Apart from the fact that this is inefficient, <em>it forms a state machine</em>! The states here are somewhat hidden; let me rewrite the code slightly to make them more visible:</p>\n\n<pre><code>state = 0\nfor i in 0 … length(very_long_text) - length(word):\n if very_long_text[i] == word[state]:\n state += 1\n if state == length(word) + 1: return i\n else:\n state = 0\nreturn -1\n</code></pre>\n\n<p>The different states here directly represent all different positions in the word we search for. There are two transitions for each node in the graph: if the letters match, go to the next state; for every other input (i.e. every other letter at the current position), go back to zero.</p>\n\n<p>This slight reformulation has a huge advantage: it can now be tweaked to yield better performance using some basic techniques. In fact, every advanced string searching algorithm (discounting index data structures for the moment) builds on top of this state machine and improves some aspects of it.</p>\n"
},
{
"answer_id": 256174,
"author": "old_timer",
"author_id": 16007,
"author_profile": "https://Stackoverflow.com/users/16007",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a tested and working example of a state machine. Say you are on a serial stream (serial port, tcp/ip data, or file are typical examples). In this case I am looking for a specific packet structure that can be broken into three parts, sync, length, and payload. I have three states, one is idle, waiting for the sync, the second is we have a good sync the next byte should be length, and the third state is accumulate the payload.</p>\n\n<p>The example is purely serial with only one buffer, as written here it will recover from a bad byte or packet, possibly discarding a packet but eventually recovering, you can do other things like a sliding window to allow for immediate recovery. This would be where you have say a partial packet that is cut short then a new complete packet starts, the code below wont detect this and will throw away the partial as well as the whole packet and recover on the next. A sliding window would save you there if you really needed to process all the whole packets.</p>\n\n<p>I use this kind of a state machine all the time be it serial data streams, tcp/ip, file i/o. Or perhaps tcp/ip protocols themselves, say you want to send an email, open the port, wait for the server to send a response, send HELO, wait for the server to send a packet, send a packet, wait for the reply, etc. Essentially in that case as well as in the case below you may be idling waiting for that next byte/packet to come in. To remember what you were waiting for, also to re-use the code that waits for something you can use state variables. The same way that state machines are used in logic (waiting for the next clock, what was I waiting for). </p>\n\n<p>Just like in logic, you may want to do something different for each state, in this case if I have a good sync pattern I reset the offset into my storage as well as reset the checksum accumulator. The packet length state demonstrates a case where you may want to abort out of the normal control path. Not all, in fact many state machines may jump around or may loop around within the normal path, the one below is pretty much linear.</p>\n\n<p>I hope this is useful and wish that state machines were used more in software.</p>\n\n<p>The test data has intentional problems with it that the state machine recovers from. There is some garbage data after the first good packet, a packet with a bad checksum, and a packet with an invalid length. My output was:</p>\n\n<p>good packet:FA0712345678EB\nInvalid sync pattern 0x12\nInvalid sync pattern 0x34\nInvalid sync pattern 0x56\nChecksum error 0xBF\nInvalid packet length 0\nInvalid sync pattern 0x12\nInvalid sync pattern 0x34\nInvalid sync pattern 0x56\nInvalid sync pattern 0x78\nInvalid sync pattern 0xEB\ngood packet:FA081234567800EA\nno more test data</p>\n\n<p>The two good packets in the stream were extracted despite the bad data. And the bad data was detected and dealt with.</p>\n\n<pre><code> #include <stdio.h>\n #include <stdlib.h>\n #include <string.h>\n\nunsigned char testdata[] =\n{\n 0xFA,0x07,0x12,0x34,0x56,0x78,0xEB, \n 0x12,0x34,0x56, \n 0xFA,0x07,0x12,0x34,0x56,0x78,0xAA, \n 0xFA,0x00,0x12,0x34,0x56,0x78,0xEB, \n 0xFA,0x08,0x12,0x34,0x56,0x78,0x00,0xEA \n};\n\nunsigned int testoff=0;\n\n//packet structure \n// [0] packet header 0xFA \n// [1] bytes in packet (n) \n// [2] payload \n// ... payload \n// [n-1] checksum \n// \n\nunsigned int state;\n\nunsigned int packlen; \nunsigned int packoff; \nunsigned char packet[256]; \nunsigned int checksum; \n\nint process_packet( unsigned char *data, unsigned int len ) \n{ \n unsigned int ra; \n\n printf(\"good packet:\");\n for(ra=0;ra<len;ra++) printf(\"%02X\",data[ra]);\n printf(\"\\n\");\n} \nint getbyte ( unsigned char *d ) \n{ \n //check peripheral for a new byte \n //or serialize a packet or file \n\n if(testoff<sizeof(testdata))\n {\n *d=testdata[testoff++];\n return(1);\n }\n else\n {\n printf(\"no more test data\\n\");\n exit(0);\n }\n return(0);\n}\n\nint main ( void ) \n{ \n unsigned char b;\n\n state=0; //idle\n\n while(1)\n {\n if(getbyte(&b))\n {\n switch(state)\n {\n case 0: //idle\n if(b!=0xFA)\n {\n printf(\"Invalid sync pattern 0x%02X\\n\",b);\n break;\n }\n packoff=0;\n checksum=b;\n packet[packoff++]=b;\n\n state++;\n break;\n case 1: //packet length\n checksum+=b;\n packet[packoff++]=b;\n\n packlen=b;\n if(packlen<3)\n {\n printf(\"Invalid packet length %u\\n\",packlen);\n state=0;\n break;\n }\n\n state++;\n break;\n case 2: //payload\n checksum+=b;\n packet[packoff++]=b;\n\n if(packoff>=packlen)\n {\n state=0;\n checksum=checksum&0xFF;\n if(checksum)\n {\n printf(\"Checksum error 0x%02X\\n\",checksum);\n }\n else\n {\n process_packet(packet,packlen);\n }\n }\n break;\n }\n }\n\n //do other stuff, handle other devices/interfaces\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 300396,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 2,
"selected": false,
"text": "<p>I didn't see anything here that actually explained the reason I see them used.</p>\n\n<p>For practical purposes, a programmer usually has to add one when he is forced to return a thread/exit right in the middle of an operation.</p>\n\n<p>For instance, if you have a multi-state HTTP request, you might have server code that looks like this:</p>\n\n<pre><code>Show form 1\nprocess form 1\nshow form 2\nprocess form 2\n</code></pre>\n\n<p>The thing is, every time you show a form, you have to quit out of your entire thread on the server (in most languages), even if your code all flows together logically and uses the same variables.</p>\n\n<p>The act of putting a break in the code and returning the thread is usually done with a switch statement and creates what is called a state machine (Very Basic Version).</p>\n\n<p>As you get more complex, it can get really difficult to figure out what states are valid. People usually then define a \"<a href=\"http://en.wikipedia.org/wiki/State_transition_table\" rel=\"nofollow noreferrer\">State Transition Table</a>\" to describe all the state transitions.</p>\n\n<p>I wrote a <a href=\"http://code.google.com/p/state-machine/\" rel=\"nofollow noreferrer\">state machine library</a>, the main concept being that you can actually implement your state transition table directly. It was a really neat exercise, not sure how well it's going to go over though...</p>\n"
},
{
"answer_id": 300497,
"author": "Mike Dunlavey",
"author_id": 23771,
"author_profile": "https://Stackoverflow.com/users/23771",
"pm_score": 0,
"selected": false,
"text": "<p>Good answers. Here's my 2 cents. Finite State Machines are a theoretical idea that can be implemented multiple different ways, such as a table, or as a while-switch (but don't tell anybody it's a way of saying goto <em>horrors</em>). It is a theorem that any FSM corresponds to a regular expression, and vice versa. Since a regular expression corresponds to a structured program, you can <strong>sometimes</strong> just write a structured program to implement your FSM. For example, a simple parser of numbers could be written along the lines of:</p>\n\n<pre><code>/* implement dd*[.d*] */\nif (isdigit(*p)){\n while(isdigit(*p)) p++;\n if (*p=='.'){\n p++;\n while(isdigit(*p)) p++;\n }\n /* got it! */\n}\n</code></pre>\n\n<p>You get the idea. And, if there's a way that runs faster, I don't know what it is.</p>\n"
},
{
"answer_id": 3529821,
"author": "thSoft",
"author_id": 90874,
"author_profile": "https://Stackoverflow.com/users/90874",
"pm_score": 0,
"selected": false,
"text": "<p>A typical use case is traffic lights.</p>\n\n<p>On an implementation note: Java 5's enums can have abstract methods, which is an excellent way to encapsulate state-dependent behavior.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31610/"
] |
In what areas of programming would I use state machines ? Why ? How could I implement one ?
**EDIT:** please provide a practical example , if it's not too much to ask .
|
In what areas of programming would I use a state machine?
---------------------------------------------------------
Use a state machine to represent a (real or logical) object that can exist in a limited number of conditions ("*states*") and progresses from one state to the next according to a fixed set of rules.
Why would I use a state machine?
--------------------------------
A state machine is often a *very* compact way to represent a set of complex rules and conditions, and to process various inputs. You'll see state machines in embedded devices that have limited memory. Implemented well, a state machine is self-documenting because each logical state represents a physical condition. A state machine can be embodied in a *tiny* amount of code in comparison to its procedural equivalent and runs extremely efficiently. Moreover, the rules that govern state changes can often be stored as data in a table, providing a compact representation that can be easily maintained.
How can I implement one?
------------------------
Trivial example:
```
enum states { // Define the states in the state machine.
NO_PIZZA, // Exit state machine.
COUNT_PEOPLE, // Ask user for # of people.
COUNT_SLICES, // Ask user for # slices.
SERVE_PIZZA, // Validate and serve.
EAT_PIZZA // Task is complete.
} STATE;
STATE state = COUNT_PEOPLE;
int nPeople, nSlices, nSlicesPerPerson;
// Serve slices of pizza to people, so that each person gets
/// the same number of slices.
while (state != NO_PIZZA) {
switch (state) {
case COUNT_PEOPLE:
if (promptForPeople(&nPeople)) // If input is valid..
state = COUNT_SLICES; // .. go to next state..
break; // .. else remain in this state.
case COUNT_SLICES:
if (promptForSlices(&nSlices))
state = SERVE_PIZZA;
break;
case SERVE_PIZZA:
if (nSlices % nPeople != 0) // Can't divide the pizza evenly.
{
getMorePizzaOrFriends(); // Do something about it.
state = COUNT_PEOPLE; // Start over.
}
else
{
nSlicesPerPerson = nSlices/nPeople;
state = EAT_PIZZA;
}
break;
case EAT_PIZZA:
// etc...
state = NO_PIZZA; // Exit the state machine.
break;
} // switch
} // while
```
**Notes:**
* The example uses a `switch()` with explicit `case`/`break` states for simplicity. In practice, a `case` will often "fall through" to the next state.
* For ease of maintaining a large state machine, the work done in each `case` can be encapsulated in a "worker" function. Get any input at the top of the `while()`, pass it to the worker function, and check the return value of the worker to compute the next state.
* For compactness, the entire `switch()` can be replaced with an array of function pointers. Each state is embodied by a function whose return value is a pointer to the next state. *Warning:* This can either simplify the state machine or render it totally unmaintainable, so consider the implementation carefully!
* An embedded device may be implemented as a state machine that exits only on a catastrophic error, after which it performs a hard reset and re-enters the state machine.
|
255,800 |
<p>I'm making a program which the user build directories (not in windows, in my app) and in these folders there are subfolders and so on; every folder must contain either folders or documents. What is the best data structure to use? Notice that the user may select a subfolder and search for documents in it and in its subfolders. And I don't want to limit the folders or the subfolders levels.</p>
|
[
{
"answer_id": 255828,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 3,
"selected": false,
"text": "<p>I can think of a few ways you could structure this, but nothing would beat the obvious:</p>\n\n<p><strong>Use the actual file system.</strong></p>\n"
},
{
"answer_id": 255841,
"author": "Jason",
"author_id": 16794,
"author_profile": "https://Stackoverflow.com/users/16794",
"pm_score": 5,
"selected": true,
"text": "<p>This is what I do:</p>\n\n<p>Every record in the database has two fields: ID and ParentID. IDs are 4-5 characters (Base36, a-z:0-9 or something similar). Parent IDs are a concatenation of the parent's complete structure...</p>\n\n<p>So...</p>\n\n<p>This structure:</p>\n\n<pre><code>Root\n Folder1\n Folder2\n Folder3\n Folder4\n Folder5\n Folder6\n</code></pre>\n\n<p>Would be represented like this:</p>\n\n<pre><code>ID ParentID Name\n\n0000 NULL ROOT\n0001 0000 Folder1\n0002 0000 Folder2\n0003 00000002 Folder3\n0004 0000 Folder4\n0005 00000004 Folder5\n0006 000000040005 Folder6\n</code></pre>\n\n<p>I like this structure because if I need to find all the files under a folder I can do a query like:</p>\n\n<pre><code>SELECT * FROM Folders WHERE ParentID LIKE '0000%' -- to find all folders under Folder1\n</code></pre>\n\n<p>To delete a folder and all its children:</p>\n\n<pre><code>DELETE FROM Folders WHERE ID='0004' AND ParentID LIKE '00000004%'\n</code></pre>\n\n<p>To move a folder and its children, you have to update all the records that use the same parent, to the new parent.</p>\n\n<blockquote>\n <p>And I don't want to linit the folders or the subfolders levels</p>\n</blockquote>\n\n<p>An obvious limitation to this is that the number of subfolders are limited to the size of your ParentID field.</p>\n"
},
{
"answer_id": 255851,
"author": "Cameron",
"author_id": 21475,
"author_profile": "https://Stackoverflow.com/users/21475",
"pm_score": 3,
"selected": false,
"text": "<p>I would look into using some sort of <a href=\"http://en.wikipedia.org/wiki/Tree_data_structure\" rel=\"nofollow noreferrer\">tree data structure</a></p>\n"
},
{
"answer_id": 256012,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": "<p>I know that the question is specifically asking for a data structure but...</p>\n\n<p>If you are using an object oriented language maybe you can use the composite design pattern which is ideally suited for this type of hierarchical tree like structure. You get what you are asking for.</p>\n"
},
{
"answer_id": 256032,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 0,
"selected": false,
"text": "<p>Most OO languages come with some sort of abstraction for the file system, so there is where I would start. Then subclass it if you need to.</p>\n\n<p>I would expect directories as an array of objects which are directories or files, for instance.</p>\n"
},
{
"answer_id": 2568242,
"author": "rohit",
"author_id": 307847,
"author_profile": "https://Stackoverflow.com/users/307847",
"pm_score": 0,
"selected": false,
"text": "<p>you can use m-way tree data structure</p>\n"
},
{
"answer_id": 19421946,
"author": "The Hun",
"author_id": 2688381,
"author_profile": "https://Stackoverflow.com/users/2688381",
"pm_score": 2,
"selected": false,
"text": "<p>I should recommend B+ Tree .... You can easily use indexing (page,folder etc ) and all .</p>\n\n<p><a href=\"http://commons.wikimedia.org/wiki/File:Btree.png\" rel=\"nofollow noreferrer\">B+ Tree http://commons.wikimedia.org/wiki/File:Btree.png</a></p>\n\n<p>for more info :\n<a href=\"http://ozark.hendrix.edu/~burch/cs/340/reading/btree/index.html\" rel=\"nofollow noreferrer\">http://ozark.hendrix.edu/~burch/cs/340/reading/btree/index.html</a></p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29276/"
] |
I'm making a program which the user build directories (not in windows, in my app) and in these folders there are subfolders and so on; every folder must contain either folders or documents. What is the best data structure to use? Notice that the user may select a subfolder and search for documents in it and in its subfolders. And I don't want to limit the folders or the subfolders levels.
|
This is what I do:
Every record in the database has two fields: ID and ParentID. IDs are 4-5 characters (Base36, a-z:0-9 or something similar). Parent IDs are a concatenation of the parent's complete structure...
So...
This structure:
```
Root
Folder1
Folder2
Folder3
Folder4
Folder5
Folder6
```
Would be represented like this:
```
ID ParentID Name
0000 NULL ROOT
0001 0000 Folder1
0002 0000 Folder2
0003 00000002 Folder3
0004 0000 Folder4
0005 00000004 Folder5
0006 000000040005 Folder6
```
I like this structure because if I need to find all the files under a folder I can do a query like:
```
SELECT * FROM Folders WHERE ParentID LIKE '0000%' -- to find all folders under Folder1
```
To delete a folder and all its children:
```
DELETE FROM Folders WHERE ID='0004' AND ParentID LIKE '00000004%'
```
To move a folder and its children, you have to update all the records that use the same parent, to the new parent.
>
> And I don't want to linit the folders or the subfolders levels
>
>
>
An obvious limitation to this is that the number of subfolders are limited to the size of your ParentID field.
|
255,815 |
<p>I have the following line:</p>
<pre><code>"14:48 say;0ed673079715c343281355c2a1fde843;2;laka;hello ;)"
</code></pre>
<p>I parse this by using a simple regexp:</p>
<pre><code>if($line =~ /(\d+:\d+)\ssay;(.*);(.*);(.*);(.*)/) {
my($ts, $hash, $pid, $handle, $quote) = ($1, $2, $3, $4, $5);
}
</code></pre>
<p>But the ; at the end messes things up and I don't know why. Shouldn't the greedy operator handle "everything"?</p>
|
[
{
"answer_id": 255827,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<p>Try making the first 3 <code>(.*)</code> ungreedy <code>(.*?)</code></p>\n"
},
{
"answer_id": 255832,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "<pre><code>(\\d+:\\d+)\\ssay;([^;]*);([^;]*);([^;]*);(.*)\n</code></pre>\n\n<p>should work better</p>\n"
},
{
"answer_id": 255839,
"author": "Barry Brown",
"author_id": 17312,
"author_profile": "https://Stackoverflow.com/users/17312",
"pm_score": 5,
"selected": true,
"text": "<p>The greedy operator tries to grab as much stuff as it can and still match the string. What's happening is the first one (after \"say\") grabs \"0ed673079715c343281355c2a1fde843;2\", the second one takes \"laka\", the third finds \"hello \" and the fourth matches the parenthesis.</p>\n\n<p>What you need to do is make all but the last one non-greedy, so they grab as little as possible and still match the string:</p>\n\n<pre><code>(\\d+:\\d+)\\ssay;(.*?);(.*?);(.*?);(.*)\n</code></pre>\n"
},
{
"answer_id": 255844,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 2,
"selected": false,
"text": "<p>You could make * non-greedy by appending a question mark:</p>\n\n<pre><code>$line =~ /(\\d+:\\d+)\\ssay;(.*?);(.*?);(.*?);(.*)/\n</code></pre>\n\n<p>or you can match everything except a semicolon in each part except the last:</p>\n\n<pre><code>$line =~ /(\\d+:\\d+)\\ssay;([^;]*);([^;]*);([^;]*);(.*)/\n</code></pre>\n"
},
{
"answer_id": 255882,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 3,
"selected": false,
"text": "<p>Although a regex can easily do this, I'm not sure it's the most straight-forward approach. It's probably the shortest, but that doesn't actually make it the most maintainable.</p>\n\n<p>Instead, I'd suggest something like this:</p>\n\n<pre><code>$x=\"14:48 say;0ed673079715c343281355c2a1fde843;2;laka;hello ;)\";\n\nif (($ts,$rest) = $x =~ /(\\d+:\\d+)\\s+(.*)/)\n{\n my($command,$hash,$pid,$handle,$quote) = split /;/, $rest, 5;\n print join \",\", map { \"[$_]\" } $ts,$command,$hash,$pid,$handle,$quote\n}\n</code></pre>\n\n<p>This results in:</p>\n\n<pre><code>[14:48],[say],[0ed673079715c343281355c2a1fde843],[2],[laka],[hello ;)]\n</code></pre>\n\n<p>I think this is just a bit more readable. Not only that, I think it's also easier to debug and maintain, because this is closer to how you would do it if a human were to attempt the same thing with pen and paper. Break the string down into chunks that you can then parse easier - have the computer do exactly what you would do. When it comes time to make modifications, I think this one will fare better. YMMV.</p>\n"
},
{
"answer_id": 256362,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 2,
"selected": false,
"text": "<p>If the values in your semicolon-delimited list cannot include any semicolons themselves, you'll get the most efficient and straightforward regular expression simply by spelling that out. If certain values can only be, say, a string of hex characters, spell that out. Solutions using a lazy or greedy dot will always lead to a lot of useless backtracking when the regex does not match the subject string.</p>\n\n<pre><code>(\\d+:\\d+)\\ssay;([a-f0-9]+);(\\d+);(\\w+);([^;\\r\\n]+)\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33232/"
] |
I have the following line:
```
"14:48 say;0ed673079715c343281355c2a1fde843;2;laka;hello ;)"
```
I parse this by using a simple regexp:
```
if($line =~ /(\d+:\d+)\ssay;(.*);(.*);(.*);(.*)/) {
my($ts, $hash, $pid, $handle, $quote) = ($1, $2, $3, $4, $5);
}
```
But the ; at the end messes things up and I don't know why. Shouldn't the greedy operator handle "everything"?
|
The greedy operator tries to grab as much stuff as it can and still match the string. What's happening is the first one (after "say") grabs "0ed673079715c343281355c2a1fde843;2", the second one takes "laka", the third finds "hello " and the fourth matches the parenthesis.
What you need to do is make all but the last one non-greedy, so they grab as little as possible and still match the string:
```
(\d+:\d+)\ssay;(.*?);(.*?);(.*?);(.*)
```
|
255,845 |
<p>I have some event handler on a boundary class that manages a persistence mechanism for a given generic transaction:</p>
<pre><code>void MyBoundaryClass::MyEventHandler(...)
{
//retrieve stuff from the UI
//...
//declare and initialize trasaction to persist
SimpleTransaction myTransaction(.../*pass down stuff*/);
//do some other checks
//...
//declare transaction persistor
TransactionPersistor myPersistor(myTransaction, .../*pass down connection to DB and other stuff*/);
//persist transaction
try
{
myPersistor.Persist();
}
catch(...)
{
//handle errors
}
}
</code></pre>
<p>Would it be better to have some kind of TransactionManager to wrap SimpleTransaction and TransactionPErsistor objects?</p>
<p>Is there any useful rule of thumb to understand if I need a further level of encapsulation? </p>
<p>At the moment the rule of thumb I follow is "if the method gets too big - do something about it". It is hard sometimes to find the right balance between procedural and object oriented when dealing with boundary event handlers.</p>
<p>Any opinion?</p>
<p>Cheers</p>
|
[
{
"answer_id": 255896,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "<p>Considering that:</p>\n\n<ul>\n<li>the <a href=\"https://stackoverflow.com/questions/99688/private-vs-public-members-in-practice-how-important-is-encapsulation#100035\">concept of encapsulation</a> is about defining a container, and </li>\n<li>object-oriented design is based on the concept of message passing (invocation of methods)</li>\n</ul>\n\n<p>I would argue that the <strong><em>API</em></strong> is a good indication about the pertinence of a new high-level encapsulation (I.e. the definition of a new object)</p>\n\n<p>If the services (i.e the API) offered by this new object are coherent, and are better exposed to the rest of the program when regrouped in one special object, then by all means, use a new object.</p>\n\n<p>Otherwise, it is probable an overkill.</p>\n\n<p>Since you expose a <strong><em>public</em></strong> API by creating a new object, the notion of <strong>test</strong> may be easier to do within that new object (and a few other <em>mock</em> objects), rather than create many legacy objects in order to test those same operations.</p>\n\n<p>In your case, if you want to test the transaction, you must actually test MyEventHandler of MyBoundaryClass, in order to retrieve data from the UI.</p>\n\n<p>But if you define a TransactionManager, that gives you the opportunity to <strong>lower coupling of different architecture levels</strong> (GUI vs. data) present in MyBoundaryClass, and to export data management into a dedicated class.<br>\nThen, you can test data persistence in independent test scenario, focusing especially on limit values, and database failure, and not-nominal conditions, and so on.</p>\n\n<p>Testing scenario can help you refine the <em>cohesion</em> (great point mentioned by <a href=\"https://stackoverflow.com/questions/255845/when-do-you-stop-encapsulating#255967\">Daok</a>) of your different objects. If your tests are simple and coherent, chances are that your objects have a well-define service boundary.</p>\n\n<p>Since it can be argued that <a href=\"http://javaboutique.internet.com/tutorials/coupcoh/\" rel=\"nofollow noreferrer\">Coupling and Cohesion are two cornerstones of OO Programming</a>, the cohesion of a new class like TransactionManager can be evaluated in term of the set of actions it will perform.</p>\n\n<blockquote>\n <p>Cohesive means that a certain class performs a set of closely related actions. A lack of cohesion, on the other hand, means that a class is performing several unrelated tasks. [...] the application software will eventually become unmanageable as more and more behaviors become scattered and end up in wrong places.</p>\n</blockquote>\n\n<p>If you regroup behaviors otherwise implemented in several different places into your TransactionManager, it should be fine, provided that its public API represent clear steps of what a transaction involves and not \"stuff about transaction\" like various utility functions. A name in itself is not enough to judge the cohesiveness of a class. The combination of the name and its public API is needed. </p>\n\n<p>For instance, one interesting aspect of a TransactionManager would be to completely encapsulate the notion of Transaction, which would :</p>\n\n<ul>\n<li>become virtually unkown by the rest f the system, and would lower coupling between the other classes and 'Transaction'</li>\n<li>reinforce the cohesiveness of TransactionManager by centering its API around transaction steps (like initTransaction(), persistTransaction(), ...), avoiding any getter or setter for any Transaction instance.</li>\n</ul>\n"
},
{
"answer_id": 255945,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 2,
"selected": false,
"text": "<p>Elaborating on VonC's suggestion, consider the following guidelines:</p>\n\n<ul>\n<li><p>If you expect to invoke the same functions elsewhere, in the same way, it's reasonable to encapsulate them in a new object.</p></li>\n<li><p>If one function (or one object) provides a set of facilities that are useful individually, it's reasonable to refactor it into smaller components.</p></li>\n</ul>\n\n<p>VonC's point about the API is an excellent litmus test: create effective <em>interfaces</em>, and the <em>objects</em> often become apparent.</p>\n"
},
{
"answer_id": 255967,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 1,
"selected": false,
"text": "<p>The level of encapsulating should be <strong>directly linked to the cohesion</strong> of your object. Your object must do a single task or must be divided in multiple class and encapsulate all its behaviors and properties.</p>\n\n<p><strong>A rule of thumb</strong> is when it's time to test your object. If you are doing Unit Testing and you realize that you are testing multiple different thing (not in the same area action) than you might try to split it up.</p>\n\n<p><strong>For you case</strong>, I would encapsulate with your idea of \"TransactionManager\". This way the \"TransactionManager\" will handle how transaction works and not \"MyBoundaryClass\".</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1311500/"
] |
I have some event handler on a boundary class that manages a persistence mechanism for a given generic transaction:
```
void MyBoundaryClass::MyEventHandler(...)
{
//retrieve stuff from the UI
//...
//declare and initialize trasaction to persist
SimpleTransaction myTransaction(.../*pass down stuff*/);
//do some other checks
//...
//declare transaction persistor
TransactionPersistor myPersistor(myTransaction, .../*pass down connection to DB and other stuff*/);
//persist transaction
try
{
myPersistor.Persist();
}
catch(...)
{
//handle errors
}
}
```
Would it be better to have some kind of TransactionManager to wrap SimpleTransaction and TransactionPErsistor objects?
Is there any useful rule of thumb to understand if I need a further level of encapsulation?
At the moment the rule of thumb I follow is "if the method gets too big - do something about it". It is hard sometimes to find the right balance between procedural and object oriented when dealing with boundary event handlers.
Any opinion?
Cheers
|
Considering that:
* the [concept of encapsulation](https://stackoverflow.com/questions/99688/private-vs-public-members-in-practice-how-important-is-encapsulation#100035) is about defining a container, and
* object-oriented design is based on the concept of message passing (invocation of methods)
I would argue that the ***API*** is a good indication about the pertinence of a new high-level encapsulation (I.e. the definition of a new object)
If the services (i.e the API) offered by this new object are coherent, and are better exposed to the rest of the program when regrouped in one special object, then by all means, use a new object.
Otherwise, it is probable an overkill.
Since you expose a ***public*** API by creating a new object, the notion of **test** may be easier to do within that new object (and a few other *mock* objects), rather than create many legacy objects in order to test those same operations.
In your case, if you want to test the transaction, you must actually test MyEventHandler of MyBoundaryClass, in order to retrieve data from the UI.
But if you define a TransactionManager, that gives you the opportunity to **lower coupling of different architecture levels** (GUI vs. data) present in MyBoundaryClass, and to export data management into a dedicated class.
Then, you can test data persistence in independent test scenario, focusing especially on limit values, and database failure, and not-nominal conditions, and so on.
Testing scenario can help you refine the *cohesion* (great point mentioned by [Daok](https://stackoverflow.com/questions/255845/when-do-you-stop-encapsulating#255967)) of your different objects. If your tests are simple and coherent, chances are that your objects have a well-define service boundary.
Since it can be argued that [Coupling and Cohesion are two cornerstones of OO Programming](http://javaboutique.internet.com/tutorials/coupcoh/), the cohesion of a new class like TransactionManager can be evaluated in term of the set of actions it will perform.
>
> Cohesive means that a certain class performs a set of closely related actions. A lack of cohesion, on the other hand, means that a class is performing several unrelated tasks. [...] the application software will eventually become unmanageable as more and more behaviors become scattered and end up in wrong places.
>
>
>
If you regroup behaviors otherwise implemented in several different places into your TransactionManager, it should be fine, provided that its public API represent clear steps of what a transaction involves and not "stuff about transaction" like various utility functions. A name in itself is not enough to judge the cohesiveness of a class. The combination of the name and its public API is needed.
For instance, one interesting aspect of a TransactionManager would be to completely encapsulate the notion of Transaction, which would :
* become virtually unkown by the rest f the system, and would lower coupling between the other classes and 'Transaction'
* reinforce the cohesiveness of TransactionManager by centering its API around transaction steps (like initTransaction(), persistTransaction(), ...), avoiding any getter or setter for any Transaction instance.
|
255,846 |
<p>I'm having a lot of issues with NSDate objects being prematurely deallocated. I suspect that the issues may be related to the way that I deal with the objects returned from NSDate convenience methods. I <em>think</em> that my showDate property declaration in the JKShow class should be "retain", but changing it to assign or copy seems to have no effect on the issue.</p>
<pre><code>JKShow *show;
NSDate *date;
NSMutableArray *list = [[NSMutableArray alloc] init];
// Show 1
show = [[JKShow alloc] init];
//...
date = [gregorian dateFromComponents:dateComponents];
show.showDate = date;
[list addObject:[show autorelease]];
// Show 2
show = [[JKShow alloc] init];
//...
date = [gregorian dateFromComponents:dateComponents];
show.showDate = date;
[list addObject:[show autorelease]];
</code></pre>
<p><em>UPDATE</em></p>
<p>The issue was not in the code copied here. In my <code>JKShow init</code> method I was not retaining the date returned from the <code>NSDate</code> convenience method. Thanks for your help, everyone.</p>
|
[
{
"answer_id": 255875,
"author": "philsquared",
"author_id": 32136,
"author_profile": "https://Stackoverflow.com/users/32136",
"pm_score": 2,
"selected": false,
"text": "<p>The date returned from dateFromComponents should be in the autorelease pool, so you are correct that your showDate property should be \"retain\". In fact it should be anyway (unless you specifically want \"copy\").</p>\n\n<p>From the code you have shown it looks like you are giving ownership of your show object entirely to the list (as you're setting autorelease on them as you add them). Are you saying that the date objects are being deallocated before the show objects are coming out of the list (or the list is being deallocated)?</p>\n\n<p>Also, are you using synthesised properties, or are you writing them by hand? If the latter, what is your setShowDate property method like?</p>\n\n<p>You can also try logging the retainCount of the date object at different places (although I always find that autorelease really complicates that).</p>\n"
},
{
"answer_id": 255890,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 2,
"selected": false,
"text": "<p>If showDate is a retain property that should be sufficient, given the code you have posted. Something else (probably in JKShow's implementation) may not be correct.</p>\n\n<p>If you want to figure out what is going on, you can use Instruments to see examine the objects lifespan. You need to run it with the allocation tool set to remember retains and releases. By default it is set up that way if you run the leaks performance tool.</p>\n\n<p>When you run Instruments like that it will record all object life spans, and the backtrace for every retain and release issued against them. If you look through the objects, find one of your dates, and look at all the retains and releases you should be able to determine where the spurious release is happening.</p>\n"
},
{
"answer_id": 255931,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 0,
"selected": false,
"text": "<p>The code you showed has no premature-release problems. In fact, it will leak the array and everything in it, because it doesn't release the array.</p>\n\n<p>Are you running with the garbage collector turned on?</p>\n\n<p>Is <code>list</code> an instance variable or static variable, or is it a local variable?</p>\n"
},
{
"answer_id": 255983,
"author": "kubi",
"author_id": 28422,
"author_profile": "https://Stackoverflow.com/users/28422",
"pm_score": 1,
"selected": true,
"text": "<p>I figured it out, thanks for all your help, but the problem was outside of the code I posted here. I was not retaining the <code>NSDate</code> I created in my init method. Unfortunatly the crash didn't occur until after I had created the two new <code>NSDate</code> objects, so I was totally barking up the wrong tree.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28422/"
] |
I'm having a lot of issues with NSDate objects being prematurely deallocated. I suspect that the issues may be related to the way that I deal with the objects returned from NSDate convenience methods. I *think* that my showDate property declaration in the JKShow class should be "retain", but changing it to assign or copy seems to have no effect on the issue.
```
JKShow *show;
NSDate *date;
NSMutableArray *list = [[NSMutableArray alloc] init];
// Show 1
show = [[JKShow alloc] init];
//...
date = [gregorian dateFromComponents:dateComponents];
show.showDate = date;
[list addObject:[show autorelease]];
// Show 2
show = [[JKShow alloc] init];
//...
date = [gregorian dateFromComponents:dateComponents];
show.showDate = date;
[list addObject:[show autorelease]];
```
*UPDATE*
The issue was not in the code copied here. In my `JKShow init` method I was not retaining the date returned from the `NSDate` convenience method. Thanks for your help, everyone.
|
I figured it out, thanks for all your help, but the problem was outside of the code I posted here. I was not retaining the `NSDate` I created in my init method. Unfortunatly the crash didn't occur until after I had created the two new `NSDate` objects, so I was totally barking up the wrong tree.
|
255,857 |
<p>I am trying to insert an image (jpg) in to a word document and the Selection.InlineShapes.AddPicture does not seem to be supported by win32old or I am doing something wrong. Has anyone had any luck inserting images. </p>
|
[
{
"answer_id": 258389,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 1,
"selected": false,
"text": "<p>Running on WinXP, Ruby 1.8.6, Word 2002/XP SP3, I recorded macros and translated them, as far as I could understand them, into this:</p>\n\n<pre><code>require 'win32ole'\n\nbegin\n word = WIN32OLE::new('Word.Application') # create winole Object\n doc = word.Documents.Add\n word.Selection.InlineShapes.AddPicture \"C:\\\\pictures\\\\some_picture.jpg\", false, true\n word.ChangeFileOpenDirectory \"C:\\\\docs\\\\\"\n doc.SaveAs \"doc_with_pic.doc\"\n word.Quit\nrescue Exception => e\n puts e\n word.Quit\nensure\n word.Quit unless word.nil?\nend\n</code></pre>\n\n<p>It seems to work. Any use?</p>\n"
},
{
"answer_id": 1326313,
"author": "RubyDubee",
"author_id": 157324,
"author_profile": "https://Stackoverflow.com/users/157324",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this by calling the Document.InlineShapes.AddPicture() method.</p>\n\n<p>The following example inserts an image into the active document, before the second sentence.</p>\n\n<pre><code> require 'win32ole'\n\n word = WIN32OLE.connect('Word.Application')\n doc = word.ActiveDocument\n\n image = 'C:\\MyImage.jpg'\n range = doc.Sentences(2)\n\n params = { 'FileName' => image, 'LinkToFile' => false, \n 'SaveWithDocument' => true, 'Range' => range }\n\n pic = doc.InlineShapes.AddPicture( params )\n</code></pre>\n\n<p>Documentation on the AddPicture() method can be found <a href=\"http://msdn.microsoft.com/en-us/library/bb148763.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Additional details on automating Word with Ruby can be found <a href=\"http://rubyonwindows.blogspot.com/search/label/word\" rel=\"nofollow noreferrer\">here</a>.<br></p>\n\n<p>This is the answer by David Mullet and can be found <a href=\"https://stackoverflow.com/questions/1316162/insert-image-in-doc-using-win32ole-library-of-ruby\">here</a></p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to insert an image (jpg) in to a word document and the Selection.InlineShapes.AddPicture does not seem to be supported by win32old or I am doing something wrong. Has anyone had any luck inserting images.
|
You can do this by calling the Document.InlineShapes.AddPicture() method.
The following example inserts an image into the active document, before the second sentence.
```
require 'win32ole'
word = WIN32OLE.connect('Word.Application')
doc = word.ActiveDocument
image = 'C:\MyImage.jpg'
range = doc.Sentences(2)
params = { 'FileName' => image, 'LinkToFile' => false,
'SaveWithDocument' => true, 'Range' => range }
pic = doc.InlineShapes.AddPicture( params )
```
Documentation on the AddPicture() method can be found [here](http://msdn.microsoft.com/en-us/library/bb148763.aspx).
Additional details on automating Word with Ruby can be found [here](http://rubyonwindows.blogspot.com/search/label/word).
This is the answer by David Mullet and can be found [here](https://stackoverflow.com/questions/1316162/insert-image-in-doc-using-win32ole-library-of-ruby)
|
255,862 |
<p>Netbeans is great but there's no way to wrap text in it (or hopefully I haven't found it yet). Is there any way to do this, and if not, is there any similarly good IDE for Java with this functionality (hopefully free as well).</p>
|
[
{
"answer_id": 527471,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Except Eclipse does not support word wrap either, and they even don't have set up a target for this. Just like Netbeans, this has been asked by many users, but was never included. It appears it requires much change, and as well does not seem to be a high priority for devs.\nThere was once a beginning of a plugin trying to word wrap in a limited way, but of course it does not work on recent versions.</p>\n"
},
{
"answer_id": 585405,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>There's word-wrap eclipse plugin: see <a href=\"http://ahtik.com/blog/eclipse-word-wrap/\" rel=\"nofollow noreferrer\">http://ahtik.com/blog/eclipse-word-wrap/</a></p>\n"
},
{
"answer_id": 684258,
"author": "Joseph Burley",
"author_id": 60723,
"author_profile": "https://Stackoverflow.com/users/60723",
"pm_score": 0,
"selected": false,
"text": "<p>When you get to where you want the line to end, just start a new line without ending the statement. It may underline it in red until you end the statement, but it won't cause any exceptions. </p>\n\n<p>I find that it is also a good way to organize long println() statements.</p>\n"
},
{
"answer_id": 684626,
"author": "Jeroen van Bergen",
"author_id": 15155,
"author_profile": "https://Stackoverflow.com/users/15155",
"pm_score": 1,
"selected": false,
"text": "<p>Like Joseph said: why would you need this. Java is not white space sensitive and having very long statements does not make your code easy to read.</p>\n"
},
{
"answer_id": 687591,
"author": "Sarel Botha",
"author_id": 35264,
"author_profile": "https://Stackoverflow.com/users/35264",
"pm_score": -1,
"selected": false,
"text": "<p>Get a bigger monitor. </p>\n\n<p>At 1920 x 1080 you don't need no steenkin word-wrap.</p>\n\n<p><strong>Update:</strong>\nWow, still getting downvotes. Maybe it's just how I said it. At least it hasn't caught up to the Eclipse answer yet. </p>\n\n<p>I really thought this was a legitimate suggestion. I never thought that having a bigger monitor would make as much of a difference to coding as it has for me. If you're using a small monitor to code please consider getting a nice big new one. It does eliminate the need for word wrap in a lot of cases.</p>\n"
},
{
"answer_id": 827459,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>It always goes back to Ultraedit.</p>\n\n<p>Why can't we as a human race figure this out? netbeans, eclipse, zend studio (eclipse), etc don't do something very simple for programming, that most programmers -need to have- to keep a sound coding convention. Sure, it's true that coding style contributes to length of lines (erm microsoft programmers, perk your ears), but sometimes one cannot avoid long string literals. This is insanity! And yet I can't be mad or ungrateful because it's open source. And i -am- grateful. Still, one has to wonder wtf programmers who make these editors are actually using themselves.</p>\n\n<p>I want an editor to wrap at column 80 or 120, not at the window's edge like notepad++. The only tool I've found that does hard/soft wrapping is ultraedit, so maybe I should try to see if I can get it to run under wine, since UE is the only 'real' editor that does it's job other than something weird / ugly / takes forever to learn and configure like emacs. And I am not going down that road- it gives me migranes to look at it because it's 2009 and we have cleartext and guis.</p>\n\n<p>Is it really that difficult a problem to solve? If you draw a line down from column x and your word crosses over it, then put the beginning of the word under the indention of the line from which it started and mark the spill over row as a wrap row. Done.</p>\n"
},
{
"answer_id": 1550965,
"author": "Darrell",
"author_id": 187993,
"author_profile": "https://Stackoverflow.com/users/187993",
"pm_score": 0,
"selected": false,
"text": "<p>Komodo Edit. In addition to its many other marvelous features, it actually wraps lines.</p>\n"
},
{
"answer_id": 2421507,
"author": "domi",
"author_id": 291044,
"author_profile": "https://Stackoverflow.com/users/291044",
"pm_score": 0,
"selected": false,
"text": "<p>2 points:</p>\n\n<ul>\n<li><p>Just found that wrapping is really needed if one wants to look into those damn SVG sources auto-generated when putting components from SVG palette...</p></li>\n<li><p>I'm going to solve my current problem with seeing full SVG source by copy-paste to jEdit which is as configurable as Ultraedit (in the aspect of wrapping) and FoC!</p></li>\n</ul>\n"
},
{
"answer_id": 3104531,
"author": "webdev",
"author_id": 374548,
"author_profile": "https://Stackoverflow.com/users/374548",
"pm_score": 4,
"selected": false,
"text": "<p>If you do web development you are going to understand why text wrapping is important. </p>\n\n<p>A programmer who has never gotten their hands dirty with HTML has never seen the real web. You can insist on MVC all you want to but 99.9% of the world wide web since its inception wasn't built that way. Unless you're always developing from a clean slate and can use MVC to separate the HTML out AND assuming you have an on-staff web designer who does html/css/javascript or you have an interface developer who you can fob it off on you WILL have to deal with everything that has been developed/kludged/hacked together with what ever technologies were at hand or popular or affordable at the time and now more or less functions as a 'web application'. And 99.9% of the time what you will have to work with is a mix of some kind of a programming language, most likely an interpreted one, with html and javascript all mixed in the same page. </p>\n\n<p>And this means no nice short lines of neat clean java code that oh so conveniently end before 80 characters.</p>\n\n<p>And when you deal with this -- which, dear hearts, is most of the web -- you magically discover the crying need for text wrapping to keep the long lines from making you scroll waaaay to the right to get to the end of it.</p>\n\n<p>Some people. Sheesh. They think the whole universe of development has always fit on 80 characters per line, and from some of these comments, they seem to think it always will.</p>\n"
},
{
"answer_id": 3486312,
"author": "CoCoMo",
"author_id": 401842,
"author_profile": "https://Stackoverflow.com/users/401842",
"pm_score": 1,
"selected": false,
"text": "<p>Actually i heard netbeans is going to add word wrap feature in 6.7 release but then they decided to include this feature in 7.0 . hopefully we would see word wrap in the next release, according to few developers this isn't a necessary feature but for web developers this is totally needed. </p>\n"
},
{
"answer_id": 3839708,
"author": "Josh",
"author_id": 450668,
"author_profile": "https://Stackoverflow.com/users/450668",
"pm_score": 0,
"selected": false,
"text": "<p>As many have already noted, the answer is \"you can't.\" As someone who uses Visual Studio and Eclipse-based products every day, when I am using Eclipse, I am constantly missing Visual Studio's line wrapping features, which I can turn on and off with a keystroke.</p>\n\n<p>To the many people who have responded \"you don't need this,\" stop being so condescending. Simply because you don't need a feature doesn't mean nobody else in the world does. Even if one were to religiously follow the advice \"never have a line over 80 characters,\" you're going to need to edit code that others have composed and goes over 80 chars. And especially in the web-world, lines can get tremendously long. It's inevitable that you'll spend a lot of time looking at other people's code that goes way over 80 chars.</p>\n\n<p>jEdit's line wrapping is very good. It preserves indentation and can be turned on an off very quickly. If I'm dealing with some very unwieldy long lines, I sometimes copy/paste in jEdit (which offers syntax highlighting for a myriad of languages) and use the line wrapping available there.</p>\n"
},
{
"answer_id": 4059100,
"author": "Sidarta",
"author_id": 269056,
"author_profile": "https://Stackoverflow.com/users/269056",
"pm_score": 6,
"selected": false,
"text": "<p>You can use word wrap in Netbeans.</p>\n\n<p>Add the following to netbeans.conf (netbeans_installation_path/etc/netbeans.conf, by default /etc/netbeans.conf under linux):</p>\n\n<pre><code>-J-Dorg.netbeans.editor.linewrap=true\n</code></pre>\n\n<p>to the sixth line so it looks like this:</p>\n\n<pre><code>netbeans_default_options=\"-J-client -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-XX:MaxPermSize=200m -J-Dapple.laf.useScreenMenuBar=true -J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true -J-Dorg.netbeans.editor.linewrap=true\"\n</code></pre>\n\n<p>and restart Netbeans.</p>\n\n<p>Set the <strong>Line Wrap</strong> option in Tools->Options->Editor->Formating.</p>\n\n<p>Works fine for me in Netbeans 6.9 and 7</p>\n"
},
{
"answer_id": 4975838,
"author": "Hoffa",
"author_id": 613852,
"author_profile": "https://Stackoverflow.com/users/613852",
"pm_score": 1,
"selected": false,
"text": "<p>There is a great solution to this at this website <a href=\"http://blog.robbychen.com/2010/04/26/enable-line-wrap-option-in-netbeans-nightly/\" rel=\"nofollow\">blog.robbychen.com</a></p>\n\n<p>The jist is to add the following line inside the quotes for netbeans_default_options inside the config file then restart netbeans:</p>\n\n<pre><code>-J-Dorg.netbeans.editor.linewrap=true\n</code></pre>\n"
},
{
"answer_id": 5898935,
"author": "Sarel Botha",
"author_id": 35264,
"author_profile": "https://Stackoverflow.com/users/35264",
"pm_score": 2,
"selected": false,
"text": "<p>Netbeans 7 is out and it supports word wrap out of the box!</p>\n"
},
{
"answer_id": 8841919,
"author": "Daniel",
"author_id": 884550,
"author_profile": "https://Stackoverflow.com/users/884550",
"pm_score": 0,
"selected": false,
"text": "<p>The new version of Netbeans supports it. See this post for instructions:</p>\n\n<p><a href=\"http://www.ozonesolutions.com/programming/2012/01/wordwrap-in-netbeans/\" rel=\"nofollow\">Word Wrap in Netbeans</a></p>\n"
},
{
"answer_id": 12350804,
"author": "bailey86",
"author_id": 450406,
"author_profile": "https://Stackoverflow.com/users/450406",
"pm_score": 0,
"selected": false,
"text": "<p>Of course word wrap is useful for coders - what about when you're writing README.txt files and you have to stick to coding standards like <a href=\"http://drupal.org/node/161085\" rel=\"nofollow\">http://drupal.org/node/161085</a> where is says there needs to be an 80 character word wrap.</p>\n"
},
{
"answer_id": 16510452,
"author": "Brandon Dewey",
"author_id": 1965708,
"author_profile": "https://Stackoverflow.com/users/1965708",
"pm_score": 0,
"selected": false,
"text": "<p>In netbeans 7.3 you go to tools->options->editor->formatting, in the left menu area select the bottom most drop down that says line wrap, select your preference...done</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Netbeans is great but there's no way to wrap text in it (or hopefully I haven't found it yet). Is there any way to do this, and if not, is there any similarly good IDE for Java with this functionality (hopefully free as well).
|
You can use word wrap in Netbeans.
Add the following to netbeans.conf (netbeans\_installation\_path/etc/netbeans.conf, by default /etc/netbeans.conf under linux):
```
-J-Dorg.netbeans.editor.linewrap=true
```
to the sixth line so it looks like this:
```
netbeans_default_options="-J-client -J-Xss2m -J-Xms32m -J-XX:PermSize=32m -J-XX:MaxPermSize=200m -J-Dapple.laf.useScreenMenuBar=true -J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true -J-Dorg.netbeans.editor.linewrap=true"
```
and restart Netbeans.
Set the **Line Wrap** option in Tools->Options->Editor->Formating.
Works fine for me in Netbeans 6.9 and 7
|
255,876 |
<p>I want to make an MVC route for a list of news, which can be served in several formats.</p>
<ul>
<li>news -> (X)HTML</li>
<li>news.rss -> RSS</li>
<li>news.atom -> ATOM</li>
</ul>
<p>Is it possible to do this (the more general "optional extension" situation crops up in several places in my planned design) with one route? Or do I need to make two routes like this:</p>
<pre><code>routes.MapRoute("News-ImplicitFormat",
"news",
new { controller = "News", action = "Browse", format = "" });
routes.MapRoute("News-ExplicitFormat",
"news.{format}"
new { controller = "News", action = "Browse" });
</code></pre>
<p>It seems like it would be useful to have the routing system support something like:</p>
<pre><code>routes.MapRoute("News",
"news(.{format})?",
new { controller = "News", action = "Browse" });
</code></pre>
|
[
{
"answer_id": 255880,
"author": "Doug McClean",
"author_id": 11173,
"author_profile": "https://Stackoverflow.com/users/11173",
"pm_score": 5,
"selected": true,
"text": "<p>I made a method to support adding pairs like this as follows:</p>\n\n<pre><code>public static void MapRouteWithOptionalFormat(this RouteCollection routes,\n string name,\n string url,\n object defaults)\n{\n Route implicitRoute = routes.MapRoute(name + \"-ImplicitFormat\",\n url,\n defaults);\n implicitRoute.Defaults.Add(\"format\", string.Empty);\n\n Route explicitRoute = routes.MapRoute(name + \"-ExplicitFormat\",\n url + \".{format}\",\n defaults);\n}\n</code></pre>\n"
},
{
"answer_id": 257028,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 0,
"selected": false,
"text": "<p>You can look into using constraints to make this work with normal routes.</p>\n\n<p>UPDATE: actually, I misread the question. The other answer is the correct thing to do for now. Or create a custom route. We're looking at the idea of optional segments as a possible future feature.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11173/"
] |
I want to make an MVC route for a list of news, which can be served in several formats.
* news -> (X)HTML
* news.rss -> RSS
* news.atom -> ATOM
Is it possible to do this (the more general "optional extension" situation crops up in several places in my planned design) with one route? Or do I need to make two routes like this:
```
routes.MapRoute("News-ImplicitFormat",
"news",
new { controller = "News", action = "Browse", format = "" });
routes.MapRoute("News-ExplicitFormat",
"news.{format}"
new { controller = "News", action = "Browse" });
```
It seems like it would be useful to have the routing system support something like:
```
routes.MapRoute("News",
"news(.{format})?",
new { controller = "News", action = "Browse" });
```
|
I made a method to support adding pairs like this as follows:
```
public static void MapRouteWithOptionalFormat(this RouteCollection routes,
string name,
string url,
object defaults)
{
Route implicitRoute = routes.MapRoute(name + "-ImplicitFormat",
url,
defaults);
implicitRoute.Defaults.Add("format", string.Empty);
Route explicitRoute = routes.MapRoute(name + "-ExplicitFormat",
url + ".{format}",
defaults);
}
```
|
255,879 |
<p>I need some help with WPF binding syntax:</p>
<pre><code>public class ApplicationPresenter
{
public ObservableCollection<Quotes> PriceList {get;}
}
public class WebSitePricesView
{
private IApplicationPresenter presenter
{
get { return (ApplicationPresenter)DataContext; }
}
// public ObservableCollection<Quotes> PriceList
// {
// get {return presenter.PriceList; }
}
}
</code></pre>
<p>This XAML works fine:</p>
<pre><code><UserControl.Resources>
<ObjectDataProvider x:Key="ApplicationPresenterDS" ObjectType="{x:Type local:ApplicationPresenter}" />
<xcdg:DataGridCollectionViewSource x:Key="price_list" Source="{Binding Path=PriceList} />
</UserControl.Resources>
<xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource price_list}} />
</code></pre>
<p>However I don't want WebSitePricesView to expose PriceList, I want to bind the DataGridCollectionViewSource directly to ApplicationPresenter.PriceList.</p>
<p>This XAML doesn't bind any values to the grid. Obviously I'm doing something wrong in defining the Binding Source for price_list .....</p>
<pre><code><UserControl.Resources>
<ObjectDataProvider x:Key="ApplicationPresenterDS" ObjectType="{x:Type local:ApplicationPresenter}" />
<xcdg:DataGridCollectionViewSource x:Key="price_list" Source="{Binding Source={StaticResource ApplicationPresenterDS}, Path=PriceList />
</UserControl.Resources>
<xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource price_list}} />
</code></pre>
<p>The debug output for the first successful binding is:</p>
<pre><code>Step into: Stepping over method without symbols 'Fenix.App.App'
System.Windows.Data Warning: 52 : Created BindingExpression (hash=35059110) for Binding (hash=15586314)
System.Windows.Data Warning: 54 : Path: 'PriceList'
System.Windows.Data Warning: 56 : BindingExpression (hash=35059110): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=35059110): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=35059110): Attach to Xceed.Wpf.DataGrid.DataGridCollectionViewSource.Source (hash=28137373)
System.Windows.Data Warning: 60 : BindingExpression (hash=35059110): Use Framework mentor <null>
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 65 : BindingExpression (hash=35059110): Framework mentor not found
System.Windows.Data Warning: 61 : BindingExpression (hash=35059110): Resolve source deferred
System.Windows.Data Warning: 91 : BindingExpression (hash=35059110): Got InheritanceContextChanged event from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: WebSitePricesXc (hash=11090012) (OK)
System.Windows.Data Warning: 67 : BindingExpression (hash=35059110): DataContext is null
System.Windows.Data Warning: 52 : Created BindingExpression (hash=53154844) for Binding (hash=52037308)
System.Windows.Data Warning: 54 : Path: ''
System.Windows.Data Warning: 56 : BindingExpression (hash=53154844): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=53154844): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=53154844): Attach to Xceed.Wpf.DataGrid.DataGridControl.ItemsSource (hash=16991442)
System.Windows.Data Warning: 63 : BindingExpression (hash=53154844): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=53154844): Found data context element: <null> (OK)
System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item <null>
System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with <null>, using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from <null> using <null>: <null>
System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value <null>
System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value <null>
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: WebSitePricesXc (hash=11090012) (OK)
System.Windows.Data Warning: 74 : BindingExpression (hash=35059110): Activate with root item ApplicationPresenter (hash=22260412)
System.Windows.Data Warning: 104 : BindingExpression (hash=35059110): At level 0 - for ApplicationPresenter.PriceList found accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 100 : BindingExpression (hash=35059110): Replace item at level 0 with ApplicationPresenter (hash=22260412), using accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=22260412) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=40261689 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=40261689 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=40261689 Count=0)
System.Windows.Data Warning: 92 : BindingExpression (hash=53154844): Got PropertyChanged event from DataGridCollectionViewSource (hash=28137373) for View
System.Windows.Data Warning: 75 : BindingExpression (hash=53154844): Deactivate
System.Windows.Data Warning: 99 : BindingExpression (hash=53154844): Replace item at level 0 with {NullDataItem}
System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with DataGridCollectionView (hash=22444475 Count=0), using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from DataGridCollectionView (hash=22444475 Count=0) using <null>: DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 91 : BindingExpression (hash=35059110): Got PropertyChanged event from ApplicationPresenter (hash=22260412)
System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=22260412) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=6408547 Count=27)
System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=6408547 Count=27)
System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=6408547 Count=27)
System.Windows.Data Warning: 92 : BindingExpression (hash=53154844): Got PropertyChanged event from DataGridCollectionViewSource (hash=28137373) for View
System.Windows.Data Warning: 75 : BindingExpression (hash=53154844): Deactivate
System.Windows.Data Warning: 99 : BindingExpression (hash=53154844): Replace item at level 0 with {NullDataItem}
System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item DataGridCollectionView (hash=61423861 Count=27)
System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with DataGridCollectionView (hash=61423861 Count=27), using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from DataGridCollectionView (hash=61423861 Count=27) using <null>: DataGridCollectionView (hash=61423861 Count=27)
System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value DataGridCollectionView (hash=61423861 Count=27)
System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value DataGridCollectionView (hash=61423861 Count=27)
</code></pre>
<p>The debug output for the second binding is:</p>
<pre><code>Step into: Stepping over method without symbols 'Fenix.App.App'
System.Windows.Data Warning: 52 : Created BindingExpression (hash=35059110) for Binding (hash=15586314)
System.Windows.Data Warning: 54 : Path: 'PriceList'
System.Windows.Data Warning: 56 : BindingExpression (hash=35059110): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=35059110): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=35059110): Attach to Xceed.Wpf.DataGrid.DataGridCollectionViewSource.Source (hash=28137373)
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: <null> (OK)
System.Windows.Data Warning: 73 : BindingExpression (hash=35059110): Use Data from ObjectDataProvider (hash=61302538)
System.Windows.Data Warning: 74 : BindingExpression (hash=35059110): Activate with root item ApplicationPresenter (hash=20390146)
System.Windows.Data Warning: 104 : BindingExpression (hash=35059110): At level 0 - for ApplicationPresenter.PriceList found accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 100 : BindingExpression (hash=35059110): Replace item at level 0 with ApplicationPresenter (hash=20390146), using accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=20390146) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=12781633 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=12781633 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=12781633 Count=0)
System.Windows.Data Warning: 52 : Created BindingExpression (hash=12661120) for Binding (hash=31408037)
System.Windows.Data Warning: 54 : Path: ''
System.Windows.Data Warning: 56 : BindingExpression (hash=12661120): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=12661120): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=12661120): Attach to Xceed.Wpf.DataGrid.DataGridControl.ItemsSource (hash=16991442)
System.Windows.Data Warning: 63 : BindingExpression (hash=12661120): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=12661120): Found data context element: <null> (OK)
System.Windows.Data Warning: 72 : BindingExpression (hash=12661120): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=12661120): Activate with root item DataGridCollectionView (hash=49343907 Count=0)
System.Windows.Data Warning: 100 : BindingExpression (hash=12661120): Replace item at level 0 with DataGridCollectionView (hash=49343907 Count=0), using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=12661120): GetValue at level 0 from DataGridCollectionView (hash=49343907 Count=0) using <null>: Data``GridCollectionView (hash=49343907 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=12661120): TransferValue - got raw value DataGridCollectionView (hash=49343907 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=12661120): TransferValue - using final value DataGridCollectionView (hash=49343907 Count=0)
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
</code></pre>
|
[
{
"answer_id": 256249,
"author": "Ian Oakes",
"author_id": 21606,
"author_profile": "https://Stackoverflow.com/users/21606",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure what your problem is, the bindings (apart from the missing end quotes) appear to be fine. The following code works fine for me.</p>\n\n<pre><code>public class Quotes\n{\n public string Description { get; set; }\n public decimal Value { get; set; }\n}\n\npublic class ApplicationPresenter\n{\n public ApplicationPresenter()\n {\n PriceList = new ObservableCollection<Quotes>()\n {\n new Quotes(){Description=\"Quote One\", Value=10m},\n new Quotes(){Description=\"Quote Two\", Value=10m},\n new Quotes(){Description=\"Quote Three\", Value=10m},\n new Quotes(){Description=\"Quote Four\", Value=10m},\n };\n }\n public ObservableCollection<Quotes> PriceList { get; private set; }\n}\n\n<Window \n x:Class=\"ObjectDataProviderPresenterSample.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:xcdg=\"http://schemas.xceed.com/wpf/xaml/datagrid\"\n xmlns:local=\"clr-namespace:ObjectDataProviderPresenterSample\"\n Title=\"Window1\" \n Height=\"300\" \n Width=\"300\" \n >\n <Window.Resources>\n <ObjectDataProvider \n x:Key=\"ApplicationPresenterDS\" \n ObjectType=\"{x:Type local:ApplicationPresenter}\" \n />\n <xcdg:DataGridCollectionViewSource \n x:Key=\"price_list\" \n Source=\"{Binding \n Source={StaticResource ApplicationPresenterDS}, \n Path=PriceList}\" \n /> \n </Window.Resources> \n\n <Grid>\n <xcdg:DataGridControl ItemsSource=\"{Binding Source={StaticResource price_list}}\" />\n </Grid>\n</Window>\n</code></pre>\n"
},
{
"answer_id": 264631,
"author": "user34577",
"author_id": 34577,
"author_profile": "https://Stackoverflow.com/users/34577",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure, since it is not very clear from your code where data go to PriceList, but what I see is that this collection is just empty in second xaml.</p>\n\n<p>Creating ObjectDataProvider in xaml in both cases just creates object of type ApplicationPresenter through default constructor. Your constructor creates empty collection PriceList. (Ian's constructor creates PriceList AND fills it with fake data. That's why his example works).</p>\n\n<p>So, DataGridCollectionViewSource in second xaml of your example basically refers to ApplicationPresenter with empty PriceList.</p>\n\n<p>The first xaml, in contrast, refers to PriceList of WebSitePricesView which, I believe, somehow is filled somewehere outside given slice of code.</p>\n\n<p>If my theory is good, the removal of ObjectDataProvider from the first xaml won't cange anything - it sill will be working, because data goes directly to presenter.PriceList.</p>\n\n<p>But, again, I am not sure. </p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30046/"
] |
I need some help with WPF binding syntax:
```
public class ApplicationPresenter
{
public ObservableCollection<Quotes> PriceList {get;}
}
public class WebSitePricesView
{
private IApplicationPresenter presenter
{
get { return (ApplicationPresenter)DataContext; }
}
// public ObservableCollection<Quotes> PriceList
// {
// get {return presenter.PriceList; }
}
}
```
This XAML works fine:
```
<UserControl.Resources>
<ObjectDataProvider x:Key="ApplicationPresenterDS" ObjectType="{x:Type local:ApplicationPresenter}" />
<xcdg:DataGridCollectionViewSource x:Key="price_list" Source="{Binding Path=PriceList} />
</UserControl.Resources>
<xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource price_list}} />
```
However I don't want WebSitePricesView to expose PriceList, I want to bind the DataGridCollectionViewSource directly to ApplicationPresenter.PriceList.
This XAML doesn't bind any values to the grid. Obviously I'm doing something wrong in defining the Binding Source for price\_list .....
```
<UserControl.Resources>
<ObjectDataProvider x:Key="ApplicationPresenterDS" ObjectType="{x:Type local:ApplicationPresenter}" />
<xcdg:DataGridCollectionViewSource x:Key="price_list" Source="{Binding Source={StaticResource ApplicationPresenterDS}, Path=PriceList />
</UserControl.Resources>
<xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource price_list}} />
```
The debug output for the first successful binding is:
```
Step into: Stepping over method without symbols 'Fenix.App.App'
System.Windows.Data Warning: 52 : Created BindingExpression (hash=35059110) for Binding (hash=15586314)
System.Windows.Data Warning: 54 : Path: 'PriceList'
System.Windows.Data Warning: 56 : BindingExpression (hash=35059110): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=35059110): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=35059110): Attach to Xceed.Wpf.DataGrid.DataGridCollectionViewSource.Source (hash=28137373)
System.Windows.Data Warning: 60 : BindingExpression (hash=35059110): Use Framework mentor <null>
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 65 : BindingExpression (hash=35059110): Framework mentor not found
System.Windows.Data Warning: 61 : BindingExpression (hash=35059110): Resolve source deferred
System.Windows.Data Warning: 91 : BindingExpression (hash=35059110): Got InheritanceContextChanged event from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: WebSitePricesXc (hash=11090012) (OK)
System.Windows.Data Warning: 67 : BindingExpression (hash=35059110): DataContext is null
System.Windows.Data Warning: 52 : Created BindingExpression (hash=53154844) for Binding (hash=52037308)
System.Windows.Data Warning: 54 : Path: ''
System.Windows.Data Warning: 56 : BindingExpression (hash=53154844): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=53154844): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=53154844): Attach to Xceed.Wpf.DataGrid.DataGridControl.ItemsSource (hash=16991442)
System.Windows.Data Warning: 63 : BindingExpression (hash=53154844): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=53154844): Found data context element: <null> (OK)
System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item <null>
System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with <null>, using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from <null> using <null>: <null>
System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value <null>
System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value <null>
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: WebSitePricesXc (hash=11090012) (OK)
System.Windows.Data Warning: 74 : BindingExpression (hash=35059110): Activate with root item ApplicationPresenter (hash=22260412)
System.Windows.Data Warning: 104 : BindingExpression (hash=35059110): At level 0 - for ApplicationPresenter.PriceList found accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 100 : BindingExpression (hash=35059110): Replace item at level 0 with ApplicationPresenter (hash=22260412), using accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=22260412) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=40261689 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=40261689 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=40261689 Count=0)
System.Windows.Data Warning: 92 : BindingExpression (hash=53154844): Got PropertyChanged event from DataGridCollectionViewSource (hash=28137373) for View
System.Windows.Data Warning: 75 : BindingExpression (hash=53154844): Deactivate
System.Windows.Data Warning: 99 : BindingExpression (hash=53154844): Replace item at level 0 with {NullDataItem}
System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with DataGridCollectionView (hash=22444475 Count=0), using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from DataGridCollectionView (hash=22444475 Count=0) using <null>: DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value DataGridCollectionView (hash=22444475 Count=0)
System.Windows.Data Warning: 91 : BindingExpression (hash=35059110): Got PropertyChanged event from ApplicationPresenter (hash=22260412)
System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=22260412) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=6408547 Count=27)
System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=6408547 Count=27)
System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=6408547 Count=27)
System.Windows.Data Warning: 92 : BindingExpression (hash=53154844): Got PropertyChanged event from DataGridCollectionViewSource (hash=28137373) for View
System.Windows.Data Warning: 75 : BindingExpression (hash=53154844): Deactivate
System.Windows.Data Warning: 99 : BindingExpression (hash=53154844): Replace item at level 0 with {NullDataItem}
System.Windows.Data Warning: 72 : BindingExpression (hash=53154844): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=53154844): Activate with root item DataGridCollectionView (hash=61423861 Count=27)
System.Windows.Data Warning: 100 : BindingExpression (hash=53154844): Replace item at level 0 with DataGridCollectionView (hash=61423861 Count=27), using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=53154844): GetValue at level 0 from DataGridCollectionView (hash=61423861 Count=27) using <null>: DataGridCollectionView (hash=61423861 Count=27)
System.Windows.Data Warning: 76 : BindingExpression (hash=53154844): TransferValue - got raw value DataGridCollectionView (hash=61423861 Count=27)
System.Windows.Data Warning: 85 : BindingExpression (hash=53154844): TransferValue - using final value DataGridCollectionView (hash=61423861 Count=27)
```
The debug output for the second binding is:
```
Step into: Stepping over method without symbols 'Fenix.App.App'
System.Windows.Data Warning: 52 : Created BindingExpression (hash=35059110) for Binding (hash=15586314)
System.Windows.Data Warning: 54 : Path: 'PriceList'
System.Windows.Data Warning: 56 : BindingExpression (hash=35059110): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=35059110): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=35059110): Attach to Xceed.Wpf.DataGrid.DataGridCollectionViewSource.Source (hash=28137373)
System.Windows.Data Warning: 63 : BindingExpression (hash=35059110): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=35059110): Found data context element: <null> (OK)
System.Windows.Data Warning: 73 : BindingExpression (hash=35059110): Use Data from ObjectDataProvider (hash=61302538)
System.Windows.Data Warning: 74 : BindingExpression (hash=35059110): Activate with root item ApplicationPresenter (hash=20390146)
System.Windows.Data Warning: 104 : BindingExpression (hash=35059110): At level 0 - for ApplicationPresenter.PriceList found accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 100 : BindingExpression (hash=35059110): Replace item at level 0 with ApplicationPresenter (hash=20390146), using accessor RuntimePropertyInfo(PriceList)
System.Windows.Data Warning: 97 : BindingExpression (hash=35059110): GetValue at level 0 from ApplicationPresenter (hash=20390146) using RuntimePropertyInfo(PriceList): ObservableCollection`1 (hash=12781633 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=35059110): TransferValue - got raw value ObservableCollection`1 (hash=12781633 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=35059110): TransferValue - using final value ObservableCollection`1 (hash=12781633 Count=0)
System.Windows.Data Warning: 52 : Created BindingExpression (hash=12661120) for Binding (hash=31408037)
System.Windows.Data Warning: 54 : Path: ''
System.Windows.Data Warning: 56 : BindingExpression (hash=12661120): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=12661120): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=12661120): Attach to Xceed.Wpf.DataGrid.DataGridControl.ItemsSource (hash=16991442)
System.Windows.Data Warning: 63 : BindingExpression (hash=12661120): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=12661120): Found data context element: <null> (OK)
System.Windows.Data Warning: 72 : BindingExpression (hash=12661120): Use View from DataGridCollectionViewSource (hash=28137373)
System.Windows.Data Warning: 74 : BindingExpression (hash=12661120): Activate with root item DataGridCollectionView (hash=49343907 Count=0)
System.Windows.Data Warning: 100 : BindingExpression (hash=12661120): Replace item at level 0 with DataGridCollectionView (hash=49343907 Count=0), using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=12661120): GetValue at level 0 from DataGridCollectionView (hash=49343907 Count=0) using <null>: Data``GridCollectionView (hash=49343907 Count=0)
System.Windows.Data Warning: 76 : BindingExpression (hash=12661120): TransferValue - got raw value DataGridCollectionView (hash=49343907 Count=0)
System.Windows.Data Warning: 85 : BindingExpression (hash=12661120): TransferValue - using final value DataGridCollectionView (hash=49343907 Count=0)
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
```
|
Not sure what your problem is, the bindings (apart from the missing end quotes) appear to be fine. The following code works fine for me.
```
public class Quotes
{
public string Description { get; set; }
public decimal Value { get; set; }
}
public class ApplicationPresenter
{
public ApplicationPresenter()
{
PriceList = new ObservableCollection<Quotes>()
{
new Quotes(){Description="Quote One", Value=10m},
new Quotes(){Description="Quote Two", Value=10m},
new Quotes(){Description="Quote Three", Value=10m},
new Quotes(){Description="Quote Four", Value=10m},
};
}
public ObservableCollection<Quotes> PriceList { get; private set; }
}
<Window
x:Class="ObjectDataProviderPresenterSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:xcdg="http://schemas.xceed.com/wpf/xaml/datagrid"
xmlns:local="clr-namespace:ObjectDataProviderPresenterSample"
Title="Window1"
Height="300"
Width="300"
>
<Window.Resources>
<ObjectDataProvider
x:Key="ApplicationPresenterDS"
ObjectType="{x:Type local:ApplicationPresenter}"
/>
<xcdg:DataGridCollectionViewSource
x:Key="price_list"
Source="{Binding
Source={StaticResource ApplicationPresenterDS},
Path=PriceList}"
/>
</Window.Resources>
<Grid>
<xcdg:DataGridControl ItemsSource="{Binding Source={StaticResource price_list}}" />
</Grid>
</Window>
```
|
255,898 |
<p>I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of <code>$1</code> easily:</p>
<pre><code>foo $1 args -o $1.ext
</code></pre>
<p>I want to be able to pass multiple input names to the script. What's the right way to do it? </p>
<p>And, of course, I want to handle filenames with spaces in them.</p>
|
[
{
"answer_id": 255913,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 12,
"selected": true,
"text": "<p>Use <code>\"$@\"</code> to represent all the arguments:</p>\n\n<pre><code>for var in \"$@\"\ndo\n echo \"$var\"\ndone\n</code></pre>\n\n<p>This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:</p>\n\n<pre><code>sh test.sh 1 2 '3 4'\n1\n2\n3 4\n</code></pre>\n"
},
{
"answer_id": 256225,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 8,
"selected": false,
"text": "<p><sup><em>Rewrite of a now-deleted <a href=\"https://stackoverflow.com/a/255939/\">answer</a> by <a href=\"https://stackoverflow.com/users/6309/vonc\">VonC</a>.</em></sup></p>\n\n<p><a href=\"https://stackoverflow.com/a/255913/417685\">Robert Gamble</a>'s succinct answer deals directly with the question.\nThis one amplifies on some issues with filenames containing spaces.</p>\n\n<p>See also: <a href=\"https://stackoverflow.com/questions/154625/1-in-binsh\">${1:+\"$@\"} in /bin/sh</a></p>\n\n<p><strong>Basic thesis:</strong> <code>\"$@\"</code> is correct, and <code>$*</code> (unquoted) is almost always wrong.\nThis is because <code>\"$@\"</code> works fine when arguments contain spaces, and\nworks the same as <code>$*</code> when they don't.\nIn some circumstances, <code>\"$*\"</code> is OK too, but <code>\"$@\"</code> usually (but not\nalways) works in the same places.\nUnquoted, <code>$@</code> and <code>$*</code> are equivalent (and almost always wrong).</p>\n\n<p>So, what is the difference between <code>$*</code>, <code>$@</code>, <code>\"$*\"</code>, and <code>\"$@\"</code>? They are all related to 'all the arguments to the shell', but they do different things. When unquoted, <code>$*</code> and <code>$@</code> do the same thing. They treat each 'word' (sequence of non-whitespace) as a separate argument. The quoted forms are quite different, though: <code>\"$*\"</code> treats the argument list as a single space-separated string, whereas <code>\"$@\"</code> treats the arguments almost exactly as they were when specified on the command line.\n<code>\"$@\"</code> expands to nothing at all when there are no positional arguments; <code>\"$*\"</code> expands to an empty string — and yes, there's a difference, though it can be hard to perceive it.\nSee more information below, after the introduction of the (non-standard) command <code>al</code>.</p>\n\n<p><strong>Secondary thesis:</strong> if you need to process arguments with spaces and then\npass them on to other commands, then you sometimes need non-standard\ntools to assist. (Or you should use arrays, carefully: <code>\"${array[@]}\"</code> behaves analogously to <code>\"$@\"</code>.)</p>\n\n<p><em>Example:</em></p>\n\n<pre><code> $ mkdir \"my dir\" anotherdir\n $ ls\n anotherdir my dir\n $ cp /dev/null \"my dir/my file\"\n $ cp /dev/null \"anotherdir/myfile\"\n $ ls -Fltr\n total 0\n drwxr-xr-x 3 jleffler staff 102 Nov 1 14:55 my dir/\n drwxr-xr-x 3 jleffler staff 102 Nov 1 14:55 anotherdir/\n $ ls -Fltr *\n my dir:\n total 0\n -rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 my file\n\n anotherdir:\n total 0\n -rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 myfile\n $ ls -Fltr \"./my dir\" \"./anotherdir\"\n ./my dir:\n total 0\n -rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 my file\n\n ./anotherdir:\n total 0\n -rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 myfile\n $ var='\"./my dir\" \"./anotherdir\"' && echo $var\n \"./my dir\" \"./anotherdir\"\n $ ls -Fltr $var\n ls: \"./anotherdir\": No such file or directory\n ls: \"./my: No such file or directory\n ls: dir\": No such file or directory\n $\n</code></pre>\n\n<p>Why doesn't that work?\nIt doesn't work because the shell processes quotes before it expands\nvariables.\nSo, to get the shell to pay attention to the quotes embedded in <code>$var</code>,\nyou have to use <code>eval</code>:</p>\n\n<pre><code> $ eval ls -Fltr $var\n ./my dir:\n total 0\n -rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 my file\n\n ./anotherdir:\n total 0\n -rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 myfile\n $ \n</code></pre>\n\n<p>This gets really tricky when you have file names such as \"<code>He said,\n\"Don't do this!\"</code>\" (with quotes and double quotes and spaces).</p>\n\n<pre><code> $ cp /dev/null \"He said, \\\"Don't do this!\\\"\"\n $ ls\n He said, \"Don't do this!\" anotherdir my dir\n $ ls -l\n total 0\n -rw-r--r-- 1 jleffler staff 0 Nov 1 15:54 He said, \"Don't do this!\"\n drwxr-xr-x 3 jleffler staff 102 Nov 1 14:55 anotherdir\n drwxr-xr-x 3 jleffler staff 102 Nov 1 14:55 my dir\n $ \n</code></pre>\n\n<p>The shells (all of them) do not make it particularly easy to handle such\nstuff, so (funnily enough) many Unix programs do not do a good job of\nhandling them.\nOn Unix, a filename (single component) can contain any characters except\nslash and NUL <code>'\\0'</code>.\nHowever, the shells strongly encourage no spaces or newlines or tabs\nanywhere in a path names.\nIt is also why standard Unix file names do not contain spaces, etc.</p>\n\n<p>When dealing with file names that may contain spaces and other\ntroublesome characters, you have to be extremely careful, and I found\nlong ago that I needed a program that is not standard on Unix.\nI call it <code>escape</code> (version 1.1 was dated 1989-08-23T16:01:45Z).</p>\n\n<p>Here is an example of <code>escape</code> in use - with the SCCS control system.\nIt is a cover script that does both a <code>delta</code> (think <em>check-in</em>) and a\n<code>get</code> (think <em>check-out</em>).\nVarious arguments, especially <code>-y</code> (the reason why you made the change)\nwould contain blanks and newlines.\nNote that the script dates from 1992, so it uses back-ticks instead of\n<code>$(cmd ...)</code> notation and does not use <code>#!/bin/sh</code> on the first line.</p>\n\n<pre><code>: \"@(#)$Id: delget.sh,v 1.8 1992/12/29 10:46:21 jl Exp $\"\n#\n# Delta and get files\n# Uses escape to allow for all weird combinations of quotes in arguments\n\ncase `basename $0 .sh` in\ndeledit) eflag=\"-e\";;\nesac\n\nsflag=\"-s\"\nfor arg in \"$@\"\ndo\n case \"$arg\" in\n -r*) gargs=\"$gargs `escape \\\"$arg\\\"`\"\n dargs=\"$dargs `escape \\\"$arg\\\"`\"\n ;;\n -e) gargs=\"$gargs `escape \\\"$arg\\\"`\"\n sflag=\"\"\n eflag=\"\"\n ;;\n -*) dargs=\"$dargs `escape \\\"$arg\\\"`\"\n ;;\n *) gargs=\"$gargs `escape \\\"$arg\\\"`\"\n dargs=\"$dargs `escape \\\"$arg\\\"`\"\n ;;\n esac\ndone\n\neval delta \"$dargs\" && eval get $eflag $sflag \"$gargs\"\n</code></pre>\n\n<p>(I would probably not use escape quite so thoroughly these days - it is\nnot needed with the <code>-e</code> argument, for example - but overall, this is\none of my simpler scripts using <code>escape</code>.)</p>\n\n<p>The <code>escape</code> program simply outputs its arguments, rather like <code>echo</code>\ndoes, but it ensures that the arguments are protected for use with\n<code>eval</code> (one level of <code>eval</code>; I do have a program which did remote shell\nexecution, and that needed to escape the output of <code>escape</code>).</p>\n\n<pre><code> $ escape $var\n '\"./my' 'dir\"' '\"./anotherdir\"'\n $ escape \"$var\"\n '\"./my dir\" \"./anotherdir\"'\n $ escape x y z\n x y z\n $ \n</code></pre>\n\n<p>I have another program called <code>al</code> that lists its arguments one per line\n(and it is even more ancient: version 1.1 dated 1987-01-27T14:35:49).\nIt is most useful when debugging scripts, as it can be plugged into a\ncommand line to see what arguments are actually passed to the command.</p>\n\n<pre><code> $ echo \"$var\"\n \"./my dir\" \"./anotherdir\"\n $ al $var\n \"./my\n dir\"\n \"./anotherdir\"\n $ al \"$var\"\n \"./my dir\" \"./anotherdir\"\n $\n</code></pre>\n\n<p>[<em>Added:</em>\nAnd now to show the difference between the various <code>\"$@\"</code> notations, here is one more example:</p>\n\n<pre><code>$ cat xx.sh\nset -x\nal $@\nal $*\nal \"$*\"\nal \"$@\"\n$ sh xx.sh * */*\n+ al He said, '\"Don'\\''t' do 'this!\"' anotherdir my dir xx.sh anotherdir/myfile my dir/my file\nHe\nsaid,\n\"Don't\ndo\nthis!\"\nanotherdir\nmy\ndir\nxx.sh\nanotherdir/myfile\nmy\ndir/my\nfile\n+ al He said, '\"Don'\\''t' do 'this!\"' anotherdir my dir xx.sh anotherdir/myfile my dir/my file\nHe\nsaid,\n\"Don't\ndo\nthis!\"\nanotherdir\nmy\ndir\nxx.sh\nanotherdir/myfile\nmy\ndir/my\nfile\n+ al 'He said, \"Don'\\''t do this!\" anotherdir my dir xx.sh anotherdir/myfile my dir/my file'\nHe said, \"Don't do this!\" anotherdir my dir xx.sh anotherdir/myfile my dir/my file\n+ al 'He said, \"Don'\\''t do this!\"' anotherdir 'my dir' xx.sh anotherdir/myfile 'my dir/my file'\nHe said, \"Don't do this!\"\nanotherdir\nmy dir\nxx.sh\nanotherdir/myfile\nmy dir/my file\n$\n</code></pre>\n\n<p>Notice that nothing preserves the original blanks between the <code>*</code> and <code>*/*</code> on the command line. Also, note that you can change the 'command line arguments' in the shell by using:</p>\n\n<pre><code>set -- -new -opt and \"arg with space\"\n</code></pre>\n\n<p>This sets 4 options, '<code>-new</code>', '<code>-opt</code>', '<code>and</code>', and '<code>arg with space</code>'.\n<br>\n]</p>\n\n<p>Hmm, that's quite a long <em>answer</em> - perhaps <em>exegesis</em> is the better term.\nSource code for <code>escape</code> available on request (email to firstname dot\nlastname at gmail dot com).\nThe source code for <code>al</code> is incredibly simple:</p>\n\n<pre><code>#include <stdio.h>\nint main(int argc, char **argv)\n{\n while (*++argv != 0)\n puts(*argv);\n return(0);\n}\n</code></pre>\n\n<p>That's all. It is equivalent to the <code>test.sh</code> script that Robert Gamble showed, and could be written as a shell function (but shell functions didn't exist in the local version of Bourne shell when I first wrote <code>al</code>).</p>\n\n<p>Also note that you can write <code>al</code> as a simple shell script:</p>\n\n<pre><code>[ $# != 0 ] && printf \"%s\\n\" \"$@\"\n</code></pre>\n\n<p>The conditional is needed so that it produces no output when passed no arguments. The <code>printf</code> command will produce a blank line with only the format string argument, but the C program produces nothing.</p>\n"
},
{
"answer_id": 1987331,
"author": "Alok Singhal",
"author_id": 226621,
"author_profile": "https://Stackoverflow.com/users/226621",
"pm_score": 7,
"selected": false,
"text": "<p>Note that Robert's answer is correct, and it works in <code>sh</code> as well. You can (portably) simplify it even further:</p>\n\n<pre><code>for i in \"$@\"\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>for i\n</code></pre>\n\n<p>I.e., you don't need anything!</p>\n\n<p>Testing (<code>$</code> is command prompt):</p>\n\n<pre><code>$ set a b \"spaces here\" d\n$ for i; do echo \"$i\"; done\na\nb\nspaces here\nd\n$ for i in \"$@\"; do echo \"$i\"; done\na\nb\nspaces here\nd\n</code></pre>\n\n<p>I first read about this in <em>Unix Programming Environment</em> by Kernighan and Pike.</p>\n\n<p>In <code>bash</code>, <code>help for</code> documents this:</p>\n\n<blockquote>\n <p><code>for NAME [in WORDS ... ;] do COMMANDS; done</code></p>\n \n <p>If <code>'in WORDS ...;'</code> is not present, then <code>'in \"$@\"'</code> is assumed.</p>\n</blockquote>\n"
},
{
"answer_id": 13118192,
"author": "nuoritoveri",
"author_id": 1065693,
"author_profile": "https://Stackoverflow.com/users/1065693",
"pm_score": 6,
"selected": false,
"text": "<p>For simple cases you can also use <code>shift</code>.\nIt treats the argument list like a queue. Each <code>shift</code> throws the first argument out and the\nindex of each of the remaining arguments is decremented.</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>#this prints all arguments\nwhile test $# -gt 0\ndo\n echo \"$1\"\n shift\ndone\n</code></pre>\n"
},
{
"answer_id": 34791882,
"author": "g24l",
"author_id": 4345926,
"author_profile": "https://Stackoverflow.com/users/4345926",
"pm_score": 3,
"selected": false,
"text": "<pre><code>aparse() {\nwhile [[ $# > 0 ]] ; do\n case \"$1\" in\n --arg1)\n varg1=${2}\n shift\n ;;\n --arg2)\n varg2=true\n ;;\n esac\n shift\ndone\n}\n\naparse \"$@\"\n</code></pre>\n"
},
{
"answer_id": 47006836,
"author": "baz",
"author_id": 6421877,
"author_profile": "https://Stackoverflow.com/users/6421877",
"pm_score": 5,
"selected": false,
"text": "<p>You can also access them as an array elements, for example if you don't want to iterate through all of them</p>\n\n<pre><code>argc=$#\nargv=(\"$@\")\n\nfor (( j=0; j<argc; j++ )); do\n echo \"${argv[j]}\"\ndone\n</code></pre>\n"
},
{
"answer_id": 60022895,
"author": "Rich Kadel",
"author_id": 10826737,
"author_profile": "https://Stackoverflow.com/users/10826737",
"pm_score": 3,
"selected": false,
"text": "<p>Amplifying on baz's answer, if you need to enumerate the argument list with an index (such as to search for a specific word), you can do this without copying the list or mutating it.</p>\n\n<p>Say you want to split an argument list at a double-dash (\"--\") and pass the arguments before the dashes to one command, and the arguments after the dashes to another:</p>\n\n<pre><code> toolwrapper() {\n for i in $(seq 1 $#); do\n [[ \"${!i}\" == \"--\" ]] && break\n done || return $? # returns error status if we don't \"break\"\n\n echo \"dashes at $i\"\n echo \"Before dashes: ${@:1:i-1}\"\n echo \"After dashes: ${@:i+1:$#}\"\n }\n</code></pre>\n\n<p>Results should look like this:</p>\n\n<pre><code> $ toolwrapper args for first tool -- and these are for the second\n dashes at 5\n Before dashes: args for first tool\n After dashes: and these are for the second\n</code></pre>\n"
},
{
"answer_id": 60510590,
"author": "JimmyLandStudios",
"author_id": 4231306,
"author_profile": "https://Stackoverflow.com/users/4231306",
"pm_score": 2,
"selected": false,
"text": "<p><strong>getopt</strong> Use command in your scripts to format any command line options or\nparameters.</p>\n\n<pre><code>#!/bin/bash\n# Extract command line options & values with getopt\n#\nset -- $(getopt -q ab:cd \"$@\")\n#\necho\nwhile [ -n \"$1\" ]\ndo\ncase \"$1\" in\n-a) echo \"Found the -a option\" ;;\n-b) param=\"$2\"\necho \"Found the -b option, with parameter value $param\"\nshift ;;\n-c) echo \"Found the -c option\" ;;\n--) shift\nbreak ;;\n*) echo \"$1 is not an option\";;\nesac\nshift\n</code></pre>\n"
},
{
"answer_id": 65982417,
"author": "Iceberg",
"author_id": 7935057,
"author_profile": "https://Stackoverflow.com/users/7935057",
"pm_score": 4,
"selected": false,
"text": "<p>Loop against $#, the number of arguments variable, works too.</p>\n<pre class=\"lang-bash prettyprint-override\"><code>#! /bin/bash\n\nfor ((i=1; i<=$#; i++))\ndo\n printf "${!i}\\n"\ndone\n</code></pre>\n<pre><code>./test.sh 1 2 '3 4'\n</code></pre>\n<p>Ouput:</p>\n<pre><code>1\n2\n3 4\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12874/"
] |
I have a complex command that I'd like to make a shell/bash script of. I can write it in terms of `$1` easily:
```
foo $1 args -o $1.ext
```
I want to be able to pass multiple input names to the script. What's the right way to do it?
And, of course, I want to handle filenames with spaces in them.
|
Use `"$@"` to represent all the arguments:
```
for var in "$@"
do
echo "$var"
done
```
This will iterate over each argument and print it out on a separate line. $@ behaves like $\* except that when quoted the arguments are broken up properly if there are spaces in them:
```
sh test.sh 1 2 '3 4'
1
2
3 4
```
|
255,907 |
<p>In Visual Studio 2008 in a C# WinForms project, there is a button on a form. In the properties view, the property "Font" is set to "Arial Unicode MS".</p>
<p>What do I need to put into the property "Text", so I get the unicode character \u0D15 displayed on the button?</p>
<p>When I put \u0D15 into the "Text" property, the button displays the six characters "\u0D15" instead of one unicode character.</p>
<p>In the following PDF, you can see the unicode character for \u0D15:
<a href="http://unicode.org/charts/PDF/U0D00.pdf" rel="noreferrer">http://unicode.org/charts/PDF/U0D00.pdf</a></p>
|
[
{
"answer_id": 255914,
"author": "axk",
"author_id": 578,
"author_profile": "https://Stackoverflow.com/users/578",
"pm_score": 0,
"selected": false,
"text": "<p>One possible way is to run \"charmap\" and copypaste from there or copypaste it from elsewhere.</p>\n"
},
{
"answer_id": 255918,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 4,
"selected": true,
"text": "<p>You don't have to escape your unicode characters in strings as C# is inherently unicode. Just put your unicode characters as they are into the string. For example:</p>\n\n<pre><code>button1.Text = \"日本\";\n</code></pre>\n"
},
{
"answer_id": 67694137,
"author": "Ragheed Al-Tayeb",
"author_id": 12519801,
"author_profile": "https://Stackoverflow.com/users/12519801",
"pm_score": -1,
"selected": false,
"text": "<p>Just try the following in you C# code:</p>\n<pre><code>button.Text = "0x0D15";\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33311/"
] |
In Visual Studio 2008 in a C# WinForms project, there is a button on a form. In the properties view, the property "Font" is set to "Arial Unicode MS".
What do I need to put into the property "Text", so I get the unicode character \u0D15 displayed on the button?
When I put \u0D15 into the "Text" property, the button displays the six characters "\u0D15" instead of one unicode character.
In the following PDF, you can see the unicode character for \u0D15:
<http://unicode.org/charts/PDF/U0D00.pdf>
|
You don't have to escape your unicode characters in strings as C# is inherently unicode. Just put your unicode characters as they are into the string. For example:
```
button1.Text = "日本";
```
|
255,916 |
<p>I use BIRT since early days and still have riddles regarding PDF emitter. </p>
<p><strong>Short story</strong>:
Can I configure fontsConfig.xml to load fonts from relative path or from jars?</p>
<p><strong>Long story:</strong>
We are using both FOP and BIRT for generating PDF in our web application. It would be nice to share fonts between libraries. Unfortunately, I can't find a way to do it with BIRT 2.3.1</p>
<p>The root of evil is fontsConfig.xml
If I configure it like shown below it works fine:</p>
<pre><code><font-paths>
<path path="fonts"/>
</font-paths>
</code></pre>
<p>But path doesn't allow me using neither relative paths not classpath (or I can't find an appropriate way how to configure it).
Neither config1 nor config2 works.</p>
<p>Config1:</p>
<pre><code><font-paths>
<path path="../fonts"/>
</font-paths>
</code></pre>
<p>Config2:</p>
<pre><code><font-paths>
<path path="classpath:fonts"/>
</font-paths>
</code></pre>
<p>Any thoughts will be appreciated.</p>
|
[
{
"answer_id": 21705054,
"author": "hvb",
"author_id": 2814025,
"author_profile": "https://Stackoverflow.com/users/2814025",
"pm_score": 3,
"selected": true,
"text": "<p>With some BIRT versions, you can use a SystemProperty \"birt.font.dirs\". This overrides the fontsConfig.xml.</p>\n\n<p>Well, this once worked, but obviously it was removed from the BIRT source code later.</p>\n\n<p>Now you can call something like</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>EngineConfig engineConfig = new EngineConfig();\nURL fontsConfigurationURL = new URL(\"file:///path/to/my/fontsConfig.xml\");\nengineConfig.setFontConfig(fontsConfigurationURL);\n\nPlatform.startup(engineConfig);\n</code></pre>\n\n<p>This allows you to supply BIRT with a customized version of fontsConfig.xml without poking around in the JARs.</p>\n\n<p>Tested with BIRT 4.3.0.</p>\n"
},
{
"answer_id": 22227211,
"author": "Saurabh Singhal",
"author_id": 3231802,
"author_profile": "https://Stackoverflow.com/users/3231802",
"pm_score": 1,
"selected": false,
"text": "<p>There is a way to have fonts on a relative path to be used in Birt.</p>\n\n<p>What you need to do is copy the fonts to a location in your Web Application. Mine was in :\nC:\\\\src\\main\\webapp\\Reports</p>\n\n<p>Now in the application, use the following command to register the fonts from the above mentioned location.</p>\n\n<pre><code>FontFactory.registerDirectory( scContext.getRealPath(\"/Reports\") );\n</code></pre>\n\n<p>This will register the font.</p>\n\n<p><strong>Tested on Birt 4.3 through Spring MVC</strong></p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19347/"
] |
I use BIRT since early days and still have riddles regarding PDF emitter.
**Short story**:
Can I configure fontsConfig.xml to load fonts from relative path or from jars?
**Long story:**
We are using both FOP and BIRT for generating PDF in our web application. It would be nice to share fonts between libraries. Unfortunately, I can't find a way to do it with BIRT 2.3.1
The root of evil is fontsConfig.xml
If I configure it like shown below it works fine:
```
<font-paths>
<path path="fonts"/>
</font-paths>
```
But path doesn't allow me using neither relative paths not classpath (or I can't find an appropriate way how to configure it).
Neither config1 nor config2 works.
Config1:
```
<font-paths>
<path path="../fonts"/>
</font-paths>
```
Config2:
```
<font-paths>
<path path="classpath:fonts"/>
</font-paths>
```
Any thoughts will be appreciated.
|
With some BIRT versions, you can use a SystemProperty "birt.font.dirs". This overrides the fontsConfig.xml.
Well, this once worked, but obviously it was removed from the BIRT source code later.
Now you can call something like
```java
EngineConfig engineConfig = new EngineConfig();
URL fontsConfigurationURL = new URL("file:///path/to/my/fontsConfig.xml");
engineConfig.setFontConfig(fontsConfigurationURL);
Platform.startup(engineConfig);
```
This allows you to supply BIRT with a customized version of fontsConfig.xml without poking around in the JARs.
Tested with BIRT 4.3.0.
|
255,941 |
<p>Is there anything out there freeware or commercial that can facilitate analysis of memory usage by a PHP application? I know xdebug can produce trace files that shows memory usage by function call but without a graphical tool the data is hard to interpret. </p>
<p>Ideally I would like to be able to view not only total memory usage but also what objects are on the heap and who references them similar to <a href="http://www.codework.com/jprofiler/product.htm" rel="noreferrer">Jprofiler</a>.</p>
|
[
{
"answer_id": 255973,
"author": "Marius Or.",
"author_id": 33314,
"author_profile": "https://Stackoverflow.com/users/33314",
"pm_score": 0,
"selected": false,
"text": "<p>A graphical tool for xdebug output is <a href=\"http://kcachegrind.sourceforge.net/\" rel=\"nofollow noreferrer\">KCacheGrind</a>.</p>\n"
},
{
"answer_id": 256295,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 0,
"selected": false,
"text": "<p>Try <a href=\"http://code.google.com/p/webgrind/\" rel=\"nofollow noreferrer\">webgrind</a>. It gives you the profiling of CacheGrinder in an easy to read, browser based format. I'm on a Mac and it has made profiling a breeze.</p>\n"
},
{
"answer_id": 257008,
"author": "user29772",
"author_id": 29772,
"author_profile": "https://Stackoverflow.com/users/29772",
"pm_score": 0,
"selected": false,
"text": "<p>phpDesigner 2008 can debug and benchmark websites using xdebug and KCacheGrind. It also has a built-in monitor.</p>\n"
},
{
"answer_id": 329809,
"author": "EvilPuppetMaster",
"author_id": 20851,
"author_profile": "https://Stackoverflow.com/users/20851",
"pm_score": 3,
"selected": false,
"text": "<p>I came across the same issue recently, couldn't find any specific tools unfortunately.</p>\n\n<p>But something that helped was to output the xdebug trace in human readable format with mem deltas enabled (an INI setting, xdebug.show_mem_deltas or something I think?). Then run sort (if you are on *nix) on the output:</p>\n\n<pre><code>sort -bgrk 3 -o sorted.txt mytracefile.xt \n</code></pre>\n\n<p>That sorts on the third col, the mem deltas. You can also sort on the second column, in which case you can find the line at which your app uses the most memory in total.</p>\n\n<p>Of course, this can't detect when an object's memory usage only creeps up in small increments but ends up using a lot of memory overall. I have a fairly dumb method that attempts to do this using a combination of object iteration and serialization. It probably doesn't equate exactly to memory usage, but hopefully gives an idea of where to start looking. Bear in mind it will use up memory itself, and also has not been extensively tested, so buyer beware:</p>\n\n<pre><code>function analyzeMem($obj, $deep=false)\n{\n if (!is_scalar($obj))\n {\n $usage = array('Total'=>strlen(serialize($obj)));\n while (list($prop, $propVal) = each($obj)) \n {\n if ($deep && (is_object($propVal) || is_array($propVal)))\n {\n $usage['Children'][$prop] = analyzeMem($propVal);\n }\n else\n {\n $usage['Children'][$prop] = strlen(serialize($propVal));\n }\n }\n return $usage;\n }\n else\n {\n return strlen(serialize($obj));\n }\n}\n\nprint_r(analyzeMem(get_defined_vars()));\n</code></pre>\n\n<p>Also, just got suggested this method by a colleague (cheers Dennis ;-) This hides the steps that are below 2 levels of indentation, you can quite easily see the points where the overall memory usage jumps up, and can narrow things down by increasing the indentation:</p>\n\n<pre><code>egrep '[0-9]+ ( ){1,2}-> ' mytracefile.xt\n</code></pre>\n"
},
{
"answer_id": 590184,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>On <a href=\"http://www.xdebug.org/updates.php\" rel=\"noreferrer\">http://www.xdebug.org/updates.php</a> for Xdebug 2.0.4 they write in section \"removed functions\": \"...Removed support for Memory profiling as that didn't work properly...\". Hence xdebug wont be an option</p>\n"
},
{
"answer_id": 23829872,
"author": "Francesco Casula",
"author_id": 828366,
"author_profile": "https://Stackoverflow.com/users/828366",
"pm_score": 5,
"selected": true,
"text": "<p>As you probably know, Xdebug dropped the memory profiling support since the 2.* version. Please search for the "removed functions" string here: <a href=\"http://www.xdebug.org/updates.php\" rel=\"noreferrer\">http://www.xdebug.org/updates.php</a></p>\n<blockquote>\n<p><strong>Removed functions</strong></p>\n<p>Removed support for Memory profiling as that didn't work properly.</p>\n</blockquote>\n<p>So I've tried another tool and it worked well for me.</p>\n<p><a href=\"https://github.com/arnaud-lb/php-memory-profiler\" rel=\"noreferrer\">https://github.com/arnaud-lb/php-memory-profiler</a></p>\n<p>This is what I've done on my Ubuntu server to enable it:</p>\n<pre><code>sudo apt-get install libjudy-dev libjudydebian1\nsudo pecl install memprof\necho "extension=memprof.so" > /etc/php5/mods-available/memprof.ini\nsudo php5enmod memprof\nservice apache2 restart\n</code></pre>\n<p>And then in my code:</p>\n<pre><code><?php\n\nmemprof_enable();\n\n// do your stuff\n\nmemprof_dump_callgrind(fopen("/tmp/callgrind.out", "w"));\n</code></pre>\n<p>Finally open the <code>callgrind.out</code> file with <a href=\"http://kcachegrind.sourceforge.net/html/Home.html\" rel=\"noreferrer\">KCachegrind</a></p>\n<h1>Using Google gperftools (recommended!)</h1>\n<p>First of all install the <strong>Google gperftools</strong> by downloading the latest package here: <a href=\"https://code.google.com/p/gperftools/\" rel=\"noreferrer\">https://code.google.com/p/gperftools/</a></p>\n<p>Then as always:</p>\n<pre><code>sudo apt-get update\nsudo apt-get install libunwind-dev -y\n./configure\nmake\nmake install\n</code></pre>\n<p>Now in your code:</p>\n<pre><code>memprof_enable();\n\n// do your magic\n\nmemprof_dump_pprof(fopen("/tmp/profile.heap", "w"));\n</code></pre>\n<p>Then open your terminal and launch:</p>\n<pre><code>pprof --web /tmp/profile.heap\n</code></pre>\n<p><em>pprof</em> will create a new window in your existing browser session with something like shown below:</p>\n<p><img src=\"https://i.stack.imgur.com/EAnGC.png\" alt=\"PHP memory profiling with memprof and gperftools\" /></p>\n<h1>Xhprof + Xhgui (the best in my opinion to profile both cpu and memory)</h1>\n<p>With <strong>Xhprof</strong> and <strong>Xhgui</strong> you can profile the cpu usage as well or just the memory usage if that's your issue at the moment.\nIt's a very complete solutions, it gives you full control and the logs can be written both on mongo or in the filesystem.</p>\n<p>For more details <a href=\"https://stackoverflow.com/questions/16787462/php-xdebug-how-to-profile-forked-process/31388948#31388948\">see my answer here</a>.</p>\n<h1>Blackfire</h1>\n<p>Blackfire is a PHP profiler by SensioLabs, the Symfony2 guys <a href=\"https://blackfire.io/\" rel=\"noreferrer\">https://blackfire.io/</a></p>\n<p>If you use <a href=\"https://puphpet.com/\" rel=\"noreferrer\">puphpet</a> to set up your virtual machine you'll be happy to know it's supported ;-)</p>\n"
},
{
"answer_id": 54487161,
"author": "Kharbat",
"author_id": 908659,
"author_profile": "https://Stackoverflow.com/users/908659",
"pm_score": 1,
"selected": false,
"text": "<p>I personally used <a href=\"https://github.com/arnaud-lb/php-memory-profiler\" rel=\"nofollow noreferrer\">https://github.com/arnaud-lb/php-memory-profiler</a></p>\n\n<p>on PHP 5.6 and Ubuntu 18, and Kcachegrind for visualizing.</p>\n\n<p>Kcachegrind is okay, but not the best. I hope to find a better alternative even if it's on Mac or Windows.</p>\n"
},
{
"answer_id": 57599832,
"author": "user24525",
"author_id": 6540060,
"author_profile": "https://Stackoverflow.com/users/6540060",
"pm_score": 1,
"selected": false,
"text": "<p>With the version 2.6.0 on 2018-01-29 xdebug added support for profiling memory usage. Now you can generate callgrind files with time and memory information. On Mac you can visualize that information for example with Qcachegrind or <a href=\"https://profilingviewer.com/\" rel=\"nofollow noreferrer\">Profiling Viewer</a> (premium).</p>\n\n<p><a href=\"https://i.stack.imgur.com/cCWR6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cCWR6.png\" alt=\"Profiling Viewer callgraph\"></a></p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2043539/"
] |
Is there anything out there freeware or commercial that can facilitate analysis of memory usage by a PHP application? I know xdebug can produce trace files that shows memory usage by function call but without a graphical tool the data is hard to interpret.
Ideally I would like to be able to view not only total memory usage but also what objects are on the heap and who references them similar to [Jprofiler](http://www.codework.com/jprofiler/product.htm).
|
As you probably know, Xdebug dropped the memory profiling support since the 2.\* version. Please search for the "removed functions" string here: <http://www.xdebug.org/updates.php>
>
> **Removed functions**
>
>
> Removed support for Memory profiling as that didn't work properly.
>
>
>
So I've tried another tool and it worked well for me.
<https://github.com/arnaud-lb/php-memory-profiler>
This is what I've done on my Ubuntu server to enable it:
```
sudo apt-get install libjudy-dev libjudydebian1
sudo pecl install memprof
echo "extension=memprof.so" > /etc/php5/mods-available/memprof.ini
sudo php5enmod memprof
service apache2 restart
```
And then in my code:
```
<?php
memprof_enable();
// do your stuff
memprof_dump_callgrind(fopen("/tmp/callgrind.out", "w"));
```
Finally open the `callgrind.out` file with [KCachegrind](http://kcachegrind.sourceforge.net/html/Home.html)
Using Google gperftools (recommended!)
======================================
First of all install the **Google gperftools** by downloading the latest package here: <https://code.google.com/p/gperftools/>
Then as always:
```
sudo apt-get update
sudo apt-get install libunwind-dev -y
./configure
make
make install
```
Now in your code:
```
memprof_enable();
// do your magic
memprof_dump_pprof(fopen("/tmp/profile.heap", "w"));
```
Then open your terminal and launch:
```
pprof --web /tmp/profile.heap
```
*pprof* will create a new window in your existing browser session with something like shown below:

Xhprof + Xhgui (the best in my opinion to profile both cpu and memory)
======================================================================
With **Xhprof** and **Xhgui** you can profile the cpu usage as well or just the memory usage if that's your issue at the moment.
It's a very complete solutions, it gives you full control and the logs can be written both on mongo or in the filesystem.
For more details [see my answer here](https://stackoverflow.com/questions/16787462/php-xdebug-how-to-profile-forked-process/31388948#31388948).
Blackfire
=========
Blackfire is a PHP profiler by SensioLabs, the Symfony2 guys <https://blackfire.io/>
If you use [puphpet](https://puphpet.com/) to set up your virtual machine you'll be happy to know it's supported ;-)
|
255,942 |
<p>I'm using Castle ActiveRecord for persistence, and I'm trying to write a base class for my persistence tests which will do the following:</p>
<ul>
<li>Open a transaction for each test case and roll it back at the end of the test case, so that I get a clean DB for each test case without me having to rebuild the schema for each test case.</li>
<li>Provide the ability to flush my NHibernate session and get a new one in the middle of a test, so that I know that my persistence operations have really hit the DB rather than just the NHibernate session.</li>
</ul>
<p>In order to prove that my base class (<code>ARTestBase</code>) is working, I've come up with the following sample tests.</p>
<pre><code>[TestFixture]
public class ARTestBaseTest : ARTestBase
{
[Test]
public void object_created_in_this_test_should_not_get_committed_to_db()
{
ActiveRecordMediator<Entity>.Save(new Entity {Name = "test"});
Assert.That(ActiveRecordMediator<Entity>.Count(), Is.EqualTo(1));
}
[Test]
public void object_created_in_previous_test_should_not_have_been_committed_to_db()
{
ActiveRecordMediator<Entity>.Save(new Entity {Name = "test"});
Assert.That(ActiveRecordMediator<Entity>.Count(), Is.EqualTo(1));
}
[Test]
public void calling_flush_should_make_nhibernate_retrieve_fresh_objects()
{
var savedEntity = new Entity {Name = "test"};
ActiveRecordMediator<Entity>.Save(savedEntity);
Flush();
// Could use FindOne, but then this test would fail if the transactions aren't being rolled back
foreach (var entity in ActiveRecordMediator<Entity>.FindAll())
{
Assert.That(entity, Is.Not.SameAs(savedEntity));
}
}
}
</code></pre>
<p>Here is my best effort at the base class. It correctly implements <code>Flush()</code>, so the third test case passes. However it does not rollback the transactions, so the second test fails.</p>
<pre><code>public class ARTestBase
{
private SessionScope sessionScope;
private TransactionScope transactionScope;
[TestFixtureSetUp]
public void InitialiseAR()
{
ActiveRecordStarter.ResetInitializationFlag();
ActiveRecordStarter.Initialize(typeof (Entity).Assembly, ActiveRecordSectionHandler.Instance);
ActiveRecordStarter.CreateSchema();
}
[SetUp]
public virtual void SetUp()
{
transactionScope = new TransactionScope(OnDispose.Rollback);
sessionScope = new SessionScope();
}
[TearDown]
public virtual void TearDown()
{
sessionScope.Dispose();
transactionScope.Dispose();
}
protected void Flush()
{
sessionScope.Dispose();
sessionScope = new SessionScope();
}
[TestFixtureTearDown]
public virtual void TestFixtureTearDown()
{
SQLiteProvider.ExplicitlyDestroyConnection();
}
}
</code></pre>
<p>Note that I'm using a custom SQLite provider with an in-memory database. My custom provider, taken from <a href="http://brian.genisio.org/2008/07/active-record-mock-framework.html" rel="nofollow noreferrer">this blog post</a>, keeps the connection open at all times to maintain the schema. Removing this and using a regular SQL Server database doesn't change the behaviour.</p>
<p>Is there a way to acheive the required behaviour?</p>
|
[
{
"answer_id": 258313,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 1,
"selected": false,
"text": "<p>Not too sure about ActiveRecord, but in NHibernate a transaction belongs to a session, not the otherway round.</p>\n\n<p>If you've used ADO.Net a lot, this will make more sense, as to create an <code>IDbTransaction</code> you need to use the connection. ActiveRecord's <code>TransactionScope</code> (and NHibnerate's <code>ITransaction</code>) essentially wrap an <code>IDbTransaction</code>, so you need to create the <code>SessionScope</code> before the <code>TransactionScope</code>.</p>\n\n<p>What you might also find (depending on if you're using NHibernate 1.2 GA or NHibernate 2.*, and what <code>FlushMode</code> your <code>SessionScope</code> has) is that your call to <code>FindAll()</code> may cause the session to flush anyway, as NHibernate will realise that it can't retrieve the correct data without actioning the last call to <code>Save</code>.</p>\n\n<p>This all said and done, have you tried using <code>SessionScope.Flush()</code> instead of creating a new <code>SessionScope</code>?</p>\n"
},
{
"answer_id": 258560,
"author": "Alex Scordellis",
"author_id": 12006,
"author_profile": "https://Stackoverflow.com/users/12006",
"pm_score": 0,
"selected": false,
"text": "<p>Using <code>SessionScope.Flush()</code> makes my third test fail. As I understand it, <code>Flush()</code> executes the SQL to push my records into the DB, but does not evict objects from the session. That fits with what you say about <code>FindAll()</code> causing a flush.</p>\n\n<p>What I really want is <code>SessionScope.Flush()</code> (to synchronise state of DB with session) plus <code>SessionScope.EvictAll()</code> (to ensure I get fresh objects in subsequent queries). My <code>new SessionScope()</code> was an attempt to simulate <code>EvictAll()</code>.</p>\n\n<p>Your comments about the session enclosing the transaction rather than the other way round did give me an idea. I'm not sure how kosher it is to create a new <code>SessionScope</code> inside a <code>TransactionScope</code> inside a flushed <code>SessionScope</code>, and expect it to participate in the transaction, but it seems to work:</p>\n\n<pre><code>public abstract class ARTestBase\n{\n private SessionScope sessionScope;\n private TransactionScope transactionScope;\n private bool reverse;\n private IList<SessionScope> undisposedScopes;\n\n [TestFixtureSetUp]\n public void InitialiseAR()\n {\n ActiveRecordStarter.ResetInitializationFlag();\n ActiveRecordStarter.Initialize(typeof (Entity).Assembly, ActiveRecordSectionHandler.Instance);\n ActiveRecordStarter.CreateSchema();\n InitialiseIoC();\n undisposedScopes = new List<SessionScope>();\n }\n\n [SetUp]\n public virtual void SetUp()\n {\n sessionScope = new SessionScope();\n transactionScope = new TransactionScope(OnDispose.Rollback);\n transactionScope.VoteRollBack();\n base.CreateInstanceUnderTest();\n reverse = false;\n }\n\n [TearDown]\n public virtual void TearDown()\n {\n if (reverse)\n {\n sessionScope.Dispose();\n transactionScope.Dispose();\n }\n else\n {\n transactionScope.Dispose();\n sessionScope.Dispose();\n }\n }\n\n [TestFixtureTearDown]\n public virtual void TestFixtureTearDown()\n {\n foreach (var scope in undisposedScopes)\n {\n scope.Dispose();\n }\n SQLiteProvider.ExplicitlyDestroyConnection();\n }\n\n protected void Flush()\n {\n reverse = true;\n sessionScope.Flush();\n undisposedScopes.Add(sessionScope);\n sessionScope = new SessionScope();\n }\n}\n</code></pre>\n\n<p>On further thought, this won't allow you to flush more than once in each test case. I think I can handle that by tracking the scopes more carefully. I might look into it later.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12006/"
] |
I'm using Castle ActiveRecord for persistence, and I'm trying to write a base class for my persistence tests which will do the following:
* Open a transaction for each test case and roll it back at the end of the test case, so that I get a clean DB for each test case without me having to rebuild the schema for each test case.
* Provide the ability to flush my NHibernate session and get a new one in the middle of a test, so that I know that my persistence operations have really hit the DB rather than just the NHibernate session.
In order to prove that my base class (`ARTestBase`) is working, I've come up with the following sample tests.
```
[TestFixture]
public class ARTestBaseTest : ARTestBase
{
[Test]
public void object_created_in_this_test_should_not_get_committed_to_db()
{
ActiveRecordMediator<Entity>.Save(new Entity {Name = "test"});
Assert.That(ActiveRecordMediator<Entity>.Count(), Is.EqualTo(1));
}
[Test]
public void object_created_in_previous_test_should_not_have_been_committed_to_db()
{
ActiveRecordMediator<Entity>.Save(new Entity {Name = "test"});
Assert.That(ActiveRecordMediator<Entity>.Count(), Is.EqualTo(1));
}
[Test]
public void calling_flush_should_make_nhibernate_retrieve_fresh_objects()
{
var savedEntity = new Entity {Name = "test"};
ActiveRecordMediator<Entity>.Save(savedEntity);
Flush();
// Could use FindOne, but then this test would fail if the transactions aren't being rolled back
foreach (var entity in ActiveRecordMediator<Entity>.FindAll())
{
Assert.That(entity, Is.Not.SameAs(savedEntity));
}
}
}
```
Here is my best effort at the base class. It correctly implements `Flush()`, so the third test case passes. However it does not rollback the transactions, so the second test fails.
```
public class ARTestBase
{
private SessionScope sessionScope;
private TransactionScope transactionScope;
[TestFixtureSetUp]
public void InitialiseAR()
{
ActiveRecordStarter.ResetInitializationFlag();
ActiveRecordStarter.Initialize(typeof (Entity).Assembly, ActiveRecordSectionHandler.Instance);
ActiveRecordStarter.CreateSchema();
}
[SetUp]
public virtual void SetUp()
{
transactionScope = new TransactionScope(OnDispose.Rollback);
sessionScope = new SessionScope();
}
[TearDown]
public virtual void TearDown()
{
sessionScope.Dispose();
transactionScope.Dispose();
}
protected void Flush()
{
sessionScope.Dispose();
sessionScope = new SessionScope();
}
[TestFixtureTearDown]
public virtual void TestFixtureTearDown()
{
SQLiteProvider.ExplicitlyDestroyConnection();
}
}
```
Note that I'm using a custom SQLite provider with an in-memory database. My custom provider, taken from [this blog post](http://brian.genisio.org/2008/07/active-record-mock-framework.html), keeps the connection open at all times to maintain the schema. Removing this and using a regular SQL Server database doesn't change the behaviour.
Is there a way to acheive the required behaviour?
|
Not too sure about ActiveRecord, but in NHibernate a transaction belongs to a session, not the otherway round.
If you've used ADO.Net a lot, this will make more sense, as to create an `IDbTransaction` you need to use the connection. ActiveRecord's `TransactionScope` (and NHibnerate's `ITransaction`) essentially wrap an `IDbTransaction`, so you need to create the `SessionScope` before the `TransactionScope`.
What you might also find (depending on if you're using NHibernate 1.2 GA or NHibernate 2.\*, and what `FlushMode` your `SessionScope` has) is that your call to `FindAll()` may cause the session to flush anyway, as NHibernate will realise that it can't retrieve the correct data without actioning the last call to `Save`.
This all said and done, have you tried using `SessionScope.Flush()` instead of creating a new `SessionScope`?
|
255,955 |
<p>Returning to WinForms in VS2008 after a long time.. Tinkering with a OOD problem in VS2008 Express Edition.</p>
<p>I need some controls to be "display only" widgets. The user should not be able to change the value of these controls... the widgets are updated by a periodic update tick event. I vaguely remember there being a ReadOnly property that you could set to have this behavior... can't find it now.</p>
<p>The <strong>Enabled</strong> property set to false: grays out the control content. I want the control to look normal.
The <strong>Locked</strong> property set to false: seems to be protecting the user from accidentally distorting the control in the Visual Form Designer.</p>
<p>What am I missing? </p>
|
[
{
"answer_id": 255965,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 5,
"selected": true,
"text": "<p>For some typical winforms controls:</p>\n\n<p><a href=\"http://jquiz.wordpress.com/2007/05/29/c-winforms-readonly-controls/\" rel=\"noreferrer\">http://jquiz.wordpress.com/2007/05/29/c-winforms-readonly-controls/</a></p>\n\n<p>This is also a good tip to preserve the appearance:</p>\n\n<pre><code> Color clr = textBox1.BackColor;\n textBox1.ReadOnly = true;\n textBox1.BackColor = clr;\n</code></pre>\n"
},
{
"answer_id": 255968,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Textbox</strong></p>\n\n<p>.ReadOnly property to true</p>\n\n<p><strong>Controls without ReadOnly</strong></p>\n\n<p>Other control do not have all the time the ReadOnly property. You will require to play with the Events to take off the editing process and keeping your value not editable.</p>\n"
},
{
"answer_id": 256035,
"author": "Grant",
"author_id": 407,
"author_profile": "https://Stackoverflow.com/users/407",
"pm_score": 1,
"selected": false,
"text": "<p>Two relevant properties ReadOnly and Enabled. ReadOnly = true prevents editing grays out the background, but it still allows focus. Enabled = false grays out the background, text and prevents editing or focus. </p>\n\n<p>Windows UI conventions dicate giving the user a visual cue that a control is readonly (that way they won't attempt to edit it and be subsequently frustrated). The grayed out disabled state is the defined system convention, but it's arguable too much of a cue (and not a legibile enough one). </p>\n\n<p>The simplest route is probababy to set your control to ReadOnly, set the background to System.Drawing.SystemColors.Window and then block focus messages. You could do this by catching OnEnter events and immediately moving Focus to another control that's not readonly (say, a Close or Edit button). Or you could derive your own control and eat any WM_SETFOCUS messages. Example below.</p>\n\n<p>I believe various third-party control sets give you additional options and granularity.</p>\n\n<pre><code>public class ReadOnlyTextBox : TextBox\n{\n const uint WM_SETFOCUS = 0x0007;\n\n public ReadOnlyTextBox()\n {\n this.ReadOnly = true;\n this.BackColor = System.Drawing.SystemColors.Window;\n this.ForeColor = System.Drawing.SystemColors.WindowText;\n }\n\n protected override void WndProc(ref Message m)\n {\n // eat all setfocus messages, pass rest to base\n if (m.Msg != WM_SETFOCUS)\n base.WndProc(ref m);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3862349,
"author": "Rajan Arora",
"author_id": 466639,
"author_profile": "https://Stackoverflow.com/users/466639",
"pm_score": 3,
"selected": false,
"text": "<p>To make the forms control Readonly instantly on one click do use the following peice of Code :</p>\n\n<pre><code> public void LockControlValues(System.Windows.Forms.Control Container)\n {\n try\n {\n foreach (Control ctrl in Container.Controls)\n {\n if (ctrl.GetType() == typeof(TextBox))\n ((TextBox)ctrl).ReadOnly = true;\n if (ctrl.GetType() == typeof(ComboBox))\n ((ComboBox)ctrl).Enabled= false;\n if (ctrl.GetType() == typeof(CheckBox))\n ((CheckBox)ctrl).Enabled = false;\n\n if (ctrl.GetType() == typeof(DateTimePicker))\n ((DateTimePicker)ctrl).Enabled = false;\n\n if (ctrl.Controls.Count > 0)\n LockControlValues(ctrl);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.ToString());\n }\n }\n</code></pre>\n\n<p>Then call it from your Button Click Event like this :</p>\n\n<pre><code>LockControlValues(this)\n</code></pre>\n\n<p>Hope, this helps to solve your problem :</p>\n\n<p>Happy Programming,</p>\n\n<p>Rajan Arora\nwww.simplyrajan.co.nr </p>\n"
},
{
"answer_id": 18882848,
"author": "C.J.",
"author_id": 321866,
"author_profile": "https://Stackoverflow.com/users/321866",
"pm_score": 0,
"selected": false,
"text": "<p>I was given this same requirement at work yesterday. Except instead of a textbox I had to make an entire form disabled without changing it's color.</p>\n\n<p>So I replaced a call to</p>\n\n<pre><code>form->Enabled = false;\n</code></pre>\n\n<p>with</p>\n\n<pre><code>IntPtr hWnd = form->Handle;\nHWND window_handle = (HWND)hWnd.ToPointer();\n::EnableWindow(window_handle, aEnable ? TRUE:FALSE);\n</code></pre>\n\n<p>Which worked well. You can see above that I am using managed C++. The entire form is now disabled, but not greyed out.</p>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695/"
] |
Returning to WinForms in VS2008 after a long time.. Tinkering with a OOD problem in VS2008 Express Edition.
I need some controls to be "display only" widgets. The user should not be able to change the value of these controls... the widgets are updated by a periodic update tick event. I vaguely remember there being a ReadOnly property that you could set to have this behavior... can't find it now.
The **Enabled** property set to false: grays out the control content. I want the control to look normal.
The **Locked** property set to false: seems to be protecting the user from accidentally distorting the control in the Visual Form Designer.
What am I missing?
|
For some typical winforms controls:
<http://jquiz.wordpress.com/2007/05/29/c-winforms-readonly-controls/>
This is also a good tip to preserve the appearance:
```
Color clr = textBox1.BackColor;
textBox1.ReadOnly = true;
textBox1.BackColor = clr;
```
|
255,969 |
<p>I'm struggling with Test::Unit. When I think of unit tests, I think of one simple test per file. But in Ruby's framework, I must instead write: </p>
<pre><code>class MyTest < Test::Unit::TestCase
def setup
end
def test_1
end
def test_1
end
end
</code></pre>
<p>But setup and teardown run for every invocation of a test_* method. This is exactly what I don't want. Rather, I want a setup method that runs just once for the whole class. But I can't seem to write my own initialize() without breaking TestCase's initialize.</p>
<p>Is that possible? Or am I making this hopelessly complicated?</p>
|
[
{
"answer_id": 256063,
"author": "Rômulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 3,
"selected": false,
"text": "<p>That's how it's supposed to work!</p>\n\n<p>Each test should be completely isolated from the rest, so the <code>setup</code> and <code>tear_down</code> methods are executed once for every test-case. There are cases, however, when you might want more control over the execution flow. Then you can group the test-cases in <em>suites</em>.</p>\n\n<p>In your case you could write something like the following:</p>\n\n<pre><code>require 'test/unit'\nrequire 'test/unit/ui/console/testrunner'\n\nclass TestDecorator < Test::Unit::TestSuite\n\n def initialize(test_case_class)\n super\n self << test_case_class.suite\n end\n\n def run(result, &progress_block)\n setup_suite\n begin\n super(result, &progress_block) \n ensure\n tear_down_suite\n end\n end\n\nend\n\nclass MyTestCase < Test::Unit::TestCase\n\n def test_1\n puts \"test_1\"\n assert_equal(1, 1)\n end\n\n def test_2\n puts \"test_2\"\n assert_equal(2, 2)\n end\n\nend\n\nclass MySuite < TestDecorator\n\n def setup_suite\n puts \"setup_suite\"\n end\n\n def tear_down_suite\n puts \"tear_down_suite\"\n end\n\nend\n\nTest::Unit::UI::Console::TestRunner.run(MySuite.new(MyTestCase))\n</code></pre>\n\n<p>The <code>TestDecorator</code> defines a special suite which provides a <code>setup</code> and <code>tear_down</code> method which run only once before and after the running of the set of test-cases it contains.</p>\n\n<p>The drawback of this is that you need to tell <em>Test::Unit</em> how to run the tests in the unit. In the event your unit contains many test-cases and you need a decorator for only one of them you'll need something like this:</p>\n\n<pre><code>require 'test/unit'\nrequire 'test/unit/ui/console/testrunner'\n\nclass TestDecorator < Test::Unit::TestSuite\n\n def initialize(test_case_class)\n super\n self << test_case_class.suite\n end\n\n def run(result, &progress_block)\n setup_suite\n begin\n super(result, &progress_block) \n ensure\n tear_down_suite\n end\n end\n\nend\n\nclass MyTestCase < Test::Unit::TestCase\n\n def test_1\n puts \"test_1\"\n assert_equal(1, 1)\n end\n\n def test_2\n puts \"test_2\"\n assert_equal(2, 2)\n end\n\nend\n\nclass MySuite < TestDecorator\n\n def setup_suite\n puts \"setup_suite\"\n end\n\n def tear_down_suite\n puts \"tear_down_suite\"\n end\n\nend\n\nclass AnotherTestCase < Test::Unit::TestCase\n\n def test_a\n puts \"test_a\"\n assert_equal(\"a\", \"a\")\n end\n\nend\n\nclass Tests\n\n def self.suite\n suite = Test::Unit::TestSuite.new\n suite << MySuite.new(MyTestCase)\n suite << AnotherTestCase.suite\n suite\n end\n\nend\n\nTest::Unit::UI::Console::TestRunner.run(Tests.suite)\n</code></pre>\n\n<p>The <a href=\"http://www.ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit.html\" rel=\"noreferrer\"><em>Test::Unit</em> documentation</a> documentation provides a good explanation on how suites work.</p>\n"
},
{
"answer_id": 256104,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 1,
"selected": false,
"text": "<p>I came across this exact problem and created a subclass of <code>Test::Unit::TestCase</code> for doing exactly what you describe.</p>\n\n<p>Here's what I came up with. It provides it's own <code>setup</code> and <code>teardown</code> methods that count the number of methods in the class that begin with 'test'. On the first call to <code>setup</code> it calls <code>global_setup</code> and on the last call to <code>teardown</code> it calls <code>global_teardown</code></p>\n\n<pre><code>class ImprovedUnitTestCase < Test::Unit::TestCase\n cattr_accessor :expected_test_count\n\n def self.global_setup; end\n def self.global_teardown; end \n\n def teardown\n if((self.class.expected_test_count-=1) == 0)\n self.class.global_teardown\n end\n end\n def setup\n cls = self.class\n\n if(not cls.expected_test_count)\n cls.expected_test_count = (cls.instance_methods.reject{|method| method[0..3] != 'test'}).length\n cls.global_setup\n end\n end\nend\n</code></pre>\n\n<p>Create your test cases like this:</p>\n\n<pre><code>class TestSomething < ImprovedUnitTestCase\n def self.global_setup\n puts 'global_setup is only run once at the beginning'\n end\n\n def self.global_teardown\n puts 'global_teardown is only run once at the end'\n end\n\n def test_1 \n end\n\n def test_2\n end\nend\n</code></pre>\n\n<p>The fault in this is that you can't provide your own per-test <code>setup</code> and <code>teardown</code> methods unless you use the <code>setup :method_name</code> class method (only available in Rails 2.X?) and if you have a test suite or something that only runs one of the test methods, then the <code>global_teardown</code> won't be called because it assumes that all the test methods will be run eventually.</p>\n"
},
{
"answer_id": 256161,
"author": "Honza",
"author_id": 8621,
"author_profile": "https://Stackoverflow.com/users/8621",
"pm_score": 0,
"selected": false,
"text": "<p>Use the TestSuite as @romulo-a-ceccon described for special preparations for each test suite.</p>\n\n<p>However I think it should be mentioned here that Unit tests are ment to run in total isolation. Thus the execution flow is setup-test-teardown which should guarantee that each test run undisturbed by anything the other tests did.</p>\n"
},
{
"answer_id": 369709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I created a mixin called SetupOnce. Here's an example of using it.</p>\n\n<pre><code>require 'test/unit'\nrequire 'setuponce'\n\n\nclass MyTest < Test::Unit::TestCase\n include SetupOnce\n\n def self.setup_once\n puts \"doing one-time setup\"\n end\n\n def self.teardown_once\n puts \"doing one-time teardown\"\n end\n\nend\n</code></pre>\n\n<p>And here is the actual code; notice it requires another module available from the first link in the footnotes.</p>\n\n<pre><code>require 'mixin_class_methods' # see footnote 1\n\nmodule SetupOnce\n mixin_class_methods\n\n define_class_methods do\n def setup_once; end\n\n def teardown_once; end\n\n def suite\n mySuite = super\n\n def mySuite.run(*args)\n @name.to_class.setup_once\n super(*args)\n @name.to_class.teardown_once\n end\n\n return mySuite\n end\n end\nend\n\n# See footnote 2\nclass String\n def to_class\n split('::').inject(Kernel) {\n |scope, const_name|\n scope.const_get(const_name)\n }\n end\nend\n</code></pre>\n\n<p>Footnotes:</p>\n\n<ol>\n<li><p><a href=\"http://redcorundum.blogspot.com/2006/06/mixing-in-class-methods.html\" rel=\"nofollow noreferrer\">http://redcorundum.blogspot.com/2006/06/mixing-in-class-methods.html</a></p></li>\n<li><p><a href=\"http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/\" rel=\"nofollow noreferrer\">http://infovore.org/archives/2006/08/02/getting-a-class-object-in-ruby-from-a-string-containing-that-classes-name/</a></p></li>\n</ol>\n"
},
{
"answer_id": 778701,
"author": "Matt Wolfe",
"author_id": 94557,
"author_profile": "https://Stackoverflow.com/users/94557",
"pm_score": 5,
"selected": false,
"text": "<p>As mentioned in Hal Fulton's book \"The Ruby Way\".\nHe overrides the self.suite method of Test::Unit which allows the test cases in a class to run as a suite. </p>\n\n<pre><code>def self.suite\n mysuite = super\n def mysuite.run(*args)\n MyTest.startup()\n super\n MyTest.shutdown()\n end\n mysuite\nend\n</code></pre>\n\n<p>Here is an example:</p>\n\n<pre><code>class MyTest < Test::Unit::TestCase\n class << self\n def startup\n puts 'runs only once at start'\n end\n def shutdown\n puts 'runs only once at end'\n end\n def suite\n mysuite = super\n def mysuite.run(*args)\n MyTest.startup()\n super\n MyTest.shutdown()\n end\n mysuite\n end\n end\n\n def setup\n puts 'runs before each test'\n end\n def teardown\n puts 'runs after each test'\n end \n def test_stuff\n assert(true)\n end\nend\n</code></pre>\n"
},
{
"answer_id": 1126566,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I accomplished basically the same way in a really ugly and horrible fashion, but it was quicker. :) Once I realized that the tests are run alphabetically:</p>\n\n<pre><code>class MyTests < Test::Unit::TestCase\ndef test_AASetup # I have a few tests that start with \"A\", but I doubt any will start with \"Aardvark\" or \"Aargh!\"\n #Run setup code\nend\n\ndef MoreTests\nend\n\ndef test_ZTeardown\n #Run teardown code\nend\n</code></pre>\n\n<p>It aint pretty, but it works :)</p>\n"
},
{
"answer_id": 4120184,
"author": "Bouke Woudstra",
"author_id": 500158,
"author_profile": "https://Stackoverflow.com/users/500158",
"pm_score": 2,
"selected": false,
"text": "<p>To solve this problem I used the setup construct, with only one test method followed. This one testmethod is calling all other tests.</p>\n\n<p>For instance</p>\n\n<pre><code>class TC_001 << Test::Unit::TestCase\n def setup\n # do stuff once\n end\n\n def testSuite\n falseArguments()\n arguments()\n end\n\n def falseArguments\n # do stuff\n end\n\n def arguments\n # do stuff\n end\nend\n</code></pre>\n"
},
{
"answer_id": 7052032,
"author": "remi",
"author_id": 544304,
"author_profile": "https://Stackoverflow.com/users/544304",
"pm_score": 0,
"selected": false,
"text": "<p>+1 for the RSpec answer above by @orion-edwards. I would have commented on his answer, but I don't have enough reputation yet to comment on answers.</p>\n\n<p>I use test/unit <em>and</em> RSpec a lot and I have to say ... the code that everyone has been posting is missing a <em>very</em> important feature of <code>before(:all)</code> which is: @instance variable support.</p>\n\n<p>In RSpec, you can do:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>describe 'Whatever' do\n before :all do\n @foo = 'foo'\n end\n\n # This will pass\n it 'first' do\n assert_equal 'foo', @foo\n @foo = 'different'\n assert_equal 'different', @foo\n end\n\n # This will pass, even though the previous test changed the \n # value of @foo. This is because RSpec stores the values of \n # all instance variables created by before(:all) and copies \n # them into your test's scope before each test runs.\n it 'second' do\n assert_equal 'foo', @foo\n @foo = 'different'\n assert_equal 'different', @foo\n end\nend\n</code></pre>\n\n<p>The implementations of <code>#startup</code> and <code>#shutdown</code> above all focus on making sure that these methods only get called once for the entire <code>TestCase</code> class, but any instance variables used in these methods would be lost!</p>\n\n<p>RSpec runs its <code>before(:all)</code> in its own instance of Object and all of the local variables are copied before each test is run.</p>\n\n<p>To access any variables that are created during a global <code>#startup</code> method, you would need to either:</p>\n\n<ul>\n<li>copy all of the instance variables created by <code>#startup</code>, like RSpec does</li>\n<li>define your variables in <code>#startup</code> into a scope that you can access from your test methods, eg. <code>@@class_variables</code> or create class-level attr_accessors that provide access to the <code>@instance_variables</code> that you create inside of <code>def self.startup</code></li>\n</ul>\n\n<p>Just my $0.02!</p>\n"
},
{
"answer_id": 12585596,
"author": "jpgeek",
"author_id": 454246,
"author_profile": "https://Stackoverflow.com/users/454246",
"pm_score": 4,
"selected": false,
"text": "<p><strong>FINALLY, test-unit has this implemented! Woot!</strong> \nIf you are using v 2.5.2 or later, you can just use this:</p>\n\n<pre><code>Test::Unit.at_start do\n # initialization stuff here\nend\n</code></pre>\n\n<p>This will run once when you start your tests off. There are also callbacks which run at the beginning of each test case (startup), in addition to the ones that run before every test (setup).</p>\n\n<p><a href=\"http://test-unit.rubyforge.org/test-unit/en/Test/Unit.html#at_start-class_method\" rel=\"noreferrer\">http://test-unit.rubyforge.org/test-unit/en/Test/Unit.html#at_start-class_method</a></p>\n"
},
{
"answer_id": 18850444,
"author": "aerostitch",
"author_id": 2787693,
"author_profile": "https://Stackoverflow.com/users/2787693",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is quite an old post, but I had the issue (and had already written classes using Tes/unit) and ave answered using another method, so if it can help...</p>\n\n<p>If you only need the equivalent of the startup function, you can use the class variables:</p>\n\n<pre><code>class MyTest < Test::Unit::TestCase\n @@cmptr = nil\n def setup\n if @@cmptr.nil?\n @@cmptr = 0\n puts \"runs at first test only\"\n @@var_shared_between_fcs = \"value\"\n end\n puts 'runs before each test'\n end\n def test_stuff\n assert(true)\n end\nend\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/255969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8913/"
] |
I'm struggling with Test::Unit. When I think of unit tests, I think of one simple test per file. But in Ruby's framework, I must instead write:
```
class MyTest < Test::Unit::TestCase
def setup
end
def test_1
end
def test_1
end
end
```
But setup and teardown run for every invocation of a test\_\* method. This is exactly what I don't want. Rather, I want a setup method that runs just once for the whole class. But I can't seem to write my own initialize() without breaking TestCase's initialize.
Is that possible? Or am I making this hopelessly complicated?
|
As mentioned in Hal Fulton's book "The Ruby Way".
He overrides the self.suite method of Test::Unit which allows the test cases in a class to run as a suite.
```
def self.suite
mysuite = super
def mysuite.run(*args)
MyTest.startup()
super
MyTest.shutdown()
end
mysuite
end
```
Here is an example:
```
class MyTest < Test::Unit::TestCase
class << self
def startup
puts 'runs only once at start'
end
def shutdown
puts 'runs only once at end'
end
def suite
mysuite = super
def mysuite.run(*args)
MyTest.startup()
super
MyTest.shutdown()
end
mysuite
end
end
def setup
puts 'runs before each test'
end
def teardown
puts 'runs after each test'
end
def test_stuff
assert(true)
end
end
```
|
256,021 |
<p>I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also creates an html index file with links to each of the snips. So I can click the hyperlink to see the file, make a note in a spreadsheet to indicate if the file is correct or not and then use the back button in the browser to take me back to the index list. </p>
<p>I was sitting here wondering if I could somehow create a delete button in the browser next to the hyperlink. My thought is I would click the hyperlink, make a judgment about the file and if it is not one I want to keep then when I get back to the main page I just press the delete button and it is gone from the directory. </p>
<p>Does anyone have any idea if this is possible. I am writing this in python but clearly the issue is is there a way to create an htm file with a delete button-I would just use Python to write the commands for the deletion button.</p>
|
[
{
"answer_id": 256028,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You would have to write the web page in Python. There are many Python web frameworks out there (e.g. Django) that are easy to work with. You could convert your entire scripting framework to a web application that has a worker thread going and crawling through html pages, saving them to a particular location, indexing them for you to see and providing a delete button that calls the system's delete function on the particular file.</p>\n"
},
{
"answer_id": 256031,
"author": "AlexJReid",
"author_id": 32320,
"author_profile": "https://Stackoverflow.com/users/32320",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than having your script output static HTML files, with a little amount of work you could probably adapt your script to run as a small web application with the help of something like web.py.</p>\n\n<p>You would start your script and point a browser at <a href=\"http://localhost:8080\" rel=\"nofollow noreferrer\">http://localhost:8080</a>, for instance. The web browser would be your user interface.</p>\n\n<p>To achieve the 'delete' functionality, all you need to do is write some Python that gets executed when a form is submitted to actually perform the deletion.</p>\n"
},
{
"answer_id": 256040,
"author": "lacker",
"author_id": 2652,
"author_profile": "https://Stackoverflow.com/users/2652",
"pm_score": 1,
"selected": false,
"text": "<p>You could make this even simpler by making it all happen in one main page. Instead of having a list of hyperlinks, just have the main page have one frame that loads one of the autocreated pages in it. Put a couple of buttons at the bottom - a \"Keep this page\" and a \"Delete this page.\" When you click either button, the main page refreshes, this time with the next autocreated page in the frame.</p>\n\n<p>You could make this as a cgi script in your favorite scripting language. You can't just do this in html because an html page only does stuff client-side, and you can only delete files server-side. You will probably need as cgi args the page to show in the frame, and the last page you viewed if the button click was a \"delete\".</p>\n"
},
{
"answer_id": 303086,
"author": "PyNEwbie",
"author_id": 30105,
"author_profile": "https://Stackoverflow.com/users/30105",
"pm_score": 1,
"selected": true,
"text": "<p>Well I finally found an answer that achieved what I wanted-I did not want to learn a new language-Python is hard enough given my lack or experience</p>\n\n<pre><code>def OnDelete(self, event):\n assert self.current, \"invalid delete operation\"\n try:\n os.remove(os.path.join(self.cwd, self.current))\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/256021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30105/"
] |
I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also creates an html index file with links to each of the snips. So I can click the hyperlink to see the file, make a note in a spreadsheet to indicate if the file is correct or not and then use the back button in the browser to take me back to the index list.
I was sitting here wondering if I could somehow create a delete button in the browser next to the hyperlink. My thought is I would click the hyperlink, make a judgment about the file and if it is not one I want to keep then when I get back to the main page I just press the delete button and it is gone from the directory.
Does anyone have any idea if this is possible. I am writing this in python but clearly the issue is is there a way to create an htm file with a delete button-I would just use Python to write the commands for the deletion button.
|
Well I finally found an answer that achieved what I wanted-I did not want to learn a new language-Python is hard enough given my lack or experience
```
def OnDelete(self, event):
assert self.current, "invalid delete operation"
try:
os.remove(os.path.join(self.cwd, self.current))
```
|
256,027 |
<p>I am developing an application which will be connected to Access database at the beginning and the plan is to switch to MS SQL or SQL Express in the near future. The datatables structures are same for both types of databases and I am trying to avoid duplicating the code and trying to find the way to minimize the code.</p>
<p>For example I wrote the following function for retrieving data from Access database:</p>
<pre><code>public static DataTable GetActiveCalls()
{
string select = "SELECT call_id, call_time, msisdn, status FROM call WHERE status = 0 OR status = 1 ORDER by call_id ASC";
OleDbCommand cmd = new OleDbCommand(select, conn);
DataTable dt = new DataTable("Active Calls");
OleDbDataAdapter DA = new OleDbDataAdapter(cmd);
try
{
conn.Open();
DA.Fill(dt);
}
catch (Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
return dt;
}
</code></pre>
<p>and the following code is for SQL Express database:</p>
<pre><code>public static DataTable GetActiveCalls()
{
string select = "SELECT call_id, call_time, msisdn, status FROM call WHERE status = 0 OR status = 1 ORDER by call_id ASC";
SqlCommand cmd = new SqlCommand(select, conn);
DataTable dt = new DataTable("Active Calls");
SqlDataAdapter DA = new SqlDataAdapter(cmd);
try
{
conn.Open();
DA.Fill(dt);
}
catch (Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
return dt;
}
</code></pre>
<p>These two methods are almost the same. The only differences are SqlCommand/OleDbCommand and SqlDataAdapter/OleDbDataAdapter.
There are also some methods which take arguments for example:</p>
<pre><code>public static void AddMessage(string callID, string content)
{
string select =
"INSERT INTO message(key, direction, content, read, write_time) VALUES (@callId, 0, @content, 0, @insertTime)";
OleDbCommand cmd = new OleDbCommand(select, conn);
cmd.Parameters.AddWithValue("callId", callID.ToString());
cmd.Parameters.AddWithValue("content", content);
cmd.Parameters.AddWithValue("insertTime", DateTime.Now.ToString());
try
{
conn.Open();
cmd.ExecuteScalar();
}
catch (Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
}
</code></pre>
<p>In this case SQL query string is also the same for both databases but there is the difference between the type of cmd (SqlCommand/OleDbCommand).</p>
<p>I would really appreciate if anyone could give any suggestion about how to avoid duplicating the code and optimize the given problem.</p>
|
[
{
"answer_id": 256028,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You would have to write the web page in Python. There are many Python web frameworks out there (e.g. Django) that are easy to work with. You could convert your entire scripting framework to a web application that has a worker thread going and crawling through html pages, saving them to a particular location, indexing them for you to see and providing a delete button that calls the system's delete function on the particular file.</p>\n"
},
{
"answer_id": 256031,
"author": "AlexJReid",
"author_id": 32320,
"author_profile": "https://Stackoverflow.com/users/32320",
"pm_score": 0,
"selected": false,
"text": "<p>Rather than having your script output static HTML files, with a little amount of work you could probably adapt your script to run as a small web application with the help of something like web.py.</p>\n\n<p>You would start your script and point a browser at <a href=\"http://localhost:8080\" rel=\"nofollow noreferrer\">http://localhost:8080</a>, for instance. The web browser would be your user interface.</p>\n\n<p>To achieve the 'delete' functionality, all you need to do is write some Python that gets executed when a form is submitted to actually perform the deletion.</p>\n"
},
{
"answer_id": 256040,
"author": "lacker",
"author_id": 2652,
"author_profile": "https://Stackoverflow.com/users/2652",
"pm_score": 1,
"selected": false,
"text": "<p>You could make this even simpler by making it all happen in one main page. Instead of having a list of hyperlinks, just have the main page have one frame that loads one of the autocreated pages in it. Put a couple of buttons at the bottom - a \"Keep this page\" and a \"Delete this page.\" When you click either button, the main page refreshes, this time with the next autocreated page in the frame.</p>\n\n<p>You could make this as a cgi script in your favorite scripting language. You can't just do this in html because an html page only does stuff client-side, and you can only delete files server-side. You will probably need as cgi args the page to show in the frame, and the last page you viewed if the button click was a \"delete\".</p>\n"
},
{
"answer_id": 303086,
"author": "PyNEwbie",
"author_id": 30105,
"author_profile": "https://Stackoverflow.com/users/30105",
"pm_score": 1,
"selected": true,
"text": "<p>Well I finally found an answer that achieved what I wanted-I did not want to learn a new language-Python is hard enough given my lack or experience</p>\n\n<pre><code>def OnDelete(self, event):\n assert self.current, \"invalid delete operation\"\n try:\n os.remove(os.path.join(self.cwd, self.current))\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/256027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22996/"
] |
I am developing an application which will be connected to Access database at the beginning and the plan is to switch to MS SQL or SQL Express in the near future. The datatables structures are same for both types of databases and I am trying to avoid duplicating the code and trying to find the way to minimize the code.
For example I wrote the following function for retrieving data from Access database:
```
public static DataTable GetActiveCalls()
{
string select = "SELECT call_id, call_time, msisdn, status FROM call WHERE status = 0 OR status = 1 ORDER by call_id ASC";
OleDbCommand cmd = new OleDbCommand(select, conn);
DataTable dt = new DataTable("Active Calls");
OleDbDataAdapter DA = new OleDbDataAdapter(cmd);
try
{
conn.Open();
DA.Fill(dt);
}
catch (Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
return dt;
}
```
and the following code is for SQL Express database:
```
public static DataTable GetActiveCalls()
{
string select = "SELECT call_id, call_time, msisdn, status FROM call WHERE status = 0 OR status = 1 ORDER by call_id ASC";
SqlCommand cmd = new SqlCommand(select, conn);
DataTable dt = new DataTable("Active Calls");
SqlDataAdapter DA = new SqlDataAdapter(cmd);
try
{
conn.Open();
DA.Fill(dt);
}
catch (Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
return dt;
}
```
These two methods are almost the same. The only differences are SqlCommand/OleDbCommand and SqlDataAdapter/OleDbDataAdapter.
There are also some methods which take arguments for example:
```
public static void AddMessage(string callID, string content)
{
string select =
"INSERT INTO message(key, direction, content, read, write_time) VALUES (@callId, 0, @content, 0, @insertTime)";
OleDbCommand cmd = new OleDbCommand(select, conn);
cmd.Parameters.AddWithValue("callId", callID.ToString());
cmd.Parameters.AddWithValue("content", content);
cmd.Parameters.AddWithValue("insertTime", DateTime.Now.ToString());
try
{
conn.Open();
cmd.ExecuteScalar();
}
catch (Exception ex)
{
string sDummy = ex.ToString();
}
finally
{
conn.Close();
}
}
```
In this case SQL query string is also the same for both databases but there is the difference between the type of cmd (SqlCommand/OleDbCommand).
I would really appreciate if anyone could give any suggestion about how to avoid duplicating the code and optimize the given problem.
|
Well I finally found an answer that achieved what I wanted-I did not want to learn a new language-Python is hard enough given my lack or experience
```
def OnDelete(self, event):
assert self.current, "invalid delete operation"
try:
os.remove(os.path.join(self.cwd, self.current))
```
|
256,038 |
<p>I'm using a <code>std::map</code> (VC++ implementation) and it's a little slow for lookups via the map's find method. </p>
<p>The key type is <code>std::string</code>.</p>
<p>Can I increase the performance of this <code>std::map</code> lookup via a custom key compare override for the map? For example, maybe <code>std::string</code> < compare doesn't take into consideration a simple <code>string::size()</code> compare before comparing its data?</p>
<p>Any other ideas to speed up the compare?</p>
<p>In my situation the map will always contain < 15 elements, but it is being queried non stop and performance is critical. Maybe there is a better data structure that I can use that would be faster?</p>
<p>Update: The map contains file paths.</p>
<p>Update2: The map's elements are changing often.</p>
|
[
{
"answer_id": 256044,
"author": "lacker",
"author_id": 2652,
"author_profile": "https://Stackoverflow.com/users/2652",
"pm_score": 3,
"selected": false,
"text": "<p>The first thing is to try using a hash_map if that's possible - you are right that the standard string compare doesn't first check for size (since it compares lexicographically), but writing your own map code is something you'd be better off avoiding. From your question it sounds like you do not need to iterate over ranges; in that case map doesn't have anything hash_map doesn't.</p>\n\n<p>It also depends on what sort of keys you have in your map. Are they typically very long? Also what does \"a little slow\" mean? If you have not profiled the code it's quite possible that it's a different part taking time.</p>\n\n<p>Update: Hmm, the bottleneck in your program is a map::find, but the map always has less than 15 elements. This makes me suspect that the profile was somehow misleading, because a find on a map this small should not be slow, at all. In fact, a map::find should be so fast, just the overhead of profiling could be more than the find call itself. I have to ask again, are you sure this is really the bottleneck in your program? You say the strings are paths, but you're not doing any sort of OS calls, file system access, disk access in this loop? Any of those should be orders of magnitude slower than a map::find on a small map. Really any way of getting a string should be slower than the map::find.</p>\n"
},
{
"answer_id": 256052,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 2,
"selected": false,
"text": "<p>std::map's comparator isn't std::equal_to it's std::less, I'm not sure what the best way to short circuit a < compare so that it would be faster than the built in one.</p>\n\n<p>If there are always < 15 elems, perhaps you could use a key besides std::string?</p>\n"
},
{
"answer_id": 256082,
"author": "coryan",
"author_id": 33325,
"author_profile": "https://Stackoverflow.com/users/33325",
"pm_score": 1,
"selected": false,
"text": "<p>Here are some things you can consider:</p>\n\n<p>0) Are you sure this is where the performance bottleneck is? Like the results from Quantify, Cachegrind, gprof or something like that? Because lookups on such a smap map should be fairly fast...</p>\n\n<p>1) You can override the functor used to compare the keys in std::map<>, there is a second template parameter to do that. I doubt you can do much better than operator<, however.</p>\n\n<p>2) Are the contents of the map changing a lot? If not, and given the very small size of your map, maybe using a sorted vector and binary search could yield better results (for example because you can exploit memory locality better.</p>\n\n<p>3) Are the elements known at compile time? You could use a perfect hash function to improve lookup times if that is the case. Search for gperf on the web.</p>\n\n<p>4) Do you have a lot of lookups that fail to find anything? If so, maybe comparing with the first and last elements in the collection may eliminate many mismatches quicker than a full search every time.</p>\n\n<p>These have been suggested already, but in more detail:</p>\n\n<p>5) Since you have so few strings, maybe you could use a different key. For example, are your keys all the same size? Can you use a class containing a fixed-length array of characters? Can you convert your strings to numbers or some data structure with only numbers?</p>\n"
},
{
"answer_id": 256089,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 4,
"selected": false,
"text": "<p>As <a href=\"https://stackoverflow.com/questions/256038/how-can-i-increase-the-performance-in-a-map-lookup-with-key-type-stdstring#256052\">Even</a> said the operator used in a <code>set</code> is <code><</code> not <code>==</code>.</p>\n\n<p>If you don't care about the order of the strings in your <code>set</code> you can pass the <code>set</code> a custom comparator that performs better than the regular <em>less-than</em>. </p>\n\n<p>For example if a lot of your strings have similar prefixes (but they vary in length) you can sort by string length (since <code>string.length</code> is constant speed).</p>\n\n<p>If you do so beware a common mistake:</p>\n\n<pre><code>struct comp {\n bool operator()(const std::string& lhs, const std::string& rhs)\n {\n if (lhs.length() < rhs.length())\n return true;\n return lhs < rhs;\n }\n};\n</code></pre>\n\n<p>This operator does not maintain a <a href=\"http://en.wikipedia.org/wiki/Strict_weak_ordering\" rel=\"nofollow noreferrer\">strict weak ordering</a>, as it can treat two strings as each less than the other.</p>\n\n<pre><code>string a = \"z\";\nstring b = \"aa\";\n</code></pre>\n\n<p>Follow the logic and you'll see that <code>comp(a, b) == true</code> and <code>comp(b, a) == true</code>.</p>\n\n<p>The correct implementation is:</p>\n\n<pre><code>struct comp {\n bool operator()(const std::string& lhs, const std::string& rhs)\n {\n if (lhs.length() != rhs.length())\n return lhs.length() < rhs.length();\n return lhs < rhs;\n }\n};\n</code></pre>\n"
},
{
"answer_id": 256095,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 2,
"selected": false,
"text": "<p>You can try to use a sorted vector (<a href=\"http://www.codeproject.com/KB/stl/sorted_vector.aspx\" rel=\"nofollow noreferrer\">here's one sample</a>), this may turn out to be faster (you'll have to <a href=\"https://stackoverflow.com/questions/61278/quick-and-dirty-way-to-profile-your-code#61279\">profile it to make sure</a> of-course). </p>\n\n<p>Reasons to think it'll be faster:</p>\n\n<ol>\n<li>Less memory allocations and deallocations (the vector will expand to the maximal size used and then reuse freed memory).</li>\n<li>Binary find with random access should be faster than tree traversal (espacially due to data locality).</li>\n</ol>\n\n<p>Reasons to think it'll be slower:</p>\n\n<ol>\n<li>Deleations and additions will mean moving strings around in memory, since <code>string</code>'s <code>swap</code> is efficiant and the size of the data set is small this may not be an issue.</li>\n</ol>\n"
},
{
"answer_id": 256096,
"author": "Dave Hillier",
"author_id": 1575281,
"author_profile": "https://Stackoverflow.com/users/1575281",
"pm_score": 0,
"selected": false,
"text": "<p><code>hash_map</code> is not standard, try using <code>unordered_map</code> available in tr1 (which is available in boost if your tool chain doesn't already have it).</p>\n\n<p>For small numbers of strings you might be better using <code>vector</code>, as <code>map</code> is typically implemented as a tree.</p>\n"
},
{
"answer_id": 256097,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>Motti has a good solution. However, I'm pretty sure that for your < 15 elements a map isn't the right way because its overhead will always be greater than that of a simple lookup table with an appropriate hashing scheme. In your case, it might even be enough to hash by length alone, and if that still produces collisions, use a linear search through all entries of the same length.</p>\n\n<p>To establish if I'm right, a benchmark is of course required but I'm quite sure of its outcome.</p>\n"
},
{
"answer_id": 256137,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 1,
"selected": false,
"text": "<p>Depending on the usage cases, there are some other techniques you can use. For example we had an application that needed to keep up with over a million different file paths. The problem with that there were thousands of objects that needed to keep small maps of these file paths.</p>\n\n<p>Since adding new file paths to the data set was an infrequent operation, when path was added to the system, a master map was searched. If the path was not found, then it was added and a new sequenced integer (starting at 1) was returned. If the path already existed, then the previously assigned integer was returned. Then each map maintained by each object was converted from a string based map to an integer map. Not only did this greatly improve performance, it reduced memory usage by not having so many duplicate copies of the strings.</p>\n\n<p>Sure, this is a very specific optimization. But when it comes to performance improvements, you often find yourself having to make tailored solutions to specific problems.</p>\n\n<p>And I hate strings :) Not are they slow to compare, but they can really trash your CPU caches on high performance software.</p>\n"
},
{
"answer_id": 256243,
"author": "Phil Hord",
"author_id": 33342,
"author_profile": "https://Stackoverflow.com/users/33342",
"pm_score": 5,
"selected": true,
"text": "<p>First, turn off all the profiling and DEBUG switches. These can slow down STL immensely.</p>\n\n<p>If that's not it, part of the problem may be that your strings are identical for the first 80-90% of the string. This isn't bad for map, necessarily, but it is for string comparisons. If this is the case, your search can take much longer. </p>\n\n<p>For example, in this code find() will likely result in a couple of string compares, but each will return after comparing the first character until \"david\", and then the first three characters will be checked. So at most, 5 characters will be checked per call.</p>\n\n<pre><code>map<string,int> names;\nnames[\"larry\"] = 1;\nnames[\"david\"] = 2;\nnames[\"juanita\"] = 3;\n\nmap<string,int>::iterator iter = names.find(\"daniel\");\n</code></pre>\n\n<p>On the other hand, in the following code, find() will likely check 135+ characters:</p>\n\n<pre><code>map<string,int> names;\nnames[\"/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/wilma\"] = 1;\nnames[\"/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/fred\"] = 2;\nnames[\"/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/barney\"] = 3;\n\nmap<string,int>::iterator iter = names.find(\"/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/betty\");\n</code></pre>\n\n<p>That's because the string comparisons have to search deeper to find a match since the beginning of each string is the same.</p>\n\n<p>Using size() in your comparison for equality won't help you much here since your data set is so small. A std::map is kept sorted so its elements can be searched with a binary search. Each call to find should result in less than 5 string comparisons for a miss, and an average of 2 comparisons for a hit. But it does depend on your data. If most of your path strings are of different lengths, then a size check like Motti describes could help a lot.</p>\n\n<p>Something to consider when thinking of alternative algorithms is how many many \"hits\" you get. Are most of your find() calls returning end() or a hit? If most of your find()s return end() (misses) then you are searching the entire map every time (2logn string compares). </p>\n\n<p>Hash_map is a good idea; it should cut your search time in about half for hits; more for misses. </p>\n\n<p>A custom algorithm may be called for because of the nature of path strings, especially if your data set has common ancestry like in the above code.</p>\n\n<p>Another thing to consider is how you get your search strings. If you are reusing them, it may help to encode them into something that is easier to compare. If you use them once and discard them, then this encoding step is probably too expensive.</p>\n\n<p>I used something like a Huffman coding tree once (a long time ago) to optimize string searches. A binary string search tree like that may be more efficient in some cases, but its pretty expensive for small sets like yours.</p>\n\n<p>Finally, look into alternative std::map implementations. I've heard bad things about some of VC's stl code performance. The DEBUG library in particular is bad about checking you on every call. <a href=\"http://stlport.sourceforge.net/\" rel=\"noreferrer\">StlPort</a> used to be a good alternative, but I haven't tried it in a few years. I've always loved <a href=\"http://www.boost.org/\" rel=\"noreferrer\">Boost</a> too.</p>\n"
},
{
"answer_id": 256263,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 1,
"selected": false,
"text": "<p>Try std::tr1::unordered_map (found in the header <tr1/unordered_map>). This is a hash map, and, while it doesn't maintain a sorted order of elements, will likely be far faster than a regular map.</p>\n\n<p>If your compiler doesn't support TR1, get a newer version. MSVC and gcc both support TR1, and I believe the newest versions of most other compilers also have support. Unfortunately, a lot of the library reference sites haven't been updated, so TR1 remains a largely-unknown piece of technology.</p>\n\n<p>I hope C++0x isn't the same way.</p>\n\n<p>EDIT: Note that the default hashing method for tr1::unordered_map is tr1::hash, which needs to be specialized to work on a UDT, probably.</p>\n"
},
{
"answer_id": 256290,
"author": "Andrew Top",
"author_id": 30036,
"author_profile": "https://Stackoverflow.com/users/30036",
"pm_score": 2,
"selected": false,
"text": "<p>You might consider pre-computing a hash for a string, and saving that in your map. Doing so gives the advantage of hash compares instead of string compares during the search through the std::map tree.</p>\n\n<pre><code>class HashedString\n{\n unsigned m_hash;\n std::string m_string;\n\npublic:\n HashedString(const std::string& str)\n : m_hash(HashString(str))\n , m_string(str)\n {};\n // ... copy constructor and etc...\n\n unsigned GetHash() const {return m_hash;}\n const std::string& GetString() const {return m_string;}\n};\n</code></pre>\n\n<p>This has the benefits of computing a hash of the string once, on construction. After this, you could implement a comparison function:</p>\n\n<pre><code>struct comp\n{\n bool operator()(const HashedString& lhs, const HashedString& rhs)\n {\n if(lhs.GetHash() < rhs.GetHash()) return true;\n if(lhs.GetHash() > rhs.GetHash()) return false;\n return lhs.GetString() < rhs.GetString();\n }\n};\n</code></pre>\n\n<p>Since hashes are now computed on <code>HashedString</code> construction, they are stored that way in the std::map, and so the compare can happen very quickly (an integer compare) in an astronomically high percentage of the time, falling back on standard string compares when the hashes are equal.</p>\n"
},
{
"answer_id": 256444,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 1,
"selected": false,
"text": "<p>Where you have long common substrings, a trie might be a better data structure than a map or a hash_map. I said \"might\", though - a hash_map already only traverses the key once per lookup, so should be fairly fast. I won't discuss it further since others already have.</p>\n\n<p>You could also consider a splay tree if some keys are more frequently looked up than others, but of course this makes the worst-case lookup worse than a balanced tree, and lookups are mutating operations, which may matter to you if you're using e.g. a reader-writer lock.</p>\n\n<p>If you care about the performance of lookups more than modifications, you might do better with an AVL tree than a red-black, which I <em>think</em> is what STL implementations generally use for map. An AVL tree is typically better balanced and so will on average require fewer comparisons per lookup, but the difference is marginal.</p>\n\n<p>Finding an implementation of these that you're happy with might be an issue. A search on the Boost main page suggests they have a splay and AVL tree but not a trie.</p>\n\n<p>You mentioned in a comment that you never have a lookup that fails to find anything. So you could in theory skip the final comparison, which in a tree of 15 < 2^4 elements could give you something like a 20-25% speedup without doing anything else. In fact, maybe more than that, since equal strings are the slowest to compare. Whether it's worth writing your own container just for this optimisation is another question.</p>\n\n<p>You might also consider locality of reference - I don't know whether you could avoid the occasional page miss by allocating the keys and the nodes out of a small heap. If you only need about 15 entries at a time, then assuming a file name limit below 256 bytes you could ensure that everything accessed during a lookup fits into a single 4k page (apart from the key being looked up, of course). It may be that comparing the strings is insignificant compared with a couple of page loads. However, if this is your bottleneck there must be an enormous number of lookups going on, so I'd guess that everything is reasonably close to the CPU. Worth checking, maybe.</p>\n\n<p>Another thought: if you are using pessimistic locking on a structure where there's a lot of contention (you said in a comment the program is massively multi-threaded) then regardless of what the profiler tells you (what code the CPU cycles are spent in), it might be costing you more than you think by effectively limiting you to 1 core. Try a reader-writer lock?</p>\n"
},
{
"answer_id": 260936,
"author": "An̲̳̳drew",
"author_id": 17035,
"author_profile": "https://Stackoverflow.com/users/17035",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe you could reverse the strings prior to using them as keys in the map? That could help if the first few letters of each string are identical.</p>\n"
},
{
"answer_id": 1168691,
"author": "navigator",
"author_id": 115387,
"author_profile": "https://Stackoverflow.com/users/115387",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you use a hashtable instead? boost::unordered_map could do. Or you can roll out your own solution, and store the crc of a string instead of the string itself. Or better yet, put #defines for the strings, and use those for lookup, e.g.,</p>\n\n<pre><code>#define \"STRING_1\" STRING_1\n</code></pre>\n"
}
] |
2008/11/01
|
[
"https://Stackoverflow.com/questions/256038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
I'm using a `std::map` (VC++ implementation) and it's a little slow for lookups via the map's find method.
The key type is `std::string`.
Can I increase the performance of this `std::map` lookup via a custom key compare override for the map? For example, maybe `std::string` < compare doesn't take into consideration a simple `string::size()` compare before comparing its data?
Any other ideas to speed up the compare?
In my situation the map will always contain < 15 elements, but it is being queried non stop and performance is critical. Maybe there is a better data structure that I can use that would be faster?
Update: The map contains file paths.
Update2: The map's elements are changing often.
|
First, turn off all the profiling and DEBUG switches. These can slow down STL immensely.
If that's not it, part of the problem may be that your strings are identical for the first 80-90% of the string. This isn't bad for map, necessarily, but it is for string comparisons. If this is the case, your search can take much longer.
For example, in this code find() will likely result in a couple of string compares, but each will return after comparing the first character until "david", and then the first three characters will be checked. So at most, 5 characters will be checked per call.
```
map<string,int> names;
names["larry"] = 1;
names["david"] = 2;
names["juanita"] = 3;
map<string,int>::iterator iter = names.find("daniel");
```
On the other hand, in the following code, find() will likely check 135+ characters:
```
map<string,int> names;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/wilma"] = 1;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/fred"] = 2;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/barney"] = 3;
map<string,int>::iterator iter = names.find("/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/betty");
```
That's because the string comparisons have to search deeper to find a match since the beginning of each string is the same.
Using size() in your comparison for equality won't help you much here since your data set is so small. A std::map is kept sorted so its elements can be searched with a binary search. Each call to find should result in less than 5 string comparisons for a miss, and an average of 2 comparisons for a hit. But it does depend on your data. If most of your path strings are of different lengths, then a size check like Motti describes could help a lot.
Something to consider when thinking of alternative algorithms is how many many "hits" you get. Are most of your find() calls returning end() or a hit? If most of your find()s return end() (misses) then you are searching the entire map every time (2logn string compares).
Hash\_map is a good idea; it should cut your search time in about half for hits; more for misses.
A custom algorithm may be called for because of the nature of path strings, especially if your data set has common ancestry like in the above code.
Another thing to consider is how you get your search strings. If you are reusing them, it may help to encode them into something that is easier to compare. If you use them once and discard them, then this encoding step is probably too expensive.
I used something like a Huffman coding tree once (a long time ago) to optimize string searches. A binary string search tree like that may be more efficient in some cases, but its pretty expensive for small sets like yours.
Finally, look into alternative std::map implementations. I've heard bad things about some of VC's stl code performance. The DEBUG library in particular is bad about checking you on every call. [StlPort](http://stlport.sourceforge.net/) used to be a good alternative, but I haven't tried it in a few years. I've always loved [Boost](http://www.boost.org/) too.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.