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
|
---|---|---|---|---|---|---|
152,024 |
<p>I have a submission table that is very simple: userId, submissionGuid</p>
<p>I want to select the username (simple inner join to get it) of all the users who have more than 10 submissions in the table. </p>
<p>I would do this with embedded queries and a group by to count submissions... but is there a better way of doing it (without embedded queries)?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 152030,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select userId, count(*)\nfrom submissions\nhaving count(*) > 10\ngroup by userId\n</code></pre>\n"
},
{
"answer_id": 152037,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 4,
"selected": true,
"text": "<p>This is the simplest way, I believe:</p>\n\n<pre><code>select userId\nfrom submission \ngroup by userId\nhaving count(submissionGuid) > 10\n</code></pre>\n"
},
{
"answer_id": 152044,
"author": "EggyBach",
"author_id": 15475,
"author_profile": "https://Stackoverflow.com/users/15475",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT \n username \nFROM \n usertable \n JOIN submissions \n ON usertable.userid = submissions.userid \nGROUP BY \n usertable.username \nHAVING \n Count(*) > 1\n</code></pre>\n\n<p>*Assuming that your \"Users\" table is call usertable and that it has a column called \"UserName\"</p>\n"
},
{
"answer_id": 152057,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 0,
"selected": false,
"text": "<p>I think the correct query is this (SQL Server):</p>\n\n<pre><code>SELECT s.userId, u.userName\nFROM submission s INNER JOIN users u on u.userId = s.userId \nGROUP BY s.userId, u.username\nHAVING COUNT(submissionGuid) > 10\n</code></pre>\n\n<p>If you don't have the HAVING clause:</p>\n\n<pre><code>SELECT u.userId, u.userName\nFROM users u INNER JOIN (\n SELECT userId, COUNT(submissionGuid) AS cnt\n FROM submission\n GROUP BY userId ) sc ON sc.userId = u.userId\nWHERE sc.cnt > 10\n</code></pre>\n"
},
{
"answer_id": 152570,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>select userid, count(submissionGUID) as submitCount</p>\n\n<p>from Submissions</p>\n\n<p>group by userid, submitCount</p>\n\n<p>having submitCount > 10</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23695/"
] |
I have a submission table that is very simple: userId, submissionGuid
I want to select the username (simple inner join to get it) of all the users who have more than 10 submissions in the table.
I would do this with embedded queries and a group by to count submissions... but is there a better way of doing it (without embedded queries)?
Thanks!
|
This is the simplest way, I believe:
```
select userId
from submission
group by userId
having count(submissionGuid) > 10
```
|
152,028 |
<p>I want to be able to compare an image taken from a webcam to an image stored on my computer.</p>
<p>The library doesn't need to be one hundred percent accurate as it won't be used in anything mission critical (e.g. police investigation), I just want something OK I can work with.</p>
<p>I have tried a demonstration project for <a href="http://www.codeproject.com/KB/cs/BackPropagationNeuralNet.aspx" rel="noreferrer">Image Recognition from CodeProject</a>, and it only works with small images / doesn't work at all when I compare an exact same image 120x90 pixels (this is not classified as OK :P ).</p>
<p>Has there been any success with image recognition before?</p>
<p>If so, would you be able to provide a link to a library I could use in either C# or VB.NET?</p>
|
[
{
"answer_id": 152059,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 7,
"selected": true,
"text": "<p>You could try this: <a href=\"http://code.google.com/p/aforge/\" rel=\"noreferrer\">http://code.google.com/p/aforge/</a></p>\n\n<p>It includes a comparison analysis that will give you a score. There are many other great imaging features of all types included as well.</p>\n\n<pre><code>// The class also can be used to get similarity level between two image of the same size, which can be useful to get information about how different/similar are images:\n// Create template matching algorithm's instance\n\n// Use zero similarity to make sure algorithm will provide anything\nExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0);\n\n// Compare two images\nTemplateMatch[] matchings = tm.ProcessImage( image1, image2 );\n\n// Check similarity level\nif (matchings[0].Similarity > 0.95)\n{\n // Do something with quite similar images\n}\n</code></pre>\n"
},
{
"answer_id": 4025495,
"author": "snndynya",
"author_id": 487822,
"author_profile": "https://Stackoverflow.com/users/487822",
"pm_score": 3,
"selected": false,
"text": "<p>You can exactly use <a href=\"http://www.emgu.com/wiki/index.php/Main_Page\" rel=\"nofollow noreferrer\">EmguCV</a> for .NET.</p>\n"
},
{
"answer_id": 12421754,
"author": "Hydarnes",
"author_id": 1671007,
"author_profile": "https://Stackoverflow.com/users/1671007",
"pm_score": 2,
"selected": false,
"text": "<p>I did it simply. Just download the EyeOpen library <a href=\"http://similarimagesfinder.codeplex.com/\" rel=\"nofollow\">here</a>.\nThen use it in your C# class and write this:</p>\n\n<pre><code> use eyeopen.imaging.processing\n</code></pre>\n\n<p>Write</p>\n\n<pre><code>ComparableImage cc;\n\nComparableImage pc;\n\nint sim;\n\nvoid compare(object sender, EventArgs e){\n\n pc = new ComparableImage(new FileInfo(files));\n\n cc = new ComparableImage(new FileInfo(file));\n\n pc.CalculateSimilarity(cc);\n\n sim = pc.CalculateSimilarity(cc);\n\n int sim2 = sim*100\n\n Messagebox.show(sim2 + \"% similar\");\n}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20900/"
] |
I want to be able to compare an image taken from a webcam to an image stored on my computer.
The library doesn't need to be one hundred percent accurate as it won't be used in anything mission critical (e.g. police investigation), I just want something OK I can work with.
I have tried a demonstration project for [Image Recognition from CodeProject](http://www.codeproject.com/KB/cs/BackPropagationNeuralNet.aspx), and it only works with small images / doesn't work at all when I compare an exact same image 120x90 pixels (this is not classified as OK :P ).
Has there been any success with image recognition before?
If so, would you be able to provide a link to a library I could use in either C# or VB.NET?
|
You could try this: <http://code.google.com/p/aforge/>
It includes a comparison analysis that will give you a score. There are many other great imaging features of all types included as well.
```
// The class also can be used to get similarity level between two image of the same size, which can be useful to get information about how different/similar are images:
// Create template matching algorithm's instance
// Use zero similarity to make sure algorithm will provide anything
ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0);
// Compare two images
TemplateMatch[] matchings = tm.ProcessImage( image1, image2 );
// Check similarity level
if (matchings[0].Similarity > 0.95)
{
// Do something with quite similar images
}
```
|
152,068 |
<p>I've been working on a very simple crud generator for pylons. I came up with something that inspects </p>
<pre><code>SomeClass._sa_class_manager.mapper.c
</code></pre>
<p>Is it ok to inspect this (or to call methods begining with underscore)? I always kind of assumed this is legal though frowned upon as it relies heavily on the internal structure of a class/object. But hey, since python does not really have interfaces in the Java sense maybe it is OK.</p>
|
[
{
"answer_id": 152080,
"author": "pi.",
"author_id": 15274,
"author_profile": "https://Stackoverflow.com/users/15274",
"pm_score": 0,
"selected": false,
"text": "<p>If it works, why not? You could have problems though when _sa_class_manager gets restructured, binding yourself to this specific version of SQLAlchemy, or creating more work to track the changes. As SQLAlchemy is a fast moving target, you may be there in a year already.</p>\n\n<p>The preferable way would be to integrate your desired API into SQLAlchemy itself.</p>\n"
},
{
"answer_id": 152083,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 4,
"selected": true,
"text": "<p>It is intentional (in Python) that there are no \"private\" scopes. It is a convention that anything that starts with an underscore should not ideally be used, and hence you may not complain if its behavior or definition changes in a next version.</p>\n"
},
{
"answer_id": 152111,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 3,
"selected": false,
"text": "<p>In general, this usually indicates that the method is effectively internal, rather than part of the documented interface, and should not be relied on. Future versions of the library are free to rename or remove such methods, so if you care about future compatability without having to rewrite, avoid doing it.</p>\n"
},
{
"answer_id": 152954,
"author": "giltay",
"author_id": 21106,
"author_profile": "https://Stackoverflow.com/users/21106",
"pm_score": 0,
"selected": false,
"text": "<p>It's generally not a good idea, for reasons already mentioned. However, Python deliberately allows this behaviour in case there is no other way of doing something.</p>\n\n<p>For example, if you have a closed-source compiled Python library where the author didn't think you'd need direct access to a certain object's internal state—but you really do—you can still get at the information you need. You have the same problems mentioned before of keeping up with different versions (if you're lucky enough that it's still maintained) but at least you can actually do what you wanted to do.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/985/"
] |
I've been working on a very simple crud generator for pylons. I came up with something that inspects
```
SomeClass._sa_class_manager.mapper.c
```
Is it ok to inspect this (or to call methods begining with underscore)? I always kind of assumed this is legal though frowned upon as it relies heavily on the internal structure of a class/object. But hey, since python does not really have interfaces in the Java sense maybe it is OK.
|
It is intentional (in Python) that there are no "private" scopes. It is a convention that anything that starts with an underscore should not ideally be used, and hence you may not complain if its behavior or definition changes in a next version.
|
152,071 |
<p>I'm trying to display a boolean field in Report Designer in Visual Studio 2008. When I tried to run it, an error occurred:</p>
<pre><code> "An error has occurred during report processing.
String was not recognized as a valid Boolean."
</code></pre>
<p>I tried to convert it using CBool() but it didn't work. </p>
|
[
{
"answer_id": 152303,
"author": "Jen",
"author_id": 20877,
"author_profile": "https://Stackoverflow.com/users/20877",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using SQL Server 2005. The data type is bit. </p>\n"
},
{
"answer_id": 158565,
"author": "RiskManager",
"author_id": 17997,
"author_profile": "https://Stackoverflow.com/users/17997",
"pm_score": 1,
"selected": false,
"text": "<p>I may be mistaken here, but CBool is to convert to boolean. What you probably want is to convert to string so that it can be displayed. However, I'm not sure what the default behaviour would be (i.e. 0/1, true/false, -1/0, Yes/No, etc.) so you could add a function to the code section in the report to display a boolean the exact way you want.</p>\n"
},
{
"answer_id": 169691,
"author": "roman m",
"author_id": 3661,
"author_profile": "https://Stackoverflow.com/users/3661",
"pm_score": 2,
"selected": false,
"text": "<pre><code>=iif(Fields!YourBool.Value, \"True\", \"False\") \n</code></pre>\n\n<p>Am I missing anything?</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20877/"
] |
I'm trying to display a boolean field in Report Designer in Visual Studio 2008. When I tried to run it, an error occurred:
```
"An error has occurred during report processing.
String was not recognized as a valid Boolean."
```
I tried to convert it using CBool() but it didn't work.
|
```
=iif(Fields!YourBool.Value, "True", "False")
```
Am I missing anything?
|
152,084 |
<p>I'm interested in actual examples of using fixed point combinators (such as the <a href="https://stackoverflow.com/questions/93526/what-is-a-y-combinator">y-combinator</a> in C++. Have you ever used a fixed point combinator with <a href="http://p-stade.sourceforge.net/boost/libs/egg/doc/html/boost_egg/function_adaptors.html#boost_egg.function_adaptors.fix" rel="noreferrer">egg</a> or <a href="http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html" rel="noreferrer">bind</a> in real live code?</p>
<p>I found this example in egg a little dense:</p>
<pre><code>void egg_example()
{
using bll::_1;
using bll::_2;
int r =
fix2(
bll::ret<int>(
// \(f,a) -> a == 0 ? 1 : a * f(a-1)
bll::if_then_else_return( _2 == 0,
1,
_2 * lazy(_1)(_2 - 1)
)
)
) (5);
BOOST_CHECK(r == 5*4*3*2*1);
}
</code></pre>
<p>Can you explain how this all works?</p>
<p>Is there a nice simple example perhaps using bind with perhaps fewer dependancies than this one?</p>
|
[
{
"answer_id": 154267,
"author": "Ted",
"author_id": 8965,
"author_profile": "https://Stackoverflow.com/users/8965",
"pm_score": 6,
"selected": true,
"text": "<p>Here is the same code converted into <code>boost::bind</code> notice the y-combinator and its application site in the main function. I hope this helps.</p>\n\n<pre><code>#include <boost/function.hpp>\n#include <boost/bind.hpp>\n#include <iostream>\n\n// Y-combinator compatible factorial\nint fact(boost::function<int(int)> f,int v)\n{\n if(v == 0)\n return 1;\n else\n return v * f(v -1);\n}\n\n// Y-combinator for the int type\nboost::function<int(int)>\n y(boost::function<int(boost::function<int(int)>,int)> f)\n{\n return boost::bind(f,boost::bind(&y,f),_1);\n}\n\n\nint main(int argc,char** argv)\n{\n boost::function<int(int)> factorial = y(fact);\n std::cout << factorial(5) << std::endl;\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 154514,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Can you explain how this all works?</p>\n</blockquote>\n\n<p>fix2 is a y-combinator (specifically, it is a combinator for functions with two arguments; the first argument is the function (for the purpose of recursion), the second argument is a \"proper\" function argument). It creates recursive functions.</p>\n\n<p>bll::ret(...) appears to create some form of a function object, the body of which is</p>\n\n<pre><code>if(second arg == 0)\n{\n return 1;\n}\nelse\n{\n return second arg * first arg(second arg - 1);\n}\n</code></pre>\n\n<p>The \"lazy\" is presumably there to stop an infinite expansion of the first (function) argument (read up on the difference between lazy and strict y combinators to see why).</p>\n\n<p>The code is quite horrible. Anonymous functions are nice to have, but the hackery to work around C++'s lack of syntactic support make them not worth the effort.</p>\n"
},
{
"answer_id": 11968754,
"author": "matthewtff",
"author_id": 1600499,
"author_profile": "https://Stackoverflow.com/users/1600499",
"pm_score": 3,
"selected": false,
"text": "<pre><code>#include <functional>\n#include <iostream>\n\ntemplate <typename Lamba, typename Type>\nauto y (std::function<Type(Lamba, Type)> f) -> std::function<Type(Type)>\n{\n return std::bind(f, std::bind(&y<Lamba, Type>, f), std::placeholders::_1);\n}\n\nint main(int argc,char** argv)\n{\n std::cout << y < std::function<int(int)>, int> ([](std::function<int(int)> f, int x) {\n return x == 0 ? 1 : x * f(x - 1);\n }) (5) << std::endl;\n return 0;\n}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] |
I'm interested in actual examples of using fixed point combinators (such as the [y-combinator](https://stackoverflow.com/questions/93526/what-is-a-y-combinator) in C++. Have you ever used a fixed point combinator with [egg](http://p-stade.sourceforge.net/boost/libs/egg/doc/html/boost_egg/function_adaptors.html#boost_egg.function_adaptors.fix) or [bind](http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html) in real live code?
I found this example in egg a little dense:
```
void egg_example()
{
using bll::_1;
using bll::_2;
int r =
fix2(
bll::ret<int>(
// \(f,a) -> a == 0 ? 1 : a * f(a-1)
bll::if_then_else_return( _2 == 0,
1,
_2 * lazy(_1)(_2 - 1)
)
)
) (5);
BOOST_CHECK(r == 5*4*3*2*1);
}
```
Can you explain how this all works?
Is there a nice simple example perhaps using bind with perhaps fewer dependancies than this one?
|
Here is the same code converted into `boost::bind` notice the y-combinator and its application site in the main function. I hope this helps.
```
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
// Y-combinator compatible factorial
int fact(boost::function<int(int)> f,int v)
{
if(v == 0)
return 1;
else
return v * f(v -1);
}
// Y-combinator for the int type
boost::function<int(int)>
y(boost::function<int(boost::function<int(int)>,int)> f)
{
return boost::bind(f,boost::bind(&y,f),_1);
}
int main(int argc,char** argv)
{
boost::function<int(int)> factorial = y(fact);
std::cout << factorial(5) << std::endl;
return 0;
}
```
|
152,099 |
<p>I have an ASP.NET page with a gridview control on it with a CommandButton column with delete and select commands active.</p>
<p>Pressing the enter key causes the first command button in the gridview to fire, which deletes a row. I don't want this to happen. Can I change the gridview control in a way that it does not react anymore to pressing the enter key?</p>
<p>There is a textbox and button on the screen as well. They don't need to be responsive to hitting enter, but you must be able to fill in the textbox. Currently we popup a confirmation dialog to prevent accidental deletes, but we need something better than this.</p>
<p>This is the markup for the gridview, as you can see it's inside an asp.net updatepanel (i forgot to mention that, sorry): (I left out most columns and the formatting)</p>
<pre><code><asp:UpdatePanel ID="upContent" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnFilter" />
<asp:AsyncPostBackTrigger ControlID="btnEdit" EventName="Click" />
</Triggers>
<ContentTemplate>
<div id="CodeGrid" class="Grid">
<asp:GridView ID="dgCode" runat="server">
<Columns>
<asp:CommandField SelectImageUrl="~/Images/Select.GIF"
ShowSelectButton="True"
ButtonType="Image"
CancelText=""
EditText=""
InsertText=""
NewText=""
UpdateText=""
DeleteImageUrl="~/Images/Delete.GIF"
ShowDeleteButton="True" />
<asp:BoundField DataField="Id" HeaderText="ID" Visible="False" />
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</code></pre>
|
[
{
"answer_id": 231265,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 0,
"selected": false,
"text": "<p>In Page_Load, set the focus on the textbox.</p>\n"
},
{
"answer_id": 233011,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 3,
"selected": false,
"text": "<p>Every once in a while I get goofy issues like this too... but usually I just implement a quick hack, and move on :)</p>\n\n<pre><code>myGridView.Attributes.Add(\"onkeydown\", \"if(event.keyCode==13)return false;\");\n</code></pre>\n\n<p>Something like that should work.</p>\n"
},
{
"answer_id": 234812,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a good <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> way of doing it. This function will automagically add the keydown event handler to all TextBoxes on the page. By using different selectors, you can control it to more or less granular levels:</p>\n\n<pre><code>//jQuery document ready function – fires when document structure loads\n$(document).ready(function() {\n\n //Find all input controls of type text and bind the given\n //function to them\n $(\":text\").keydown(function(e) {\n if (e.keyCode == 13) {\n return false;\n }\n });\n\n});\n</code></pre>\n\n<p>This will make all textboxes ignore the Enter key and has the advantage of being automatically applied to any new HTML or ASP.Net controls that you might add to the page (or that may be generated by ASP.Net).</p>\n"
},
{
"answer_id": 253191,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>This solution is blocking the enter key on the entire page</p>\n\n<p><a href=\"http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx\" rel=\"nofollow noreferrer\">Disable Enter Key</a></p>\n"
},
{
"answer_id": 2721527,
"author": "Heather",
"author_id": 326889,
"author_profile": "https://Stackoverflow.com/users/326889",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone else having the same problem where this code is not preventing the event from firing, this worked for me:</p>\n\n<pre><code>if (window.event.keyCode == 13) { \n event.returnValue=false; \n event.cancel = true;\n}\n</code></pre>\n"
},
{
"answer_id": 7602331,
"author": "Derrick",
"author_id": 971829,
"author_profile": "https://Stackoverflow.com/users/971829",
"pm_score": 1,
"selected": false,
"text": "<p>In the PreRender event you can toggle</p>\n\n<pre><code>Private Sub gvSerials_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvSerials.PreRender\n If gvSerials.EditIndex < 0 'READ ONLY MODE\n 'Enables the form submit during Read mode on my 'search' submit button\n Me.bnSearch.UseSubmitBehavior = True\n Else 'EDIT MODE\n 'disables the form submit during edit mode, this allows the APPLY/Update button to be activated after Enter Key is pressed (which really is creating a form submit)\n Me.bnSearch.UseSubmitBehavior = False\n End If\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23697/"
] |
I have an ASP.NET page with a gridview control on it with a CommandButton column with delete and select commands active.
Pressing the enter key causes the first command button in the gridview to fire, which deletes a row. I don't want this to happen. Can I change the gridview control in a way that it does not react anymore to pressing the enter key?
There is a textbox and button on the screen as well. They don't need to be responsive to hitting enter, but you must be able to fill in the textbox. Currently we popup a confirmation dialog to prevent accidental deletes, but we need something better than this.
This is the markup for the gridview, as you can see it's inside an asp.net updatepanel (i forgot to mention that, sorry): (I left out most columns and the formatting)
```
<asp:UpdatePanel ID="upContent" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnFilter" />
<asp:AsyncPostBackTrigger ControlID="btnEdit" EventName="Click" />
</Triggers>
<ContentTemplate>
<div id="CodeGrid" class="Grid">
<asp:GridView ID="dgCode" runat="server">
<Columns>
<asp:CommandField SelectImageUrl="~/Images/Select.GIF"
ShowSelectButton="True"
ButtonType="Image"
CancelText=""
EditText=""
InsertText=""
NewText=""
UpdateText=""
DeleteImageUrl="~/Images/Delete.GIF"
ShowDeleteButton="True" />
<asp:BoundField DataField="Id" HeaderText="ID" Visible="False" />
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
```
|
This solution is blocking the enter key on the entire page
[Disable Enter Key](http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx)
|
152,104 |
<p>I work on a Webproject using <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a> and CakePHP. I use <a href="http://www.appelsiini.net/projects/jeditable" rel="nofollow noreferrer">jeditable</a> as an inplace edit plugin. For textareas I extend it using the <a href="http://www.appelsiini.net/2008/4/autogrow-textarea-for-jeditable" rel="nofollow noreferrer">autogrow plugin</a>.</p>
<p>Well, I have two problems with this:</p>
<ul>
<li>First, autogrow does only work on Firefox, not on IE, Safari, Opera and Chrome.</li>
<li>Second, I need a callback event for jeditable, when its finished showing the edit-component, to recalculate the <a href="http://kelvinluck.com/assets/jquery/jScrollPane/jScrollPane.html" rel="nofollow noreferrer">scrollbar</a></li>
</ul>
<p>Im not so familiar with Javascript, so i can't extend/correct this two libraries by my own. Has anyone used another js-library for inplace edit with auto growing textareas (no complete editors like TinyMCE, I need a solution for plain text)?</p>
<p>I also found <a href="http://plugins.jquery.com/project/Growfield" rel="nofollow noreferrer">Growfield</a>, it would work for other browsers, but there's no jeditable integration...</p>
<p><em>(sorry for my english)</em></p>
|
[
{
"answer_id": 154377,
"author": "Alexander Pendleton",
"author_id": 21201,
"author_profile": "https://Stackoverflow.com/users/21201",
"pm_score": 3,
"selected": true,
"text": "<p>I didn't see any problems using Autogrow with jeditable in any browsers but here is an implementation of Growfield with jeditable. It works much in the same way that the Autogrow plugin for jeditable does. You create a special input type for jeditable and just apply .growfield() to it. The necessary javascript is below, a demo can be <a href=\"http://alexcpendletonapps.appspot.com/editauto/growfield.html\" rel=\"nofollow noreferrer\" title=\"found here\">found here</a>.</p>\n\n<pre><code><script type=\"text/javascript\">\n/* This is the growfield integration into jeditable\n You can use almost any field plugin you'd like if you create an input type for it.\n It just needs the \"element\" function (to create the editable field) and the \"plugin\"\n function which applies the effect to the field. This is very close to the code in the\n jquery.jeditable.autogrow.js input type that comes with jeditable.\n */\n$.editable.addInputType('growfield', {\n element : function(settings, original) {\n var textarea = $('<textarea>');\n if (settings.rows) {\n textarea.attr('rows', settings.rows);\n } else {\n textarea.height(settings.height);\n }\n if (settings.cols) {\n textarea.attr('cols', settings.cols);\n } else {\n textarea.width(settings.width);\n }\n // will execute when textarea is rendered\n textarea.ready(function() {\n // implement your scroll pane code here\n });\n $(this).append(textarea);\n return(textarea);\n },\n plugin : function(settings, original) {\n // applies the growfield effect to the in-place edit field\n $('textarea', this).growfield(settings.growfield);\n }\n});\n\n/* jeditable initialization */\n$(function() {\n $('.editable_textarea').editable('postto.html', {\n type: \"growfield\", // tells jeditable to use your growfield input type from above\n submit: 'OK', // this and below are optional\n tooltip: \"Click to edit...\",\n onblur: \"ignore\",\n growfield: { } // use this to pass options to the growfield that gets created\n });\n})\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 157029,
"author": "Roman Ganz",
"author_id": 17981,
"author_profile": "https://Stackoverflow.com/users/17981",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Thank you Alex!</strong> Your growfield-Plugin works.\nIn meantime I managed to solve the other problem. I took another <a href=\"http://flesler.blogspot.com/2007/10/jqueryscrollto.html\" rel=\"nofollow noreferrer\">Scroll-Library</a> and hacked a callback event into the jeditable-plugin. It was not that hard as I thought...</p>\n"
},
{
"answer_id": 161433,
"author": "Mika Tuupola",
"author_id": 24433,
"author_profile": "https://Stackoverflow.com/users/24433",
"pm_score": 1,
"selected": false,
"text": "<p><strong>knight_killer</strong>: What do you mean Autogrow works only with FireFox? I just tested with FF3, FF2, Safari, IE7 and Chrome. Works fine with all of them. I did not have Opera available.</p>\n\n<p><strong>Alex</strong>: Is there a download link for your Growfield Jeditable custom input? I would like to link it from my blog. It is really great!</p>\n"
},
{
"answer_id": 166955,
"author": "Roman Ganz",
"author_id": 17981,
"author_profile": "https://Stackoverflow.com/users/17981",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Mika Tuupola</strong>: If you are Interested in my modified jeditable (added two callback events), you can <a href=\"http://knightkiller.ch/jquery.jeditable.js\" rel=\"nofollow noreferrer\">get it here</a>. It would be great if you would provide these events in your official version of jeditable!</p>\n\n<p>Here is my (simplified) integration code. I use the events for more then just for the hover effect. It's just one usecase.</p>\n\n<pre><code>$('.edit_memo').editable('/cakephp/efforts/updateValue', {\n id : 'data[Effort][id]',\n name : 'data[Effort][value]',\n type : 'growfield',\n cancel : 'Abort',\n submit : 'Save',\n tooltip : 'click to edit',\n indicator : \"<span class='save'>saving...</span>\",\n onblur : 'ignore',\n placeholder : '<span class=\"hint\">&lt;click to edit&gt;</span>',\n loadurl : '/cakephp/efforts/getValue',\n loadtype : 'POST',\n loadtext : 'loading...',\n width : 447,\n onreadytoedit : function(value){\n $(this).removeClass('edit_memo_hover'); //remove css hover effect\n },\n onfinishededit : function(value){\n $(this).addClass('edit_memo_hover'); //add css hover effect\n }\n});\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17981/"
] |
I work on a Webproject using [jQuery](http://jquery.com/) and CakePHP. I use [jeditable](http://www.appelsiini.net/projects/jeditable) as an inplace edit plugin. For textareas I extend it using the [autogrow plugin](http://www.appelsiini.net/2008/4/autogrow-textarea-for-jeditable).
Well, I have two problems with this:
* First, autogrow does only work on Firefox, not on IE, Safari, Opera and Chrome.
* Second, I need a callback event for jeditable, when its finished showing the edit-component, to recalculate the [scrollbar](http://kelvinluck.com/assets/jquery/jScrollPane/jScrollPane.html)
Im not so familiar with Javascript, so i can't extend/correct this two libraries by my own. Has anyone used another js-library for inplace edit with auto growing textareas (no complete editors like TinyMCE, I need a solution for plain text)?
I also found [Growfield](http://plugins.jquery.com/project/Growfield), it would work for other browsers, but there's no jeditable integration...
*(sorry for my english)*
|
I didn't see any problems using Autogrow with jeditable in any browsers but here is an implementation of Growfield with jeditable. It works much in the same way that the Autogrow plugin for jeditable does. You create a special input type for jeditable and just apply .growfield() to it. The necessary javascript is below, a demo can be [found here](http://alexcpendletonapps.appspot.com/editauto/growfield.html "found here").
```
<script type="text/javascript">
/* This is the growfield integration into jeditable
You can use almost any field plugin you'd like if you create an input type for it.
It just needs the "element" function (to create the editable field) and the "plugin"
function which applies the effect to the field. This is very close to the code in the
jquery.jeditable.autogrow.js input type that comes with jeditable.
*/
$.editable.addInputType('growfield', {
element : function(settings, original) {
var textarea = $('<textarea>');
if (settings.rows) {
textarea.attr('rows', settings.rows);
} else {
textarea.height(settings.height);
}
if (settings.cols) {
textarea.attr('cols', settings.cols);
} else {
textarea.width(settings.width);
}
// will execute when textarea is rendered
textarea.ready(function() {
// implement your scroll pane code here
});
$(this).append(textarea);
return(textarea);
},
plugin : function(settings, original) {
// applies the growfield effect to the in-place edit field
$('textarea', this).growfield(settings.growfield);
}
});
/* jeditable initialization */
$(function() {
$('.editable_textarea').editable('postto.html', {
type: "growfield", // tells jeditable to use your growfield input type from above
submit: 'OK', // this and below are optional
tooltip: "Click to edit...",
onblur: "ignore",
growfield: { } // use this to pass options to the growfield that gets created
});
})
```
|
152,115 |
<p>How can I set points on a 24h period spreaded by the Gaussian distributions? For example to have the peak at 10 o'clock?</p>
|
[
{
"answer_id": 152224,
"author": "Mastermind",
"author_id": 22213,
"author_profile": "https://Stackoverflow.com/users/22213",
"pm_score": 2,
"selected": false,
"text": "<p>If you have trouble generating gaussian distributed random points look up <a href=\"http://en.wikipedia.org/wiki/Box-Muller_transform\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Box-Muller_transform</a></p>\n\n<p>Else please clarify your question.</p>\n"
},
{
"answer_id": 153016,
"author": "Chris Johnson",
"author_id": 23732,
"author_profile": "https://Stackoverflow.com/users/23732",
"pm_score": 4,
"selected": true,
"text": "<p>The following code generates a gaussian distributed random time (in hours, plus fractions of an hour) centered at a given time, and with a given standard deviation. The random times may 'wrap around' the clock, especially if the standard deviation is several hours: this is handled correctly. A different 'wrapping' algorithm may be more efficient if your standard deviations are very large (many days), but the distribution will be almost uniform in this case, anyway.</p>\n\n<pre><code>$peak=10; // Peak at 10-o-clock\n$stdev=2; // Standard deviation of two hours\n$hoursOnClock=24; // 24-hour clock\n\ndo // Generate gaussian variable using Box-Muller\n{\n $u=2.0*mt_rand()/mt_getrandmax()-1.0;\n $v=2.0*mt_rand()/mt_getrandmax()-1.0;\n $s = $u*$u+$v*$v;\n} while ($s > 1);\n$gauss=$u*sqrt(-2.0*log($s)/$s);\n\n$gauss = $gauss*$stdev + $peak; // Transform to correct peak and standard deviation\n\nwhile ($gauss < 0) $gauss+=$hoursOnClock; // Wrap around hours to keep the random time \n$result = fmod($gauss,$hoursOnClock); // on the clock\n\necho $result;\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22470/"
] |
How can I set points on a 24h period spreaded by the Gaussian distributions? For example to have the peak at 10 o'clock?
|
The following code generates a gaussian distributed random time (in hours, plus fractions of an hour) centered at a given time, and with a given standard deviation. The random times may 'wrap around' the clock, especially if the standard deviation is several hours: this is handled correctly. A different 'wrapping' algorithm may be more efficient if your standard deviations are very large (many days), but the distribution will be almost uniform in this case, anyway.
```
$peak=10; // Peak at 10-o-clock
$stdev=2; // Standard deviation of two hours
$hoursOnClock=24; // 24-hour clock
do // Generate gaussian variable using Box-Muller
{
$u=2.0*mt_rand()/mt_getrandmax()-1.0;
$v=2.0*mt_rand()/mt_getrandmax()-1.0;
$s = $u*$u+$v*$v;
} while ($s > 1);
$gauss=$u*sqrt(-2.0*log($s)/$s);
$gauss = $gauss*$stdev + $peak; // Transform to correct peak and standard deviation
while ($gauss < 0) $gauss+=$hoursOnClock; // Wrap around hours to keep the random time
$result = fmod($gauss,$hoursOnClock); // on the clock
echo $result;
```
|
152,127 |
<p>I am trying to use Lucene Java 2.3.2 to implement search on a catalog of products. Apart from the regular fields for a product, there is field called 'Category'. A product can fall in multiple categories. Currently, I use FilteredQuery to search for the same search term with every Category to get the number of results per category.</p>
<p>This results in 20-30 internal search calls per query to display the results. This is slowing down the search considerably. Is there a faster way of achieving the same result using Lucene?</p>
|
[
{
"answer_id": 152764,
"author": "Matt Quail",
"author_id": 15790,
"author_profile": "https://Stackoverflow.com/users/15790",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to consider looking through all the documents that match categories using a <a href=\"http://lucene.apache.org/java/2_3_2/api/core/org/apache/lucene/index/TermDocs.html\" rel=\"nofollow noreferrer\">TermDocs iterator</a>.</p>\n\n<p>This example code goes through each \"Category\" term, and then counts the number of documents that match that term.</p>\n\n<pre><code>public static void countDocumentsInCategories(IndexReader reader) throws IOException {\n TermEnum terms = null;\n TermDocs td = null;\n\n\n try {\n terms = reader.terms(new Term(\"Category\", \"\"));\n td = reader.termDocs();\n do {\n Term currentTerm = terms.term();\n\n if (!currentTerm.field().equals(\"Category\")) {\n break;\n }\n\n int numDocs = 0;\n td.seek(terms);\n while (td.next()) {\n numDocs++;\n }\n\n System.out.println(currentTerm.field() + \" : \" + currentTerm.text() + \" --> \" + numDocs);\n } while (terms.next());\n } finally {\n if (td != null) td.close();\n if (terms != null) terms.close();\n }\n}\n</code></pre>\n\n<p>This code should run reasonably fast even for large indexes.</p>\n\n<p>Here is some code that tests that method:</p>\n\n<pre><code>public static void main(String[] args) throws Exception {\n RAMDirectory store = new RAMDirectory();\n\n IndexWriter w = new IndexWriter(store, new StandardAnalyzer());\n addDocument(w, 1, \"Apple\", \"fruit\", \"computer\");\n addDocument(w, 2, \"Orange\", \"fruit\", \"colour\");\n addDocument(w, 3, \"Dell\", \"computer\");\n addDocument(w, 4, \"Cumquat\", \"fruit\");\n w.close();\n\n IndexReader r = IndexReader.open(store);\n countDocumentsInCategories(r);\n r.close();\n}\n\nprivate static void addDocument(IndexWriter w, int id, String name, String... categories) throws IOException {\n Document d = new Document();\n d.add(new Field(\"ID\", String.valueOf(id), Field.Store.YES, Field.Index.UN_TOKENIZED));\n d.add(new Field(\"Name\", name, Field.Store.NO, Field.Index.UN_TOKENIZED));\n\n for (String category : categories) {\n d.add(new Field(\"Category\", category, Field.Store.NO, Field.Index.UN_TOKENIZED));\n }\n\n w.addDocument(d);\n}\n</code></pre>\n"
},
{
"answer_id": 158945,
"author": "Rowan",
"author_id": 22424,
"author_profile": "https://Stackoverflow.com/users/22424",
"pm_score": 3,
"selected": false,
"text": "<p>I don't have enough reputation to comment (!) but in Matt Quail's answer I'm pretty sure you could replace this:</p>\n\n<pre><code>int numDocs = 0;\ntd.seek(terms);\nwhile (td.next()) {\n numDocs++;\n}\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code>int numDocs = terms.docFreq()\n</code></pre>\n\n<p>and then get rid of the td variable altogether. This should make it even faster.</p>\n"
},
{
"answer_id": 392107,
"author": "Rowan",
"author_id": 22424,
"author_profile": "https://Stackoverflow.com/users/22424",
"pm_score": 0,
"selected": false,
"text": "<p>So let me see if I understand the question correctly: Given a query from the user, you want to show how many matches there are for the query in each category. Correct?</p>\n\n<p>Think of it like this: your query is actually <code>originalQuery AND (category1 OR category2 or ...)</code> except as well an overall score you want to get a number for each of the categories. Unfortunately the interface for collecting hits in Lucene is very narrow, only giving you an overall score for a query. But you could implement a custom Scorer/Collector.</p>\n\n<p>Have a look at the source for org.apache.lucene.search.DisjunctionSumScorer. You could copy some of that to write a custom scorer that iterates through category matches while your main search is going on. And you could keep a <code>Map<String,Long></code> to keep track of matches in each category.</p>\n"
},
{
"answer_id": 482639,
"author": "itsadok",
"author_id": 7581,
"author_profile": "https://Stackoverflow.com/users/7581",
"pm_score": 3,
"selected": false,
"text": "<p>Here's what I did, though it's a bit heavy on memory:</p>\n\n<p>What you need is to create in advance a bunch of <a href=\"http://java.sun.com/javase/6/docs/api/java/util/BitSet.html\" rel=\"noreferrer\"><code>BitSet</code></a>s, one for each category, containing the doc id of all the documents in a category. Now, on search time you use a <a href=\"http://hudson.zones.apache.org/hudson/job/Lucene-trunk/javadoc//org/apache/lucene/search/HitCollector.html\" rel=\"noreferrer\">HitCollector</a> and check the doc ids against the BitSets.</p>\n\n<p>Here's the code to create the bit sets:</p>\n\n<pre><code>public BitSet[] getBitSets(IndexSearcher indexSearcher, \n Category[] categories) {\n BitSet[] bitSets = new BitSet[categories.length];\n for(int i=0; i<categories.length; i++)\n {\n Query query = categories[i].getQuery();\n final BitSet bitset = new BitSet()\n indexSearcher.search(query, new HitCollector() {\n public void collect(int doc, float score) {\n bitSet.set(doc);\n }\n });\n bitSets[i] = bitSet;\n }\n return bitSets;\n}\n</code></pre>\n\n<p>This is just one way to do this. You could probably use <a href=\"http://hudson.zones.apache.org/hudson/job/Lucene-trunk/javadoc/org/apache/lucene/index/TermDocs.html\" rel=\"noreferrer\">TermDocs</a> instead of running a full search if your categories are simple enough, but this should only run once when you load the index anyway.</p>\n\n<p>Now, when it's time to count categories of search results you do this:</p>\n\n<pre><code>public int[] getCategroryCount(IndexSearcher indexSearcher, \n Query query, \n final BitSet[] bitSets) {\n final int[] count = new int[bitSets.length];\n indexSearcher.search(query, new HitCollector() {\n public void collect(int doc, float score) {\n for(int i=0; i<bitSets.length; i++) {\n if(bitSets[i].get(doc)) count[i]++;\n }\n }\n });\n return count;\n}\n</code></pre>\n\n<p>What you end up with is an array containing the count of every category within the search results. If you also need the search results, you should add a TopDocCollector to your hit collector (yo dawg...). Or, you could just run the search again. 2 searches are better than 30.</p>\n"
},
{
"answer_id": 741559,
"author": "Yuval F",
"author_id": 1702,
"author_profile": "https://Stackoverflow.com/users/1702",
"pm_score": 2,
"selected": false,
"text": "<p>Sachin, I believe you want <a href=\"http://en.wikipedia.org/wiki/Faceted_browser\" rel=\"nofollow noreferrer\">faceted search</a>. It does not come out of the box with Lucene. I suggest you try using <a href=\"http://lucene.apache.org/solr/\" rel=\"nofollow noreferrer\">SOLR</a>, that has <a href=\"http://www.lucidimagination.com/Community/Hear-from-the-Experts/Articles/Faceted-Search-Solr\" rel=\"nofollow noreferrer\">faceting</a> as a major and convenient feature.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to use Lucene Java 2.3.2 to implement search on a catalog of products. Apart from the regular fields for a product, there is field called 'Category'. A product can fall in multiple categories. Currently, I use FilteredQuery to search for the same search term with every Category to get the number of results per category.
This results in 20-30 internal search calls per query to display the results. This is slowing down the search considerably. Is there a faster way of achieving the same result using Lucene?
|
I don't have enough reputation to comment (!) but in Matt Quail's answer I'm pretty sure you could replace this:
```
int numDocs = 0;
td.seek(terms);
while (td.next()) {
numDocs++;
}
```
with this:
```
int numDocs = terms.docFreq()
```
and then get rid of the td variable altogether. This should make it even faster.
|
152,137 |
<p>I don't need a Link but rather only the href= part of the ActionLink.</p>
<p>But if I call Html.ActionLink(...) I get a back.
Is there a way to just return the URL of the Action while not getting the ?</p>
|
[
{
"answer_id": 152165,
"author": "Casper",
"author_id": 18729,
"author_profile": "https://Stackoverflow.com/users/18729",
"pm_score": 2,
"selected": false,
"text": "<p>Edit: in response to commment, now including parameters:</p>\n\n<pre><code><% =Html.BuildUrlFromExpression<YourController>(c => c.YourAction(parameter)) %>\n</code></pre>\n"
},
{
"answer_id": 152898,
"author": "Dave Weaver",
"author_id": 11991,
"author_profile": "https://Stackoverflow.com/users/11991",
"pm_score": 4,
"selected": true,
"text": "<p>MVC also provides a UrlHelper class which can do the same thing:</p>\n\n<pre><code><%=Url.Action(actionName)%>\n<%=Url.Action(actionName, htmlValues)%>\n<%=Url.Action(actionName, controllerName, htmlValues)%>\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21699/"
] |
I don't need a Link but rather only the href= part of the ActionLink.
But if I call Html.ActionLink(...) I get a back.
Is there a way to just return the URL of the Action while not getting the ?
|
MVC also provides a UrlHelper class which can do the same thing:
```
<%=Url.Action(actionName)%>
<%=Url.Action(actionName, htmlValues)%>
<%=Url.Action(actionName, controllerName, htmlValues)%>
```
|
152,138 |
<p>I have a class proposing translations utilities. The translations themselves should be reloaded every 30 minutes. I use Spring Timer support for that. Basically, my class looks like :</p>
<pre><code>public interface Translator {
public void loadTranslations();
public String getTranslation(String key);
}
</code></pre>
<p>loadTranslations() can be pretty long to run, so while it is running the old translations are still available. This is done by loading the translations in a local Map and just changing the reference when all translations are loaded.</p>
<p>My problem is : how do I make sure that when a thread is already loading translations, is a second one also tries to run, it detects that and returns immediately, without starting a second update.</p>
<p>A synchronized method will only queue the loads ... I'm still on Java 1.4, so no java.util.concurrent.</p>
<p>Thanks for your help !</p>
|
[
{
"answer_id": 152147,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "<p>Keep a handle on the load thread to see if it's running?</p>\n\n<p>Or can't you just use a synchronized flag to indicate if a load is in progress?</p>\n"
},
{
"answer_id": 152152,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 1,
"selected": false,
"text": "<p>I am from a .net background(no java experience at all), but you could try a simple static flag of some sort that checks at the beginning of the method if its alrady running. Then all you need to do is make sure any read/write of that flag is synchronized. So at beginning check the flag, if its not set, set it, if it is set, return. If its not set, run the rest of the method, and after its complete, unset it. Just make sure to put the code in a try/finally and the flag iunsetting in the finally so it always gets unset in case of error. Very simplified but may be all you need.</p>\n\n<p>Edit: This actually probably works better than synchronizing the method. Because do you really need a new translation <em>immediately</em> after the one before it finishes? And you may not want to lock up a thread for too long if it has to wait a while.</p>\n"
},
{
"answer_id": 152201,
"author": "Ewan Makepeace",
"author_id": 9731,
"author_profile": "https://Stackoverflow.com/users/9731",
"pm_score": 0,
"selected": false,
"text": "<p>This is actually identical to the code that is required to manage the construction of a Singleton (gasp!) when done the classical way:</p>\n\n<pre><code>if (instance == null) {\n synchronized {\n if (instance == null) {\n instance = new SomeClass();\n }\n }\n}\n</code></pre>\n\n<p>The inner test is identical to the outer test. The outer test is so that we dont routinely enter a synchronised block, the inner test is to confirm that the situation has not changed since we last made the test (the thread could have been preempted before entering Synchronized).</p>\n\n<p>In your case:</p>\n\n<pre><code>if (translationsNeedLoading()) {\n synchronized {\n if (translationsNeedLoading()) {\n loadTranslations();\n }\n }\n}\n</code></pre>\n\n<p>UPDATE: This way of constructing a singleton will not work reliably under your JDK1.4. For explanation <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html\" rel=\"nofollow noreferrer\">see here</a>. However I think you are you will be OK in this scenario.</p>\n"
},
{
"answer_id": 152593,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": true,
"text": "<p>Use some form of locking mechanism to only perform the task if it is not already in progress. Acquiring the locking token must be a one-step process. See:</p>\n\n<pre><code>/**\n * @author McDowell\n */\npublic abstract class NonconcurrentTask implements Runnable {\n\n private boolean token = true;\n\n private synchronized boolean acquire() {\n boolean ret = token;\n token = false;\n return ret;\n }\n\n private synchronized void release() {\n token = true;\n }\n\n public final void run() {\n if (acquire()) {\n try {\n doTask();\n } finally {\n release();\n }\n }\n }\n\n protected abstract void doTask();\n\n}\n</code></pre>\n\n<p>Test code that will throw an exception if the task runs concurrently:</p>\n\n<pre><code>public class Test {\n\n public static void main(String[] args) {\n final NonconcurrentTask shared = new NonconcurrentTask() {\n private boolean working = false;\n\n protected void doTask() {\n System.out.println(\"Working: \"\n + Thread.currentThread().getName());\n if (working) {\n throw new IllegalStateException();\n }\n working = true;\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n if (!working) {\n throw new IllegalStateException();\n }\n working = false;\n }\n };\n\n Runnable taskWrapper = new Runnable() {\n public void run() {\n while (true) {\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n shared.run();\n }\n }\n };\n for (int i = 0; i < 100; i++) {\n new Thread(taskWrapper).start();\n }\n }\n\n}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23704/"
] |
I have a class proposing translations utilities. The translations themselves should be reloaded every 30 minutes. I use Spring Timer support for that. Basically, my class looks like :
```
public interface Translator {
public void loadTranslations();
public String getTranslation(String key);
}
```
loadTranslations() can be pretty long to run, so while it is running the old translations are still available. This is done by loading the translations in a local Map and just changing the reference when all translations are loaded.
My problem is : how do I make sure that when a thread is already loading translations, is a second one also tries to run, it detects that and returns immediately, without starting a second update.
A synchronized method will only queue the loads ... I'm still on Java 1.4, so no java.util.concurrent.
Thanks for your help !
|
Use some form of locking mechanism to only perform the task if it is not already in progress. Acquiring the locking token must be a one-step process. See:
```
/**
* @author McDowell
*/
public abstract class NonconcurrentTask implements Runnable {
private boolean token = true;
private synchronized boolean acquire() {
boolean ret = token;
token = false;
return ret;
}
private synchronized void release() {
token = true;
}
public final void run() {
if (acquire()) {
try {
doTask();
} finally {
release();
}
}
}
protected abstract void doTask();
}
```
Test code that will throw an exception if the task runs concurrently:
```
public class Test {
public static void main(String[] args) {
final NonconcurrentTask shared = new NonconcurrentTask() {
private boolean working = false;
protected void doTask() {
System.out.println("Working: "
+ Thread.currentThread().getName());
if (working) {
throw new IllegalStateException();
}
working = true;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (!working) {
throw new IllegalStateException();
}
working = false;
}
};
Runnable taskWrapper = new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
shared.run();
}
}
};
for (int i = 0; i < 100; i++) {
new Thread(taskWrapper).start();
}
}
}
```
|
152,160 |
<p>Has anyone used the <a href="http://www.cs.tufts.edu/~nr/noweb/" rel="noreferrer">noweb</a> literate programming tool on a large Java project, where several source code files must be generated in different subdirectories? How did you manage this with noweb? Are there any resources and/or best practices out there?</p>
|
[
{
"answer_id": 433328,
"author": "Thorbjørn Ravn Andersen",
"author_id": 53897,
"author_profile": "https://Stackoverflow.com/users/53897",
"pm_score": 2,
"selected": false,
"text": "<p>Literate Programming works its best if the generated intermediate code can point back to the original source file to allow debugging, and analyzing compiler errors. This usually means pre processor support, which Java doesn't support.</p>\n\n<p>Additionally Literate Programming is really not necessary for Java, as the original need for a strict sequential order - which was what prompted Knuth to write a tool to put snippets together in the appropriate sequence - is not present. The final benefit of literate programming, namely being able to write prose about the code, is also available as Javadoc which allow you to put everything in as comments.</p>\n\n<p>To me, there is no benefit in literate programming for Java, and only troubles (just imagine getting IDE support).</p>\n\n<p>Any particular reason you are considering it?</p>\n"
},
{
"answer_id": 775062,
"author": "Jason Catena",
"author_id": 27685,
"author_profile": "https://Stackoverflow.com/users/27685",
"pm_score": 3,
"selected": false,
"text": "<p>Noweb will dump out files relative to the current working directory, or at the absolute path you specify. Just don't use * at the end of your filename (to avoid inserting the # preprocessor directives). I would recommend using %def with @ to show where you define and use names.</p>\n\n<pre><code><</path/to/file.java>>=\n reallyImportantVariable += 1;\n@ %def reallyImportantVariable\n</code></pre>\n\n<p>noweb lets you reorder and (the real win) reuse snippets of code, which I don't think javac would understand.</p>\n\n<p>I'd agree that since most people expect that you'll use javadoc, you're probably swimming against the stream to use noweb.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1428/"
] |
Has anyone used the [noweb](http://www.cs.tufts.edu/~nr/noweb/) literate programming tool on a large Java project, where several source code files must be generated in different subdirectories? How did you manage this with noweb? Are there any resources and/or best practices out there?
|
Noweb will dump out files relative to the current working directory, or at the absolute path you specify. Just don't use \* at the end of your filename (to avoid inserting the # preprocessor directives). I would recommend using %def with @ to show where you define and use names.
```
<</path/to/file.java>>=
reallyImportantVariable += 1;
@ %def reallyImportantVariable
```
noweb lets you reorder and (the real win) reuse snippets of code, which I don't think javac would understand.
I'd agree that since most people expect that you'll use javadoc, you're probably swimming against the stream to use noweb.
|
152,187 |
<p>What type of authentication would you suggest for the service that is:</p>
<ul>
<li>implemented as WCF and exposed via
varios enpoints (including XML-RPC)</li>
<li>has to be consumed easily by various cross-platform clients</li>
</ul>
<p>Why?</p>
<p>Options that I'm aware of are:</p>
<ul>
<li>Forms-based authentication for IIS-hosted WCF (easy to implement, but has horrible cross-platform support, plus it is not REST)</li>
<li>Sending plain-text username/pwd with every call (easy to use on any platform, but totally unsecure)</li>
<li>Using ticket-based authentication, when username&pwd are used to create a ticket that is valid for some time and is passed with every request (can be consumed by any client easily, but the API model is bound to this type of security)</li>
</ul>
<p>Thanks for your time!</p>
|
[
{
"answer_id": 433328,
"author": "Thorbjørn Ravn Andersen",
"author_id": 53897,
"author_profile": "https://Stackoverflow.com/users/53897",
"pm_score": 2,
"selected": false,
"text": "<p>Literate Programming works its best if the generated intermediate code can point back to the original source file to allow debugging, and analyzing compiler errors. This usually means pre processor support, which Java doesn't support.</p>\n\n<p>Additionally Literate Programming is really not necessary for Java, as the original need for a strict sequential order - which was what prompted Knuth to write a tool to put snippets together in the appropriate sequence - is not present. The final benefit of literate programming, namely being able to write prose about the code, is also available as Javadoc which allow you to put everything in as comments.</p>\n\n<p>To me, there is no benefit in literate programming for Java, and only troubles (just imagine getting IDE support).</p>\n\n<p>Any particular reason you are considering it?</p>\n"
},
{
"answer_id": 775062,
"author": "Jason Catena",
"author_id": 27685,
"author_profile": "https://Stackoverflow.com/users/27685",
"pm_score": 3,
"selected": false,
"text": "<p>Noweb will dump out files relative to the current working directory, or at the absolute path you specify. Just don't use * at the end of your filename (to avoid inserting the # preprocessor directives). I would recommend using %def with @ to show where you define and use names.</p>\n\n<pre><code><</path/to/file.java>>=\n reallyImportantVariable += 1;\n@ %def reallyImportantVariable\n</code></pre>\n\n<p>noweb lets you reorder and (the real win) reuse snippets of code, which I don't think javac would understand.</p>\n\n<p>I'd agree that since most people expect that you'll use javadoc, you're probably swimming against the stream to use noweb.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47366/"
] |
What type of authentication would you suggest for the service that is:
* implemented as WCF and exposed via
varios enpoints (including XML-RPC)
* has to be consumed easily by various cross-platform clients
Why?
Options that I'm aware of are:
* Forms-based authentication for IIS-hosted WCF (easy to implement, but has horrible cross-platform support, plus it is not REST)
* Sending plain-text username/pwd with every call (easy to use on any platform, but totally unsecure)
* Using ticket-based authentication, when username&pwd are used to create a ticket that is valid for some time and is passed with every request (can be consumed by any client easily, but the API model is bound to this type of security)
Thanks for your time!
|
Noweb will dump out files relative to the current working directory, or at the absolute path you specify. Just don't use \* at the end of your filename (to avoid inserting the # preprocessor directives). I would recommend using %def with @ to show where you define and use names.
```
<</path/to/file.java>>=
reallyImportantVariable += 1;
@ %def reallyImportantVariable
```
noweb lets you reorder and (the real win) reuse snippets of code, which I don't think javac would understand.
I'd agree that since most people expect that you'll use javadoc, you're probably swimming against the stream to use noweb.
|
152,188 |
<p>I have read in some of the ClickOnce posts that ClickOnce does not allow you to create a desktop icon for you application. Is there any way around this?</p>
|
[
{
"answer_id": 152194,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>The desktop icon can be a shortcut to the <code>.application</code> file. Install this as one of the first things your application does.</p>\n"
},
{
"answer_id": 152202,
"author": "FryHard",
"author_id": 231,
"author_profile": "https://Stackoverflow.com/users/231",
"pm_score": 4,
"selected": false,
"text": "<p>It seems like there is a way to place an icon on the desktop in ClickOnce.</p>\n<ol>\n<li>Upgrade to Visual Studio 2008 SP 1, and there will be a placed an icon on the desktop check box in the options page of the publish section of the project properties window.</li>\n<li>The second option is to add code to your application that copies the shortcut to the desktop on the first run of the application. See the blog post <em><a href=\"https://web.archive.org/web/20200221094617/http://geekswithblogs.net:80/murraybgordon/archive/2006/10/04/93203.aspx\" rel=\"nofollow noreferrer\">How to add Desktop Shortcut to ClickOnce Deployment Application</a></em>.</li>\n</ol>\n"
},
{
"answer_id": 152208,
"author": "Timo",
"author_id": 15415,
"author_profile": "https://Stackoverflow.com/users/15415",
"pm_score": 5,
"selected": true,
"text": "<p>In Visual Studio 2005, <a href=\"http://en.wikipedia.org/wiki/ClickOnce\" rel=\"noreferrer\">ClickOnce</a> does not have the ability to create a desktop icon, but it is now available in Visual Studio 2008 SP1. In Visual Studio 2005, you can use the following code to create a desktop icon for you when the application starts.</p>\n\n<p>I have used this code over several projects for a couple of months now without any problem. I must say that all my applications have been deployed over an intranet in a controlled environment. Also, the icon is not removed when the application is uninstalled. This code creates a shortcut to the shortcut on the start menu that ClickOnce creates.</p>\n\n<pre><code>private void CreateDesktopIcon()\n{\n ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;\n\n if (ad.IsFirstRun)\n {\n Assembly assembly = Assembly.GetEntryAssembly();\n string company = string.Empty;\n string description = string.Empty;\n\n if (Attribute.IsDefined(assembly, typeof(AssemblyCompanyAttribute)))\n {\n AssemblyCompanyAttribute ascompany =\n (AssemblyCompanyAttribute)Attribute.GetCustomAttribute(\n assembly, typeof(AssemblyCompanyAttribute));\n\n company = ascompany.Company;\n }\n if (Attribute.IsDefined(assembly, typeof(AssemblyDescriptionAttribute)))\n {\n AssemblyDescriptionAttribute asdescription =\n (AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(\n assembly, typeof(AssemblyDescriptionAttribute));\n\n description = asdescription.Description;\n }\n if (!string.IsNullOrEmpty(company))\n {\n string desktopPath = string.Empty;\n desktopPath = string.Concat(\n Environment.GetFolderPath(Environment.SpecialFolder.Desktop),\n \"\\\\\",\n description,\n \".appref-ms\");\n\n string shortcutName = string.Empty;\n shortcutName = string.Concat(\n Environment.GetFolderPath(Environment.SpecialFolder.Programs),\n \"\\\\\",\n company,\n \"\\\\\",\n description,\n \".appref-ms\");\n\n System.IO.File.Copy(shortcutName, desktopPath, true);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55631037,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In Visual Studio 2017 and 2019 you can do the following:</p>\n\n<p>Go to Project Properties -> Publish -> Manifests and select the option <strong>Create desktop shortcut</strong> </p>\n"
},
{
"answer_id": 65900724,
"author": "Krzysztof Gapski",
"author_id": 1837177,
"author_profile": "https://Stackoverflow.com/users/1837177",
"pm_score": 0,
"selected": false,
"text": "<p>If you would like to user powershell you can create shortcut to .bat file:</p>\n<pre><code>@ECHO OFF\nPowerShell -ExecutionPolicy Unrestricted .\\script.ps1 >> "%TEMP%\\StartupLog.txt" 2>&1\nEXIT /B %errorlevel%\n</code></pre>\n<p>which silently run script.ps1:</p>\n<pre><code>$app = "http://your.site/YourApp/YourApp.application";\n[Diagnostics.Process]::Start("rundll32.exe", "dfshim.dll,ShOpenVerbApplication " + $app);\n</code></pre>\n<p>which open your ClickOnce app.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18826/"
] |
I have read in some of the ClickOnce posts that ClickOnce does not allow you to create a desktop icon for you application. Is there any way around this?
|
In Visual Studio 2005, [ClickOnce](http://en.wikipedia.org/wiki/ClickOnce) does not have the ability to create a desktop icon, but it is now available in Visual Studio 2008 SP1. In Visual Studio 2005, you can use the following code to create a desktop icon for you when the application starts.
I have used this code over several projects for a couple of months now without any problem. I must say that all my applications have been deployed over an intranet in a controlled environment. Also, the icon is not removed when the application is uninstalled. This code creates a shortcut to the shortcut on the start menu that ClickOnce creates.
```
private void CreateDesktopIcon()
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
if (ad.IsFirstRun)
{
Assembly assembly = Assembly.GetEntryAssembly();
string company = string.Empty;
string description = string.Empty;
if (Attribute.IsDefined(assembly, typeof(AssemblyCompanyAttribute)))
{
AssemblyCompanyAttribute ascompany =
(AssemblyCompanyAttribute)Attribute.GetCustomAttribute(
assembly, typeof(AssemblyCompanyAttribute));
company = ascompany.Company;
}
if (Attribute.IsDefined(assembly, typeof(AssemblyDescriptionAttribute)))
{
AssemblyDescriptionAttribute asdescription =
(AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(
assembly, typeof(AssemblyDescriptionAttribute));
description = asdescription.Description;
}
if (!string.IsNullOrEmpty(company))
{
string desktopPath = string.Empty;
desktopPath = string.Concat(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"\\",
description,
".appref-ms");
string shortcutName = string.Empty;
shortcutName = string.Concat(
Environment.GetFolderPath(Environment.SpecialFolder.Programs),
"\\",
company,
"\\",
description,
".appref-ms");
System.IO.File.Copy(shortcutName, desktopPath, true);
}
}
}
}
```
|
152,190 |
<p>I'm using StringBuffer in Java to concat strings together, like so:</p>
<pre><code>StringBuffer str = new StringBuffer();
str.append("string value");
</code></pre>
<p>I would like to know if there's a method (although I didn't find anything from a quick glance at the documentation) or some other way to add "padding".</p>
<p>Let me explain; every time I append something to the string, I want to add a space in the end, like so:</p>
<pre><code>String foo = "string value";
str.append(foo + " ");
</code></pre>
<p>and I have several calls to append.. and every time, I want to add a space. Is there a way to set the object so that it will add a space automatically after each append?</p>
<p>EDIT --</p>
<pre><code>String input
StringBuffer query = new StringBuffer();
Scanner scanner = new Scanner(System.in);
scanner.UseDelimiter("\n");
do {
System.out.println("sql> ");
input = scanner.next();
if (!empty(input)) query.append(input);
if (query.toString().trim().endsWith(";")) {
//run query
}
}
while (!input.equalsIgnoreCase("exit");
</code></pre>
<p>I'll use StringBuilder though as grom suggested, but that's how the code looks right now</p>
|
[
{
"answer_id": 152195,
"author": "Johan",
"author_id": 11347,
"author_profile": "https://Stackoverflow.com/users/11347",
"pm_score": 2,
"selected": false,
"text": "<p>Just add the space yourself, it's easy enough, as per your own example.</p>\n"
},
{
"answer_id": 152210,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 2,
"selected": false,
"text": "<p>Can you not create a new class which wraps around <code>StringBuffer</code> and add an <code>appendWithTrailingSpace()</code> method?</p>\n\n<pre><code>CustomStringBuffer str = new CustomStringBuffer();\nstr.appendWithTrailingSpace(\"string value\");\n</code></pre>\n\n<p>(Although you may want to call your method something a little shorter.)</p>\n"
},
{
"answer_id": 152217,
"author": "Dimo",
"author_id": 21140,
"author_profile": "https://Stackoverflow.com/users/21140",
"pm_score": 2,
"selected": false,
"text": "<p>StringBuffer is final. You cannot derive from it.\nThe Best solution really is to add the padding for yourself. Write a method for it and use a PADDING-Constant so that you can easily change it, or better put it in a parameter.</p>\n"
},
{
"answer_id": 152247,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 3,
"selected": false,
"text": "<p>You should be using <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html\" rel=\"nofollow noreferrer\">StringBuilder</a>.</p>\n\n<blockquote>\n <p>Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.</p>\n</blockquote>\n"
},
{
"answer_id": 152270,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 1,
"selected": false,
"text": "<p>Another possibility is that StringBuilder objects return themselves when you call append, meaning you can do:</p>\n\n<pre><code>str.append(\"string value\").append(\" \");\n</code></pre>\n\n<p>Not quite as slick, but it is probably an easier solution than the + \" \" method.</p>\n\n<p>Another possibility is to build a wrapper class, like PaddedStringBuilder, that provides the same methods but applies the padding you want, since you can't inherit.</p>\n"
},
{
"answer_id": 152677,
"author": "kolrie",
"author_id": 14540,
"author_profile": "https://Stackoverflow.com/users/14540",
"pm_score": 4,
"selected": true,
"text": "<p>I think this is handled easier either with a helper method (untested code):</p>\n\n<pre><code>public String myMethod() {\n StringBuilder sb = new StringBuilder();\n addToBuffer(sb, \"Hello\").addToBuffer(\"there,\");\n addToBuffer(sb, \"it\").addToBuffer(sb, \"works\");\n}\n\nprivate StringBuilder addToBuffer(StringBuilder sb, String what) {\n return sb.append(what).append(' '); // char is even faster here! ;)\n}\n</code></pre>\n\n<p>Or even using a Builder pattern with a fluent interface (also untested code):</p>\n\n<pre><code>public String myMethod() {\n SBBuilder builder = new SBBuilder()\n .add(\"Hello\").add(\"there\")\n .add(\"it\", \"works\", \"just\", \"fine!\");\n\n for (int i = 0; i < 10; i++) {\n builder.add(\"adding\").add(String.valueOf(i));\n }\n\n System.out.println(builder.build());\n}\n\npublic static class SBBuilder {\n private StringBuilder sb = new StringBuilder();\n\n public SBBuilder add(String... parts) {\n for (String p : parts) {\n sb.append(p).append(' '); // char is even faster here! ;)\n }\n return this;\n }\n\n public String build() {\n return sb.toString();\n }\n}\n</code></pre>\n\n<p>Here's an <a href=\"http://java.dzone.com/news/factories-builders-and-fluent-\" rel=\"noreferrer\">article</a> on the subject.</p>\n\n<p>Hope it helps! :)</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6618/"
] |
I'm using StringBuffer in Java to concat strings together, like so:
```
StringBuffer str = new StringBuffer();
str.append("string value");
```
I would like to know if there's a method (although I didn't find anything from a quick glance at the documentation) or some other way to add "padding".
Let me explain; every time I append something to the string, I want to add a space in the end, like so:
```
String foo = "string value";
str.append(foo + " ");
```
and I have several calls to append.. and every time, I want to add a space. Is there a way to set the object so that it will add a space automatically after each append?
EDIT --
```
String input
StringBuffer query = new StringBuffer();
Scanner scanner = new Scanner(System.in);
scanner.UseDelimiter("\n");
do {
System.out.println("sql> ");
input = scanner.next();
if (!empty(input)) query.append(input);
if (query.toString().trim().endsWith(";")) {
//run query
}
}
while (!input.equalsIgnoreCase("exit");
```
I'll use StringBuilder though as grom suggested, but that's how the code looks right now
|
I think this is handled easier either with a helper method (untested code):
```
public String myMethod() {
StringBuilder sb = new StringBuilder();
addToBuffer(sb, "Hello").addToBuffer("there,");
addToBuffer(sb, "it").addToBuffer(sb, "works");
}
private StringBuilder addToBuffer(StringBuilder sb, String what) {
return sb.append(what).append(' '); // char is even faster here! ;)
}
```
Or even using a Builder pattern with a fluent interface (also untested code):
```
public String myMethod() {
SBBuilder builder = new SBBuilder()
.add("Hello").add("there")
.add("it", "works", "just", "fine!");
for (int i = 0; i < 10; i++) {
builder.add("adding").add(String.valueOf(i));
}
System.out.println(builder.build());
}
public static class SBBuilder {
private StringBuilder sb = new StringBuilder();
public SBBuilder add(String... parts) {
for (String p : parts) {
sb.append(p).append(' '); // char is even faster here! ;)
}
return this;
}
public String build() {
return sb.toString();
}
}
```
Here's an [article](http://java.dzone.com/news/factories-builders-and-fluent-) on the subject.
Hope it helps! :)
|
152,205 |
<p>I'm working on a Java library and would like to remove some functions from it. My reasons for this is public API and design cleanup. Some objects have setters, but should be immutable, some functionality has been implemented better/cleaner in different methods, etc.</p>
<p>I have marked these methods 'deprecated', and would like to remove them eventually. At the moment I'm thinking about removing these after few sprints (two week development cycles).</p>
<p>Are there any 'best practices' about removing redundant public code?</p>
<p>/JaanusSiim </p>
|
[
{
"answer_id": 152213,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"http://java.sun.com/j2se/1.4.2/docs/guide/misc/deprecation/deprecated.html\" rel=\"nofollow noreferrer\">@deprecated</a> tag. Read the <a href=\"http://java.sun.com/j2se/1.4.2/docs/guide/misc/deprecation/index.html\" rel=\"nofollow noreferrer\">Deprecation of APIs</a> document for more info.</p>\n\n<p>After everyone using the code tells you they have cleaned up on their side, start removing the deprecated code and wait and see if someone complains - then tell them to fix their own code...</p>\n"
},
{
"answer_id": 152229,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on how often the code is rebuild. For example, if there are 4 applications using the library, and they are rebuild daily, a month is a long enough time to fix the deprecated calls. </p>\n\n<p>Also, if you use the deprecated tag, provide some comment on which code replaces the deprecated call.</p>\n"
},
{
"answer_id": 152234,
"author": "Chad",
"author_id": 17382,
"author_profile": "https://Stackoverflow.com/users/17382",
"pm_score": 2,
"selected": false,
"text": "<p>Consider it this way, customer A downloads the latest version of you library file or frame work. He hits compile on this machine and suddenly he see thousands of errors because the member file or function does no longer exist. From this point on, you've given the customer a reason why not to upgrade to your new version and to stay with the old version.</p>\n\n<p>Raymond Chen answers this the best with his blog about win32 API,</p>\n\n<p>Though, our experience in our software house has been, once the API has been written we have to carry the API to the end of the product life cycle. To help users to new versions, we provide backwards compatibility with the old commands in the new framework.</p>\n"
},
{
"answer_id": 152235,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>Set a date and publicize it in the @deprecated tag. The amount of time given to the removal depends on the amount of users your code has, how well connected you are with them and the the reason for the change.</p>\n\n<p>If you have thousands of users and you barely talk to them, the time frame should probably be in the decades range :-)</p>\n\n<p>If your users are your 10 coworkers and you see them daily, the time frame can easily be in the weeks range.</p>\n\n<pre><code>/**\n * @deprecated\n * This method will be removed after Halloween!\n * @see #newLocationForFunctionality\n */\n</code></pre>\n"
},
{
"answer_id": 152242,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 0,
"selected": false,
"text": "<p>Given that this is a library, consider archiving a version with the deprecated functions. Make this version available in both source code and compiled form, as a backup solution for those who haven't modernized their code to your new API. (The binary form is needed, because even you may have trouble compiling the old version in a few years.) Make it clear that this version will not be supported and enhanced. Tag this version with a symbolic symbol in your version control system. Then move forward.</p>\n"
},
{
"answer_id": 152267,
"author": "user17222",
"author_id": 17222,
"author_profile": "https://Stackoverflow.com/users/17222",
"pm_score": -1,
"selected": false,
"text": "<p>too bad you are not using .Net :(</p>\n\n<p>The built in <a href=\"http://msdn.microsoft.com/en-us/library/22kk2b44(VS.80).aspx\" rel=\"nofollow noreferrer\">Obsolete</a> attribute generates compiler warnings.</p>\n"
},
{
"answer_id": 152285,
"author": "Oli",
"author_id": 15296,
"author_profile": "https://Stackoverflow.com/users/15296",
"pm_score": 0,
"selected": false,
"text": "<p>It certainly depends at which scale your API is used and what you promised upfront to your customers.</p>\n\n<p>As described by Vinko Vrsalovic, you should enter a date when they have to expect the abandon of the function.</p>\n\n<p>In production, if it's \"just\" a matter of getting cleaner code, I tend to leave things in place even past the deprecating date as long as it doesn't break anything.</p>\n\n<p>On the other hand in development I do it immediately, in order to get things sorted out quickly.</p>\n"
},
{
"answer_id": 155216,
"author": "Giulio Piancastelli",
"author_id": 22904,
"author_profile": "https://Stackoverflow.com/users/22904",
"pm_score": 0,
"selected": false,
"text": "<p>You may be interested in examples of how deprecation works in some other projects. For example, here follows what the <a href=\"http://docs.djangoproject.com/en/dev/internals/release-process/\" rel=\"nofollow noreferrer\">policy in the Django project for function deprecation</a> is:</p>\n\n<blockquote>\n <p>A minor release may deprecate certain features from previous releases. If a feature in version A.B is deprecated, it will continue to work in version A.B+1. In version A.B+2, use of the feature will raise a PendingDeprecationWarning but will continue to work. Version A.B+3 will remove the feature entirely.</p>\n</blockquote>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706/"
] |
I'm working on a Java library and would like to remove some functions from it. My reasons for this is public API and design cleanup. Some objects have setters, but should be immutable, some functionality has been implemented better/cleaner in different methods, etc.
I have marked these methods 'deprecated', and would like to remove them eventually. At the moment I'm thinking about removing these after few sprints (two week development cycles).
Are there any 'best practices' about removing redundant public code?
/JaanusSiim
|
Set a date and publicize it in the @deprecated tag. The amount of time given to the removal depends on the amount of users your code has, how well connected you are with them and the the reason for the change.
If you have thousands of users and you barely talk to them, the time frame should probably be in the decades range :-)
If your users are your 10 coworkers and you see them daily, the time frame can easily be in the weeks range.
```
/**
* @deprecated
* This method will be removed after Halloween!
* @see #newLocationForFunctionality
*/
```
|
152,216 |
<p>Boost range library (<a href="http://www.boost.org/doc/libs/1_35_0/libs/range/index.html" rel="noreferrer">http://www.boost.org/doc/libs/1_35_0/libs/range/index.html</a>) allows us to abstract a pair of iterators into a range. Now I want to combine two ranges into one, viz:</p>
<p>given two ranges r1 and r2, define r which traverses [r1.begin(), r1.end()[ and then [r2.begin(), r2.end()[. Is there some way to define r as a range using r1 and r2?</p>
|
[
{
"answer_id": 152227,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 0,
"selected": false,
"text": "<p>I think you'd have to make a custom iterator that will 'roll over' r1.end() to r2.begin() when r1.end() is reached. Begin() and end() of that iterator would then be combined into your range r. AFAIK there is no standard boost function that will give you this behavior.</p>\n"
},
{
"answer_id": 152239,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>Can't you call the function twice, once for both ranges? Or are there problems with this approach?</li>\n<li>Copy the two ranges into one container and pass that.</li>\n<li>Write your own range class, so it iterates through r1 first and and through r2 second.</li>\n</ul>\n"
},
{
"answer_id": 3308176,
"author": "amit kumar",
"author_id": 19501,
"author_profile": "https://Stackoverflow.com/users/19501",
"pm_score": 4,
"selected": true,
"text": "<p>I needed this again so I had a second look. There is a way to concat two ranges using boost/range/join.hpp. Unluckily the output range type is not included in the interface: </p>\n\n<pre><code>#include \"boost/range/join.hpp\"\n#include \"boost/foreach.hpp\"\n#include <iostream>\n\nint main() {\n int a[] = {1, 2, 3, 4};\n int b[] = {7, 2, 3, 4};\n\n boost::iterator_range<int*> ai(&a[0], &a[4]);\n boost::iterator_range<int*> bi(&b[0], &b[4]);\n boost::iterator_range<\n boost::range_detail::\n join_iterator<int*, int*, int, int&, \n boost::random_access_traversal_tag> > ci = boost::join(ai, bi); \n\n BOOST_FOREACH(int& i, ci) {\n std::cout << i; //prints 12347234\n }\n}\n</code></pre>\n\n<p>I found the output type using the compiler messages. C++0x <code>auto</code> will be relevant there as well. </p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19501/"
] |
Boost range library (<http://www.boost.org/doc/libs/1_35_0/libs/range/index.html>) allows us to abstract a pair of iterators into a range. Now I want to combine two ranges into one, viz:
given two ranges r1 and r2, define r which traverses [r1.begin(), r1.end()[ and then [r2.begin(), r2.end()[. Is there some way to define r as a range using r1 and r2?
|
I needed this again so I had a second look. There is a way to concat two ranges using boost/range/join.hpp. Unluckily the output range type is not included in the interface:
```
#include "boost/range/join.hpp"
#include "boost/foreach.hpp"
#include <iostream>
int main() {
int a[] = {1, 2, 3, 4};
int b[] = {7, 2, 3, 4};
boost::iterator_range<int*> ai(&a[0], &a[4]);
boost::iterator_range<int*> bi(&b[0], &b[4]);
boost::iterator_range<
boost::range_detail::
join_iterator<int*, int*, int, int&,
boost::random_access_traversal_tag> > ci = boost::join(ai, bi);
BOOST_FOREACH(int& i, ci) {
std::cout << i; //prints 12347234
}
}
```
I found the output type using the compiler messages. C++0x `auto` will be relevant there as well.
|
152,218 |
<p>Here's the problem:</p>
<pre><code>split=re.compile('\\W*')
</code></pre>
<p>This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like <code>k&amp;auml;ytt&amp;auml;j&aml;auml;</code>.</p>
<p>What should I add to the regex to include the <code>&</code> and <code>;</code> characters?</p>
|
[
{
"answer_id": 152225,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 4,
"selected": true,
"text": "<p>You probably want to take the problem reverse, i.e. finding all the character without the spaces:</p>\n\n<pre><code>[^ \\t\\n]*\n</code></pre>\n\n<p>Or you want to add the extra characters:</p>\n\n<pre><code>[a-zA-Z0-9&;]*\n</code></pre>\n\n<p>In case you want to match HTML entities, you should try something like:</p>\n\n<pre><code>(\\w+|&\\w+;)*\n</code></pre>\n"
},
{
"answer_id": 152245,
"author": "Steven Oxley",
"author_id": 3831,
"author_profile": "https://Stackoverflow.com/users/3831",
"pm_score": 2,
"selected": false,
"text": "<p>you should make a character class that would include the extra characters. For example:</p>\n\n<pre><code>split=re.compile('[\\w&;]+')\n</code></pre>\n\n<p>This should do the trick. For your information</p>\n\n<ul>\n<li><code>\\w</code> (lower case 'w') matches word characters (alphanumeric)</li>\n<li><code>\\W</code> (capital W) is a negated character class (meaning it matches any non-alphanumeric character) </li>\n<li><code>*</code> matches 0 or more times and <code>+</code> matches one or more times, so <code>*</code> will match anything (even if there are no characters there).</li>\n</ul>\n"
},
{
"answer_id": 152249,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>I would treat the entities as a unit (since they also can contain numerical character codes), resulting in the following regular expression:</p>\n\n<pre><code>(\\w|&(#(x[0-9a-fA-F]+|[0-9]+)|[a-z]+);)+\n</code></pre>\n\n<p>This matches</p>\n\n<ul>\n<li>either a word character (including “<code>_</code>”), or</li>\n<li>an HTML entity consisting of\n\n<ul>\n<li>the character “<code>&</code>”,\n\n<ul>\n<li>the character “<code>#</code>”,\n\n<ul>\n<li>the character “<code>x</code>” followed by at least one hexadecimal digit, or</li>\n<li>at least one decimal digit, or</li>\n</ul></li>\n<li>at least one letter (= named entity),</li>\n</ul></li>\n<li>a semicolon</li>\n</ul></li>\n<li>at least once.</li>\n</ul>\n\n<p>/EDIT: Thanks to ΤΖΩΤΖΙΟΥ for pointing out an error.</p>\n"
},
{
"answer_id": 152305,
"author": "kari.patila",
"author_id": 21716,
"author_profile": "https://Stackoverflow.com/users/21716",
"pm_score": -1,
"selected": false,
"text": "<p>Looks like this RegEx did the trick:</p>\n\n<pre><code>split=re.compile('(\\\\\\W+&\\\\\\W+;)*')\n</code></pre>\n\n<p>Thanks for the suggestions. Most of them worked fine on Reggy, but I don't quite understand why they failed with <code>re.compile</code>.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21716/"
] |
Here's the problem:
```
split=re.compile('\\W*')
```
This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like `k&auml;ytt&auml;j&aml;auml;`.
What should I add to the regex to include the `&` and `;` characters?
|
You probably want to take the problem reverse, i.e. finding all the character without the spaces:
```
[^ \t\n]*
```
Or you want to add the extra characters:
```
[a-zA-Z0-9&;]*
```
In case you want to match HTML entities, you should try something like:
```
(\w+|&\w+;)*
```
|
152,243 |
<p>I have a database scenario (I'm using Oracle) in which several processes make inserts into a table and a single process selects from it. The table is basically used as intermediate storage, to which multiple processes (in the following called the Writers) write log events, and from which a single process (in the following referred to as the Reader) reads the events for further processing. The Reader must read all events inserted into the table.</p>
<p>Currently, this is done by each inserted record being assigned an id from an ascending sequence. The reader periodically selects a block of entries from the table where the id is larger than the largest id of the previously read block. E.g. something like:</p>
<pre><code>SELECT
*
FROM
TRANSACTION_LOG
WHERE
id > (
SELECT
last_id
FROM
READER_STATUS
);
</code></pre>
<p>The problem with this approach is that since writers operate concurrently, rows are not always inserted in order according to their assigned id, even though these are assigned in sequentially ascending order. That is, a row with id=100 is sometimes written after a record with id=110, because the process of writing the row with id=110 started after the processes writing the record id=100, but committed first. This can result in the Reader missing the row with id=100 if it has already read row with id=110.</p>
<p>Forcing the Writers to an exclusive lock on the table would solve the problem as this would force them to insert sequentially and also for the Reader to wait for any outstanding commits. This, however, would probably not be very fast.</p>
<p>It is my thinking, that it would suffice for the Reader to wait for any outstanding Writer commits before reading. That is, Writers may continue to operate concurrently as longs as the Reader does read until all writers have finished.</p>
<p>My question is this:<br>
How can I instruct my reader process to wait for any outstanding commits of my writer processes? Any alternative suggestions to the above problem are also welcome. </p>
|
[
{
"answer_id": 152375,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 1,
"selected": false,
"text": "<p>Interesting problem. It sounds like you're building a nice solution.<br />\nI hope I can help.</p>\n<p>A couple of suggestions...</p>\n<h2>Writer Status</h2>\n<p>You could create a table, WRITER_STATUS, which has a last_id field: Each writer updates this table before writing with the ID it is going to write to the log, but only if its ID is greater than the current value of last_id.</p>\n<p>The reader also checks this table and now knows if any writers have not yet written.</p>\n<h2>Reader Log</h2>\n<p>This may be more efficient.<br />\nAfter the reader does a read, it checks for any holes in the records it's retrieved.<br />\nIt then logs any missing IDs to a MISSING_IDS table and for its next read it does something like</p>\n<pre><code>SELECT *\nFROM TRANSACTION_LOG\nWHERE id > (SELECT last_id\n FROM READER_STATUS)\nOR id IN ( SELECT id from MISSING_IDS ) \n</code></pre>\n"
},
{
"answer_id": 152413,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 1,
"selected": false,
"text": "<p>You might want to put an exclusive lock on the table in the reader process. This will wait until all writers finish and release their row locks, so you can be sure there are no outstanding writer transactions.</p>\n"
},
{
"answer_id": 154056,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "<p>I wouldn't do any locking, that can interfere with concurrency and throughput.</p>\n\n<p>You don't need the Reader_Status table either, if you keep track of which log rows you've processed on a row by row basis.</p>\n\n<p>Here's what I'd do: add a new column to your log table. Call it \"processed\" for example. Make it a boolean, defaults to false (or small integer, defaults to 0, or whatever). The Writers use the default value when they insert.</p>\n\n<p>When the Reader queries for the next block of records to process, he queries for rows where processed is false and the id value is low. </p>\n\n<pre><code>SELECT * FROM Transaction_Log\nWHERE processed = 0\nORDER BY id\nLIMIT 10;\n</code></pre>\n\n<p>As he processes them, the Reader uses UPDATE to change processed from false to true. So the next time the Reader queries for a block of records, he is sure he won't get rows he has already processed.</p>\n\n<pre><code>UPDATE Transaction_Log\nSET processed = 1\nWHERE id = ?; -- do this for each row processed\n</code></pre>\n\n<p>This UPDATE shouldn't conflict with the INSERT operations done by the Writers.</p>\n\n<p>If any rows are committed out of sequence by other Writers, the Reader will see them next time he queries, if he always processes them in order of the id column from lowest value to highest value.</p>\n"
},
{
"answer_id": 154406,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 0,
"selected": false,
"text": "<p>Since you know <code>last_id</code> processed by Reader, you can request next work item in this manner:</p>\n\n<pre><code>select * from Transaction_log where id = (\n select last_id + 1 /* or whatever increment your sequencer has */\n from Reader_status)\n</code></pre>\n"
},
{
"answer_id": 156175,
"author": "Rejeev Divakaran",
"author_id": 10980,
"author_profile": "https://Stackoverflow.com/users/10980",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with AJ's solution ( <a href=\"https://stackoverflow.com/questions/152243/transaction-encapsulation-of-multi-process-writes#152375\">link</a> ). Additionally following suggestions may help to reduce the number of holes.</p>\n\n<p>1) Use <code>Oracle Sequence</code> to create the id and use <code>auto-increment</code> like as follows</p>\n\n<pre><code>INSERT INTO transaction_table VALUES(id__seq.nextval, <other columns>);\n</code></pre>\n\n<p>2) Use <code>autoCommit(true)</code> so that insert will commit immediately.</p>\n\n<p>These two steps will reduce the number of holes substantially. Still there is a possibility that some inserts started first but got committed later and a read operation happened in between.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7742/"
] |
I have a database scenario (I'm using Oracle) in which several processes make inserts into a table and a single process selects from it. The table is basically used as intermediate storage, to which multiple processes (in the following called the Writers) write log events, and from which a single process (in the following referred to as the Reader) reads the events for further processing. The Reader must read all events inserted into the table.
Currently, this is done by each inserted record being assigned an id from an ascending sequence. The reader periodically selects a block of entries from the table where the id is larger than the largest id of the previously read block. E.g. something like:
```
SELECT
*
FROM
TRANSACTION_LOG
WHERE
id > (
SELECT
last_id
FROM
READER_STATUS
);
```
The problem with this approach is that since writers operate concurrently, rows are not always inserted in order according to their assigned id, even though these are assigned in sequentially ascending order. That is, a row with id=100 is sometimes written after a record with id=110, because the process of writing the row with id=110 started after the processes writing the record id=100, but committed first. This can result in the Reader missing the row with id=100 if it has already read row with id=110.
Forcing the Writers to an exclusive lock on the table would solve the problem as this would force them to insert sequentially and also for the Reader to wait for any outstanding commits. This, however, would probably not be very fast.
It is my thinking, that it would suffice for the Reader to wait for any outstanding Writer commits before reading. That is, Writers may continue to operate concurrently as longs as the Reader does read until all writers have finished.
My question is this:
How can I instruct my reader process to wait for any outstanding commits of my writer processes? Any alternative suggestions to the above problem are also welcome.
|
Interesting problem. It sounds like you're building a nice solution.
I hope I can help.
A couple of suggestions...
Writer Status
-------------
You could create a table, WRITER\_STATUS, which has a last\_id field: Each writer updates this table before writing with the ID it is going to write to the log, but only if its ID is greater than the current value of last\_id.
The reader also checks this table and now knows if any writers have not yet written.
Reader Log
----------
This may be more efficient.
After the reader does a read, it checks for any holes in the records it's retrieved.
It then logs any missing IDs to a MISSING\_IDS table and for its next read it does something like
```
SELECT *
FROM TRANSACTION_LOG
WHERE id > (SELECT last_id
FROM READER_STATUS)
OR id IN ( SELECT id from MISSING_IDS )
```
|
152,250 |
<p>I have my winform application gathering data using databinding. Everything looks fine except that I have to link the <strong>property</strong> with the <strong>textedit</strong> using a string:</p>
<blockquote>
<p>Me.TextEdit4.DataBindings.Add(New System.Windows.Forms.Binding("EditValue", Me.MyClassBindingSource, "MyClassProperty", True))</p>
</blockquote>
<p>This works fine but if I change the class' property name, the compiler obviously will not warn me . </p>
<p>I would like to be able to get the property name by reflection but I don't know how to specify the name of the property I want (I only know how to iterate among all the properties of the class) </p>
<p>Any idea?</p>
|
[
{
"answer_id": 152254,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>Ironically reflection expects that you provide property name to get it's info :) </p>\n\n<p>You can create custom attribute, apply it to desired property. Then you will be able to simply get name of the property having this attribute.</p>\n"
},
{
"answer_id": 152257,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>You'll have the same problem using reflection because in order to find the right property in all the type's properties, you'll have to know its name, right?</p>\n"
},
{
"answer_id": 152258,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 0,
"selected": false,
"text": "<p>You can reflect a Type, but you can't reflect its members except by name.</p>\n\n<p>If that were the only property, or you knew for certain the ordering you could find it by index, but generally speaking a string is the safest way to go.</p>\n\n<p>I believe changing the name will cause a run-time exception, but am not 100% certain, in either case that is probably the best possibility.</p>\n\n<p>Assuming no exception occurs automatically, you could add a Debug.Assert that checks to see if the property by that name exists, but again that is run time only.</p>\n"
},
{
"answer_id": 152260,
"author": "martinsb",
"author_id": 837,
"author_profile": "https://Stackoverflow.com/users/837",
"pm_score": 0,
"selected": false,
"text": "<p>1) Specify the exact property name that you want and keep it that way</p>\n\n<p>2) Write a test involving that property name.</p>\n"
},
{
"answer_id": 152279,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": true,
"text": "<p>Here is an example of what I'm talking about:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Property)]\nclass TextProperyAttribute: Attribute\n{}\n\nclass MyTextBox\n{\n [TextPropery]\n public string Text { get; set;}\n public int Foo { get; set;}\n public double Bar { get; set;}\n}\n\n\nstatic string GetTextProperty(Type type)\n{\n foreach (PropertyInfo info in type.GetProperties())\n {\n if (info.GetCustomAttributes(typeof(TextProperyAttribute), true).Length > 0)\n {\n return info.Name;\n }\n }\n\n return null;\n}\n\n...\n\nType type = typeof (MyTextBox);\n\nstring name = GetTextProperty(type);\n\nConsole.WriteLine(name); // Prints \"Text\"\n</code></pre>\n"
},
{
"answer_id": 152293,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using C# 3.0, there is a way to get the name of the property dynamically, without hard coded it.</p>\n\n<pre><code>private string GetPropertyName<TValue>(Expression<Func<BindingSourceType, TValue>> propertySelector)\n{\n var memberExpression = propertySelector.Body as MemberExpression;\n return memberExpression != null \n ? memberExpression.Member.Name \n : string.empty;\n}\n</code></pre>\n\n<p>Where <code>BindingSourceType</code> is the class name of your datasource object instance.</p>\n\n<p>Then, you could use a lambda expression to select the property you want to bind, in a strongly typed manner :</p>\n\n<pre><code>this.textBox.DataBindings.Add(GetPropertyName(o => o.MyClassProperty),\n this.myDataSourceObject,\n \"Text\");\n</code></pre>\n\n<p>It will allow you to refactor your code safely, without braking all your databinding stuff. But using expression trees is the same as using reflection, in terms of performance.</p>\n\n<p><strong>The previous code is quite ugly and unchecked, but you get the idea.</strong></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have my winform application gathering data using databinding. Everything looks fine except that I have to link the **property** with the **textedit** using a string:
>
> Me.TextEdit4.DataBindings.Add(New System.Windows.Forms.Binding("EditValue", Me.MyClassBindingSource, "MyClassProperty", True))
>
>
>
This works fine but if I change the class' property name, the compiler obviously will not warn me .
I would like to be able to get the property name by reflection but I don't know how to specify the name of the property I want (I only know how to iterate among all the properties of the class)
Any idea?
|
Here is an example of what I'm talking about:
```
[AttributeUsage(AttributeTargets.Property)]
class TextProperyAttribute: Attribute
{}
class MyTextBox
{
[TextPropery]
public string Text { get; set;}
public int Foo { get; set;}
public double Bar { get; set;}
}
static string GetTextProperty(Type type)
{
foreach (PropertyInfo info in type.GetProperties())
{
if (info.GetCustomAttributes(typeof(TextProperyAttribute), true).Length > 0)
{
return info.Name;
}
}
return null;
}
...
Type type = typeof (MyTextBox);
string name = GetTextProperty(type);
Console.WriteLine(name); // Prints "Text"
```
|
152,261 |
<p>I have a Delphi DLL with a function defined as:</p>
<p>function SubmitJobStringList(joblist: tStringList; var jobno: Integer): Integer;</p>
<p>I am calling this from C#. How do I declare the first parameter as a tStringList does not exist in C#. I currently have the declaration as:</p>
<pre><code>[DllImport("opt7bja.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int SubmitJobStringList(string[] tStringList, ref int jobno);
</code></pre>
<p>But when I call it I get a memory access violation exception.</p>
<p>Anyone know how to pass to a tStringList correctly from C#?</p>
|
[
{
"answer_id": 152322,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 5,
"selected": true,
"text": "<p>You'll most likely not have any luck with this. The TStringList is more than just an array, it's a full-blown class, and the exact implementation details may differ from what is possible with .NET. Take a look at the Delphi VCL source code (that is, if you have it) and try to find out if you can rebuild the class in C#, and pass it with the help of your best friend, the Interop Marshaller. Note that even the Delphi string type is different from the .NET string type, and passing it without telling the marshaller what he should do, he will pass it as a char-array, most likely.</p>\n\n<p>Other than that, I would suggest changing the Delphi DLL. It's never a good thing to expose anything Delphi-specific in a DLL that is to be used by non-Delphi clients. Make the parameter an array of PChar and you should be fine.</p>\n"
},
{
"answer_id": 152334,
"author": "Hemant",
"author_id": 23671,
"author_profile": "https://Stackoverflow.com/users/23671",
"pm_score": 0,
"selected": false,
"text": "<p>I am not exactly clear your way of using delphi and C#. It seems you have created a Win32 DLL which you want to call from C#. Offcourse you must be using PInvoke for this.</p>\n\n<p>I would suggest that you create a .NET DLL using your source code since complete porting of VCL is available. I can further elaborate if you wish....</p>\n"
},
{
"answer_id": 152368,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 0,
"selected": false,
"text": "<p>In theory, you <em>could</em> do something like this by using pointers (casting them as the C# IntPtr type) instead of strongly typed object references (or perhaps wrapping them in some other type to avoid having to declare unsafe blocks), but the essential catch is this: The Delphi runtime must be the mechanism for allocating and deallocating memory for the objects. To that end, you must declare functions in your Delphi-compiled DLL which invoke the constructors and destructors for the TStringList class, you must make sure that your Delphi DLL uses the ShareMem unit, and you must take responsibility for incrementing and decrementing the reference count for your Delphi AnsiStrings before they leave the DLL and after they enter it, preferably also as functions exported from your Delphi DLL.</p>\n\n<p>In short, it's a <strong>lot</strong> of work since you must juggle two memory managers in the same process (the .NET CLR and Delphi's allocators) and you must both manage the memory manually <em>and</em> \"fool\" the Delphi memory manager and runtime. Is there a particular reason you are bound to this setup? Could you describe the problem you are trying to solve at a higher level?</p>\n"
},
{
"answer_id": 152421,
"author": "Shunyata Kharg",
"author_id": 23724,
"author_profile": "https://Stackoverflow.com/users/23724",
"pm_score": 0,
"selected": false,
"text": "<p>As Hemant Jangid said, you should easily be able to do this by compiling your code as a .NET dll and then referring to that assembly in your c# project.</p>\n\n<p>Of course, you'll only be able to do this if the version of Delphi you have has Delphi.NET.</p>\n"
},
{
"answer_id": 152455,
"author": "Bruce McGee",
"author_id": 19183,
"author_profile": "https://Stackoverflow.com/users/19183",
"pm_score": 2,
"selected": false,
"text": "<p>If this is your DLL, I'd rewrite the function to accept an array of strings instead. Avoid passing classes as DLL parameters.</p>\n\n<p>Or, if you <em>really</em> want to use a TStringList for some reason, Delphi's VCL.Net can be used from any .Net language.</p>\n\n<p>An old example using TIniFile: <a href=\"http://cc.codegear.com/Item/22691\" rel=\"nofollow noreferrer\">http://cc.codegear.com/Item/22691</a></p>\n\n<p>The example uses .Net 1.1 in Delphi 2005. Delphi 2006 and 2007 support .Net 2.0.</p>\n"
},
{
"answer_id": 152491,
"author": "Bruce McGee",
"author_id": 19183,
"author_profile": "https://Stackoverflow.com/users/19183",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't control the DLL and they can't or won't change it, you could always write your own Delphi wrapper in a separate DLL with parameters that are more cross-language friendly.</p>\n\n<p>Having a class as a parameter of a DLL function really is bad form.</p>\n"
},
{
"answer_id": 156170,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know a lot about c#, but a technique that I use for transporting stringlists across contexts is using the .text property to get a string representing the list, then assigning that property on \"the other side\".</p>\n\n<p>It's usually easier to get a string over the wall that it is a full blown object.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3585/"
] |
I have a Delphi DLL with a function defined as:
function SubmitJobStringList(joblist: tStringList; var jobno: Integer): Integer;
I am calling this from C#. How do I declare the first parameter as a tStringList does not exist in C#. I currently have the declaration as:
```
[DllImport("opt7bja.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int SubmitJobStringList(string[] tStringList, ref int jobno);
```
But when I call it I get a memory access violation exception.
Anyone know how to pass to a tStringList correctly from C#?
|
You'll most likely not have any luck with this. The TStringList is more than just an array, it's a full-blown class, and the exact implementation details may differ from what is possible with .NET. Take a look at the Delphi VCL source code (that is, if you have it) and try to find out if you can rebuild the class in C#, and pass it with the help of your best friend, the Interop Marshaller. Note that even the Delphi string type is different from the .NET string type, and passing it without telling the marshaller what he should do, he will pass it as a char-array, most likely.
Other than that, I would suggest changing the Delphi DLL. It's never a good thing to expose anything Delphi-specific in a DLL that is to be used by non-Delphi clients. Make the parameter an array of PChar and you should be fine.
|
152,262 |
<p>I am in charge of a website at work and recently I have added ajaxy requests to make it faster and more responsive. But it has raised an issue.</p>
<p>On my pages, there is an index table on the left, like a menu. Once you have clicked on it, it makes a request that fills the rest of the page. At anytime you can click on another item of the index to load a different page.</p>
<p>Before adding javascript, it was possible to middle click (open new tabs) for each item of the index, which allowed to have other pages loading while I was dealing with one of them.
But since I have changed all the links to be ajax requests, they now execute some javascript instead of being real links. So they are only opening empty tabs when I middle click on them.</p>
<p>Is there a way to combine both functionalities: links firing javascript when left clicked or new tabs when middle clicked?
Does it have to be some ugly javascript that catches every clicks and deal with them accordingly?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 152271,
"author": "Franck Mesirard",
"author_id": 16070,
"author_profile": "https://Stackoverflow.com/users/16070",
"pm_score": 0,
"selected": false,
"text": "<p>Possibly, I could provide two links each time, one firing the javascript and another being a real link that would allow for middle click.\nI presume, one of them would have to be an image to avoid overloading the index.</p>\n"
},
{
"answer_id": 152273,
"author": "Guvante",
"author_id": 16800,
"author_profile": "https://Stackoverflow.com/users/16800",
"pm_score": 1,
"selected": false,
"text": "<p>It would require some testing, but I believe that most browsers do not execute the click handler when you click them, meaning that only the link is utilized.</p>\n\n<p>Not however that your handler function needs to return false to ensure these links aren't used when normally clicking.</p>\n\n<p><strong>EDIT:</strong>\nFelt this could use an example:</p>\n\n<pre><code><a href=\"/Whatever/Wherever.htm\" onclick=\"handler(); return false;\" />\n</code></pre>\n"
},
{
"answer_id": 152274,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 4,
"selected": false,
"text": "<p>Yes. Instead of:</p>\n<pre><code><a href="javascript:code">...</a>\n</code></pre>\n<p>Do this:</p>\n<pre><code><a href="/non/ajax/display/page" id="thisLink">...</a>\n</code></pre>\n<p>And then in your JS, hook the link via it's ID to do the AJAX call. Remember that you need to stop the click event from bubbling up. Most frameworks have an event killer built in that you can call (just look at its Event class).</p>\n<p>Here's the event handling and event-killer in jquery:</p>\n<pre><code>$("#thisLink").click(function(ev, ob) {\n alert("thisLink was clicked");\n ev.stopPropagation();\n});\n</code></pre>\n<p>Of course you can be a lot more clever, while juggling things like this but I think it's important to stress that this method is <em>so</em> much cleaner than using <code>onclick</code> attributes.</p>\n<h1>Keep your JS in the JS!</h1>\n"
},
{
"answer_id": 152277,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 0,
"selected": false,
"text": "<p>The onclick event won't be fired for that type of click, so you need to add an <code>href</code> attribute which would actually work. One possible way to do this by adding a <code>#bookmark</code> to the URL to indicate to the target page what the required state is.</p>\n"
},
{
"answer_id": 152301,
"author": "Lewis Jubb",
"author_id": 6503,
"author_profile": "https://Stackoverflow.com/users/6503",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, You need to lookup progressive enhancement and unobtrusive Javascript, and code your site to work with out Javascript enabled first and then add the Javascripts functions after you have the basic site working.</p>\n"
},
{
"answer_id": 153275,
"author": "Fczbkk",
"author_id": 22920,
"author_profile": "https://Stackoverflow.com/users/22920",
"pm_score": 1,
"selected": false,
"text": "<pre><code><a href=\"/original/url\" onclick=\"return !doSomething();\">link text</a>\n</code></pre>\n\n<p>For more info and detailed explanation view <a href=\"https://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0#143410\">my answer in another post</a>.</p>\n"
},
{
"answer_id": 15722884,
"author": "viggity",
"author_id": 4572,
"author_profile": "https://Stackoverflow.com/users/4572",
"pm_score": 2,
"selected": false,
"text": "<p>I liked Oli's approach, but it didn't discern from left and middle clicks. checking the \"which\" field on the eventArgs will let you know.</p>\n\n<pre><code>$(\".detailLink\").click(function (ev, ob) {\n //ev.which == 1 == left\n //ev.which == 2 == middle\n if (ev.which == 1) {\n //do ajaxy stuff\n\n return false; //tells browser to stop processing the event\n }\n //else just let it go on its merry way and open the new tab.\n});\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16070/"
] |
I am in charge of a website at work and recently I have added ajaxy requests to make it faster and more responsive. But it has raised an issue.
On my pages, there is an index table on the left, like a menu. Once you have clicked on it, it makes a request that fills the rest of the page. At anytime you can click on another item of the index to load a different page.
Before adding javascript, it was possible to middle click (open new tabs) for each item of the index, which allowed to have other pages loading while I was dealing with one of them.
But since I have changed all the links to be ajax requests, they now execute some javascript instead of being real links. So they are only opening empty tabs when I middle click on them.
Is there a way to combine both functionalities: links firing javascript when left clicked or new tabs when middle clicked?
Does it have to be some ugly javascript that catches every clicks and deal with them accordingly?
Thanks.
|
Yes. Instead of:
```
<a href="javascript:code">...</a>
```
Do this:
```
<a href="/non/ajax/display/page" id="thisLink">...</a>
```
And then in your JS, hook the link via it's ID to do the AJAX call. Remember that you need to stop the click event from bubbling up. Most frameworks have an event killer built in that you can call (just look at its Event class).
Here's the event handling and event-killer in jquery:
```
$("#thisLink").click(function(ev, ob) {
alert("thisLink was clicked");
ev.stopPropagation();
});
```
Of course you can be a lot more clever, while juggling things like this but I think it's important to stress that this method is *so* much cleaner than using `onclick` attributes.
Keep your JS in the JS!
=======================
|
152,276 |
<p>I have report on my asp page and every time I change a filter and click view report, I get this error:</p>
<p>Microsoft JScript runtime error: 'this._postBackSettings.async' is null or not an object</p>
<p>I tried change the EnablePartialRendering="true" to EnablePartialRendering="false" but then people can't login on the site</p>
|
[
{
"answer_id": 229605,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Put the button inside a panel (not update panel), then add this line to the panel\nDefaultButton=\"Button1\"</p>\n\n<p>This will avoid the error.</p>\n"
},
{
"answer_id": 1289646,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I also had this problem, although in my case there were no reports involved: it was a just a normal asp.net page with an image button. The thing was that on client click I was cancelling the next javascript events with this code: </p>\n\n<pre><code>event.cancelBubble = true;\nif (event.stopPropagation)\n event.stopPropagation();\n</code></pre>\n\n<p>I removed the code and the problem also disapeared. My guess is that asp.net ajax needs to do some processing on client click and maybe your report control is doing something like I was doing. Hope it helps you find your problem and sorry for my english :)\nRegards,\nMMM</p>\n"
},
{
"answer_id": 1594758,
"author": "Robin Malmberg",
"author_id": 193130,
"author_profile": "https://Stackoverflow.com/users/193130",
"pm_score": 1,
"selected": false,
"text": "<p>I got this problem just now and found a solution by accident.</p>\n\n<p>Problem started showing up after I moved the ScriptManager to a master page - and only when I was using pages with no update panels.</p>\n\n<p>Solved it by moving the ScriptManager tag to just in front of the content area of the master page.</p>\n\n<p>JavaScript ordering problems?</p>\n"
},
{
"answer_id": 3342506,
"author": "Sunil Pandey",
"author_id": 403242,
"author_profile": "https://Stackoverflow.com/users/403242",
"pm_score": 2,
"selected": false,
"text": "<p>This problem is solved by setting <code>EnablePartialRendering</code> to false of <code>ScriptManager</code>.</p>\n\n<pre><code>ScriptManager1.EnablePartialRendering = false;\n</code></pre>\n\n<p>In <code>OnInit</code> event of the page where <code>rsweb:ReportViewer</code> is used.\nIf you want to enable for other page then set it true on master page's <code>OnInit</code>.</p>\n"
},
{
"answer_id": 5105110,
"author": "Gorgsenegger",
"author_id": 412036,
"author_profile": "https://Stackoverflow.com/users/412036",
"pm_score": 2,
"selected": false,
"text": "<p>I've had the same problem and haven't really found any satisfying solution until I ended up on <a href=\"https://siderite.dev/blog/thispostbacksettingsasync-is-null-or.html\" rel=\"nofollow noreferrer\">https://siderite.dev/blog/thispostbacksettingsasync-is-null-or.html</a> which does exactly what I want.</p>\n\n<p>Just to avoid problems with possible dead links in the future, here is the code:</p>\n\n<pre><code>var script = @\"\nif (Sys &&\n Sys.WebForms && Sys.WebForms.PageRequestManager &&\n Sys.WebForms.PageRequestManager.getInstance) \n{\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n if (prm &&\n !prm._postBackSettings)\n {\n prm._postBackSettings = prm._createPostBackSettings(false, null, null);\n }\";\n\nScriptManager.RegisterOnSubmitStatement(\n Page, \n Page.GetType(), \n \"FixPopupFormSubmit\", \n script);\n</code></pre>\n\n<p>In case of a submit without the _postBackSettings being set it creates them, causing the null reference exception to disappear as _postBackSettings.async is then available.</p>\n"
},
{
"answer_id": 7242348,
"author": "Andre",
"author_id": 919582,
"author_profile": "https://Stackoverflow.com/users/919582",
"pm_score": 2,
"selected": false,
"text": "<p>I discovered another solution to this problem.</p>\n\n<p>I use the Telerik RadScriptManager and RadAjaxManager (which are built upon the respective ASP.NET framework objects). I discovered some issues when I implemented JQuery UI animations to hide the buttons--animations which I executed \"OnClientClick\" of the button.</p>\n\n<p>To solve the problem, I handled the OnRequestStart and OnResponseEnd client events and executed the applicable hide and show animations from OnRequestStart and OnResponseEnd, respectively.</p>\n\n<p>I know not everyone uses Telerik, but this concept might be key, and probably applies to other AJAX frameworks: When performing client-side changes on ajaxified elements (especially changes like animations which occur during AJAX request processing), make those changes in your framework's RequestStart/ResponseEnd client side event handlers rather than in the client side event handlers of the ajaxified elements.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12311/"
] |
I have report on my asp page and every time I change a filter and click view report, I get this error:
Microsoft JScript runtime error: 'this.\_postBackSettings.async' is null or not an object
I tried change the EnablePartialRendering="true" to EnablePartialRendering="false" but then people can't login on the site
|
This problem is solved by setting `EnablePartialRendering` to false of `ScriptManager`.
```
ScriptManager1.EnablePartialRendering = false;
```
In `OnInit` event of the page where `rsweb:ReportViewer` is used.
If you want to enable for other page then set it true on master page's `OnInit`.
|
152,288 |
<p>I've been pulling my hear out over this problem for a few hours yesterday:</p>
<p>I've a database on MySQL 4.1.22 server with encoding set to "UTF-8 Unicode (utf8)" (as reported by phpMyAdmin). Tables in this database have default charset set to <b>latin2</b>. But, the web application (CMS Made Simple written in PHP) using it displays pages in <b>utf8</b>...</p>
<p>However screwed up this may be, it actually works. The web app displays characters correctly (mostly Czech and Polish are used).</p>
<p>I run: "mysqldump -u xxx -p -h yyy dbname > dump.sql". This gives me an SQL script which:</p>
<ul>
<li>looks perfect in any editor (like Notepad+) when displaying in <b>UTF-8</b> - all characters display properly</li>
<li>all tables in the script have default charset set to <b>latin2</b></li>
<li>it has "/*!40101 SET NAMES latin2 */;" line at the beginning (among other settings)</li>
</ul>
<p>Now, I want to export this database to another server running on MySQL 5.0.67, also with server encoding set to "UTF-8 Unicode (utf8)". I copied the whole CMS Made Simple installation over, copied the dump.sql script and ran "mysql -h ddd -u zzz -p dbname < dump.sql". After that, all the characters are scrambled when displaying CMSMS web pages.</p>
<p>I tried setting:<br>
SET character_set_client = utf8;<br>
SET character_set_connection = latin2;</p>
<p>And all combinations (just to be safe, even if it doesn't make any sense to me): latin2/utf8, latin2/latin2, utf8/utf8, etc. - doesn't help. All characters still scrambled, however sometimes in a different way :).</p>
<p>I also tried replacing all latin2 settings with utf8 in the script (set names and default charsets for tables). Nothing.</p>
<p>Are there any MySQL experts here who could explain in just a few words (I'm sure it's simple after all) how this whole encoding stuff really works? I read <a href="http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html" rel="noreferrer">9.1.4. Connection Character Sets and Collations</a> but found nothing helpful there.</p>
<p>Thanks,
Matt</p>
|
[
{
"answer_id": 152730,
"author": "Matt",
"author_id": 23723,
"author_profile": "https://Stackoverflow.com/users/23723",
"pm_score": 1,
"selected": true,
"text": "<p>Ugh... ok, seems I found a solution.</p>\n\n<p>MySQL isn't the culprit here. I did a simple dump and load now, with no changes to the dump.sql script - meaning I left \"set names latin2\" and tables charsets as they were. Then I switched my original CMSMS installation over to the new database and... it worked correctly. So actually encoding in the database is ok, or at least it works fine with CMSMS installation I had at my old hosting provider (CMSMS apparently <a href=\"http://forum.cmsmadesimple.org/index.php/topic,21346.0.html\" rel=\"nofollow noreferrer\">does funny things with characters encoding</a>).</p>\n\n<p>To make it work on my new hosting provider, I actually had to add this line to lib/adodb/drivers/adodb-mysql.inc.php in CMSMS installation:</p>\n\n<pre>mysql_query('set names latin2',$this->_connectionID);</pre>\n\n<p>This is a slightly modified solution from <a href=\"http://gallery.menalto.com/node/36886\" rel=\"nofollow noreferrer\">this post</a>. You can find the exact line there as well. So it looks like mysql client configuration issue.</p>\n"
},
{
"answer_id": 152740,
"author": "kolrie",
"author_id": 14540,
"author_profile": "https://Stackoverflow.com/users/14540",
"pm_score": 5,
"selected": false,
"text": "<p>Did you try adding the --default-character-set=name option, like this:</p>\n\n<pre><code>mysql --default-character-set=utf8 -h ddd -u zzz -p dbname < dump.sql\n</code></pre>\n\n<p>I had that problem before and it worked after using that option.</p>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 21157493,
"author": "T.Todua",
"author_id": 2377343,
"author_profile": "https://Stackoverflow.com/users/2377343",
"pm_score": 0,
"selected": false,
"text": "<p>SOLUTION for me:</p>\n\n<p>set this option in your php file, after <strong>mysql_connect</strong> (or after <strong>mysql_select_db</strong>)..</p>\n\n<pre><code>mysql_query(\"SET NAMES 'utf8'\");\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23723/"
] |
I've been pulling my hear out over this problem for a few hours yesterday:
I've a database on MySQL 4.1.22 server with encoding set to "UTF-8 Unicode (utf8)" (as reported by phpMyAdmin). Tables in this database have default charset set to **latin2**. But, the web application (CMS Made Simple written in PHP) using it displays pages in **utf8**...
However screwed up this may be, it actually works. The web app displays characters correctly (mostly Czech and Polish are used).
I run: "mysqldump -u xxx -p -h yyy dbname > dump.sql". This gives me an SQL script which:
* looks perfect in any editor (like Notepad+) when displaying in **UTF-8** - all characters display properly
* all tables in the script have default charset set to **latin2**
* it has "/\*!40101 SET NAMES latin2 \*/;" line at the beginning (among other settings)
Now, I want to export this database to another server running on MySQL 5.0.67, also with server encoding set to "UTF-8 Unicode (utf8)". I copied the whole CMS Made Simple installation over, copied the dump.sql script and ran "mysql -h ddd -u zzz -p dbname < dump.sql". After that, all the characters are scrambled when displaying CMSMS web pages.
I tried setting:
SET character\_set\_client = utf8;
SET character\_set\_connection = latin2;
And all combinations (just to be safe, even if it doesn't make any sense to me): latin2/utf8, latin2/latin2, utf8/utf8, etc. - doesn't help. All characters still scrambled, however sometimes in a different way :).
I also tried replacing all latin2 settings with utf8 in the script (set names and default charsets for tables). Nothing.
Are there any MySQL experts here who could explain in just a few words (I'm sure it's simple after all) how this whole encoding stuff really works? I read [9.1.4. Connection Character Sets and Collations](http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html) but found nothing helpful there.
Thanks,
Matt
|
Ugh... ok, seems I found a solution.
MySQL isn't the culprit here. I did a simple dump and load now, with no changes to the dump.sql script - meaning I left "set names latin2" and tables charsets as they were. Then I switched my original CMSMS installation over to the new database and... it worked correctly. So actually encoding in the database is ok, or at least it works fine with CMSMS installation I had at my old hosting provider (CMSMS apparently [does funny things with characters encoding](http://forum.cmsmadesimple.org/index.php/topic,21346.0.html)).
To make it work on my new hosting provider, I actually had to add this line to lib/adodb/drivers/adodb-mysql.inc.php in CMSMS installation:
```
mysql_query('set names latin2',$this->_connectionID);
```
This is a slightly modified solution from [this post](http://gallery.menalto.com/node/36886). You can find the exact line there as well. So it looks like mysql client configuration issue.
|
152,299 |
<p>I am about to set up a subversion server to be accessed via svn+ssh. I was wondering, where the <em>default</em> repository location is (on a unix box).</p>
<p>Do you put it in</p>
<pre><code>/opt/svn
</code></pre>
<p>or</p>
<pre><code>/home/svn
</code></pre>
<p>or</p>
<pre><code>/usr/subversion
</code></pre>
<p>or even</p>
<pre><code>/svn
</code></pre>
<p>or somewhere else?</p>
<p>I am looking for the place, most people put it. Is there a convention?</p>
<p>EDIT:</p>
<p>It is absolutely possible to "hide" the actual repository location from the user. For example (in my case) by wrapping the <code>svnserve</code> executable in a way that it is called like:</p>
<pre><code>svnserve -r /var/svn/repos
</code></pre>
|
[
{
"answer_id": 152403,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 4,
"selected": true,
"text": "<p>I typically place the repositories somewhere under <code>/var</code>, usually in <code>/var/lib/svn</code> - I'm trying to follow the <a href=\"http://www.pathname.com/fhs/\" rel=\"nofollow noreferrer\">Filesystem Hierarchy Standard</a> which has this to say about the <a href=\"http://www.pathname.com/fhs/pub/fhs-2.3.html#PURPOSE31\" rel=\"nofollow noreferrer\">purpose of /var</a>:</p>\n\n<p><code>/var</code> is specified here in order to make it possible to mount <code>/usr</code> read-only. Everything that once went into <code>/usr</code> that is written to during system operation (as opposed to installation and software maintenance) must be in <code>/var</code>.</p>\n"
},
{
"answer_id": 152428,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 2,
"selected": false,
"text": "<p><code>/home/svn</code> here, mostly because I thought that at some point I might need a <code>svn</code> user...</p>\n"
},
{
"answer_id": 152429,
"author": "Joe Chin",
"author_id": 5906,
"author_profile": "https://Stackoverflow.com/users/5906",
"pm_score": 1,
"selected": false,
"text": "<p>It should definitely be in /var. I keep mine in /var/lib/svn. /opt is useful for keeping applications that you might not necessarily want as part of the system, for example: Firefox or MySql. A repository is not an application so it doesn't make sense to keep it in /opt. </p>\n\n<p>And like the comment above you can refer to the <a href=\"http://www.pathname.com/fhs/pub/fhs-2.3.html\" rel=\"nofollow noreferrer\">FHS</a></p>\n"
},
{
"answer_id": 152697,
"author": "dexedrine",
"author_id": 20266,
"author_profile": "https://Stackoverflow.com/users/20266",
"pm_score": 2,
"selected": false,
"text": "<p>Based on the new FHS, you're supposed to put \"Data for services provided by this system\" into the /srv directory. There isn't any other guidance in the FHS except to put everything that is data for services in that directory, such as http, etc. I would suggest /srv/svn/.</p>\n"
},
{
"answer_id": 153789,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 2,
"selected": false,
"text": "<p>As far as the path for the repository goes, I like to partition and mount a directory called repository on it ;) </p>\n\n<blockquote>\n <p>/repository</p>\n</blockquote>\n\n<p>This way I can check the size easily using \"df\"</p>\n\n<blockquote>\n <p>Is it possible to hide the absolute\n path from the users?</p>\n</blockquote>\n\n<p>To answer this question, yes, but only if they don't have full access to the box. You set them up with an account, and have them generate a public/private key to login but you never give them the password. </p>\n\n<p>Then you cat their key into /home/<_user>/.ssh/authorized_keys and you edit the settings so that logging in with said key launches svn-serve.</p>\n\n<pre><code>command=\"/usr/local/bin/svnserve -t -r /repository/\" \n</code></pre>\n\n<p>Now create a project in the repository:</p>\n\n<pre><code>svnadmin create /repository/proj1\n</code></pre>\n\n<p>With SVN you have to give the user read/write access to the project directory. Then they are able to check out code like:</p>\n\n<pre><code>svn co svn+ssh://host/proj1\n</code></pre>\n\n<p>The user never sees or knows the absolute path of the repository. </p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] |
I am about to set up a subversion server to be accessed via svn+ssh. I was wondering, where the *default* repository location is (on a unix box).
Do you put it in
```
/opt/svn
```
or
```
/home/svn
```
or
```
/usr/subversion
```
or even
```
/svn
```
or somewhere else?
I am looking for the place, most people put it. Is there a convention?
EDIT:
It is absolutely possible to "hide" the actual repository location from the user. For example (in my case) by wrapping the `svnserve` executable in a way that it is called like:
```
svnserve -r /var/svn/repos
```
|
I typically place the repositories somewhere under `/var`, usually in `/var/lib/svn` - I'm trying to follow the [Filesystem Hierarchy Standard](http://www.pathname.com/fhs/) which has this to say about the [purpose of /var](http://www.pathname.com/fhs/pub/fhs-2.3.html#PURPOSE31):
`/var` is specified here in order to make it possible to mount `/usr` read-only. Everything that once went into `/usr` that is written to during system operation (as opposed to installation and software maintenance) must be in `/var`.
|
152,307 |
<p>I've got an ASP.NET 2.0 website with a custom 404 page. When content is not found the site serves the custom 404 page with a query string addition of aspxerrorpath=/mauro.aspx. The 404 page itself is served with an <a href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" rel="nofollow noreferrer">HTTP</a> status of 200. To try to resolve this I've added</p>
<pre><code> protected void Page_Load(object sender, EventArgs e)
{
Response.StatusCode = 404;
}
</code></pre>
<p>I added the Google widget and have two issues with it. In <a href="http://en.wikipedia.org/wiki/Internet_Explorer_7" rel="nofollow noreferrer">Internet Explorer 7</a> it does not display where it should. If I add it to the content, I get an "unknown error" on char 79 line 226 or thereabouts; if I add it to the head section the search boxes appear above the content. In Firefox it works fine.</p>
<p>So my issues are:</p>
<ol>
<li>How do I make the widget appear
inline?</li>
<li>How do I make the error page
render as a 404 with the original
name and path of the file being
requested so that when I request
mauro.aspx I get the content for the
404 page, but with the URL of
mauro.aspx? (I assume that I will
have to do some <a href="http://en.wikipedia.org/wiki/Rewrite_engine" rel="nofollow noreferrer">URL rewriting</a> in the
begin_request global.asax file, but
would like this confirmed before I
do anything silly.)</li>
</ol>
|
[
{
"answer_id": 152366,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 2,
"selected": true,
"text": "<p>I've handled the 404 by doing this in the global.asax file</p>\n\n<pre><code>protected void Application_BeginRequest(object sender, EventArgs e)\n{\n string url = Request.RawUrl;\n if ((url.Contains(\".aspx\")) && (!System.IO.File.Exists(Server.MapPath(url))))\n {\n Server.Transfer(\"/Error/FileNotFound.aspx\");\n }\n}\n</code></pre>\n\n<p>Now, if anyone can help me with the google widget that would be great!</p>\n"
},
{
"answer_id": 152373,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 3,
"selected": false,
"text": "<p>There is a new redirect mode in ASP.NET 3.5 SP1 that you can now use so it doesn't redirect. It shows the error page, but keeps the URL the same:</p>\n\n<p>\"Also nice for URL redirects. If you set the redirectMode on in web.config to \"responseRewrite\" you can avoid a redirect to a custom error page and leave the URL in the browser untouched.\"</p>\n\n<ul>\n<li><em><a href=\"http://msdn.microsoft.com/en-us/library/system.web.configuration.customerrorssection.redirectmode.aspx\" rel=\"nofollow noreferrer\">CustomErrorsSection.RedirectMode Property</a></em> (MSDN)</li>\n</ul>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2208/"
] |
I've got an ASP.NET 2.0 website with a custom 404 page. When content is not found the site serves the custom 404 page with a query string addition of aspxerrorpath=/mauro.aspx. The 404 page itself is served with an [HTTP](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) status of 200. To try to resolve this I've added
```
protected void Page_Load(object sender, EventArgs e)
{
Response.StatusCode = 404;
}
```
I added the Google widget and have two issues with it. In [Internet Explorer 7](http://en.wikipedia.org/wiki/Internet_Explorer_7) it does not display where it should. If I add it to the content, I get an "unknown error" on char 79 line 226 or thereabouts; if I add it to the head section the search boxes appear above the content. In Firefox it works fine.
So my issues are:
1. How do I make the widget appear
inline?
2. How do I make the error page
render as a 404 with the original
name and path of the file being
requested so that when I request
mauro.aspx I get the content for the
404 page, but with the URL of
mauro.aspx? (I assume that I will
have to do some [URL rewriting](http://en.wikipedia.org/wiki/Rewrite_engine) in the
begin\_request global.asax file, but
would like this confirmed before I
do anything silly.)
|
I've handled the 404 by doing this in the global.asax file
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
string url = Request.RawUrl;
if ((url.Contains(".aspx")) && (!System.IO.File.Exists(Server.MapPath(url))))
{
Server.Transfer("/Error/FileNotFound.aspx");
}
}
```
Now, if anyone can help me with the google widget that would be great!
|
152,313 |
<p>When should you use XML attributes and when should you use XML elements?</p>
<p>e.g.</p>
<pre><code><customData>
<records>
<record name="foo" description="bar" />
</records>
</customData>
</code></pre>
<p>or</p>
<pre><code><customData>
<records>
<record>
<name>foo</name>
<description>bar</description>
</record>
</records>
</customData>
</code></pre>
|
[
{
"answer_id": 152321,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>Personally I like using attributes for simple single-valued properties. Elements are (obviously) more suitable for complex types or repeated values.</p>\n\n<p>For single-valued properties, attributes lead to more compact XML and simpler addressing in most APIs.</p>\n"
},
{
"answer_id": 152346,
"author": "Rory Becker",
"author_id": 11356,
"author_profile": "https://Stackoverflow.com/users/11356",
"pm_score": 3,
"selected": false,
"text": "<p>It's largely a matter of preference. \nI use Elements for grouping and attributes for data where possible as I see this as more compact than the alternative.</p>\n\n<p>For example I prefer.....</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<data>\n <people>\n <person name=\"Rory\" surname=\"Becker\" age=\"30\" />\n <person name=\"Travis\" surname=\"Illig\" age=\"32\" />\n <person name=\"Scott\" surname=\"Hanselman\" age=\"34\" />\n </people>\n</data>\n</code></pre>\n\n<p>...Instead of....</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<data>\n <people>\n <person>\n <name>Rory</name>\n <surname>Becker</surname>\n <age>30</age>\n </person>\n <person>\n <name>Travis</name>\n <surname>Illig</surname>\n <age>32</age>\n </person>\n <person>\n <name>Scott</name>\n <surname>Hanselman</surname>\n <age>34</age>\n </person>\n </people>\n</data>\n</code></pre>\n\n<p>However if I have data which does not represent easily inside of say 20-30 characters or contains many quotes or other characters that need escaping then I'd say it's time to break out the elements... possibly with CData blocks.</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<data>\n <people>\n <person name=\"Rory\" surname=\"Becker\" age=\"30\" >\n <comment>A programmer whose interested in all sorts of misc stuff. His Blog can be found at http://rorybecker.blogspot.com and he's on twitter as @RoryBecker</comment>\n </person>\n <person name=\"Travis\" surname=\"Illig\" age=\"32\" >\n <comment>A cool guy for who has helped me out with all sorts of SVn information</comment>\n </person>\n <person name=\"Scott\" surname=\"Hanselman\" age=\"34\" >\n <comment>Scott works for MS and has a great podcast available at http://www.hanselminutes.com </comment>\n </person>\n </people>\n</data>\n</code></pre>\n"
},
{
"answer_id": 155713,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 2,
"selected": false,
"text": "<p>The limitations on attributes tell you where you can and can't use them: the attribute names must be unique, their order cannot be significant, and both the name and the value can contain only text. Elements, by contrast, can have non-unique names, have significant ordering, and can have mixed content.</p>\n\n<p>Attributes are usable in domains where they map onto data structures that follow those rules: the names and values of properties on an object, of columns in a row of a table, of entries in a dictionary. (But not if the properties aren't all value types, or the entries in the dictionary aren't strings.)</p>\n"
},
{
"answer_id": 172688,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 4,
"selected": false,
"text": "<p>One of the better thought-out element vs attribute arguments comes from the <a href=\"https://web.archive.org/web/20090903101841/http://www.govtalk.gov.uk/documents/schema-guidelines-3_1(1).pdf\" rel=\"nofollow noreferrer\">UK GovTalk guidelines</a>. This defines the modelling techniques used for government-related XML exchanges, but it stands on its own merits and is worth considering.</p>\n\n<blockquote>\n <p>Schemas MUST be designed so that\n elements are the main holders of\n information content in the XML\n instances. Attributes are more suited\n to holding ancillary metadata – simple\n items providing more information about\n the element content. Attributes MUST\n NOT be used to qualify other\n attributes where this could cause\n ambiguity. </p>\n \n <p>Unlike elements, attributes cannot\n hold structured data. For this reason,\n elements are preferred as the\n principal holders of information\n content. However, allowing the use of\n attributes to hold metadata about an\n element's content (for example, the\n format of a date, a unit of measure or\n the identification of a value set) can\n make an instance document simpler and\n easier to understand. </p>\n \n <p>A date of birth might be represented\n in a message as: </p>\n</blockquote>\n\n<pre><code> <DateOfBirth>1975-06-03</DateOfBirth> \n</code></pre>\n\n<blockquote>\n <p>However, more information might be\n required, such as how that date of\n birth has been verified. This could be\n defined as an attribute, making the\n element in a message look like: </p>\n</blockquote>\n\n<pre><code><DateOfBirth VerifiedBy=\"View of Birth Certificate\">1975-06-03</DateOfBirth> \n</code></pre>\n\n<blockquote>\n <p>The following would be inappropriate: </p>\n</blockquote>\n\n<pre><code><DateOfBirth VerifiedBy=\"View of Birth Certificate\" ValueSet=\"ISO 8601\" Code=\"2\">1975-06-03</DateOfBirth> \n</code></pre>\n\n<blockquote>\n <p>It is not clear here whether the Code\n is qualifying the VerifiedBy or the\n ValueSet attribute. A more appropriate\n rendition would be: </p>\n</blockquote>\n\n<pre><code> <DateOfBirth> \n <VerifiedBy Code=\"2\">View of Birth Certificate</VerifiedBy> \n <Value ValueSet=\"ISO 8601\">1975-06-03</Value>\n </DateOfBirth>\n</code></pre>\n"
},
{
"answer_id": 172721,
"author": "Ryan Taylor",
"author_id": 19977,
"author_profile": "https://Stackoverflow.com/users/19977",
"pm_score": 5,
"selected": false,
"text": "<p>There is an article titled \"<a href=\"http://www.ibm.com/developerworks/xml/library/x-eleatt.html\" rel=\"nofollow noreferrer\">Principles of XML design: When to use elements versus attributes</a>\" on IBM's website.</p>\n\n<p>Though there doesn't appear to be many hard and fast rules, there are some good guidelines mentioned in the posting. For instance, one of the recommendations is to use elements when your data must not be normalized for white space as XML processors can normalize data within an attribute thereby modifying the raw text.</p>\n\n<p>I find myself referring to this article from time to time as I develop various XML structures. Hopefully this will be helpful to others as well.</p>\n\n<p>edit - From the site:</p>\n\n<p><strong>Principle of core content</strong></p>\n\n<p>If you consider the information in question to be part of the essential material that is being expressed or communicated in the XML, put it in an element. For human-readable documents this generally means the core content that is being communicated to the reader. For machine-oriented records formats this generally means the data that comes directly from the problem domain. If you consider the information to be peripheral or incidental to the main communication, or purely intended to help applications process the main communication, use attributes. This avoids cluttering up the core content with auxiliary material. For machine-oriented records formats, this generally means application-specific notations on the main data from the problem-domain.</p>\n\n<p>As an example, I have seen many XML formats, usually home-grown in businesses, where document titles were placed in an attribute. I think a title is such a fundamental part of the communication of a document that it should always be in element content. On the other hand, I have often seen cases where internal product identifiers were thrown as elements into descriptive records of the product. In some of these cases, attributes were more appropriate because the specific internal product code would not be of primary interest to most readers or processors of the document, especially when the ID was of a very long or inscrutable format.</p>\n\n<p>You might have heard the principle data goes in elements, metadata in attributes. The above two paragraphs really express the same principle, but in more deliberate and less fuzzy language.</p>\n\n<p><strong>Principle of structured information</strong></p>\n\n<p>If the information is expressed in a structured form, especially if the structure may be extensible, use elements. On the other hand: If the information is expressed as an atomic token, use attributes. Elements are the extensible engine for expressing structure in XML. Almost all XML processing tools are designed around this fact, and if you break down structured information properly into elements, you'll find that your processing tools complement your design, and that you thereby gain productivity and maintainability. Attributes are designed for expressing simple properties of the information represented in an element. If you work against the basic architecture of XML by shoehorning structured information into attributes you may gain some specious terseness and convenience, but you will probably pay in maintenance costs.</p>\n\n<p>Dates are a good example: A date has fixed structure and generally acts as a single token, so it makes sense as an attribute (preferably expressed in ISO-8601). Representing personal names, on the other hand, is a case where I've seen this principle surprise designers. I see names in attributes a lot, but I have always argued that personal names should be in element content. A personal name has surprisingly variable structure (in some cultures you can cause confusion or offense by omitting honorifics or assuming an order of parts of names). A personal name is also rarely an atomic token. As an example, sometimes you may want to search or sort by a forename and sometimes by a surname. I should point out that it is just as problematic to shoehorn a full name into the content of a single element as it is to put it in an attribute.</p>\n"
},
{
"answer_id": 486606,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 2,
"selected": false,
"text": "<p>Check out <a href=\"http://nedbatchelder.com/blog/200412/elements_vs_attributes.html\" rel=\"nofollow noreferrer\">Elements vs. attributes</a> by Ned Batchelder. </p>\n\n<p>Nice explanation and a good list of the benefits and disadvantages of Elements and Attributes.</p>\n\n<p>He boils it down to:</p>\n\n<blockquote>\n <p>Recommendation: Use elements for data that will be produced or consumed by a business application, and attributes for metadata.</p>\n</blockquote>\n\n<p>Important: Please see @maryisdead's comment below for further clarification.</p>\n"
},
{
"answer_id": 636710,
"author": "dommer",
"author_id": 75701,
"author_profile": "https://Stackoverflow.com/users/75701",
"pm_score": 1,
"selected": false,
"text": "<p>I tend to use elements when it's data that a human reader would need to know and attributes when it's only for processing (e.g. IDs). This means that I rarely use attributes, as the majority of the data is relevant to the domain being modeled.</p>\n"
},
{
"answer_id": 2734004,
"author": "Iz.",
"author_id": 328405,
"author_profile": "https://Stackoverflow.com/users/328405",
"pm_score": 1,
"selected": false,
"text": "<p>Here is another strategy that can help distinguishing elements from attributes: think of objects and keep in mind MVC.</p>\n\n<p>Objects can have members (object variables) and properties (members with setters and getters). Properties are highly useful with MVC design, allowing change notification mechanism.</p>\n\n<p>If this is the direction taken, attributes will be used for internal application data that cannot be changed by the user; classic examples will be ID or DATE_MODIFIED. Elements will therefore be used to data that can be modified by users.</p>\n\n<p>So the following would make sense considering the librarian first add a book item (or a magazine), and then can edit its name author ISBN etc:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<item id=\"69\" type=\"book\">\n <authors count=\"1\">\n <author>\n <name>John Smith</name>\n <author>\n </authors>\n <ISBN>123456790</ISBN>\n</item>\n</code></pre>\n"
},
{
"answer_id": 6940948,
"author": "Dan",
"author_id": 189412,
"author_profile": "https://Stackoverflow.com/users/189412",
"pm_score": 3,
"selected": false,
"text": "<p>As a general rule, I avoid attributes altogether. Yes, attributes are more compact, but elements are more flexible, and flexibility is one of the most important advantages of using a data format like XML. What is a single value today can become a list of values tomorrow.</p>\n\n<p>Also, if everything's an element, you never have to remember how you modeled any particular bit of information. Not using attributes means you have one less thing to think about.</p>\n"
},
{
"answer_id": 14177728,
"author": "Calmarius",
"author_id": 58805,
"author_profile": "https://Stackoverflow.com/users/58805",
"pm_score": 2,
"selected": false,
"text": "<p>My personal rule of thumb: if an element can contain only one of that thing, and its an atomic data (id, name, age, type, etc...) it should be an attribute otherwise an element.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23726/"
] |
When should you use XML attributes and when should you use XML elements?
e.g.
```
<customData>
<records>
<record name="foo" description="bar" />
</records>
</customData>
```
or
```
<customData>
<records>
<record>
<name>foo</name>
<description>bar</description>
</record>
</records>
</customData>
```
|
There is an article titled "[Principles of XML design: When to use elements versus attributes](http://www.ibm.com/developerworks/xml/library/x-eleatt.html)" on IBM's website.
Though there doesn't appear to be many hard and fast rules, there are some good guidelines mentioned in the posting. For instance, one of the recommendations is to use elements when your data must not be normalized for white space as XML processors can normalize data within an attribute thereby modifying the raw text.
I find myself referring to this article from time to time as I develop various XML structures. Hopefully this will be helpful to others as well.
edit - From the site:
**Principle of core content**
If you consider the information in question to be part of the essential material that is being expressed or communicated in the XML, put it in an element. For human-readable documents this generally means the core content that is being communicated to the reader. For machine-oriented records formats this generally means the data that comes directly from the problem domain. If you consider the information to be peripheral or incidental to the main communication, or purely intended to help applications process the main communication, use attributes. This avoids cluttering up the core content with auxiliary material. For machine-oriented records formats, this generally means application-specific notations on the main data from the problem-domain.
As an example, I have seen many XML formats, usually home-grown in businesses, where document titles were placed in an attribute. I think a title is such a fundamental part of the communication of a document that it should always be in element content. On the other hand, I have often seen cases where internal product identifiers were thrown as elements into descriptive records of the product. In some of these cases, attributes were more appropriate because the specific internal product code would not be of primary interest to most readers or processors of the document, especially when the ID was of a very long or inscrutable format.
You might have heard the principle data goes in elements, metadata in attributes. The above two paragraphs really express the same principle, but in more deliberate and less fuzzy language.
**Principle of structured information**
If the information is expressed in a structured form, especially if the structure may be extensible, use elements. On the other hand: If the information is expressed as an atomic token, use attributes. Elements are the extensible engine for expressing structure in XML. Almost all XML processing tools are designed around this fact, and if you break down structured information properly into elements, you'll find that your processing tools complement your design, and that you thereby gain productivity and maintainability. Attributes are designed for expressing simple properties of the information represented in an element. If you work against the basic architecture of XML by shoehorning structured information into attributes you may gain some specious terseness and convenience, but you will probably pay in maintenance costs.
Dates are a good example: A date has fixed structure and generally acts as a single token, so it makes sense as an attribute (preferably expressed in ISO-8601). Representing personal names, on the other hand, is a case where I've seen this principle surprise designers. I see names in attributes a lot, but I have always argued that personal names should be in element content. A personal name has surprisingly variable structure (in some cultures you can cause confusion or offense by omitting honorifics or assuming an order of parts of names). A personal name is also rarely an atomic token. As an example, sometimes you may want to search or sort by a forename and sometimes by a surname. I should point out that it is just as problematic to shoehorn a full name into the content of a single element as it is to put it in an attribute.
|
152,319 |
<p>I'm looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other <a href="http://web.archive.org/web/20180224071555/http://www.cs.ubc.ca:80/~harrison/Java/sorting-demo.html" rel="noreferrer">sort algorithm</a> other than bubble or merge would suffice.</p>
<p>Please note that this is to work with MS Project 2003, so should avoid any of the Excel native functions and anything .net related.</p>
|
[
{
"answer_id": 152325,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 8,
"selected": true,
"text": "<p><del>Take a look <a href=\"http://en.allexperts.com/q/Visual-Basic-1048/string-manipulation.htm\" rel=\"noreferrer\">here</a>:</del><br>\n<strong>Edit:</strong> The referenced source (allexperts.com) has since closed, but here are the relevant <a href=\"https://web.archive.org/web/20090629091145/http://www.allexperts.com:80/ep/1048-18393/Visual-Basic/Robert-Nunemaker.htm\" rel=\"noreferrer\">author</a> comments:</p>\n\n<blockquote>\n <p>There are many algorithms available on the web for sorting. The most versatile and usually the quickest is the <a href=\"https://en.wikipedia.org/wiki/Quicksort\" rel=\"noreferrer\"><strong>Quicksort algorithm</strong></a>. Below is a function for it. </p>\n \n <p>Call it simply by passing an array of values (string or numeric; it doesn't matter) with the <strong>Lower Array Boundary</strong> (usually <code>0</code>) and the <strong>Upper Array Boundary</strong> (i.e. <code>UBound(myArray)</code>.)</p>\n \n <p><strong><em>Example</em></strong>: <code>Call QuickSort(myArray, 0, UBound(myArray))</code></p>\n \n <p>When it's done, <code>myArray</code> will be sorted and you can do what you want with it.<br>\n <sub>(Source: <a href=\"https://web.archive.org/web/20090621095100/http://en.allexperts.com:80/q/Visual-Basic-1048/string-manipulation.htm\" rel=\"noreferrer\">archive.org</a>)</sub></p>\n</blockquote>\n\n<pre><code>Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)\n Dim pivot As Variant\n Dim tmpSwap As Variant\n Dim tmpLow As Long\n Dim tmpHi As Long\n\n tmpLow = inLow\n tmpHi = inHi\n\n pivot = vArray((inLow + inHi) \\ 2)\n\n While (tmpLow <= tmpHi)\n While (vArray(tmpLow) < pivot And tmpLow < inHi)\n tmpLow = tmpLow + 1\n Wend\n\n While (pivot < vArray(tmpHi) And tmpHi > inLow)\n tmpHi = tmpHi - 1\n Wend\n\n If (tmpLow <= tmpHi) Then\n tmpSwap = vArray(tmpLow)\n vArray(tmpLow) = vArray(tmpHi)\n vArray(tmpHi) = tmpSwap\n tmpLow = tmpLow + 1\n tmpHi = tmpHi - 1\n End If\n Wend\n\n If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi\n If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi\nEnd Sub\n</code></pre>\n\n<p>Note that this only works with <strong>single-dimensional</strong> (aka \"normal\"?) arrays. (There's a working multi-dimensional array QuickSort <a href=\"https://stackoverflow.com/a/5104206/8112776\">here</a>.) </p>\n"
},
{
"answer_id": 152333,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.activevb.de/tipps/vb6tipps/tipp0188.html\" rel=\"noreferrer\">Explanation</a> in German but the code is a well-tested in-place implementation:</p>\n\n<pre><code>Private Sub QuickSort(ByRef Field() As String, ByVal LB As Long, ByVal UB As Long)\n Dim P1 As Long, P2 As Long, Ref As String, TEMP As String\n\n P1 = LB\n P2 = UB\n Ref = Field((P1 + P2) / 2)\n\n Do\n Do While (Field(P1) < Ref)\n P1 = P1 + 1\n Loop\n\n Do While (Field(P2) > Ref)\n P2 = P2 - 1\n Loop\n\n If P1 <= P2 Then\n TEMP = Field(P1)\n Field(P1) = Field(P2)\n Field(P2) = TEMP\n\n P1 = P1 + 1\n P2 = P2 - 1\n End If\n Loop Until (P1 > P2)\n\n If LB < P2 Then Call QuickSort(Field, LB, P2)\n If P1 < UB Then Call QuickSort(Field, P1, UB)\nEnd Sub\n</code></pre>\n\n<p>Invoked like this:</p>\n\n<pre><code>Call QuickSort(MyArray, LBound(MyArray), UBound(MyArray))\n</code></pre>\n"
},
{
"answer_id": 4347723,
"author": "Alain",
"author_id": 529618,
"author_profile": "https://Stackoverflow.com/users/529618",
"pm_score": 5,
"selected": false,
"text": "<p>I converted the 'fast quick sort' algorithm to VBA, if anyone else wants it.</p>\n\n<p>I have it optimized to run on an array of Int/Longs but it should be simple to convert it to one that works on arbitrary comparable elements.</p>\n\n<pre><code>Private Sub QuickSort(ByRef a() As Long, ByVal l As Long, ByVal r As Long)\n Dim M As Long, i As Long, j As Long, v As Long\n M = 4\n\n If ((r - l) > M) Then\n i = (r + l) / 2\n If (a(l) > a(i)) Then swap a, l, i '// Tri-Median Methode!'\n If (a(l) > a(r)) Then swap a, l, r\n If (a(i) > a(r)) Then swap a, i, r\n\n j = r - 1\n swap a, i, j\n i = l\n v = a(j)\n Do\n Do: i = i + 1: Loop While (a(i) < v)\n Do: j = j - 1: Loop While (a(j) > v)\n If (j < i) Then Exit Do\n swap a, i, j\n Loop\n swap a, i, r - 1\n QuickSort a, l, j\n QuickSort a, i + 1, r\n End If\nEnd Sub\n\nPrivate Sub swap(ByRef a() As Long, ByVal i As Long, ByVal j As Long)\n Dim T As Long\n T = a(i)\n a(i) = a(j)\n a(j) = T\nEnd Sub\n\nPrivate Sub InsertionSort(ByRef a(), ByVal lo0 As Long, ByVal hi0 As Long)\n Dim i As Long, j As Long, v As Long\n\n For i = lo0 + 1 To hi0\n v = a(i)\n j = i\n Do While j > lo0\n If Not a(j - 1) > v Then Exit Do\n a(j) = a(j - 1)\n j = j - 1\n Loop\n a(j) = v\n Next i\nEnd Sub\n\nPublic Sub sort(ByRef a() As Long)\n QuickSort a, LBound(a), UBound(a)\n InsertionSort a, LBound(a), UBound(a)\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 5104600,
"author": "Nigel Heffernan",
"author_id": 362712,
"author_profile": "https://Stackoverflow.com/users/362712",
"pm_score": 3,
"selected": false,
"text": "<p>I posted some code in answer to a related question on StackOverflow:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/4873182/sorting-a-multidimensional-array-in-vba/5104206#5104206\">Sorting a multidimensionnal array in VBA</a></p>\n\n<p>The code samples in that thread include:</p>\n\n<ol>\n<li>A vector array Quicksort;</li>\n<li>A multi-column array QuickSort;</li>\n<li>A BubbleSort.</li>\n</ol>\n\n<p>Alain's optimised Quicksort is very shiny: I just did a basic split-and-recurse, but the code sample above has a 'gating' function that cuts down on redundant comparisons of duplicated values. On the other hand, I code for Excel, and there's a bit more in the way of defensive coding - be warned, you'll need it if your array contains the pernicious 'Empty()' variant, which will break your While... Wend comparison operators and trap your code in an infinite loop.</p>\n\n<p>Note that quicksort algorthms - and any recursive algorithm - can fill the stack and crash Excel. If your array has fewer than 1024 members, I'd use a rudimentary BubbleSort. </p>\n\n<p><PRE>\nPublic Sub QuickSortArray(ByRef SortArray As Variant, _\n Optional lngMin As Long = -1, _ \n Optional lngMax As Long = -1, _ \n Optional lngColumn As Long = 0)\nOn Error Resume Next<BR />\n'Sort a 2-Dimensional array<BR />\n' Sample Usage: sort arrData by the contents of column 3\n'\n' QuickSortArray arrData, , , 3<BR />\n'\n'Posted by Jim Rech 10/20/98 Excel.Programming<BR />\n'Modifications, Nigel Heffernan:<BR />\n' ' Escape failed comparison with empty variant\n' ' Defensive coding: check inputs<BR />\nDim i As Long\nDim j As Long\nDim varMid As Variant\nDim arrRowTemp As Variant\nDim lngColTemp As Long<BR /><BR />\n If IsEmpty(SortArray) Then\n Exit Sub\n End If<BR />\n If InStr(TypeName(SortArray), \"()\") < 1 Then 'IsArray() is somewhat broken: Look for brackets in the type name\n Exit Sub\n End If<BR />\n If lngMin = -1 Then\n lngMin = LBound(SortArray, 1)\n End If<BR /> \n If lngMax = -1 Then\n lngMax = UBound(SortArray, 1)\n End If<BR /> \n If lngMin >= lngMax Then ' no sorting required\n Exit Sub\n End If<BR /><BR />\n i = lngMin\n j = lngMax<BR />\n varMid = Empty\n varMid = SortArray((lngMin + lngMax) \\ 2, lngColumn)<BR />\n ' We send 'Empty' and invalid data items to the end of the list:\n If IsObject(varMid) Then ' note that we don't check isObject(SortArray(n)) - varMid <em>might</em> pick up a valid default member or property\n i = lngMax\n j = lngMin\n ElseIf IsEmpty(varMid) Then\n i = lngMax\n j = lngMin\n ElseIf IsNull(varMid) Then\n i = lngMax\n j = lngMin\n ElseIf varMid = \"\" Then\n i = lngMax\n j = lngMin\n ElseIf varType(varMid) = vbError Then\n i = lngMax\n j = lngMin\n ElseIf varType(varMid) > 17 Then\n i = lngMax\n j = lngMin\n End If<BR /><BR />\n While i <= j<BR />\n While SortArray(i, lngColumn) < varMid And i < lngMax\n i = i + 1\n Wend<BR />\n While varMid < SortArray(j, lngColumn) And j > lngMin\n j = j - 1\n Wend<BR /><BR />\n If i <= j Then<BR />\n ' Swap the rows\n ReDim arrRowTemp(LBound(SortArray, 2) To UBound(SortArray, 2))\n For lngColTemp = LBound(SortArray, 2) To UBound(SortArray, 2)\n arrRowTemp(lngColTemp) = SortArray(i, lngColTemp)\n SortArray(i, lngColTemp) = SortArray(j, lngColTemp)\n SortArray(j, lngColTemp) = arrRowTemp(lngColTemp)\n Next lngColTemp\n Erase arrRowTemp<BR />\n i = i + 1\n j = j - 1<BR />\n End If<BR /><br>\n Wend<BR />\n If (lngMin < j) Then Call QuickSortArray(SortArray, lngMin, j, lngColumn)\n If (i < lngMax) Then Call QuickSortArray(SortArray, i, lngMax, lngColumn)<BR /><BR /> \nEnd Sub<BR />\n</PRE></p>\n"
},
{
"answer_id": 6123532,
"author": "lucas0x7B",
"author_id": 516035,
"author_profile": "https://Stackoverflow.com/users/516035",
"pm_score": 2,
"selected": false,
"text": "<p>You didn't want an Excel-based solution but since I had the same problem today and wanted to test using other Office Applications functions I wrote the function below.</p>\n\n<p>Limitations:</p>\n\n<ul>\n<li>2-dimensional arrays;</li>\n<li>maximum of 3 columns as sort keys;</li>\n<li>depends on Excel;</li>\n</ul>\n\n<p>Tested calling Excel 2010 from Visio 2010</p>\n\n<hr>\n\n<pre><code>Option Base 1\n\n\nPrivate Function sort_array_2D_excel(array_2D, array_sortkeys, Optional array_sortorders, Optional tag_header As String = \"Guess\", Optional tag_matchcase As String = \"False\")\n\n' Dependencies: Excel; Tools > References > Microsoft Excel [Version] Object Library\n\n Dim excel_application As Excel.Application\n Dim excel_workbook As Excel.Workbook\n Dim excel_worksheet As Excel.Worksheet\n\n Set excel_application = CreateObject(\"Excel.Application\")\n\n excel_application.Visible = True\n excel_application.ScreenUpdating = False\n excel_application.WindowState = xlNormal\n\n Set excel_workbook = excel_application.Workbooks.Add\n excel_workbook.Activate\n\n Set excel_worksheet = excel_workbook.Worksheets.Add\n excel_worksheet.Activate\n excel_worksheet.Visible = xlSheetVisible\n\n Dim excel_range As Excel.Range\n Set excel_range = excel_worksheet.Range(\"A1\").Resize(UBound(array_2D, 1) - LBound(array_2D, 1) + 1, UBound(array_2D, 2) - LBound(array_2D, 2) + 1)\n excel_range = array_2D\n\n\n For i_sortkey = LBound(array_sortkeys) To UBound(array_sortkeys)\n\n If IsNumeric(array_sortkeys(i_sortkey)) Then\n sortkey_range = Chr(array_sortkeys(i_sortkey) + 65 - 1) & \"1\"\n Set array_sortkeys(i_sortkey) = excel_worksheet.Range(sortkey_range)\n\n Else\n MsgBox \"Error in sortkey parameter:\" & vbLf & \"array_sortkeys(\" & i_sortkey & \") = \" & array_sortkeys(i_sortkey) & vbLf & \"Terminating...\"\n End\n\n End If\n\n Next i_sortkey\n\n\n For i_sortorder = LBound(array_sortorders) To UBound(array_sortorders)\n Select Case LCase(array_sortorders(i_sortorder))\n Case \"asc\"\n array_sortorders(i_sortorder) = XlSortOrder.xlAscending\n Case \"desc\"\n array_sortorders(i_sortorder) = XlSortOrder.xlDescending\n Case Else\n array_sortorders(i_sortorder) = XlSortOrder.xlAscending\n End Select\n Next i_sortorder\n\n Select Case LCase(tag_header)\n Case \"yes\"\n tag_header = Excel.xlYes\n Case \"no\"\n tag_header = Excel.xlNo\n Case \"guess\"\n tag_header = Excel.xlGuess\n Case Else\n tag_header = Excel.xlGuess\n End Select\n\n Select Case LCase(tag_matchcase)\n Case \"true\"\n tag_matchcase = True\n Case \"false\"\n tag_matchcase = False\n Case Else\n tag_matchcase = False\n End Select\n\n\n Select Case (UBound(array_sortkeys) - LBound(array_sortkeys) + 1)\n Case 1\n Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Header:=tag_header, MatchCase:=tag_matchcase)\n Case 2\n Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Header:=tag_header, MatchCase:=tag_matchcase)\n Case 3\n Call excel_range.Sort(Key1:=array_sortkeys(1), Order1:=array_sortorders(1), Key2:=array_sortkeys(2), Order2:=array_sortorders(2), Key3:=array_sortkeys(3), Order3:=array_sortorders(3), Header:=tag_header, MatchCase:=tag_matchcase)\n Case Else\n MsgBox \"Error in sortkey parameter:\" & vbLf & \"Maximum number of sort columns is 3!\" & vbLf & \"Currently passed: \" & (UBound(array_sortkeys) - LBound(array_sortkeys) + 1)\n End\n End Select\n\n\n For i_row = 1 To excel_range.Rows.Count\n\n For i_column = 1 To excel_range.Columns.Count\n\n array_2D(i_row, i_column) = excel_range(i_row, i_column)\n\n Next i_column\n\n Next i_row\n\n\n excel_workbook.Close False\n excel_application.Quit\n\n Set excel_worksheet = Nothing\n Set excel_workbook = Nothing\n Set excel_application = Nothing\n\n\n sort_array_2D_excel = array_2D\n\n\nEnd Function\n</code></pre>\n\n<hr>\n\n<h2>This is an example on how to test the function:</h2>\n\n<pre><code>Private Sub test_sort()\n\n array_unsorted = dim_sort_array()\n\n Call msgbox_array(array_unsorted)\n\n array_sorted = sort_array_2D_excel(array_unsorted, Array(2, 1, 3), Array(\"desc\", \"\", \"asdas\"), \"yes\", \"False\")\n\n Call msgbox_array(array_sorted)\n\nEnd Sub\n\n\nPrivate Function dim_sort_array()\n\n Dim array_unsorted(1 To 5, 1 To 3) As String\n\n i_row = 0\n\n i_row = i_row + 1\n array_unsorted(i_row, 1) = \"Column1\": array_unsorted(i_row, 2) = \"Column2\": array_unsorted(i_row, 3) = \"Column3\"\n\n i_row = i_row + 1\n array_unsorted(i_row, 1) = \"OR\": array_unsorted(i_row, 2) = \"A\": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & \"_\" & array_unsorted(i_row, 2)\n\n i_row = i_row + 1\n array_unsorted(i_row, 1) = \"XOR\": array_unsorted(i_row, 2) = \"A\": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & \"_\" & array_unsorted(i_row, 2)\n\n i_row = i_row + 1\n array_unsorted(i_row, 1) = \"NOT\": array_unsorted(i_row, 2) = \"B\": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & \"_\" & array_unsorted(i_row, 2)\n\n i_row = i_row + 1\n array_unsorted(i_row, 1) = \"AND\": array_unsorted(i_row, 2) = \"A\": array_unsorted(i_row, 3) = array_unsorted(i_row, 1) & \"_\" & array_unsorted(i_row, 2)\n\n dim_sort_array = array_unsorted\n\nEnd Function\n\n\nSub msgbox_array(array_2D, Optional string_info As String = \"2D array content:\")\n\n msgbox_string = string_info & vbLf\n\n For i_row = LBound(array_2D, 1) To UBound(array_2D, 1)\n\n msgbox_string = msgbox_string & vbLf & i_row & vbTab\n\n For i_column = LBound(array_2D, 2) To UBound(array_2D, 2)\n\n msgbox_string = msgbox_string & array_2D(i_row, i_column) & vbTab\n\n Next i_column\n\n Next i_row\n\n MsgBox msgbox_string\n\nEnd Sub\n</code></pre>\n\n<hr>\n\n<p>If anybody tests this using other versions of office please post here if there are any problems.</p>\n"
},
{
"answer_id": 19415281,
"author": "Profex",
"author_id": 1445339,
"author_profile": "https://Stackoverflow.com/users/1445339",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Natural Number (Strings) Quick Sort</strong> </p>\n\n<p>Just to pile onto the topic. \nNormally, if you sort strings with numbers you'll get something like this:</p>\n\n<pre><code> Text1\n Text10\n Text100\n Text11\n Text2\n Text20\n</code></pre>\n\n<p>But you really want it to recognize the numerical values and be sorted like </p>\n\n<pre><code> Text1\n Text2\n Text10\n Text11\n Text20\n Text100\n</code></pre>\n\n<p>Here's how to do it...</p>\n\n<p>Note: </p>\n\n<ul>\n<li>I stole the Quick Sort from the internet a long time ago, not sure where now... </li>\n<li>I translated the CompareNaturalNum function which was originally written in C from the internet as well.</li>\n<li>Difference from other Q-Sorts: I don't swap the values if the BottomTemp = TopTemp</li>\n</ul>\n\n<p><strong>Natural Number Quick Sort</strong></p>\n\n<pre><code>Public Sub QuickSortNaturalNum(strArray() As String, intBottom As Integer, intTop As Integer)\nDim strPivot As String, strTemp As String\nDim intBottomTemp As Integer, intTopTemp As Integer\n\n intBottomTemp = intBottom\n intTopTemp = intTop\n\n strPivot = strArray((intBottom + intTop) \\ 2)\n\n Do While (intBottomTemp <= intTopTemp)\n ' < comparison of the values is a descending sort\n Do While (CompareNaturalNum(strArray(intBottomTemp), strPivot) < 0 And intBottomTemp < intTop)\n intBottomTemp = intBottomTemp + 1\n Loop\n Do While (CompareNaturalNum(strPivot, strArray(intTopTemp)) < 0 And intTopTemp > intBottom) '\n intTopTemp = intTopTemp - 1\n Loop\n If intBottomTemp < intTopTemp Then\n strTemp = strArray(intBottomTemp)\n strArray(intBottomTemp) = strArray(intTopTemp)\n strArray(intTopTemp) = strTemp\n End If\n If intBottomTemp <= intTopTemp Then\n intBottomTemp = intBottomTemp + 1\n intTopTemp = intTopTemp - 1\n End If\n Loop\n\n 'the function calls itself until everything is in good order\n If (intBottom < intTopTemp) Then QuickSortNaturalNum strArray, intBottom, intTopTemp\n If (intBottomTemp < intTop) Then QuickSortNaturalNum strArray, intBottomTemp, intTop\nEnd Sub\n</code></pre>\n\n<p><strong>Natural Number Compare(Used in Quick Sort)</strong></p>\n\n<pre><code>Function CompareNaturalNum(string1 As Variant, string2 As Variant) As Integer\n'string1 is less than string2 -1\n'string1 is equal to string2 0\n'string1 is greater than string2 1\nDim n1 As Long, n2 As Long\nDim iPosOrig1 As Integer, iPosOrig2 As Integer\nDim iPos1 As Integer, iPos2 As Integer\nDim nOffset1 As Integer, nOffset2 As Integer\n\n If Not (IsNull(string1) Or IsNull(string2)) Then\n iPos1 = 1\n iPos2 = 1\n Do While iPos1 <= Len(string1)\n If iPos2 > Len(string2) Then\n CompareNaturalNum = 1\n Exit Function\n End If\n If isDigit(string1, iPos1) Then\n If Not isDigit(string2, iPos2) Then\n CompareNaturalNum = -1\n Exit Function\n End If\n iPosOrig1 = iPos1\n iPosOrig2 = iPos2\n Do While isDigit(string1, iPos1)\n iPos1 = iPos1 + 1\n Loop\n\n Do While isDigit(string2, iPos2)\n iPos2 = iPos2 + 1\n Loop\n\n nOffset1 = (iPos1 - iPosOrig1)\n nOffset2 = (iPos2 - iPosOrig2)\n\n n1 = Val(Mid(string1, iPosOrig1, nOffset1))\n n2 = Val(Mid(string2, iPosOrig2, nOffset2))\n\n If (n1 < n2) Then\n CompareNaturalNum = -1\n Exit Function\n ElseIf (n1 > n2) Then\n CompareNaturalNum = 1\n Exit Function\n End If\n\n ' front padded zeros (put 01 before 1)\n If (n1 = n2) Then\n If (nOffset1 > nOffset2) Then\n CompareNaturalNum = -1\n Exit Function\n ElseIf (nOffset1 < nOffset2) Then\n CompareNaturalNum = 1\n Exit Function\n End If\n End If\n ElseIf isDigit(string2, iPos2) Then\n CompareNaturalNum = 1\n Exit Function\n Else\n If (Mid(string1, iPos1, 1) < Mid(string2, iPos2, 1)) Then\n CompareNaturalNum = -1\n Exit Function\n ElseIf (Mid(string1, iPos1, 1) > Mid(string2, iPos2, 1)) Then\n CompareNaturalNum = 1\n Exit Function\n End If\n\n iPos1 = iPos1 + 1\n iPos2 = iPos2 + 1\n End If\n Loop\n ' Everything was the same so far, check if Len(string2) > Len(String1)\n ' If so, then string1 < string2\n If Len(string2) > Len(string1) Then\n CompareNaturalNum = -1\n Exit Function\n End If\n Else\n If IsNull(string1) And Not IsNull(string2) Then\n CompareNaturalNum = -1\n Exit Function\n ElseIf IsNull(string1) And IsNull(string2) Then\n CompareNaturalNum = 0\n Exit Function\n ElseIf Not IsNull(string1) And IsNull(string2) Then\n CompareNaturalNum = 1\n Exit Function\n End If\n End If\nEnd Function\n</code></pre>\n\n<p><strong>isDigit(Used in CompareNaturalNum)</strong></p>\n\n<pre><code>Function isDigit(ByVal str As String, pos As Integer) As Boolean\nDim iCode As Integer\n If pos <= Len(str) Then\n iCode = Asc(Mid(str, pos, 1))\n If iCode >= 48 And iCode <= 57 Then isDigit = True\n End If\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 33755670,
"author": "Jarek",
"author_id": 5571713,
"author_profile": "https://Stackoverflow.com/users/5571713",
"pm_score": 2,
"selected": false,
"text": "<p>I wonder what would you say about this array sorting code. It's quick for implementation and does the job ... haven't tested for large arrays yet. It works for one-dimensional arrays, for multidimensional additional values re-location matrix would need to be build (with one less dimension that the initial array).</p>\n\n<pre><code> For AR1 = LBound(eArray, 1) To UBound(eArray, 1)\n eValue = eArray(AR1)\n For AR2 = LBound(eArray, 1) To UBound(eArray, 1)\n If eArray(AR2) < eValue Then\n eArray(AR1) = eArray(AR2)\n eArray(AR2) = eValue\n eValue = eArray(AR1)\n End If\n Next AR2\n Next AR1\n</code></pre>\n"
},
{
"answer_id": 37779637,
"author": "Reged",
"author_id": 4765416,
"author_profile": "https://Stackoverflow.com/users/4765416",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I use to sort in memory - it can easily be expanded to sort an array.</p>\n\n<pre><code>Sub sortlist()\n\n Dim xarr As Variant\n Dim yarr As Variant\n Dim zarr As Variant\n\n xarr = Sheets(\"sheet\").Range(\"sing col range\")\n ReDim yarr(1 To UBound(xarr), 1 To 1)\n ReDim zarr(1 To UBound(xarr), 1 To 1)\n\n For n = 1 To UBound(xarr)\n zarr(n, 1) = 1\n Next n\n\n For n = 1 To UBound(xarr) - 1\n y = zarr(n, 1)\n For a = n + 1 To UBound(xarr)\n If xarr(n, 1) > xarr(a, 1) Then\n y = y + 1\n Else\n zarr(a, 1) = zarr(a, 1) + 1\n End If\n Next a\n yarr(y, 1) = xarr(n, 1)\n Next n\n\n y = zarr(UBound(xarr), 1)\n yarr(y, 1) = xarr(UBound(xarr), 1)\n\n yrng = \"A1:A\" & UBound(yarr)\n Sheets(\"sheet\").Range(yrng) = yarr\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 41886947,
"author": "Moreno",
"author_id": 6254149,
"author_profile": "https://Stackoverflow.com/users/6254149",
"pm_score": 0,
"selected": false,
"text": "<p>I think my code (tested) is more \"educated\", assuming <em>the simpler the better</em>.</p>\n\n<pre><code>Option Base 1\n\n'Function to sort an array decscending\nFunction SORT(Rango As Range) As Variant\n Dim check As Boolean\n check = True\n If IsNull(Rango) Then\n check = False\n End If\n If check Then\n Application.Volatile\n Dim x() As Variant, n As Double, m As Double, i As Double, j As Double, k As Double\n n = Rango.Rows.Count: m = Rango.Columns.Count: k = n * m\n ReDim x(n, m)\n For i = 1 To n Step 1\n For j = 1 To m Step 1\n x(i, j) = Application.Large(Rango, k)\n k = k - 1\n Next j\n Next i\n SORT = x\n Else\n Exit Function\n End If\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 45379461,
"author": "Prasand Kumar",
"author_id": 6486100,
"author_profile": "https://Stackoverflow.com/users/6486100",
"pm_score": 4,
"selected": false,
"text": "<pre><code>Dim arr As Object\nDim InputArray\n\n'Creating a array list\nSet arr = CreateObject(\"System.Collections.ArrayList\")\n\n'String\nInputArray = Array(\"d\", \"c\", \"b\", \"a\", \"f\", \"e\", \"g\")\n\n'number\n'InputArray = Array(6, 5, 3, 4, 2, 1)\n\n' adding the elements in the array to array_list\nFor Each element In InputArray\n arr.Add element\nNext\n\n'sorting happens\narr.Sort\n\n'Converting ArrayList to an array\n'so now a sorted array of elements is stored in the array sorted_array.\n\nsorted_array = arr.toarray\n</code></pre>\n"
},
{
"answer_id": 56689287,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://en.wikipedia.org/wiki/Heapsort\" rel=\"nofollow noreferrer\">Heapsort</a> implementation. An O(n log(n)) (both average and worst case), in place, <a href=\"https://en.wikipedia.org/wiki/Sorting_algorithm#Stability\" rel=\"nofollow noreferrer\">unstable</a> sorting algorithm.</p>\n\n<p>Use with: <code>Call HeapSort(A)</code>, where <code>A</code> is a one dimensional array of variants, with <code>Option Base 1</code>.</p>\n\n<pre><code>Sub SiftUp(A() As Variant, I As Long)\n Dim K As Long, P As Long, S As Variant\n K = I\n While K > 1\n P = K \\ 2\n If A(K) > A(P) Then\n S = A(P): A(P) = A(K): A(K) = S\n K = P\n Else\n Exit Sub\n End If\n Wend\nEnd Sub\n\nSub SiftDown(A() As Variant, I As Long)\n Dim K As Long, L As Long, S As Variant\n K = 1\n Do\n L = K + K\n If L > I Then Exit Sub\n If L + 1 <= I Then\n If A(L + 1) > A(L) Then L = L + 1\n End If\n If A(K) < A(L) Then\n S = A(K): A(K) = A(L): A(L) = S\n K = L\n Else\n Exit Sub\n End If\n Loop\nEnd Sub\n\nSub HeapSort(A() As Variant)\n Dim N As Long, I As Long, S As Variant\n N = UBound(A)\n For I = 2 To N\n Call SiftUp(A, I)\n Next I\n For I = N To 2 Step -1\n S = A(I): A(I) = A(1): A(1) = S\n Call SiftDown(A, I - 1)\n Next\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 57996291,
"author": "pstraton",
"author_id": 3685516,
"author_profile": "https://Stackoverflow.com/users/3685516",
"pm_score": 1,
"selected": false,
"text": "<p>@Prasand Kumar, here's a complete sort routine based on Prasand's concepts:</p>\n\n<pre><code>Public Sub ArrayListSort(ByRef SortArray As Variant)\n '\n 'Uses the sort capabilities of a System.Collections.ArrayList object to sort an array of values of any simple\n 'data-type.\n '\n 'AUTHOR: Peter Straton\n '\n 'CREDIT: Derived from Prasand Kumar's post at: https://stackoverflow.com/questions/152319/vba-array-sort-function\n '\n '*************************************************************************************************************\n\n Static ArrayListObj As Object\n Dim i As Long\n Dim LBnd As Long\n Dim UBnd As Long\n\n LBnd = LBound(SortArray)\n UBnd = UBound(SortArray)\n\n 'If necessary, create the ArrayList object, to be used to sort the specified array's values\n\n If ArrayListObj Is Nothing Then\n Set ArrayListObj = CreateObject(\"System.Collections.ArrayList\")\n Else\n ArrayListObj.Clear 'Already allocated so just clear any old contents\n End If\n\n 'Add the ArrayList elements from the array of values to be sorted. (There appears to be no way to do this\n 'using a single assignment statement.)\n\n For i = LBnd To UBnd\n ArrayListObj.Add SortArray(i)\n Next i\n\n ArrayListObj.Sort 'Do the sort\n\n 'Transfer the sorted ArrayList values back to the original array, which can be done with a single assignment\n 'statement. But the result is always zero-based so then, if necessary, adjust the resulting array to match\n 'its original index base.\n\n SortArray = ArrayListObj.ToArray\n If LBnd <> 0 Then ReDim Preserve SortArray(LBnd To UBnd)\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 60141995,
"author": "q335r49",
"author_id": 1318498,
"author_profile": "https://Stackoverflow.com/users/1318498",
"pm_score": 1,
"selected": false,
"text": "<p>Somewhat related, but I was also looking for a native excel VBA solution since advanced data structures (Dictionaries, etc.) aren't working in my environment. The following implements sorting via a binary tree in VBA:</p>\n\n<ul>\n<li>Assumes array is populated one by one</li>\n<li><strong>Removes duplicates</strong></li>\n<li>Returns a separated string (<code>\"0|2|3|4|9\"</code>) which can then be split.</li>\n</ul>\n\n<p>I used it for returning a raw sorted enumeration of rows selected for an arbitrarily selected range</p>\n\n<pre><code>Private Enum LeafType: tEMPTY: tTree: tValue: End Enum\nPrivate Left As Variant, Right As Variant, Center As Variant\nPrivate LeftType As LeafType, RightType As LeafType, CenterType As LeafType\nPublic Sub Add(x As Variant)\n If CenterType = tEMPTY Then\n Center = x\n CenterType = tValue\n ElseIf x > Center Then\n If RightType = tEMPTY Then\n Right = x\n RightType = tValue\n ElseIf RightType = tTree Then\n Right.Add x\n ElseIf x <> Right Then\n curLeaf = Right\n Set Right = New TreeList\n Right.Add curLeaf\n Right.Add x\n RightType = tTree\n End If\n ElseIf x < Center Then\n If LeftType = tEMPTY Then\n Left = x\n LeftType = tValue\n ElseIf LeftType = tTree Then\n Left.Add x\n ElseIf x <> Left Then\n curLeaf = Left\n Set Left = New TreeList\n Left.Add curLeaf\n Left.Add x\n LeftType = tTree\n End If\n End If\nEnd Sub\nPublic Function GetList$()\n Const sep$ = \"|\"\n If LeftType = tValue Then\n LeftList$ = Left & sep\n ElseIf LeftType = tTree Then\n LeftList = Left.GetList & sep\n End If\n If RightType = tValue Then\n RightList$ = sep & Right\n ElseIf RightType = tTree Then\n RightList = sep & Right.GetList\n End If\n GetList = LeftList & Center & RightList\nEnd Function\n\n'Sample code\nDim Tree As new TreeList\nTree.Add(\"0\")\nTree.Add(\"2\")\nTree.Add(\"2\")\nTree.Add(\"-1\")\nDebug.Print Tree.GetList() 'prints \"-1|0|2\"\nsortedList = Split(Tree.GetList(),\"|\")\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4134/"
] |
I'm looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other [sort algorithm](http://web.archive.org/web/20180224071555/http://www.cs.ubc.ca:80/~harrison/Java/sorting-demo.html) other than bubble or merge would suffice.
Please note that this is to work with MS Project 2003, so should avoid any of the Excel native functions and anything .net related.
|
~~Take a look [here](http://en.allexperts.com/q/Visual-Basic-1048/string-manipulation.htm):~~
**Edit:** The referenced source (allexperts.com) has since closed, but here are the relevant [author](https://web.archive.org/web/20090629091145/http://www.allexperts.com:80/ep/1048-18393/Visual-Basic/Robert-Nunemaker.htm) comments:
>
> There are many algorithms available on the web for sorting. The most versatile and usually the quickest is the [**Quicksort algorithm**](https://en.wikipedia.org/wiki/Quicksort). Below is a function for it.
>
>
> Call it simply by passing an array of values (string or numeric; it doesn't matter) with the **Lower Array Boundary** (usually `0`) and the **Upper Array Boundary** (i.e. `UBound(myArray)`.)
>
>
> ***Example***: `Call QuickSort(myArray, 0, UBound(myArray))`
>
>
> When it's done, `myArray` will be sorted and you can do what you want with it.
>
> (Source: [archive.org](https://web.archive.org/web/20090621095100/http://en.allexperts.com:80/q/Visual-Basic-1048/string-manipulation.htm))
>
>
>
```
Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)
Dim pivot As Variant
Dim tmpSwap As Variant
Dim tmpLow As Long
Dim tmpHi As Long
tmpLow = inLow
tmpHi = inHi
pivot = vArray((inLow + inHi) \ 2)
While (tmpLow <= tmpHi)
While (vArray(tmpLow) < pivot And tmpLow < inHi)
tmpLow = tmpLow + 1
Wend
While (pivot < vArray(tmpHi) And tmpHi > inLow)
tmpHi = tmpHi - 1
Wend
If (tmpLow <= tmpHi) Then
tmpSwap = vArray(tmpLow)
vArray(tmpLow) = vArray(tmpHi)
vArray(tmpHi) = tmpSwap
tmpLow = tmpLow + 1
tmpHi = tmpHi - 1
End If
Wend
If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi
End Sub
```
Note that this only works with **single-dimensional** (aka "normal"?) arrays. (There's a working multi-dimensional array QuickSort [here](https://stackoverflow.com/a/5104206/8112776).)
|
152,323 |
<p>I would like to send mail from a script on a Windows Server 2003 Standard Edition. I think the server setup is pretty much out of the box.</p>
<p>The mail server is an Exchange one, and when you're on the internal network you can use plain old SMTP. I have done it from my machine with Perl, but unfortunately Perl is not available on the server.</p>
<p>Is there an easy way of doing this from a .bat-file or any other way that doesn't require installing some additional software?</p>
<p><code>Edit:</code><br>
Thanks for the quick replies. The "blat" thingie would probably work fine but with wscript I don't have to use a separate binary.</p>
<p>I didn't see PhiLho's post the first time I edited and selected an answer. No need for me to duplicate the code here.</p>
<p>Just save the script to a file, say sendmail.vbs, and then call it from the command prompt like so:<br>
<code>wscript sendmail.vbs</code></p>
|
[
{
"answer_id": 152356,
"author": "Moshe",
"author_id": 9941,
"author_profile": "https://Stackoverflow.com/users/9941",
"pm_score": 0,
"selected": false,
"text": "<p>I think that you'll have to install some ActiveX or other component what could be invoked from WScript, such as:\n<a href=\"http://www.activexperts.com/ActivEmail/\" rel=\"nofollow noreferrer\">http://www.activexperts.com/ActivEmail/</a>\nand:\n<a href=\"http://www.emailarchitect.net/webapp/SMTPCOM/developers/scripting.asp\" rel=\"nofollow noreferrer\">http://www.emailarchitect.net/webapp/SMTPCOM/developers/scripting.asp</a></p>\n\n<p>Otherwise, you'll have to write the entire SMTP logic (if possible, not sure) in WScript all on your own.</p>\n"
},
{
"answer_id": 152377,
"author": "Jacek Szymański",
"author_id": 23242,
"author_profile": "https://Stackoverflow.com/users/23242",
"pm_score": 3,
"selected": false,
"text": "<p>I don't know if dropping a binary alongside the .bat file counts as installing software, but, if not, you can use <a href=\"http://www.blat.net/\" rel=\"noreferrer\">blat</a> to do this.</p>\n"
},
{
"answer_id": 152392,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 1,
"selected": false,
"text": "<p>If you have outlook/exchange installed you should be able to use CDONTs, just create a mail.vbs file and call it in a batch file like so (amusing they are in the same dir)</p>\n\n<pre><code>wscript mail.vbs\n</code></pre>\n\n<p>for the VBScript code check out </p>\n\n<p><a href=\"http://support.microsoft.com/kb/197920\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/197920</a> </p>\n\n<p><a href=\"http://www.w3schools.com/asp/asp_send_email.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/asp/asp_send_email.asp</a></p>\n\n<p>forget the fact they the two links speak about ASP, it should work fine as a stand alone script with out iis.</p>\n"
},
{
"answer_id": 152407,
"author": "vacpro",
"author_id": 23730,
"author_profile": "https://Stackoverflow.com/users/23730",
"pm_score": 0,
"selected": false,
"text": "<p>Use CDONTS with Windows Scripting Host (WScript)</p>\n"
},
{
"answer_id": 152411,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 5,
"selected": true,
"text": "<p>It is possible with Wscript, using CDO:</p>\n\n<pre><code>Dim objMail\n\nSet objMail = CreateObject(\"CDO.Message\")\n\nobjMail.From = \"Me <[email protected]>\"\nobjMail.To = \"You <[email protected]>\"\nobjMail.Subject = \"That's a mail\"\nobjMail.Textbody = \"Hello World\"\nobjMail.AddAttachment \"C:\\someFile.ext\"\n\n---8<----- You don't need this part if you have an active Outlook [Express] account -----\n' Use an SMTP server\nobjMail.Configuration.Fields.Item _\n (\"http://schemas.microsoft.com/cdo/configuration/sendusing\") = 2\n\n' Name or IP of Remote SMTP Server\nobjMail.Configuration.Fields.Item _\n (\"http://schemas.microsoft.com/cdo/configuration/smtpserver\") = _\n \"smtp.server.com\"\n\n' Server port (typically 25)\nobjMail.Configuration.Fields.Item _\n (\"http://schemas.microsoft.com/cdo/configuration/smtpserverport\") = 25\n\nobjMail.Configuration.Fields.Update\n----- End of SMTP usage ----->8---\n\nobjMail.Send\n\nSet objMail=Nothing\nWscript.Quit\n</code></pre>\n\n<p>Update: found more info there: <a href=\"http://www.paulsadowski.com/WSH/cdo.htm\" rel=\"noreferrer\" title=\"VBScript To Send Email Using CDO\">VBScript To Send Email Using CDO</a>\nBy default it seems it uses Outlook [Express], so it didn't worked on my computer but you can use a given SMTP server, which worked fine for me.</p>\n"
},
{
"answer_id": 5250579,
"author": "DssTrainer",
"author_id": 551686,
"author_profile": "https://Stackoverflow.com/users/551686",
"pm_score": 0,
"selected": false,
"text": "<p>Is there a way you send without referencing the outside schema urls.\n<a href=\"http://schemas.microsoft.com/cdo/configuration/\" rel=\"nofollow\">http://schemas.microsoft.com/cdo/configuration/</a></p>\n\n<p>That is highly useless as it can't be assumed all boxes will have outside internet access to send mail internally on the local exchange. Is there a way to save the info from those urls locally? </p>\n"
},
{
"answer_id": 13573876,
"author": "Nathan Hartley",
"author_id": 80161,
"author_profile": "https://Stackoverflow.com/users/80161",
"pm_score": 3,
"selected": false,
"text": "<p>If the server happened (I realize how old this question is) to have Powershell v2 installed, the CmdLet Send-MailMessage would do this in one line.</p>\n\n<pre><code>Send-MailMessage [-To] <string[]> [-Subject] <string> -From <string> [[-Body] <string>] [[-SmtpServer] <string>] [-Attachments <string[]>] [-Bcc <string[]>] [-BodyAsHtml] [-Cc <string[]>] [-Credential <PSCredential>] [-DeliveryNotficationOption {None | OnSuccess | OnFailure | Delay | Never}] [-Encoding <Encoding>] [-Priority {Normal | Low | High}] [-UseSsl] [<CommonParameters>]\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264/"
] |
I would like to send mail from a script on a Windows Server 2003 Standard Edition. I think the server setup is pretty much out of the box.
The mail server is an Exchange one, and when you're on the internal network you can use plain old SMTP. I have done it from my machine with Perl, but unfortunately Perl is not available on the server.
Is there an easy way of doing this from a .bat-file or any other way that doesn't require installing some additional software?
`Edit:`
Thanks for the quick replies. The "blat" thingie would probably work fine but with wscript I don't have to use a separate binary.
I didn't see PhiLho's post the first time I edited and selected an answer. No need for me to duplicate the code here.
Just save the script to a file, say sendmail.vbs, and then call it from the command prompt like so:
`wscript sendmail.vbs`
|
It is possible with Wscript, using CDO:
```
Dim objMail
Set objMail = CreateObject("CDO.Message")
objMail.From = "Me <[email protected]>"
objMail.To = "You <[email protected]>"
objMail.Subject = "That's a mail"
objMail.Textbody = "Hello World"
objMail.AddAttachment "C:\someFile.ext"
---8<----- You don't need this part if you have an active Outlook [Express] account -----
' Use an SMTP server
objMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
' Name or IP of Remote SMTP Server
objMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"smtp.server.com"
' Server port (typically 25)
objMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMail.Configuration.Fields.Update
----- End of SMTP usage ----->8---
objMail.Send
Set objMail=Nothing
Wscript.Quit
```
Update: found more info there: [VBScript To Send Email Using CDO](http://www.paulsadowski.com/WSH/cdo.htm "VBScript To Send Email Using CDO")
By default it seems it uses Outlook [Express], so it didn't worked on my computer but you can use a given SMTP server, which worked fine for me.
|
152,328 |
<p>What is better?</p>
<p><strong>A:</strong></p>
<pre><code>server:1080/repo/projectA/trunk/...
branches/branch1
branches/branch2
branches/branch3
tags/tag1/...
tags/tag2/...
server:1080/repo/projectB/trunk/...
branches/branch1
branches/branch2
branches/branch3
tags/tag1/...
tags/tag2/...
</code></pre>
<p><strong>B:</strong></p>
<pre><code>server:1080/repo/trunk/projectA/...
branches/projectA/branch1
branches/projectA/branch2
branches/projectA/branch3
tags/projectA/tag1/...
tags/projectA/tag2/...
server:1080/repo/trunk/projectB/trunk/...
branches/projectB/branch1
branches/projectB/branch2
branches/projectB/branch3
tags/projectB/tag1/...
tags/projectB/tag2/...
</code></pre>
<p>What repository structure do you use and WHY?</p>
|
[
{
"answer_id": 152341,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 4,
"selected": false,
"text": "<p>We use A, because the other one didn't make sense to us. Note that a \"project\" with regard to SVN is not necessarily a single project, but may be several projects that belong together (i.e. what you would put into a Solution in Visual Studio). This way, you have anything related grouped together. All branches, tags and the trunk of a specific project. Makes perfect sense to me.</p>\n\n<p>Grouping by branch/tag instead does not make sense to me, because the branches of different projects have nothing in common, except that they're all branches.</p>\n\n<p>But in the end, people use both ways. Do what you like, but when you decided, try to stay with it :)</p>\n\n<p>As an addition: We have separate repositories per customer, i.e. all projects for a customer are in the same repository. This way you can e.g. make backups of a single customer at once, or give the source code of anything the customer owns to him without fighting with SVN.</p>\n"
},
{
"answer_id": 152345,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>I would suggest an option C:</p>\n\n<pre><code>server:1080/projectA/trunk/...\n branches/branch1\n branches/branch2\n branches/branch3\n tags/tag1/...\n tags/tag2/...\nserver:1080/projectB/trunk/...\n branches/branch1\n branches/branch2\n branches/branch3\n tags/tag1/...\n tags/tag2/...\n</code></pre>\n\n<p>I prefer to keep separate projects in separate repositories. Using <a href=\"http://svnbook.red-bean.com/en/1.0/ch07s03.html\" rel=\"noreferrer\">svn:externals</a> makes it easy to manage code library projects that are shared among two or more application projects.</p>\n"
},
{
"answer_id": 152353,
"author": "Peter Parker",
"author_id": 23264,
"author_profile": "https://Stackoverflow.com/users/23264",
"pm_score": 1,
"selected": false,
"text": "<p>We use setting B. Beause it is easier to check out/tag multiple projects at once. In svn 1.5 it is possible via sparse checkout, but not a one-click operation. \nYou want to use setting B, if some projects have hidden dependencies inbeetween. </p>\n"
},
{
"answer_id": 152355,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 5,
"selected": true,
"text": "<p>The <a href=\"http://svnbook.red-bean.com/en/1.5/svn.reposadmin.html\" rel=\"noreferrer\">Repository Administration</a> chapter of the <a href=\"http://svnbook.red-bean.com/en/1.5/index.html\" rel=\"noreferrer\">SVN book</a> includes a section on <a href=\"http://svnbook.red-bean.com/en/1.5/svn.reposadmin.planning.html#svn.reposadmin.projects.chooselayout\" rel=\"noreferrer\">Planning Your Repository Organization</a> outlining different strategies and their implication, particularly <a href=\"http://svnbook.red-bean.com/en/1.5/svn.branchmerge.maint.html#svn.branchmerge.maint.layout\" rel=\"noreferrer\">the implications of the repository layout on branching and merging</a>.</p>\n"
},
{
"answer_id": 152456,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>We use </p>\n\n<pre><code>/repos/projectA/component1/trunk - branches - tags\n/repos/projectA/component2/trunk - branches - tags\n/repos/projectB/component3/trunk - branches - tags\n/repos/projectB/component4/trunk - branches - tags\n</code></pre>\n\n<p>Which I'm starting to regret. It should be flatter. This would be better.</p>\n\n<pre><code>/repos/projectA/trunk - branches - tags\n/repos/projectB/trunk - branches - tags\n/repos/component1/trunk - branches - tags\n/repos/component2/trunk - branches - tags\n/repos/component3/trunk - branches - tags\n/repos/component4/trunk - branches - tags\n</code></pre>\n\n<p>Why? Products (components, finished software) last forever. Projects come and go. Last year there's just one project team creating product QUUX. Next year, that team is dispersed and one or two people maintain QUUX. Next year, there will be two big QUUX expansion projects.</p>\n\n<p>Given that timeline, should QUUX appear in three project repositories? No, QUUX is independent of any particular project. It is true that the projects do have work products (documents, backlogs, etc.) that are part of getting the work done, but aren't the actual goal of the work. Hence the \"projectX\" repositories for that material -- stuff that no one will care about after the project is done.</p>\n\n<p>I worked on one product that had three teams. Big problem with coordination of work because each project managed it's repository independently. There were inter-team releases and inter-team coordination. At then end of the day, it was supposed to one piece of software. However, as you can guess, it was three pieces of software with weird overlaps and redundancy.</p>\n"
},
{
"answer_id": 8688758,
"author": "altern",
"author_id": 50962,
"author_profile": "https://Stackoverflow.com/users/50962",
"pm_score": 0,
"selected": false,
"text": "<p>Personally I use following repository structure:</p>\n\n<pre><code>/project\n /trunk\n /tags\n /builds\n /PA\n /A\n /B\n /releases\n /AR\n /BR\n /RC\n /ST\n /branches\n /experimental\n /maintenance\n /versions\n /platforms\n /releases\n</code></pre>\n\n<p>There is also a <a href=\"http://scm.altern.kiev.ua/images/branches_naming_A3.en.jpg\" rel=\"nofollow noreferrer\">diagram</a> illustrating how those directories are used. Also there is specific version numbering approach I use. It plays significant role in repository structuring. Recently I have developed training dedicated to Software Configuration Management where I describe version numbering approach and why exactly this repository structure is the best. Here are <a href=\"http://www.slideshare.net/altern/tag/training\" rel=\"nofollow noreferrer\">presentation slides</a>. </p>\n\n<p>There is also my <a href=\"https://stackoverflow.com/questions/1761513/multiple-svn-repositories-or-single-company-repository/1762051#1762051\">answer</a> on the <a href=\"https://stackoverflow.com/questions/1761513/multiple-svn-repositories-or-single-company-repository/\">question</a> about 'Multiple SVN Repositories vs single company repository'. It might be helpful as long as you address this aspect of repository structuring in your question.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8986/"
] |
What is better?
**A:**
```
server:1080/repo/projectA/trunk/...
branches/branch1
branches/branch2
branches/branch3
tags/tag1/...
tags/tag2/...
server:1080/repo/projectB/trunk/...
branches/branch1
branches/branch2
branches/branch3
tags/tag1/...
tags/tag2/...
```
**B:**
```
server:1080/repo/trunk/projectA/...
branches/projectA/branch1
branches/projectA/branch2
branches/projectA/branch3
tags/projectA/tag1/...
tags/projectA/tag2/...
server:1080/repo/trunk/projectB/trunk/...
branches/projectB/branch1
branches/projectB/branch2
branches/projectB/branch3
tags/projectB/tag1/...
tags/projectB/tag2/...
```
What repository structure do you use and WHY?
|
The [Repository Administration](http://svnbook.red-bean.com/en/1.5/svn.reposadmin.html) chapter of the [SVN book](http://svnbook.red-bean.com/en/1.5/index.html) includes a section on [Planning Your Repository Organization](http://svnbook.red-bean.com/en/1.5/svn.reposadmin.planning.html#svn.reposadmin.projects.chooselayout) outlining different strategies and their implication, particularly [the implications of the repository layout on branching and merging](http://svnbook.red-bean.com/en/1.5/svn.branchmerge.maint.html#svn.branchmerge.maint.layout).
|
152,337 |
<p>Does anybody know what user privileges are needed for the following code needs to successfully execute as a scheduled task on Windows Server 2003:</p>
<pre><code>System.Diagnostics.Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)
</code></pre>
<p>When NOT running as scheduled task i.e. under a logged in user, as long as the user is a member of "Performance Monitor Users", this code will not throw an exception.</p>
<p>When running as a scheduled task under the same user account, it fails.</p>
<p>The only way I can get it to work is to run it as a member of the Local Administrator group.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 152390,
"author": "EggyBach",
"author_id": 15475,
"author_profile": "https://Stackoverflow.com/users/15475",
"pm_score": -1,
"selected": false,
"text": "<p>Taken from <a href=\"http://msdn.microsoft.com/en-us/library/z3w4xdc9.aspx\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p><strong>Permissions</strong> LinkDemand - for full\n trust for the immediate caller. This\n member cannot be used by partially\n trusted code.</p>\n</blockquote>\n"
},
{
"answer_id": 152458,
"author": "John Dyer",
"author_id": 2862,
"author_profile": "https://Stackoverflow.com/users/2862",
"pm_score": 0,
"selected": false,
"text": "<p>One issue that I have seen with reading the process name is that access to the performance counters can get disabled.</p>\n\n<p>Crack open your registry and see if this key is there:\n[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\PerfProc\\Performance]\n\"Disable Performance Counters\"=dword:00000001</p>\n\n<p>You can either set it to zero or deleted it.</p>\n"
},
{
"answer_id": 152559,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": false,
"text": "<p>What user rights assignments have you given the account that is running as a scheduled task? You'll need to give the account in question 'Log on as a batch job' in your local security settings.</p>\n\n<p><strong>Update:</strong> Does your app write to any files and if so does the scheduled task user have enough rights?</p>\n\n<p>I just knocked up a test app that writes the process names from the Process[] array returned by Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName) to a file and it works just fine as a scheduled task...even running under the identity of a user that is only a member of the Users group (not even a member of 'Performance Monitor Users'.</p>\n\n<p>The folder it writes to is assigned modify rights to SYSTEM, Administrators and the scheduled task user.</p>\n\n<p>Any chance of pasting your code or at least a small enough snippet that demonstrates the exe failing as a scheduled task so we can help diagnose the problem?</p>\n\n<p>Cheers<br>\nKev</p>\n"
},
{
"answer_id": 156695,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>My humblest apologies. The user I was using was NOT a member of \"Performance Monitor Users\" group.</p>\n\n<p>This is necessary for .NET Framework 1.1 implementation of System.Diagnostics.</p>\n\n<p>I have added the user to this group, and all is well.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Does anybody know what user privileges are needed for the following code needs to successfully execute as a scheduled task on Windows Server 2003:
```
System.Diagnostics.Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)
```
When NOT running as scheduled task i.e. under a logged in user, as long as the user is a member of "Performance Monitor Users", this code will not throw an exception.
When running as a scheduled task under the same user account, it fails.
The only way I can get it to work is to run it as a member of the Local Administrator group.
Any ideas?
|
My humblest apologies. The user I was using was NOT a member of "Performance Monitor Users" group.
This is necessary for .NET Framework 1.1 implementation of System.Diagnostics.
I have added the user to this group, and all is well.
|
152,342 |
<p>I fill a collection one single time when my J2EE webapp starts.
Then, several thread may access it at same time but only to read it.</p>
<p>I know using a synchronized collection is mandatory for parallels write but do I still need it for parallels read ?</p>
|
[
{
"answer_id": 152348,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 5,
"selected": true,
"text": "<p>Normally no because you are not changing the internal state of the collection in this case. When you iterate over the collection a new instance of the iterator is created and the state of the iteration is per iterator instance.</p>\n\n<hr>\n\n<p><strong>Aside note:</strong> Remember that by keeping a read-only collection you are only preventing modifications to the collection itself. Each collection element is still changeable.</p>\n\n<pre><code>class Test {\n public Test(final int a, final int b) {\n this.a = a;\n this.b = b;\n }\n\n public int a;\n public int b;\n}\n\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n List<Test> values = new ArrayList<Test>(2);\n values.add(new Test(1, 2));\n values.add(new Test(3, 4));\n\n List<Test> readOnly = Collections.unmodifiableList(values);\n for (Test t : readOnly) {\n t.a = 5;\n }\n\n for (Test t : values) {\n System.out.println(t.a);\n }\n }\n\n}\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>5\n5\n</code></pre>\n\n<hr>\n\n<p>Important considerations from @WMR answser.</p>\n\n<blockquote>\n <p>It depends on if the threads that are\n reading your collection are started\n before or after you're filling it. If\n they're started before you fill it,\n you have no guarantees (without\n synchronizing), that these threads\n will ever see the updated values. </p>\n \n <p>The reason for this is the Java Memory\n Model, if you wanna know more read the\n section \"Visibility\" at this link:\n <a href=\"http://gee.cs.oswego.edu/dl/cpj/jmm.html\" rel=\"nofollow noreferrer\">http://gee.cs.oswego.edu/dl/cpj/jmm.html</a></p>\n \n <p>And even if the threads are started\n after you fill your collection, you\n might have to synchronize because your\n collection implementation could change\n its internal state even on read\n operations (thanks <a href=\"https://stackoverflow.com/questions/152342/in-java-do-i-need-to-declare-my-collection-synchronized-if-its-read-only#152425\">Michael\n Bar-Sinai</a>,\n I didn't know such collections\n existed).</p>\n \n <p>Another very interesting read on the\n topic of concurrency which covers\n topics like publishing of objects,\n visibility, etc. in much more detail\n is Brian Goetz's book <a href=\"http://www.briangoetz.com/pubs.html\" rel=\"nofollow noreferrer\">Java\n Concurrency in\n Practice</a>.</p>\n</blockquote>\n"
},
{
"answer_id": 152357,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 0,
"selected": false,
"text": "<p>The collection itself does not, but keep in mind that if what it holds is not immutable also, those seperate classes need their own synchronization.</p>\n"
},
{
"answer_id": 152367,
"author": "Nicolas",
"author_id": 1730,
"author_profile": "https://Stackoverflow.com/users/1730",
"pm_score": 2,
"selected": false,
"text": "<p>You do not have to, as explained in other answers. If you want to ensure that your collection is read only, you can use:</p>\n\n<pre><code>yourCollection = Collections.unmodifableCollection(yourCollection);\n</code></pre>\n\n<p>(similar method exist for List, Set, Map and other collection types)</p>\n"
},
{
"answer_id": 152391,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 3,
"selected": false,
"text": "<p>It depends on if the threads that are reading your collection are started before or after you're filling it. If they're started before you fill it, you have no guarantees (without synchronizing), that these threads will ever see the updated values. </p>\n\n<p>The reason for this is the Java Memory Model, if you wanna know more read the section \"Visibility\" at this link: <a href=\"http://gee.cs.oswego.edu/dl/cpj/jmm.html\" rel=\"nofollow noreferrer\">http://gee.cs.oswego.edu/dl/cpj/jmm.html</a> </p>\n\n<p>And even if the threads are started after you fill your collection, you might have to synchronize because your collection implementation could change its internal state even on read operations (thanks <a href=\"https://stackoverflow.com/questions/152342/in-java-do-i-need-to-declare-my-collection-synchronized-if-its-read-only#152425\">Michael Bar-Sinai</a>, I didn't know such collections existed in the standard JDK).</p>\n\n<p>Another very interesting read on the topic of concurrency which covers topics like publishing of objects, visibility, etc. in much more detail is Brian Goetz's book <a href=\"http://www.briangoetz.com/pubs.html\" rel=\"nofollow noreferrer\">Java Concurrency in Practice</a>.</p>\n"
},
{
"answer_id": 152425,
"author": "Michael Bar-Sinai",
"author_id": 11699,
"author_profile": "https://Stackoverflow.com/users/11699",
"pm_score": 3,
"selected": false,
"text": "<p>In the general case, you should. This is because some collections change their internal structure during reads. A LinkedHashMap that uses access order is a good example. But don't just take my word for it:</p>\n\n<blockquote>\n <p>In access-ordered linked hash maps, merely querying the map with get is a structural modification\n <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedHashMap.html\" rel=\"noreferrer\">The Linked hash map's javadoc</a></p>\n</blockquote>\n\n<p>If you are absolutely sure that there are no caches, no collection statistics, no optimizations, no funny stuff at all - you don't need to sync. In that case I would have put a type constraint on the collection: Don't declare the collection as a Map (which would allow LinkedHashMap) but as HashMap (for the purists, a final subclass of HashMap, but that might be taking it too far...).</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3122/"
] |
I fill a collection one single time when my J2EE webapp starts.
Then, several thread may access it at same time but only to read it.
I know using a synchronized collection is mandatory for parallels write but do I still need it for parallels read ?
|
Normally no because you are not changing the internal state of the collection in this case. When you iterate over the collection a new instance of the iterator is created and the state of the iteration is per iterator instance.
---
**Aside note:** Remember that by keeping a read-only collection you are only preventing modifications to the collection itself. Each collection element is still changeable.
```
class Test {
public Test(final int a, final int b) {
this.a = a;
this.b = b;
}
public int a;
public int b;
}
public class Main {
public static void main(String[] args) throws Exception {
List<Test> values = new ArrayList<Test>(2);
values.add(new Test(1, 2));
values.add(new Test(3, 4));
List<Test> readOnly = Collections.unmodifiableList(values);
for (Test t : readOnly) {
t.a = 5;
}
for (Test t : values) {
System.out.println(t.a);
}
}
}
```
This outputs:
```
5
5
```
---
Important considerations from @WMR answser.
>
> It depends on if the threads that are
> reading your collection are started
> before or after you're filling it. If
> they're started before you fill it,
> you have no guarantees (without
> synchronizing), that these threads
> will ever see the updated values.
>
>
> The reason for this is the Java Memory
> Model, if you wanna know more read the
> section "Visibility" at this link:
> <http://gee.cs.oswego.edu/dl/cpj/jmm.html>
>
>
> And even if the threads are started
> after you fill your collection, you
> might have to synchronize because your
> collection implementation could change
> its internal state even on read
> operations (thanks [Michael
> Bar-Sinai](https://stackoverflow.com/questions/152342/in-java-do-i-need-to-declare-my-collection-synchronized-if-its-read-only#152425),
> I didn't know such collections
> existed).
>
>
> Another very interesting read on the
> topic of concurrency which covers
> topics like publishing of objects,
> visibility, etc. in much more detail
> is Brian Goetz's book [Java
> Concurrency in
> Practice](http://www.briangoetz.com/pubs.html).
>
>
>
|
152,344 |
<p>I have a statusItem application written in PyObjC. The statusItem has a menuItem which is supposed to launch a new window when it is clicked:</p>
<pre><code># Create statusItem
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
statusItem.setHighlightMode_(TRUE)
statusItem.setEnabled_(TRUE)
statusItem.retain()
# Create menuItem
menu = NSMenu.alloc().init()
menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Preferences', 'launchPreferences:', '')
menu.addItem_(menuitem)
statusItem.setMenu_(menu)
</code></pre>
<p>The launchPreferences: method is:</p>
<pre><code>def launchPreferences_(self, notification):
preferences = Preferences.alloc().initWithWindowNibName_('Preferences')
preferences.showWindow_(self)
</code></pre>
<p>Preferences is an NSWindowController class:</p>
<pre><code>class Preferences(NSWindowController):
</code></pre>
<p>When I run the application in XCode (Build & Go), this works fine. However, when I run the built .app file externally from XCode, the statusItem and menuItem appear as expected but when I click on the Preferences menuItem the window does not appear. I have verified that the launchPreferences code is running by checking console output. </p>
<p>Further, if I then double click the .app file again, the window appears but if I change the active window away by clicking, for example, on a Finder window, the preferences window disappears. This seems to me to be something to do with the active window. </p>
<p><strong>Update 1</strong>
I have tried <a href="https://stackoverflow.com/questions/152344/nswindow-launched-from-statusitem-menuitem-does-not-appear-as-active-window#152399">these</a> <a href="https://stackoverflow.com/questions/152344/nswindow-launched-from-statusitem-menuitem-does-not-appear-as-active-window#152409">two</a> answers but neither work. If I add in to the launchPreferences method:</p>
<pre><code>preferences.makeKeyAndOrderFront_()
</code></pre>
<p>or</p>
<pre><code>preferences.setLevel_(NSNormalWindowLevel)
</code></pre>
<p>then I just get an error:</p>
<blockquote>
<p>'Preferences' object has no attribute</p>
</blockquote>
|
[
{
"answer_id": 152399,
"author": "Nathan Kinsinger",
"author_id": 20045,
"author_profile": "https://Stackoverflow.com/users/20045",
"pm_score": 3,
"selected": false,
"text": "<p>You need to send the application an activateIgnoringOtherApps: message and then send the window makeKeyAndOrderFront:. </p>\n\n<p>In Objective-C this would be:</p>\n\n<pre><code>[NSApp activateIgnoringOtherApps:YES];\n[[self window] makeKeyAndOrderFront:self];\n</code></pre>\n"
},
{
"answer_id": 152409,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 1,
"selected": false,
"text": "<p>I have no idea of PyObjC, never used that, but if this was Objective-C code, I'd say you should call <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSWindow_Class/Reference/Reference.html#//apple_ref/occ/instm/NSWindow/makeKeyAndOrderFront:\" rel=\"nofollow noreferrer\">makeKeyAndOrderFront</a>: on the window object if you want it to become the very first front window. A newly created window needs to be neither key, nor front, unless you make it either or like in this case, both.</p>\n\n<p>The other issue that worries me is that you say the window goes away (gets invisible) when it's not active anymore. This sounds like your window is no real window. Have you accidentally set it to be a \"Utility Window\" in Interface Builder? Could you try to manually set the window level, using setLevel: to NSNormalWindowLevel before the window is displayed on screen for the first time whether it still goes away when becoming inactive?</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] |
I have a statusItem application written in PyObjC. The statusItem has a menuItem which is supposed to launch a new window when it is clicked:
```
# Create statusItem
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
statusItem.setHighlightMode_(TRUE)
statusItem.setEnabled_(TRUE)
statusItem.retain()
# Create menuItem
menu = NSMenu.alloc().init()
menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Preferences', 'launchPreferences:', '')
menu.addItem_(menuitem)
statusItem.setMenu_(menu)
```
The launchPreferences: method is:
```
def launchPreferences_(self, notification):
preferences = Preferences.alloc().initWithWindowNibName_('Preferences')
preferences.showWindow_(self)
```
Preferences is an NSWindowController class:
```
class Preferences(NSWindowController):
```
When I run the application in XCode (Build & Go), this works fine. However, when I run the built .app file externally from XCode, the statusItem and menuItem appear as expected but when I click on the Preferences menuItem the window does not appear. I have verified that the launchPreferences code is running by checking console output.
Further, if I then double click the .app file again, the window appears but if I change the active window away by clicking, for example, on a Finder window, the preferences window disappears. This seems to me to be something to do with the active window.
**Update 1**
I have tried [these](https://stackoverflow.com/questions/152344/nswindow-launched-from-statusitem-menuitem-does-not-appear-as-active-window#152399) [two](https://stackoverflow.com/questions/152344/nswindow-launched-from-statusitem-menuitem-does-not-appear-as-active-window#152409) answers but neither work. If I add in to the launchPreferences method:
```
preferences.makeKeyAndOrderFront_()
```
or
```
preferences.setLevel_(NSNormalWindowLevel)
```
then I just get an error:
>
> 'Preferences' object has no attribute
>
>
>
|
You need to send the application an activateIgnoringOtherApps: message and then send the window makeKeyAndOrderFront:.
In Objective-C this would be:
```
[NSApp activateIgnoringOtherApps:YES];
[[self window] makeKeyAndOrderFront:self];
```
|
152,376 |
<p>How do I set the background colour of items in a list box dynamically? i.e. there is some property on my business object that I'm binding too, so based on some business rules I want the background colour to be different?</p>
<pre><code> <ListBox Background="Red">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Background" Value="Red"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBlock VerticalAlignment="Bottom"
FontFamily="Comic Sans MS"
FontSize="12"
Width="70"
Text="{Binding Name}" />
<TextBlock VerticalAlignment="Bottom"
FontFamily="Comic Sans MS"
FontSize="12"
Width="70"
Text="{Binding Age}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
<p>EDIT: It says <a href="http://msdn.microsoft.com/en-us/library/cc189093(VS.95).aspx" rel="nofollow noreferrer">here</a></p>
<blockquote>
<p>In Silverlight, you must add x:Key
attributes to your custom styles and
reference them as static resources.
Silverlight does not support implicit
styles applied using the TargetType
attribute value.</p>
</blockquote>
<p>Does this impact my approach?</p>
|
[
{
"answer_id": 152437,
"author": "Dan",
"author_id": 230,
"author_profile": "https://Stackoverflow.com/users/230",
"pm_score": 0,
"selected": false,
"text": "<p>@Matt Thanks for the reply. I'll look into triggers.</p>\n\n<p>My only problem is that, the logic for determining whether a row should be coloured is slightly more involved so I cant just checking a property, so I actually need to run some logic to determine the colour. Any ideas?</p>\n\n<p>I guess I could make a UI object with all the relevant fields I need, but I kinda didnt want to take the approach.</p>\n"
},
{
"answer_id": 152453,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>Ok - if you need custom logic to determine the background then I would look into building a simple IValueConverter class. You just need to implement the IValueConverter interface and, in its Convert method, change the supplied value into a Brush. </p>\n\n<p>Here's a quick post from Sahil Malik that describes IValueConverters - it might help:</p>\n\n<p><a href=\"http://blah.winsmarts.com/2007-3-WPF__DataBinding_to_Calculated_Values--The_IValueConverter_interface.aspx\" rel=\"nofollow noreferrer\">http://blah.winsmarts.com/2007-3-WPF__DataBinding_to_Calculated_Values--The_IValueConverter_interface.aspx</a></p>\n"
},
{
"answer_id": 152502,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 1,
"selected": false,
"text": "<p>To bind your background to more than one property, you can use IMultiValueConverter. It's just like IValueConverter except that it works with MultiBinding to pass more than one value into a class and get back a single value.</p>\n\n<p>Here's a post I found with a run-through on IMultiValueConverter and MultiBinding:</p>\n\n<p><a href=\"http://blog.paranoidferret.com/index.php/2008/07/21/wpf-tutorial-using-multibindings/\" rel=\"nofollow noreferrer\">http://blog.paranoidferret.com/index.php/2008/07/21/wpf-tutorial-using-multibindings/</a></p>\n\n<p>Edit: If IMultiValueConverter isn't available (it looks like Silverlight only has IValueConverter) then you can always pass your entire bound object (eg your Person object) to an IValueConverter and use various properties from that to return your Brush.</p>\n"
},
{
"answer_id": 1123045,
"author": "Stephen Price",
"author_id": 24395,
"author_profile": "https://Stackoverflow.com/users/24395",
"pm_score": 0,
"selected": false,
"text": "<p>You could try binding something in your controltemplate (ie a border or something) to the TemplateBackground. Then set the background on your listbox to determine the colour it will be. </p>\n\n<pre><code><Border Margin=\"-2,-2,-2,0\" Background=\"{TemplateBinding Background}\" BorderBrush=\"{TemplateBinding BorderBrush}\" BorderThickness=\"1,1,1,0\" CornerRadius=\"11,11,0,0\">\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] |
How do I set the background colour of items in a list box dynamically? i.e. there is some property on my business object that I'm binding too, so based on some business rules I want the background colour to be different?
```
<ListBox Background="Red">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Background" Value="Red"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBlock VerticalAlignment="Bottom"
FontFamily="Comic Sans MS"
FontSize="12"
Width="70"
Text="{Binding Name}" />
<TextBlock VerticalAlignment="Bottom"
FontFamily="Comic Sans MS"
FontSize="12"
Width="70"
Text="{Binding Age}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
```
EDIT: It says [here](http://msdn.microsoft.com/en-us/library/cc189093(VS.95).aspx)
>
> In Silverlight, you must add x:Key
> attributes to your custom styles and
> reference them as static resources.
> Silverlight does not support implicit
> styles applied using the TargetType
> attribute value.
>
>
>
Does this impact my approach?
|
Ok - if you need custom logic to determine the background then I would look into building a simple IValueConverter class. You just need to implement the IValueConverter interface and, in its Convert method, change the supplied value into a Brush.
Here's a quick post from Sahil Malik that describes IValueConverters - it might help:
<http://blah.winsmarts.com/2007-3-WPF__DataBinding_to_Calculated_Values--The_IValueConverter_interface.aspx>
|
152,382 |
<p>We recently installed SVN 1.5.2 (with VisualSVN/Apache) on some of our servers / virtual machines, and now when I send a commandline command with username/password they don't get cached anymore.
Before, we were running SVN 1.5.0 installed with CollabNet, on svn://, and the credentials were cached after the first command.</p>
<p>So far, I'm finding difficulties in troubleshooting this. My situation is:</p>
<ul>
<li>SERVER_SVN (SVN 1.5.2 via svn://)</li>
<li>SERVER_HTTP (SVN 1.5.2 via http://)</li>
</ul>
<p>Command from commandline to SERVER_SVN: credentials cached fine</p>
<p>Same command to SERVER_HTTP: credentials are not cached</p>
<p>So, it seems like an http/apache server problem... BUT, from Tortoise the credentials are cached to both servers, so it also seems a client call problem. I'm running out of ideas... </p>
<p>A sample command sequence I use:</p>
<pre><code>
svn ls c:\mylocalfolderSVN --username foo --password bar
svn ls c:\mylocalfolderSVN // this works
svn ls c:\mylocalfolderHTTP --username foo --password bar
svn ls c:\mylocalfolderHTTP // this fails
</code></pre>
<p>The last command stops and asks for authentication.</p>
<p>Is credentials caching different between svn:// and http://, or did we miss something in the server configuration?</p>
<p>Thanks in advance for any suggestion.</p>
|
[
{
"answer_id": 159009,
"author": "wds",
"author_id": 10098,
"author_profile": "https://Stackoverflow.com/users/10098",
"pm_score": 1,
"selected": false,
"text": "<p>AFAIK the credential caching is a client responsibility. All the server does is ask for those credentials when necessary. I'd check the local client configuration files and maybe see what happens with different version clients.</p>\n"
},
{
"answer_id": 159075,
"author": "Instantsoup",
"author_id": 9861,
"author_profile": "https://Stackoverflow.com/users/9861",
"pm_score": 0,
"selected": false,
"text": "<p>Are you fully qualifying the domain name of the SVN server? If the caching for HTTP is cookie based and the server is writing a cookie with the FQDN, but your request doesn't use the FQDN (you are using svnserver and the FQDN is svnserver.company) then the cookie may not be valid and each request will need authentication.</p>\n"
},
{
"answer_id": 161419,
"author": "Filini",
"author_id": 21162,
"author_profile": "https://Stackoverflow.com/users/21162",
"pm_score": 0,
"selected": false,
"text": "<p>As wds points out, SVN credentials caching is done on the client side by svn.exe, after receiving a response from the server like \"ok, I actually used the credentials you send, and they're fine\". </p>\n\n<p>And this is why I can't figure out what's happening: I have 2 servers installed from scratch, I send the same commandlines to both, one set of credentials is cached, the other is not... but TortoiseSVN, which uses the same svn.exe underneath, caches both (maybe it cheats, caching the credentials then svn.exe fails to do so).</p>\n\n<p>My best guess right now is that the http:// server does not send an \"appropriate\" response to svn.exe, but I really don't feel like sniffing all the http requests to see what's happening, call me lazy, but I've got funnier stuff to do :-)</p>\n\n<p>So I changed my design, now I'll be keeping the SVN password in memory (WinForm client application, all used in our internal network), and pass it with each command.</p>\n"
},
{
"answer_id": 1071691,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>In order to cache credentials, apart from appropriate configuration, you need to execute SVN like this:</p>\n\n<p><code>svn ls REPOSITORY_URL</code></p>\n\n<p>instead of</p>\n\n<p><code>svn ls WORKING_COPY_PATH</code></p>\n\n<p>This is what worked for me, not really sure if this is the solution in this case.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21162/"
] |
We recently installed SVN 1.5.2 (with VisualSVN/Apache) on some of our servers / virtual machines, and now when I send a commandline command with username/password they don't get cached anymore.
Before, we were running SVN 1.5.0 installed with CollabNet, on svn://, and the credentials were cached after the first command.
So far, I'm finding difficulties in troubleshooting this. My situation is:
* SERVER\_SVN (SVN 1.5.2 via svn://)
* SERVER\_HTTP (SVN 1.5.2 via http://)
Command from commandline to SERVER\_SVN: credentials cached fine
Same command to SERVER\_HTTP: credentials are not cached
So, it seems like an http/apache server problem... BUT, from Tortoise the credentials are cached to both servers, so it also seems a client call problem. I'm running out of ideas...
A sample command sequence I use:
```
svn ls c:\mylocalfolderSVN --username foo --password bar
svn ls c:\mylocalfolderSVN // this works
svn ls c:\mylocalfolderHTTP --username foo --password bar
svn ls c:\mylocalfolderHTTP // this fails
```
The last command stops and asks for authentication.
Is credentials caching different between svn:// and http://, or did we miss something in the server configuration?
Thanks in advance for any suggestion.
|
AFAIK the credential caching is a client responsibility. All the server does is ask for those credentials when necessary. I'd check the local client configuration files and maybe see what happens with different version clients.
|
152,416 |
<p>Given the following idioms:</p>
<p>1)</p>
<p><pre><code>variable = value1
if condition
variable = value2</code></pre></p>
<p>2)</p>
<p><pre><code>variable = value2
if not condition
variable = value1</pre></code></p>
<p>3)</p>
<p><pre><code>if condition
variable = value2
else
variable = value1</pre></code></p>
<p>4)</p>
<p><pre><code>if not condition
variable = value1
else
variable = value2</pre></code></p>
<p>Which do you prefer, and why?</p>
<p>We assume the most common execution path to be that of <code>condition</code> being false.</p>
<p>I tend to learn towards using 1), although I'm not exactly sure why I like it more.</p>
<p><em>Note: The following examples may be simpler—and thus possibly more readable—but not all languages provide such syntax, and they are not suitable for extending the variable assignment to include more than one statement in the future.</em></p>
<pre><code>variable = condition ? value2 : value1
...
variable = value2 if condition else value1</code></pre>
|
[
{
"answer_id": 152423,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 4,
"selected": true,
"text": "<p>In theory, I prefer #3 as it avoids having to assign a value to the variable twice. In the real world though I use any of the four above that would be more readable or would express more clearly my intention.</p>\n"
},
{
"answer_id": 152424,
"author": "Jarrett Meyer",
"author_id": 5834,
"author_profile": "https://Stackoverflow.com/users/5834",
"pm_score": 0,
"selected": false,
"text": "<p><code>switch</code> statement also works. If it's simple and more than 2 or 3 options, that's what I use.</p>\n"
},
{
"answer_id": 152431,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 1,
"selected": false,
"text": "<p>I tend to use #1 alot myself. <code>if condition</code> reads easier than <code>if !condition</code>, especially if you acidentally miss the '!', atleast to my mind atleast. </p>\n\n<p>Most coding I do is in C#, but I still tend to steer clear of the terniary operator, unless I'm working with (mostly) local variables. Lines tend to get long VERY quickly in a ternary operator if you're calling three layers deep into some structure, which quickly decreases the readability again.</p>\n"
},
{
"answer_id": 152434,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer method 3 because it is more concise and a logical unit. It sets the value only once, it can be moved around as a block, and it's not that error-prone (which happens, esp. in method 1 if setting-to-value1 and checking-and-optionally-setting-to-value2 are separated by other statements)</p>\n"
},
{
"answer_id": 152449,
"author": "Ólafur Waage",
"author_id": 22459,
"author_profile": "https://Stackoverflow.com/users/22459",
"pm_score": 0,
"selected": false,
"text": "<p>In a situation where the condition might not happen. I would go with 1 or 2. Otherwise its just based on what i want the code to do. (ie. i agree with cruizer)</p>\n"
},
{
"answer_id": 152452,
"author": "Joe Chin",
"author_id": 5906,
"author_profile": "https://Stackoverflow.com/users/5906",
"pm_score": 0,
"selected": false,
"text": "<p>I tend to use if not...return.</p>\n\n<p>But that's if you are looking to return a variable. Getting disqualifiers out of the way first tends to make it more readable. It really depends on the context of the statement and also the language. A case statement might work better and be readable most of the time, but performance suffers under VB so a series of if/else statements makes more sense in that specific case.</p>\n"
},
{
"answer_id": 152459,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 0,
"selected": false,
"text": "<p>Method 1 or method 3 for me. Method 1 can avoid an extra scope entrance/exit, but method 3 avoids an extra assignment. I'd tend to avoid Method 2 as I try to keep condition logic as simple as possible (in this case, the ! is extraneous as it could be rewritten as method 1 without it) and the same reason applies for method 4.</p>\n"
},
{
"answer_id": 152574,
"author": "DaveF",
"author_id": 17579,
"author_profile": "https://Stackoverflow.com/users/17579",
"pm_score": 0,
"selected": false,
"text": "<p>It depends on what the condition is I'm testing. </p>\n\n<p>If it's an error flag condition then I'll use 1) setting the Error flag to catch the error and then if the condition is successfull clear the error flag. That way there's no chance of missing an error condition.</p>\n\n<p>For everything else I'd use 3) </p>\n\n<p>The NOT logic just adds to confusion when reading the code - well in my head, can't speak for eveyone else :-)</p>\n"
},
{
"answer_id": 152584,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>If the variable has a natural default value I would go with #1. If either value is equally (in)appropriate for a default then I would go with #2.</p>\n"
},
{
"answer_id": 152600,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Note: The following examples may be simpler—and thus possibly more readable—but not all languages provide such syntax</p>\n</blockquote>\n\n<p>This is no argument for not using them in languages that do provide such a syntax. Incidentally, that includes all current mainstream languages after my last count.</p>\n\n<blockquote>\n <p>and they are not suitable for extending the variable assignment to include more than one statement in the future.</p>\n</blockquote>\n\n<p>This is true. However, it's often certain that such an extension will absolutely never take place because the <code>condition</code> will always yield one of two possible cases.</p>\n\n<p>In such situations I will always prefer the expression variant over the statement variant because it reduces syntactic clutter and improves expressiveness. In other situations I tend to go with the <code>switch</code> statement mentioned before – if the language allows this usage. If not, fall-back to generic <code>if</code>.</p>\n"
},
{
"answer_id": 152614,
"author": "Kristopher Johnson",
"author_id": 1175,
"author_profile": "https://Stackoverflow.com/users/1175",
"pm_score": 2,
"selected": false,
"text": "<p>3) is the clearest expression of what you want to happen. I think all the others require some extra thinking to determine which value is going to end up in the variable.</p>\n\n<p>In practice, I would use the ternary operator (?:) if I was using a language that supported it. I prefer to write in functional or declarative style over imperative whenever I can.</p>\n"
},
{
"answer_id": 152621,
"author": "Bart Read",
"author_id": 17786,
"author_profile": "https://Stackoverflow.com/users/17786",
"pm_score": 0,
"selected": false,
"text": "<p>It depends. I like the ternary operators, but sometimes it's clearer if you use an 'if' statement. Which of the four alternatives you choose depends on the context, but I tend to go for whichever makes the code's function clearer, and that varies from situation to situation.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709/"
] |
Given the following idioms:
1)
```
variable = value1
if condition
variable = value2
```
2)
```
variable = value2
if not condition
variable = value1
```
3)
```
if condition
variable = value2
else
variable = value1
```
4)
```
if not condition
variable = value1
else
variable = value2
```
Which do you prefer, and why?
We assume the most common execution path to be that of `condition` being false.
I tend to learn towards using 1), although I'm not exactly sure why I like it more.
*Note: The following examples may be simpler—and thus possibly more readable—but not all languages provide such syntax, and they are not suitable for extending the variable assignment to include more than one statement in the future.*
```
variable = condition ? value2 : value1
...
variable = value2 if condition else value1
```
|
In theory, I prefer #3 as it avoids having to assign a value to the variable twice. In the real world though I use any of the four above that would be more readable or would express more clearly my intention.
|
152,419 |
<p>I've added a custom soap header <code><MyApp:FOO></code> element to the <code><soap:Header></code> element and the requirments states that i must sign this element , how would one do that?
<code><MyApp:FOO></code> contains a number of things (username, preferences, etc) that identifies a user on higher level.
I've succesfully used a policy file and now a policyClass with CertificateAssertions and SoapFilters to sign wsu:Timestamp, wsu:action, wsu:MessageId etc. But now the <code><MyApp:FOO></code> element needs to signed aswell.</p>
<p>What i've understood this far is that the element that needs to be signed must be indentified with a wsu:Id attribute and then transformed using xml-exc-c14n.</p>
<p>So, how do I specify that the soap header should be signed aswell?
This is the current class that i use for signing my message.</p>
<pre><code>internal class FOOClientOutFilter: SendSecurityFilter
{
X509SecurityToken clientToken;
public FOOClientOutFilter(SSEKCertificateAssertion parentAssertion)
: base(parentAssertion.ServiceActor, true)
{
// Get the client security token.
clientToken = X509TokenProvider.CreateToken(StoreLocation.CurrentUser, StoreName.My, "CN=TestClientCert");
// Get the server security token.
serverToken = X509TokenProvider.CreateToken(StoreLocation.LocalMachine, StoreName.My, "CN=TestServerCert");
}
public override void SecureMessage(SoapEnvelope envelope, Security security)
{
// Sign the SOAP message with the client's security token.
security.Tokens.Add(clientToken);
security.Elements.Add(new MessageSignature(clientToken));
}
}
</code></pre>
|
[
{
"answer_id": 152522,
"author": "Carl-Johan",
"author_id": 15406,
"author_profile": "https://Stackoverflow.com/users/15406",
"pm_score": 2,
"selected": false,
"text": "<p>My current version of SecureMessage seems to do the trick..</p>\n\n<pre><code> public override void SecureMessage(SoapEnvelope envelope, Security security)\n {\n //EncryptedData data = new EncryptedData(userToken);\n SignatureReference ssekSignature = new SignatureReference();\n MessageSignature signature = new MessageSignature(clientToken);\n // encrypt custom headers\n\n for (int index = 0; index < envelope.Header.ChildNodes.Count; index++)\n {\n XmlElement child =\n envelope.Header.ChildNodes[index] as XmlElement;\n\n // find all FOO headers\n if (child != null && child.Name == \"FOO\")\n {\n string id = Guid.NewGuid().ToString();\n child.SetAttribute(\"Id\", \"http://docs.oasis-\" +\n \"open.org/wss/2004/01/oasis-200401-\" +\n \"wss-wssecurity-utility-1.0.xsd\", id);\n signature.AddReference(new SignatureReference(\"#\" + id));\n }\n }\n\n // Sign the SOAP message with the client's security token.\n security.Tokens.Add(clientToken);\n\n security.Elements.Add(signature);\n }\n</code></pre>\n"
},
{
"answer_id": 435360,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 1,
"selected": false,
"text": "<p>Including supplementary articles from MSDN</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa529237.aspx\" rel=\"nofollow noreferrer\"><strong>How to: Add an Id Attribute to a SOAP Header</strong></a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa528813.aspx\" rel=\"nofollow noreferrer\"><strong>How to: Digitally Sign a Custom SOAP Header</strong></a></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15406/"
] |
I've added a custom soap header `<MyApp:FOO>` element to the `<soap:Header>` element and the requirments states that i must sign this element , how would one do that?
`<MyApp:FOO>` contains a number of things (username, preferences, etc) that identifies a user on higher level.
I've succesfully used a policy file and now a policyClass with CertificateAssertions and SoapFilters to sign wsu:Timestamp, wsu:action, wsu:MessageId etc. But now the `<MyApp:FOO>` element needs to signed aswell.
What i've understood this far is that the element that needs to be signed must be indentified with a wsu:Id attribute and then transformed using xml-exc-c14n.
So, how do I specify that the soap header should be signed aswell?
This is the current class that i use for signing my message.
```
internal class FOOClientOutFilter: SendSecurityFilter
{
X509SecurityToken clientToken;
public FOOClientOutFilter(SSEKCertificateAssertion parentAssertion)
: base(parentAssertion.ServiceActor, true)
{
// Get the client security token.
clientToken = X509TokenProvider.CreateToken(StoreLocation.CurrentUser, StoreName.My, "CN=TestClientCert");
// Get the server security token.
serverToken = X509TokenProvider.CreateToken(StoreLocation.LocalMachine, StoreName.My, "CN=TestServerCert");
}
public override void SecureMessage(SoapEnvelope envelope, Security security)
{
// Sign the SOAP message with the client's security token.
security.Tokens.Add(clientToken);
security.Elements.Add(new MessageSignature(clientToken));
}
}
```
|
My current version of SecureMessage seems to do the trick..
```
public override void SecureMessage(SoapEnvelope envelope, Security security)
{
//EncryptedData data = new EncryptedData(userToken);
SignatureReference ssekSignature = new SignatureReference();
MessageSignature signature = new MessageSignature(clientToken);
// encrypt custom headers
for (int index = 0; index < envelope.Header.ChildNodes.Count; index++)
{
XmlElement child =
envelope.Header.ChildNodes[index] as XmlElement;
// find all FOO headers
if (child != null && child.Name == "FOO")
{
string id = Guid.NewGuid().ToString();
child.SetAttribute("Id", "http://docs.oasis-" +
"open.org/wss/2004/01/oasis-200401-" +
"wss-wssecurity-utility-1.0.xsd", id);
signature.AddReference(new SignatureReference("#" + id));
}
}
// Sign the SOAP message with the client's security token.
security.Tokens.Add(clientToken);
security.Elements.Add(signature);
}
```
|
152,439 |
<p>I am actually new to this forum and I kept trying for a few days to find an easy way to copy an entire LDAP subtree to another tree. Since I couldn't find anything useful, i thought of dropping a question here as well. Does anybody know how to do this programatically ?</p>
<p>For normal operations like add, remove, search, I've been using Spring LDAP. </p>
<p>Thanks a lot !</p>
|
[
{
"answer_id": 152529,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 1,
"selected": false,
"text": "<p>I actually don't know Spring LDAP but if your LDAP interface does not provide any high level abstraction for moving/renaming or copying an entire subtree you have to move/rename or copy all subtree nodes recursively. The LDAP API does not provide such an option directly.</p>\n\n<p>The following is pseudo-code:</p>\n\n<pre><code>function copySubtree(oldDn, newDn)\n{\n copyNode(oldDn, newDn); // the new node will be created here\n if (nodeHasChildren(oldDn) { \n foreach (nodeGetChildren(oldDn) as childDn) {\n childRdn=getRdn(childDn); // we have to get the 'local' part, the so called RDN \n newChildDn=childRdn + ',' + newDn; // the new DN will be the old RDN concatenated with the new parent's DN\n copySubtree(childDn, newChildDn); // call this function recursively\n } \n }\n}\n</code></pre>\n"
},
{
"answer_id": 387058,
"author": "geoffc",
"author_id": 32247,
"author_profile": "https://Stackoverflow.com/users/32247",
"pm_score": 0,
"selected": false,
"text": "<p>Do note that passwords are tricky to copy. You may or may not be able to read them via the LDAP API. It would depend on the LDAP implementation you are using this against.</p>\n\n<p>Thus a copy to a new location may not get everything you want or need.</p>\n"
},
{
"answer_id": 711726,
"author": "Joe Koberg",
"author_id": 76310,
"author_profile": "https://Stackoverflow.com/users/76310",
"pm_score": 1,
"selected": false,
"text": "<p>Dump it as LDIF, edit the DNs via search & replace (or via script), and import the new LDIF.</p>\n\n<p>Spring may not be the tool to do this. Is it necessary that you manipulate the directory with Spring? I presume OpenLDAP's ldapsearch and ldapadd should work against any server, and they will dump/load LDIF.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am actually new to this forum and I kept trying for a few days to find an easy way to copy an entire LDAP subtree to another tree. Since I couldn't find anything useful, i thought of dropping a question here as well. Does anybody know how to do this programatically ?
For normal operations like add, remove, search, I've been using Spring LDAP.
Thanks a lot !
|
I actually don't know Spring LDAP but if your LDAP interface does not provide any high level abstraction for moving/renaming or copying an entire subtree you have to move/rename or copy all subtree nodes recursively. The LDAP API does not provide such an option directly.
The following is pseudo-code:
```
function copySubtree(oldDn, newDn)
{
copyNode(oldDn, newDn); // the new node will be created here
if (nodeHasChildren(oldDn) {
foreach (nodeGetChildren(oldDn) as childDn) {
childRdn=getRdn(childDn); // we have to get the 'local' part, the so called RDN
newChildDn=childRdn + ',' + newDn; // the new DN will be the old RDN concatenated with the new parent's DN
copySubtree(childDn, newChildDn); // call this function recursively
}
}
}
```
|
152,447 |
<p>When I backup or restore a database using MS SQL Server Management Studio, I get a visual indication of how far the process has progressed, and thus how much longer I still need to wait for it to finish. If I kick off the backup or restore with a script, is there a way to monitor the progress, or do I just sit back and wait for it to finish (hoping that nothing has gone wrong?)</p>
<p><strong>Edited:</strong> My need is specifically to be able to monitor the backup or restore progress completely separate from the session where the backup or restore was initiated.</p>
|
[
{
"answer_id": 152465,
"author": "Pavel Chuchuva",
"author_id": 14131,
"author_profile": "https://Stackoverflow.com/users/14131",
"pm_score": 2,
"selected": false,
"text": "<p>Use STATS option: <a href=\"http://msdn.microsoft.com/en-us/library/ms186865.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms186865.aspx</a></p>\n"
},
{
"answer_id": 152477,
"author": "Veldmuis",
"author_id": 18826,
"author_profile": "https://Stackoverflow.com/users/18826",
"pm_score": 8,
"selected": false,
"text": "<p>I found this sample script <a href=\"http://sql-articles.com/scripts/estimated-time-for-backup-restore/\" rel=\"noreferrer\">here</a> that seems to be working pretty well:</p>\n\n<pre><code>SELECT r.session_id,r.command,CONVERT(NUMERIC(6,2),r.percent_complete)\nAS [Percent Complete],CONVERT(VARCHAR(20),DATEADD(ms,r.estimated_completion_time,GetDate()),20) AS [ETA Completion Time],\nCONVERT(NUMERIC(10,2),r.total_elapsed_time/1000.0/60.0) AS [Elapsed Min],\nCONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0) AS [ETA Min],\nCONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0/60.0) AS [ETA Hours],\nCONVERT(VARCHAR(1000),(SELECT SUBSTRING(text,r.statement_start_offset/2,\nCASE WHEN r.statement_end_offset = -1 THEN 1000 ELSE (r.statement_end_offset-r.statement_start_offset)/2 END)\nFROM sys.dm_exec_sql_text(sql_handle))) AS [SQL]\nFROM sys.dm_exec_requests r WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')\n</code></pre>\n"
},
{
"answer_id": 152496,
"author": "David L Morris",
"author_id": 3137,
"author_profile": "https://Stackoverflow.com/users/3137",
"pm_score": 2,
"selected": false,
"text": "<p>Use STATS in the BACKUP command if it is just a script.</p>\n\n<p>Inside code it is a bit more complicated. In ODBC for example, you set SQL_ATTR_ASYNC_ENABLE and then look for SQL_STILL_EXECUTING return code, and do some repeated calls of SQLExecDirect until you get a SQL_SUCCESS (or eqiv).</p>\n"
},
{
"answer_id": 156112,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 5,
"selected": true,
"text": "<p>Yes. If you have installed <a href=\"http://blogs.msdn.com/chadboyd/archive/2007/08/15/sp-who-for-sql-2005-sp-who2k5.aspx\" rel=\"noreferrer\">sp_who2k5</a> into your master database, you can simply run:</p>\n\n<pre><code>sp_who2k5 1,1\n</code></pre>\n\n<p>The resultset will include all the active transactions. The currently running backup(s) will contain the string \"BACKUP\" in the <strong>requestCommand</strong> field. The aptly named <strong>percentComplete</strong> field will give you the progress of the backup.</p>\n\n<p>Note: sp_who2k5 should be a part of everyone's toolkit, it does a lot more than just this.</p>\n"
},
{
"answer_id": 11270498,
"author": "Allen",
"author_id": 1492386,
"author_profile": "https://Stackoverflow.com/users/1492386",
"pm_score": 4,
"selected": false,
"text": "<p>If you know the sessionID then you can use the following:</p>\n\n<pre><code>SELECT * FROM sys.dm_exec_requests WHERE session_id = 62\n</code></pre>\n\n<p>Or if you want to narrow it down:</p>\n\n<pre><code>SELECT command, percent_complete, start_time FROM sys.dm_exec_requests WHERE session_id = 62\n</code></pre>\n"
},
{
"answer_id": 34287344,
"author": "Shahbaz I Shaikh",
"author_id": 5681714,
"author_profile": "https://Stackoverflow.com/users/5681714",
"pm_score": 3,
"selected": false,
"text": "<pre><code>SELECT session_id as SPID, command, a.text AS Query, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time \nFROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a \nWHERE r.command in ('BACKUP DATABASE','RESTORE DATABASE')\n</code></pre>\n"
},
{
"answer_id": 36465055,
"author": "Liam Fleming",
"author_id": 5479334,
"author_profile": "https://Stackoverflow.com/users/5479334",
"pm_score": 0,
"selected": false,
"text": "<p>To monitor the backup or restore progress completely separate from the session where the backup or restore was initiated. No third party tools required. Tested on Microsoft SQL Server 2012.</p>\n\n<pre><code>SELECT percent_complete, *\nFROM sys.dm_exec_requests\nWHERE command In ( 'RESTORE DATABASE', 'BACKUP DATABASE' )\n</code></pre>\n"
},
{
"answer_id": 40132685,
"author": "Wilfred Kimani",
"author_id": 7042562,
"author_profile": "https://Stackoverflow.com/users/7042562",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a simple script that generally does the trick for me:</p>\n\n<pre><code>SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time\n FROM sys.dm_exec_requests\n WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE') \n</code></pre>\n"
},
{
"answer_id": 43353366,
"author": "BMDaemon",
"author_id": 7852396,
"author_profile": "https://Stackoverflow.com/users/7852396",
"pm_score": 2,
"selected": false,
"text": "<p>I think the best way to find out how your restore or backup progress is by the following query: </p>\n\n<pre><code>USE[master]\nGO\nSELECT session_id AS SPID, command, a.text AS Query, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time \n FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a \n WHERE r.command in ('BACKUP DATABASE','RESTORE DATABASE')\nGO\n</code></pre>\n\n<p>The query above, identify the session by itself and perform a percentage progress every time you press F5 or Execute button on SSMS!</p>\n\n<p>The query was performed by the guy who write this <a href=\"https://www.mssqltips.com/sqlservertip/2343/how-to-monitor-backup-and-restore-progress-in-sql-server/\" rel=\"nofollow noreferrer\">post</a> </p>\n"
},
{
"answer_id": 43615134,
"author": "RC Bird",
"author_id": 6905853,
"author_profile": "https://Stackoverflow.com/users/6905853",
"pm_score": 0,
"selected": false,
"text": "<p>I am using sp_whoisactive, very informative an basically industry standard. it returns percent complete as well. </p>\n"
},
{
"answer_id": 44916688,
"author": "ahsan Mumtaz Abbasi",
"author_id": 7900789,
"author_profile": "https://Stackoverflow.com/users/7900789",
"pm_score": -1,
"selected": false,
"text": "<p>simply run bkp_status on master db you will get backup status</p>\n"
},
{
"answer_id": 49243927,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p><strong><a href=\"https://alwayssql.wordpress.com/2018/03/10/query-to-check-the-backup-and-restore-progress-in-sql-server/\" rel=\"noreferrer\">Script to check the Backup and Restore progress in SQL Server</a>:</strong></p>\n</blockquote>\n\n<p>Many times it happens that your backup (or restore) activity has been started by another Database Administrator or by a job, and you cannot use the GUI anything else to check the progress of that Backup / Restore.</p>\n\n<p>By combining multiple commands, I have generated below script which can give us a summary of current backups and restores which are happening on the server.</p>\n\n<pre><code>select \nr.session_id, \nr.blocking_session_id, \ndb_name(database_id) as [DatabaseName],\nr.command, \n[SQL_QUERY_TEXT] = Substring(Query.TEXT, (r.statement_start_offset / 2) + 1, (\n (\n CASE r.statement_end_offset\n WHEN - 1\n THEN Datalength(Query.TEXT)\n ELSE r.statement_end_offset\n END - r.statement_start_offset\n ) / 2\n ) + 1),\n [SP_Name] =Coalesce(Quotename(Db_name(Query.dbid)) + N'.' + Quotename(Object_schema_name(Query.objectid, Query.dbid)) + N'.' + \n Quotename(Object_name(Query.objectid, Query.dbid)), ''),\nr.percent_complete,\nstart_time,\nCONVERT(VARCHAR(20), DATEADD(ms, [estimated_completion_time],\nGETDATE()), 20) AS [ETA_COMPLETION_TIME],\nCONVERT(NUMERIC(6, 2), r.[total_elapsed_time] / 1000.0 / 60.0) AS [Elapsed_MIN],\nCONVERT(NUMERIC(6, 2), r.[estimated_completion_time] / 1000.0 / 60.0) AS [Remaning_ETA_MIN],\nCONVERT(NUMERIC(6, 2), r.[estimated_completion_time] / 1000.0 / 60.0/ 60.0) AS [ETA_Hours],\nwait_type,\nwait_time/1000 as Wait_Time_Sec, \nwait_resource\nfrom sys.dm_exec_requests r \ncross apply sys.fn_get_sql(r.sql_handle) as Query where r.session_id>50 and command IN ('RESTORE DATABASE','BACKUP DATABASE', 'RESTORE LOG', 'BACKUP LOG')\n</code></pre>\n"
},
{
"answer_id": 54400831,
"author": "Zaalouni Mohamed",
"author_id": 5897616,
"author_profile": "https://Stackoverflow.com/users/5897616",
"pm_score": 3,
"selected": false,
"text": "<p>Try wih :</p>\n\n<pre><code>SELECT * FROM sys.dm_exec_requests where command like '%BACKUP%'\n\nSELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command like '%BACKUP%'\n\nSELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time\n FROM sys.dm_exec_requests\n WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')\n</code></pre>\n"
},
{
"answer_id": 54400876,
"author": "Zaalouni Mohamed",
"author_id": 5897616,
"author_profile": "https://Stackoverflow.com/users/5897616",
"pm_score": 2,
"selected": false,
"text": "<p>Add <code>STATS=10</code> or <code>STATS=1</code> in backup command.</p>\n\n<pre><code>BACKUP DATABASE [xxxxxx] TO DISK = N'E:\\\\Bachup_DB.bak' WITH NOFORMAT, NOINIT, \nNAME = N'xxxx-Complète Base de données Sauvegarde', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10\nGO.\n</code></pre>\n"
},
{
"answer_id": 56609589,
"author": "Ben",
"author_id": 1830764,
"author_profile": "https://Stackoverflow.com/users/1830764",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT session_id as SPID, command, start_time, percent_complete,\n dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time,\n a.text AS Query \nFROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a\nWHERE r.command in ('BACKUP DATABASE', 'BACKUP LOG', 'RESTORE DATABASE', 'RESTORE LOG')\n</code></pre>\n"
},
{
"answer_id": 57171267,
"author": "bsplosion",
"author_id": 2738164,
"author_profile": "https://Stackoverflow.com/users/2738164",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone running SQL Server on RDS (AWS), there's a <a href=\"https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/SQLServer.Procedural.Importing.html#SQLServer.Procedural.Importing.Native.Using.Poll\" rel=\"nofollow noreferrer\">built-in procedure</a> callable in the <code>msdb</code> database which provides comprehensive information for all backup and restore tasks:</p>\n\n<pre><code>exec msdb.dbo.rds_task_status;\n</code></pre>\n\n<p>This will give a full rundown of each task, its configuration, details about execution (such as completed percentage and total duration), and a <code>task_info</code> column which is immensely helpful when trying to figure out what's wrong with a backup or restore.</p>\n"
},
{
"answer_id": 63606677,
"author": "Promise Preston",
"author_id": 10907864,
"author_profile": "https://Stackoverflow.com/users/10907864",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar issue when working on Database restore operation on MS SQL Server 2012.</p>\n<p>However, for my own scenario, I just needed to see the progress of the <strong>DATABASE RESTORE</strong> operation in the script window</p>\n<p>All I had to do was add the STATS option to the script:</p>\n<pre><code>USE master;\nGO\n\nALTER DATABASE mydb SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\nGO\n \nRESTORE DATABASE mydb\n FROM DISK = 'C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\Backup\\my_db_21-08-2020.bak'\n WITH REPLACE,\n STATS = 10,\n RESTART,\n MOVE 'my_db' TO 'C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\my_db.mdf',\n MOVE 'my_db_log' TO 'C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\mydb_log.ldf'\nGO\n \nALTER DATABASE mydb SET MULTI_USER;\nGO\n</code></pre>\n<p>And then I switched to the <strong>Messages</strong> tab of the Script window to see the progress of the <strong>DATABASE RESTORE</strong> operation:</p>\n<p><a href=\"https://i.stack.imgur.com/sD4Tv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sD4Tv.png\" alt=\"enter image description here\" /></a></p>\n<p>If you want to get more information <strong>after</strong> the DATABASE RESTORE operation you can use this command suggested by <a href=\"https://stackoverflow.com/users/1934989/eythort\">eythort</a>:</p>\n<pre><code>SELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command = 'RESTORE DATABASE'\n</code></pre>\n<p>That's all.</p>\n<p><strong>I hope this helps</strong></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18826/"
] |
When I backup or restore a database using MS SQL Server Management Studio, I get a visual indication of how far the process has progressed, and thus how much longer I still need to wait for it to finish. If I kick off the backup or restore with a script, is there a way to monitor the progress, or do I just sit back and wait for it to finish (hoping that nothing has gone wrong?)
**Edited:** My need is specifically to be able to monitor the backup or restore progress completely separate from the session where the backup or restore was initiated.
|
Yes. If you have installed [sp\_who2k5](http://blogs.msdn.com/chadboyd/archive/2007/08/15/sp-who-for-sql-2005-sp-who2k5.aspx) into your master database, you can simply run:
```
sp_who2k5 1,1
```
The resultset will include all the active transactions. The currently running backup(s) will contain the string "BACKUP" in the **requestCommand** field. The aptly named **percentComplete** field will give you the progress of the backup.
Note: sp\_who2k5 should be a part of everyone's toolkit, it does a lot more than just this.
|
152,457 |
<p>This was a question raised by one of the software engineers in my organisation. I'm interested in the broadest definition.</p>
|
[
{
"answer_id": 152463,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 5,
"selected": false,
"text": "<p>A socket = IP Address + a port (numeric address)<br>\nTogether they identify an end-point for a network connection on a machine. (Did I just flunk network 101?)</p>\n"
},
{
"answer_id": 152470,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 7,
"selected": false,
"text": "<p><strong>A socket</strong> represents a single connection between two network applications. These two applications nominally run on different computers, but sockets can also be used for interprocess communication on a single computer. Applications can create multiple sockets for communicating with each other. Sockets are bidirectional, meaning that either side of the connection is capable of both sending and receiving data.\nTherefore a socket can be created theoretically at any level of the OSI model from 2 upwards. Programmers often use sockets in network programming, albeit indirectly. Programming libraries like Winsock hide many of the low-level details of socket programming. Sockets have been in widespread use since the early 1980s.</p>\n\n<p><strong>A port</strong> represents an endpoint or \"channel\" for network communications. Port numbers allow different applications on the same computer to utilize network resources without interfering with each other. Port numbers most commonly appear in network programming, particularly socket programming. Sometimes, though, port numbers are made visible to the casual user. For example, some Web sites a person visits on the Internet use a URL like the following:</p>\n\n<p><a href=\"http://www.mairie-metz.fr:8080/\" rel=\"noreferrer\">http://www.mairie-metz.fr:8080/</a> In this example, the number 8080 refers to the port number used by the Web browser to connect to the Web server. Normally, a Web site uses port number 80 and this number need not be included with the URL (although it can be).</p>\n\n<p>In IP networking, port numbers can theoretically range from 0 to 65535. Most popular network applications, though, use port numbers at the low end of the range (such as 80 for HTTP).</p>\n\n<p>Note: The term port also refers to several other aspects of network technology. A port can refer to a physical connection point for peripheral devices such as serial, parallel, and USB ports. The term port also refers to certain Ethernet connection points, such as those on a hub, switch, or router.</p>\n\n<p>ref <a href=\"http://compnetworking.about.com/od/basicnetworkingconcepts/l/bldef_port.htm\" rel=\"noreferrer\">http://compnetworking.about.com/od/basicnetworkingconcepts/l/bldef_port.htm</a></p>\n\n<p>ref <a href=\"http://compnetworking.about.com/od/itinformationtechnology/l/bldef_socket.htm\" rel=\"noreferrer\">http://compnetworking.about.com/od/itinformationtechnology/l/bldef_socket.htm</a></p>\n"
},
{
"answer_id": 152475,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 5,
"selected": false,
"text": "<p>They are terms from two different domains: 'port' is a concept from TCP/IP networking, 'socket' is an API (programming) thing. A 'socket' is made (in code) by taking a port and a hostname or network adapter and combining them into a data structure that you can use to send or receive data.</p>\n"
},
{
"answer_id": 152478,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 2,
"selected": false,
"text": "<p>A socket is basically an endpoint for network communication, consisting of at least an IP-address and a port. In Java/C# a socket is a higher level implementation of one side of a two-way connection.</p>\n<p>Also, a (non-normative) definition in the <a href=\"http://java.sun.com/docs/books/tutorial/networking/sockets/definition.html\" rel=\"nofollow noreferrer\">Java Tutorial</a>.</p>\n"
},
{
"answer_id": 152479,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 3,
"selected": false,
"text": "<p>A socket is a data I/O mechanism. A port is a <em>contractual</em> concept of a <em>communication protocol</em>. A socket can exist without a port. A port can exist witout a specific socket (e.g. if several sockets are active on the same port, which may be allowed for some protocols).</p>\n\n<p>A port is used to determine which socket the receiver should route the packet to, with many protocols, but it is not always required and the receiving socket selection can be done by other means - a port is entirely a tool used by the protocol handler in the network subsystem. e.g. if a protocol does not use a port, packets can go to all listening sockets or any socket.</p>\n"
},
{
"answer_id": 152481,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": "<p>A socket is a structure in your software. It's more-or-less a file; it has operations like read and write. It isn't a physical thing; it's a way for your software to refer to physical things.</p>\n\n<p>A port is a device-like thing. Each host has one or more networks (those are physical); a host has an address on each network. Each address can have thousands of ports. </p>\n\n<p>One socket only may be using a port at an address. The socket allocates the port approximately like allocating a device for file system I/O. Once the port is allocated, no other socket can connect to that port. The port will be freed when the socket is closed.</p>\n\n<p>Take a look at <a href=\"http://publib.boulder.ibm.com/infocenter/systems/index.jsp?topic=/com.ibm.aix.commadmn/doc/commadmndita/tcpip_terms.htm\" rel=\"nofollow noreferrer\">TCP/IP Terminology</a>.</p>\n"
},
{
"answer_id": 152507,
"author": "balaweblog",
"author_id": 22162,
"author_profile": "https://Stackoverflow.com/users/22162",
"pm_score": 3,
"selected": false,
"text": "<p>Port:</p>\n\n<p>A port can refer to a physical connection point \nfor peripheral devices such as serial, parallel, and USB ports.\n The term port also refers to certain Ethernet connection points, s\nuch as those on a hub, switch, or router. </p>\n\n<p>Socket:</p>\n\n<p>A socket represents a single connection between two network applications.\n These two applications nominally run on different computers,\n but sockets can also be used for interprocess communication on a single computer. \nApplications can create multiple sockets for communicating with each other.\n Sockets are bidirectional, meaning that either side of the connection is capable of both sending and receiving data. </p>\n"
},
{
"answer_id": 152510,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 4,
"selected": false,
"text": "<p>A socket is a communication endpoint. A socket is not directly related to the TCP/IP protocol family, it can be used with any protocol your system supports. The C socket API expects you to first get a blank socket object from the system that you can then either bind to a local socket address (to directly retrieve incoming traffic for connection-less protocols or to accept incoming connection requests for connection-oriented protocols) or that you can connect to a remote socket address (for either kind of protocol). You can even do both if you want to control both, the local socket address a socket is bound to and the remote socket address a socket is connected to. For connection-less protocols connecting a socket is even optional but if you don't do that, you'll have to also pass the destination address with every packet you want to send over the socket as how else would the socket know where to send this data to? Advantage is that you can use a single socket to send packets to different socket addresses. Once you have your socket configured and maybe even connected, consider it to be a bi-directional communication pipe. You can use it to pass data to some destination and some destination can use it to pass data back to you. What you write to a socket is send out and what has been received is available for reading.</p>\n<p>Ports on the other hand are something that only certain protocols of the TCP/IP protocol stack have. TCP and UDP packets have ports. A port is just a simple number. The combination of source port and destination port identify a communication channel between two hosts. E.g. you may have a server that shall be both, a simple HTTP server and a simple FTP server. If now a packet arrives for the address of that server, how would it know if that is a packet for the HTTP or the FTP server? Well, it will know so as the HTTP server will run on port 80 and the FTP server on port 21, so if the packet arrives with a destination port 80, it is for the HTTP server and not for the FTP server. Also the packet has a source port since without such a source port, a server could only have one connection to one IP address at a time. The source port makes it possible for a server to distinguish otherwise identical connections: they all have the same destination port, e.g. port 80, the same destination IP (the IP of the server), and the same source IP, as they all come from the same client, but as they have different source ports, the server can distinguish them from each other. And when the server sends back replies, it will do so to the port the request came from, that way the client can also distinguish different replies it receives from the same server.</p>\n"
},
{
"answer_id": 152521,
"author": "VoidPointer",
"author_id": 23424,
"author_profile": "https://Stackoverflow.com/users/23424",
"pm_score": 2,
"selected": false,
"text": "<p>A port denotes a communication endpoint in the TCP and UDP transports for the IP network protocol. A socket is a software abstraction for a communication endpoint commonly used in implementations of these protocols (socket API). An alternative implementation is the XTI/TLI API.</p>\n\n<p>See also:</p>\n\n<p>Stevens, W. R. 1998, UNIX Network Programming: Networking APIs: Sockets and XTI; Volume 1, Prentice Hall.<br>\nStevens, W. R., 1994, TCP/IP Illustrated, Volume 1: The Protocols, Addison-Wesley.</p>\n"
},
{
"answer_id": 152768,
"author": "Tall Jeff",
"author_id": 1553,
"author_profile": "https://Stackoverflow.com/users/1553",
"pm_score": 3,
"selected": false,
"text": "<p>Relative TCP/IP terminology which is what I assume is implied by the question. In layman's terms:</p>\n\n<p>A PORT is like the telephone number of a particular house in a particular zip code. The ZIP code of the town could be thought of as the IP address of the town and all the houses in that town.</p>\n\n<p>A SOCKET on the other hand is more like an established phone call between telephones of a pair of houses talking to each other. Those calls can be established between houses in the same town or two houses in different towns. It's that temporary established pathway between the pair of phones talking to each other that is the SOCKET.</p>\n"
},
{
"answer_id": 152863,
"author": "Peter Wone",
"author_id": 1715673,
"author_profile": "https://Stackoverflow.com/users/1715673",
"pm_score": 10,
"selected": false,
"text": "<h2>Summary</h2>\n<p><strong>A TCP socket is an endpoint <em>instance</em></strong> defined by an IP address and a port in the context of either a particular TCP connection or the listening state.</p>\n<p><strong>A port is a virtualisation identifier</strong> defining a service endpoint (as distinct from a service <em>instance</em> endpoint aka session identifier).</p>\n<p><strong>A TCP socket is <em>not</em> a connection</strong>, it is the endpoint of a specific connection.</p>\n<p><strong>There can be concurrent connections to a service endpoint</strong>, because a connection is identified by <em>both its local and remote</em> endpoints, allowing traffic to be routed to a specific service instance.</p>\n<p><strong>There can only be one listener socket for a given address/port combination</strong>.</p>\n<h2>Exposition</h2>\n<p>This was an interesting question that forced me to re-examine a number of things I thought I knew inside out. You'd think a name like "socket" would be self-explanatory: it was obviously chosen to evoke imagery of the endpoint into which you plug a network cable, there being strong functional parallels. Nevertheless, in network parlance the word "socket" carries so much baggage that a careful re-examination is necessary.</p>\n<p>In the broadest possible sense, a port is a point of ingress or egress. Although not used in a networking context, the French word <em>porte</em> literally means <em>door or gateway</em>, further emphasising the fact that ports are transportation endpoints whether you ship data or big steel containers.</p>\n<p>For the purpose of this discussion I will limit consideration to the context of TCP-IP networks. The OSI model is all very well but has never been completely implemented, much less widely deployed in high-traffic high-stress conditions.</p>\n<p>The combination of an IP address and a port is strictly known as an endpoint and is sometimes called a socket. This usage originates with RFC793, the original TCP specification.</p>\n<p>A TCP <em>connection</em> is defined by two endpoints aka <em>sockets</em>.</p>\n<p>An endpoint (socket) is defined by the combination of a network address and a <em>port</em> identifier. Note that address/port does <em>not</em> completely identify a socket (more on this later).</p>\n<p>The purpose of ports is to differentiate multiple endpoints on a given network address. You could say that a port is a virtualised endpoint. This virtualisation makes multiple concurrent connections on a single network interface possible.</p>\n<blockquote>\n<p>It is the socket pair (the 4-tuple\nconsisting of the client IP address,\nclient port number, server IP address,\nand server port number) that specifies\nthe two endpoints that uniquely\nidentifies each TCP connection in an\ninternet. (<em>TCP-IP Illustrated Volume 1</em>, W. Richard Stevens)</p>\n</blockquote>\n<p>In most C-derived languages, TCP connections are established and manipulated using methods on an instance of a Socket class. Although it is common to operate on a higher level of abstraction, typically an instance of a NetworkStream class, this generally exposes a reference to a socket object. To the coder this socket object appears to represent the connection because the connection is created and manipulated using methods of the socket object.</p>\n<p>In C#, to establish a TCP connection (to an existing listener) first you create a <em>TcpClient</em>. If you don't specify an endpoint to the <em>TcpClient</em> constructor it uses defaults - one way or another the local endpoint is defined. Then you invoke the <em>Connect</em>\nmethod on the instance you've created. This method requires a parameter describing the other endpoint.</p>\n<p>All this is a bit confusing and leads you to believe that a socket is a connection, which is bollocks. I was labouring under this misapprehension until Richard Dorman asked the question.</p>\n<p>Having done a lot of reading and thinking, I'm now convinced that it would make a lot more sense to have a class <em>TcpConnection</em> with a constructor that takes two arguments, <em>LocalEndpoint</em> and <em>RemoteEndpoint</em>. You could probably support a single argument <em>RemoteEndpoint</em> when defaults are acceptable for the local endpoint. This is ambiguous on multihomed computers, but the ambiguity can be resolved using the routing table by selecting the interface with the shortest route to the remote endpoint.</p>\n<p>Clarity would be enhanced in other respects, too. A socket is <em>not</em> identified by the combination of IP address and port:</p>\n<blockquote>\n<p>[...]TCP demultiplexes incoming segments using all four values that comprise the local and foreign addresses: destination IP address, destination port number, source IP address, and source port number. TCP cannot determine which process gets an incoming segment by looking at the destination port only. Also, the only one of the [various] endpoints at [a given port number] that will receive incoming connection requests is the one in the listen state. (p255, <em>TCP-IP Illustrated Volume 1</em>, W. Richard Stevens)</p>\n</blockquote>\n<p>As you can see, it is not just possible but quite likely for a network service to have numerous sockets with the same address/port, but only one listener socket on a particular address/port combination. Typical library implementations present a socket class, an instance of which is used to create and manage a connection. This is extremely unfortunate, since it causes confusion and has lead to widespread conflation of the two concepts.</p>\n<p>Hagrawal doesn't believe me (see comments) so here's a real sample. I connected a web browser to <a href=\"http://dilbert.com\" rel=\"noreferrer\">http://dilbert.com</a> and then ran <code>netstat -an -p tcp</code>. The last six lines of the output contain two examples of the fact that address and port are not enough to uniquely identify a socket. There are two distinct connections between 192.168.1.3 (my workstation) and 54.252.94.236:80 (the remote HTTP server)</p>\n<pre><code> TCP 192.168.1.3:63240 54.252.94.236:80 SYN_SENT\n TCP 192.168.1.3:63241 54.252.94.236:80 SYN_SENT\n TCP 192.168.1.3:63242 207.38.110.62:80 SYN_SENT\n TCP 192.168.1.3:63243 207.38.110.62:80 SYN_SENT\n TCP 192.168.1.3:64161 65.54.225.168:443 ESTABLISHED\n</code></pre>\n<p>Since a socket is the endpoint of a connection, there are two sockets with the address/port combination <code>207.38.110.62:80</code> and two more with the address/port combination <code>54.252.94.236:80</code>.</p>\n<p>I think Hagrawal's misunderstanding arises from my very careful use of the word "identifies". I mean "completely, unambiguously and uniquely identifies". In the above sample there are two endpoints with the address/port combination <code>54.252.94.236:80</code>. If all you have is address and port, you don't have enough information to tell these sockets apart. It's not enough information to <em>identify</em> a socket.</p>\n<h2>Addendum</h2>\n<p>Paragraph two of section 2.7 of RFC793 says</p>\n<blockquote>\n<p>A connection is fully specified by the pair of sockets at the ends. A\nlocal socket may participate in many connections to different foreign\nsockets.</p>\n</blockquote>\n<p>This definition of socket is not helpful from a programming perspective because it is not the same as a socket <em>object</em>, which is the endpoint of a particular connection. To a programmer, and most of this question's audience are programmers, this is a vital functional difference.</p>\n<p>@plugwash makes a salient observation.</p>\n<blockquote>\n<p>The fundamental problem is that the TCP RFC definition of socket is in conflict with the defintion of socket used by all major operating systems and libraries.</p>\n</blockquote>\n<p>By definition the RFC is correct. When a library misuses terminology, this does not supersede the RFC. Instead, it imposes a burden of responsibility on users of that library to understand both interpretations and to be careful with words and context. Where RFCs do not agree, the most recent and most directly applicable RFC takes precedence.</p>\n<h2>References</h2>\n<ol>\n<li><p><em>TCP-IP Illustrated Volume 1 The Protocols</em>, W. Richard Stevens, 1994 Addison Wesley</p>\n</li>\n<li><p><em><a href=\"https://www.rfc-editor.org/rfc/rfc793\" rel=\"noreferrer\">RFC793</a></em>, Information Sciences Institute, University of Southern California for DARPA</p>\n</li>\n<li><p><em><a href=\"https://www.rfc-editor.org/rfc/rfc147\" rel=\"noreferrer\">RFC147</a></em>, The Definition of a Socket, Joel M. Winett, Lincoln Laboratory</p>\n</li>\n</ol>\n"
},
{
"answer_id": 153015,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 5,
"selected": false,
"text": "<p>There seems to be a lot of answers equating socket with the connection between 2 PC's..which I think is absolutely incorrect. A socket has always been the <em>endpoint</em> on 1 PC, that may or may not be connected - surely we've all used listener or UDP sockets* at some point. The important part is that it's addressable and active. Sending a message to 1.1.1.1:1234 is not likely to work, as there is no socket defined for that endpoint.</p>\n\n<p>Sockets are protocol specific - so the implementation of uniqueness that both <a href=\"http://www.networksorcery.com/enp/protocol/tcp.htm\" rel=\"noreferrer\">TCP</a>/<a href=\"http://www.networksorcery.com/enp/protocol/ip.htm\" rel=\"noreferrer\">IP</a> and <a href=\"http://www.networksorcery.com/enp/protocol/udp.htm\" rel=\"noreferrer\">UDP</a>/<a href=\"http://www.networksorcery.com/enp/protocol/ip.htm\" rel=\"noreferrer\">IP</a> uses* (ipaddress:port), is different than eg., <a href=\"http://docsrv.sco.com/SDK_netware/IPX_Addressing.html\" rel=\"noreferrer\">IPX</a> (Network, Node, and...ahem, socket - but a different socket than is meant by the general \"socket\" term. IPX socket numbers are equivalent to IP ports). But, they all offer a unique addressable endpoint.</p>\n\n<p>Since IP has become the dominant protocol, a port (in networking terms) has become synonomous with either a UDP or TCP port number - which is a portion of the socket address.</p>\n\n<ul>\n<li><p>UDP is connection-less - meaning no virtual circuit between the 2 endpoints is ever created. However, we still refer to <a href=\"http://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-5.html\" rel=\"noreferrer\">UDP sockets</a> as the endpoint. The API functions make it clear that both are just different type of sockets - <code>SOCK_DGRAM</code> is UDP (just sending a message) and <code>SOCK_STREAM</code> is TCP (creating a virtual circuit).</p></li>\n<li><p>Technically, the IP header holds the IP Address, and the protocol on top of IP (UDP or TCP) holds the port number. This makes it possible to have other protocols (eg. <a href=\"http://www.networksorcery.com/enp/protocol/icmp.htm\" rel=\"noreferrer\">ICMP</a> that have no port numbers, but do have IP addressing information).</p></li>\n</ul>\n"
},
{
"answer_id": 402490,
"author": "Harty",
"author_id": 30303,
"author_profile": "https://Stackoverflow.com/users/30303",
"pm_score": 2,
"selected": false,
"text": "<p>In a broad sense,\nSocket - is just that, a socket, just like your electrical, cable or telephone socket. A point where \"requisite stuff\" (power, signal, information) can go out and come in from. It hides a lot of detailed stuff, which is not required for the use of the \"requisite stuff\". In software parlance, it provides a generic way of defining a mechanism of communication between two entities (those entities could be anything - two applications, two physically separate devices, User & Kernel space within an OS, etc)</p>\n\n<p>A Port is an endpoint discriminator. It differentiates one endpoint from another. At networking level, it differentiates one application from another, so that the networking stack can pass on information to the appropriate application.</p>\n"
},
{
"answer_id": 2153191,
"author": "Yufei Ren",
"author_id": 260685,
"author_profile": "https://Stackoverflow.com/users/260685",
"pm_score": -1,
"selected": false,
"text": "<p>A connection socket (fd) is presented for local address + local port + peer address + peer port. Process recv/send data via socket abstract.\nA listening socket (fd) is presented for local address + local listening port. Process can accept new connection via socket.</p>\n"
},
{
"answer_id": 10057986,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>Firsty, I think we should start with a little understanding of what constitutes getting a packet from A to B.</p>\n\n<p>A common definition for a network is the use of the <a href=\"http://en.wikipedia.org/wiki/OSI_model\">OSI Model</a> which separates a network out into a number of layers according to purpose. There are a few important ones, which we'll cover here:</p>\n\n<ul>\n<li>The <em>data link layer</em>. This layer is responsible for getting packets of data from one network device to another and is just above the layer that actually does the transmitting. It talks about MAC addresses and knows how to find hosts based on their MAC (hardware) address, but nothing more.</li>\n<li>The <em>network layer</em> is the layer that allows you to transport data across machines and over physical boundaries, such as physical devices. The network layer must essentially support an additional address based mechanism which relates somehow to the physical address; enter the Internet Protocol (IPv4). An IP address can get your packet from A to B over the internet, but knows nothing about how to traverse individual hops. This is handled by the layer above in accordance with routing information.</li>\n<li>The <em>transport layer</em>. This layer is responsible for defining the way information gets from A to B and any restrictions, checks or errors on that behaviour. For example, TCP adds additional information to a packet such that it is possible to deduce if packets have been lost.</li>\n</ul>\n\n<p>TCP contains, amongst other things, the concept of <a href=\"http://en.wikipedia.org/wiki/Transmission_Control_Protocol#TCP_ports\">ports</a>. These are effectively different data endpoints on the same IP address to which an Internet Socket (<code>AF_INET</code>) can bind. </p>\n\n<p>As it happens, <a href=\"http://en.wikipedia.org/wiki/TCP_and_UDP_port\">so too does UDP</a>, and other transport layer protocols. They don't technically <em>need</em> to feature ports, but these ports do provide a way for multiple applications in the layers above to use the same computer to receive (and indeed make) outgoing connections.</p>\n\n<p>Which brings us to the anatomy of a TCP or UDP connection. Each features a source port and address, and a target port and address. This is so that in any given session, the target application can respond, as well as receive, from the source.</p>\n\n<p>So ports are essentially a specification-mandated way of allowing multiple concurrent connections sharing the same address.</p>\n\n<p>Now, we need to take a look at how you communicate from an application point of view to the outside world. To do this, you need to kindly ask your operating system and since most OSes support the Berkeley Sockets way of doing things, we see we can create sockets involving ports from an application like this:</p>\n\n<pre><code>int fd = socket(AF_INET, SOCK_STREAM, 0); // tcp socket\nint fd = socket(AF_INET, SOCK_DGRAM, 0); // udp socket\n// later we bind...\n</code></pre>\n\n<p>Great! So in the <code>sockaddr</code> structures, we'll specify our port and bam! Job done! Well, almost, except:</p>\n\n<pre><code>int fd = socket(AF_UNIX, SOCK_STREAM, 0);\n</code></pre>\n\n<p>is also possible. Urgh, that's thrown a spanner in the works!</p>\n\n<p>Ok, well actually it hasn't. All we need to do is come up with some appropriate definitions:</p>\n\n<ul>\n<li>An internet socket is the combination of an IP address, a protocol and its associated port number on which a service may provide data. So tcp port 80, stackoverflow.com is an internet socket. </li>\n<li>An unix socket is an IPC endpoint represented in the file system, e.g. <code>/var/run/database.sock</code>.</li>\n<li>A socket API is a method of requesting an application be able to read and write data to a socket.</li>\n</ul>\n\n<p>Voila! That tidies things up. So in our scheme then, </p>\n\n<ul>\n<li>A port is a numeric identifier which, as part of a transport layer protocol, identifies the service number which should respond to the given request.</li>\n</ul>\n\n<p>So really a port is a subset of the requirements for forming an internet socket. Unfortunately, it just so happens that the meaning of the word socket has been applied to several different ideas. So I heartily advise you name your next project socket, just to add to the confusion ;)</p>\n"
},
{
"answer_id": 11782471,
"author": "RT_",
"author_id": 1572063,
"author_profile": "https://Stackoverflow.com/users/1572063",
"pm_score": 8,
"selected": false,
"text": "<p>A socket consists of three things:</p>\n\n<ol>\n<li>An IP address</li>\n<li>A transport protocol</li>\n<li>A port number</li>\n</ol>\n\n<p>A port is a number between 1 and 65535 inclusive that signifies a logical gate in a device.\nEvery connection between a client and server requires a unique socket.</p>\n\n<p>For example:</p>\n\n<ul>\n<li>1030 is a port.</li>\n<li>(10.1.1.2 , TCP , port 1030) is a socket.</li>\n</ul>\n"
},
{
"answer_id": 15418988,
"author": "Colin",
"author_id": 423068,
"author_profile": "https://Stackoverflow.com/users/423068",
"pm_score": 4,
"selected": false,
"text": "<p>After reading the excellent up-voted answers, I found that the following point needed emphasis for me, a newcomer to network programming:</p>\n\n<p>TCP-IP connections are bi-directional pathways connecting one address:port combination with another address:port combination. Therefore, whenever you open a connection from your local machine to a port on a remote server (say www.google.com:80), you are also associating a new port number on your machine with the connection, to allow the server to send things back to you, (e.g. 127.0.0.1:65234). It can be helpful to use netstat to look at your machine's connections:</p>\n\n<pre><code>> netstat -nWp tcp (on OS X)\nActive Internet connections\nProto Recv-Q Send-Q Local Address Foreign Address (state) \ntcp4 0 0 192.168.0.6.49871 17.172.232.57.5223 ESTABLISHED\n...\n</code></pre>\n"
},
{
"answer_id": 15479868,
"author": "Sylar",
"author_id": 1124895,
"author_profile": "https://Stackoverflow.com/users/1124895",
"pm_score": -1,
"selected": false,
"text": "<p>A port is an entity that is used by networking protocols to attain access to connected hosts. Ports could be application-specific or related to a certain communication medium. Different protocols use different ports to access the hosts, like HTTP uses port 80 or FTP uses port 23. You can assign user-defined port numbers in your application, but they should be above 1023. </p>\n\n<p>Ports open up the connection to the required host while sockets are an endpoint in an inter-network or an inter-process communication.\nSockets are assigned by APIs(Application Programming Interface) by the system. </p>\n\n<p>A more subtle difference can be made saying that, when a system is rebooted ports will be present while the sockets will be destroyed. </p>\n"
},
{
"answer_id": 17320677,
"author": "Omkar Ramtekkar",
"author_id": 831192,
"author_profile": "https://Stackoverflow.com/users/831192",
"pm_score": 2,
"selected": false,
"text": "<p>Already theoretical answers have been given to this question. I would like to give a practical example to this question, which will clear your understanding about Socket and Port.</p>\n\n<p>I found it <a href=\"http://www.dummies.com/how-to/content/network-basics-tcpudp-socket-and-port-overview.html\" rel=\"nofollow\">here</a></p>\n\n<blockquote>\n <p>This example will walk you thru the process of connecting to a website, such as Wiley. You would open your web browser (like Mozilla Firefox) and type www.wiley.com into the address bar. Your web browser uses a Domain Name System (DNS) server to look up the name www.wiley.com to identify its IP address is. For this example, the address is 192.0.2.100.</p>\n \n <p>Firefox makes a connection to the 192.0.2.100 address and to the port\n where the application layer web server is operating. Firefox knows\n what port to expect because it is a well-known port . The well-known\n port for a web server is TCP port 80.</p>\n \n <p>The destination socket that Firefox attempts to connect is written as\n socket:port, or in this example, 192.0.2.100:80. This is the server\n side of the connect, but the server needs to know where to send the\n web page you want to view in Mozilla Firefox, so you have a socket for\n the client side of the connection also.</p>\n \n <p>The client side connection is made up of your IP address, such as\n 192.168.1.25, and a randomly chosen dynamic port number. The socket associated with Firefox looks like 192.168.1.25:49175. Because web\n servers operate on TCP port 80, both of these sockets are TCP sockets,\n whereas if you were connecting to a server operating on a UDP port,\n both the server and client sockets would be UDP sockets.</p>\n</blockquote>\n"
},
{
"answer_id": 19400591,
"author": "Navneet Singh",
"author_id": 2885936,
"author_profile": "https://Stackoverflow.com/users/2885936",
"pm_score": 2,
"selected": false,
"text": "<p>Socket is an abstraction provided by kernel to user applications for data I/O. A socket type is defined by the protocol it's handling, an IPC communication etc. So if somebody creates a TCP socket he can do manipulations like reading data to socket and writing data to it by simple methods and the lower level protocol handling like TCP conversions and forwarding packets to lower level network protocols is done by the particular socket implementation in the kernel. The advantage is that user need not worry about handling protocol specific nitigrities and should just read and write data to socket like a normal buffer. Same is true in case of IPC, user just reads and writes data to socket and kernel handles all lower level details based on the type of socket created.</p>\n<p>Port together with IP is like providing an address to the socket, though its not necessary, but it helps in network communications.</p>\n"
},
{
"answer_id": 20563814,
"author": "kta",
"author_id": 539023,
"author_profile": "https://Stackoverflow.com/users/539023",
"pm_score": 5,
"selected": false,
"text": "<p>Generally, you will get a lot of theoretical but one of the easiest ways to differentiate these two concepts is as follows:</p>\n<p>In order to get a service, you need a service number. This service number is called a port. Simple as that.</p>\n<p>For example, the HTTP as a service is running on port 80.</p>\n<p>Now, many people can request the service, and a connection from client-server gets established. There will be a lot of connections. Each connection represents a client. In order to maintain each connection, the server creates a socket per connection to maintain its client.</p>\n"
},
{
"answer_id": 22494525,
"author": "Andy",
"author_id": 533549,
"author_profile": "https://Stackoverflow.com/users/533549",
"pm_score": 5,
"selected": false,
"text": "<p>Short brief answer.</p>\n\n<p>A <strong>port</strong> can be described as an <strong>internal address</strong> within a host that identifies a program or process.</p>\n\n<p>A <strong>socket</strong> can be described as a <strong>programming interface</strong> allowing a program to communicate with other programs or processes, on the internet, or locally. </p>\n"
},
{
"answer_id": 23031392,
"author": "yondoo",
"author_id": 1717907,
"author_profile": "https://Stackoverflow.com/users/1717907",
"pm_score": 3,
"selected": false,
"text": "<p>from <a href=\"http://docs.oracle.com/javase/tutorial/networking/sockets/definition.html\" rel=\"nofollow noreferrer\">Oracle Java Tutorial</a>:</p>\n\n<blockquote>\n <p>A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.</p>\n</blockquote>\n"
},
{
"answer_id": 24120147,
"author": "Krishna",
"author_id": 2545550,
"author_profile": "https://Stackoverflow.com/users/2545550",
"pm_score": 4,
"selected": false,
"text": "<p>A socket is a special type of file handle which is used by a process to request network services from the operating system.\nA socket address is the triple:\n{protocol, local-address, local-process} where the local process is identified by a port number.</p>\n\n<p>In the TCP/IP suite, for example:</p>\n\n<p>{tcp, 193.44.234.3, 12345}</p>\n\n<p>A conversation is the communication link between two processes thus depicting an association between two.\nAn association is the 5-tuple that completely specifies the two processes that comprise a connection:\n{protocol, local-address, local-process, foreign-address, foreign-process}</p>\n\n<p>In the TCP/IP suite, for example:</p>\n\n<p>{tcp, 193.44.234.3, 1500, 193.44.234.5, 21}</p>\n\n<p>could be a valid association.</p>\n\n<p>A half-association is either:\n{protocol, local-address, local-process}</p>\n\n<p>or</p>\n\n<p>{protocol, foreign-address, foreign-process}</p>\n\n<p>which specify each half of a connection.</p>\n\n<p>The half-association is also called a socket or a transport address. That is, a socket is an end point for communication that can be named and addressed in a network.\nThe socket interface is one of several application programming interfaces (APIs) to the communication protocols. Designed to be a generic communication programming interface, it was first introduced by the 4.2BSD UNIX system. Although it has not been standardized, it has become a de facto industry standard.</p>\n"
},
{
"answer_id": 28873658,
"author": "rasnjlee",
"author_id": 4635849,
"author_profile": "https://Stackoverflow.com/users/4635849",
"pm_score": -1,
"selected": false,
"text": "<p>A socket allows to the communication between two applications in a single \nmachine or two machine. actually it is like door. if the door opens there can\n be a connection between the process or application that are inside the door\n and outside the door. </p>\n\n<p>There are 4 types of sockets:</p>\n\n<ul>\n<li>stream sockets</li>\n<li>datagram sockets</li>\n<li>raw sockets</li>\n<li>sequential packet sockets.</li>\n</ul>\n\n<p>Sockets are mostly used in client-server applications. The port identifies different end points on a network address. It contains a numerical value. As overall a socket is a combination of a port and a network address.</p>\n"
},
{
"answer_id": 32103041,
"author": "MMacD",
"author_id": 1403742,
"author_profile": "https://Stackoverflow.com/users/1403742",
"pm_score": -1,
"selected": false,
"text": "<p>As simply as possible, there's no <em>physical</em> difference between a socket and a port, the way there is between, e.g., PATA and SATA. They're just bits of software reading and writing a NIC.</p>\n\n<p>A port is essentially a <em>public</em> socket, some of which are well-known/well-accepted, the usual example being 80, dedicated to HTTP. Anyone who wants to exchange traffic using a certain protocol, HTTP in this instance, canonically goes to port 80. Of course, 80 is not <em>physically</em> dedicated to HTTP (it's not physically anything, it's just a number, a logical value), and could be used on some particular machine for some other protocol ad libitum, as long as those attempting to connect know which protocol (which could be quite private) to use.</p>\n\n<p>A socket is essentially a <em>private</em> port, established for particular purposes known to the connecting parties but not necessarily known to anyone else. The underlying <em>transport layer</em> is usually TCP or UDP, but it doesn't have to be. The essential characteristic is that both ends know what's going on, whatever that might be.</p>\n\n<p>The key here is that when a connection request is received on some port, the reply handshake includes information about the socket created to service the particular requester. Subsequent communication takes place through that (private) socket connection, not the public port connection on which the service continues to listen for connection requests.</p>\n"
},
{
"answer_id": 32303691,
"author": "guest",
"author_id": 5283279,
"author_profile": "https://Stackoverflow.com/users/5283279",
"pm_score": 2,
"selected": false,
"text": "<p>A single port can have one or more sockets connected with different external IP's like a multiple electrical outlet.</p>\n\n<pre><code> TCP 192.168.100.2:9001 155.94.246.179:39255 ESTABLISHED 1312\n TCP 192.168.100.2:9001 171.25.193.9:61832 ESTABLISHED 1312\n TCP 192.168.100.2:9001 178.62.199.226:37912 ESTABLISHED 1312\n TCP 192.168.100.2:9001 188.193.64.150:40900 ESTABLISHED 1312\n TCP 192.168.100.2:9001 198.23.194.149:43970 ESTABLISHED 1312\n TCP 192.168.100.2:9001 198.49.73.11:38842 ESTABLISHED 1312\n</code></pre>\n"
},
{
"answer_id": 33070997,
"author": "inf3rno",
"author_id": 607033,
"author_profile": "https://Stackoverflow.com/users/607033",
"pm_score": 3,
"selected": false,
"text": "<p>The port was the easiest part, it is just a unique identifier for a socket. A socket is something processes can use to establish connections and to communicate with each other. Tall Jeff had a great telephone analogy which was not perfect, so I decided to fix it:</p>\n\n<ul>\n<li>ip and port ~ phone number</li>\n<li>socket ~ phone device</li>\n<li>connection ~ phone call</li>\n<li>establishing connection ~ calling a number</li>\n<li>processes, remote applications ~ people</li>\n<li>messages ~ speech</li>\n</ul>\n"
},
{
"answer_id": 37919535,
"author": "eRaisedToX",
"author_id": 5992618,
"author_profile": "https://Stackoverflow.com/users/5992618",
"pm_score": 7,
"selected": false,
"text": "<p><strong>With some analogy</strong></p>\n\n<p>Although a lot technical stuff is already given above for <strong>sockets</strong>...\nI would like to add my answer, just in case , <strong>if somebody still could not feel the difference between ip, port and sockets</strong></p>\n\n<p><strong>Consider a server S</strong>,</p>\n\n<p>and say <strong>person X,Y,Z</strong> need a service (say chat service) from that <strong>server S</strong></p>\n\n<p>then </p>\n\n<p><strong>IP address tells</strong> --> <strong><em>who?</strong> is that chat server 'S' that X,Y,Z want to contact</em></p>\n\n<p><em>okay, you got \"who is the server\"</em></p>\n\n<p>but suppose that server 'S' is providing some other services to other people as well,say <em>'S' provides storage services to person A,B,C</em></p>\n\n<p><em>then</em></p>\n\n<p><strong>port tells</strong> ---> <strong>which?</strong> service you <em>(X,Y,Z)</em> need i.e. chat service and not that storage service</p>\n\n<p><em>okay.., you make server to come to know that 'chat service' is what you want and not the storage</em></p>\n\n<p>but </p>\n\n<p>you are three and the <em>server might want to identify all the three differently</em></p>\n\n<p>there comes the <strong>socket</strong></p>\n\n<p>now <strong>socket tells</strong>--> <strong><em>which one?</strong> particular connection</em></p>\n\n<p>that is , say ,</p>\n\n<p><em>socket 1 for person X</em></p>\n\n<p><em>socket 2 for person Y</em></p>\n\n<p><em>and socket 3 for person Z</em></p>\n\n<p>I hope it helps someone who was still confused \n:)</p>\n"
},
{
"answer_id": 39066979,
"author": "Vishal S",
"author_id": 5378121,
"author_profile": "https://Stackoverflow.com/users/5378121",
"pm_score": 1,
"selected": false,
"text": "<p>I know that there are lot of explanations. But, there is one more easy way to understand with practical example. We all can connect to HTTP port 80, but does it mean only one user can connect to that port at a time?. The answer is obviously 'no'. Multiple users for multiple purposes can access HTTP port 80 but they still get proper response they are waiting for, from the server, can't they?. Now think about it for a minute, how?. \n Yes you are correct, its <strong>IP address</strong> that uniquely identifies different users who contacts for different purposes. If you would have read the previous answers before reaching here, you would know that IP address is a part of information that socket consists. Think about it, is it possible to have a communication without sockets?. The answer is 'Yes' but you cannot run more than one application in a port but we know that we are not a 'Dump' switch that runs on just hardware.</p>\n"
},
{
"answer_id": 39847362,
"author": "Ugnes",
"author_id": 6200830,
"author_profile": "https://Stackoverflow.com/users/6200830",
"pm_score": 3,
"selected": false,
"text": "<p>An application consists of pair of processes which communicate over the network (client-server pair). These processes send and receive messages, into and from the network through a software interface called <strong>socket</strong>. Considering the analogy presented in the book \"Computer Networking: Top Down Approach\". There is a house that wants to communicate with other house. Here, house is analogous to a process, and door to a socket. Sending process assumes that there is a infrastructure on the other side of the door that will transport the data to the destination. Once the message is arrived on the other side, it passes through receiver's door (socket) into the house (process). This illustration from the same book can help you:<br>\n<a href=\"https://i.stack.imgur.com/4APkp.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4APkp.png\" alt=\"enter image description here\"></a>\n<br>Sockets are part of transport layer, which provides logical communication to applications. This means that from application's point of view both hosts are directly connected to each other, even though there are numerous routers and/or switches between them. Thus a socket is not a connection itself, it's the end point of the connection. Transport layer protocols are implemented only on hosts, and not on intermediate routers.<br>\n<strong>Ports</strong> provide means of internal addressing to a machine. The primary purpose it to allow multiple processes to send and receive data over the network without interfering with other processes (their data). All sockets are provided with a port number. When a segment arrives to a host, the transport layer examines the destination port number of the segment. It then forwards the segment to the corresponding socket. This job of delivering the data in a transport layer segment to the correct socket is called <strong>de-multiplexing</strong>. The segment's data is then forwarded to the process attached to the socket.</p>\n"
},
{
"answer_id": 41834131,
"author": "Zaz",
"author_id": 405550,
"author_profile": "https://Stackoverflow.com/users/405550",
"pm_score": 4,
"selected": false,
"text": "<h1>A socket address is an IP address & port number</h1>\n<pre><code>123.132.213.231 # IP address\n :1234 # port number\n123.132.213.231:1234 # socket address\n</code></pre>\n<p>A connection occurs when 2 sockets are bound together.</p>\n"
},
{
"answer_id": 43345791,
"author": "Shridhar410",
"author_id": 6547748,
"author_profile": "https://Stackoverflow.com/users/6547748",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <blockquote>\n <p>Port and socket can be compared to the Bank Branch.</p>\n </blockquote>\n</blockquote>\n\n<p>The building number of the \"Bank\" is analogous to IP address.\nA bank has got different sections like:</p>\n\n<ol>\n<li>Savings account department</li>\n<li>Personal loan department</li>\n<li>Home loan department</li>\n<li>Grievance department</li>\n</ol>\n\n<p>So 1 (savings account department), 2 (personal loan department), 3 (home loan department) and 4 (grievance department) are ports.</p>\n\n<p>Now let us say you go to open a savings account, you go to the bank (IP address), then you go to \"savings account department\" (port number 1), then you meet one of the employees working under \"savings account department\". Let us call him SAVINGACCOUNT_EMPLOYEE1 for opening account.</p>\n\n<p>SAVINGACCOUNT_EMPLOYEE1 is your socket descriptor, so there may be \nSAVINGACCOUNT_EMPLOYEE1 to SAVINGACCOUNT_EMPLOYEEN. These are all socket descriptors.</p>\n\n<p>Likewise, other departments will be having employess working under them and they are analogous to socket.</p>\n"
},
{
"answer_id": 52932345,
"author": "Dražen G.",
"author_id": 9556832,
"author_profile": "https://Stackoverflow.com/users/9556832",
"pm_score": 2,
"selected": false,
"text": "<p>Socket is SW abstraction of networking endpoint, used as the interface to the application. In Java, C# it is represented by object, in Linux, Unix it is a file. </p>\n\n<p>Port is just a property of a socket you have specify if you want to establish a communication. To receieve packet from a socket you have to bind it to specific local port and NIC (with local IP address) or all NICs (INADDR_ANY is specified in the bind call). To send packet, you have to specify port and IP of the remote socket.</p>\n"
},
{
"answer_id": 54760661,
"author": "Mosab Shaheen",
"author_id": 2197108,
"author_profile": "https://Stackoverflow.com/users/2197108",
"pm_score": 5,
"selected": false,
"text": "<p>These are basic networking concepts so I will explain them in an easy yet a comprehensive way to understand in details.</p>\n\n<ul>\n<li><strong>A socket</strong> is like a telephone (i.e. end to end device for communication)</li>\n<li><strong>IP</strong> is like your telephone number (i.e. address for your socket)</li>\n<li><strong>Port</strong> is like the person you want to talk to (i.e. the service you want to order from that address)</li>\n<li>A socket can be a client or a server socket (i.e. in a company the telephone of the customer support is a server but a telephone in your home is mostly a client)</li>\n</ul>\n\n<p>So a socket in networking is a virtual communication device bound to a pair (ip , port) = (address , service). <br></p>\n\n<p><strong>Note:</strong> <br></p>\n\n<ul>\n<li>A machine, a computer, a host, a mobile, or a PC can have multiple addresses , multiple open ports, and thus multiple sockets. Like in an office you can have multiple telephones with multiple telephone numbers and multiple people to talk to. </li>\n<li>Existence of an open/active port necessitate that you must have a socket bound to it, because it is the socket that makes the port accessible. However, you may have unused ports for the time being.</li>\n<li>Also note, in a server socket you can bind it to (a port, a specific address of a machine) or to (a port, all addresses of a machine) as in the telephone you may connect many telephone lines (telephone numbers) to a telephone or one specific telephone line to a telephone and still you can reach a person through all these telephone lines or through a specific telephone line.</li>\n<li>You can not associate (bind) a socket with two ports as in the telephone usually you can not always have two people using the same telephone at the same time .</li>\n<li>Advanced: on the same machine you cannot have two sockets with same type (client, or server) and same port and ip. However, if you are a client you can open two connections, with two sockets, to a server because the local port in each of these client's sockets is different)</li>\n</ul>\n\n<p>Hope it clears you doubts</p>\n"
},
{
"answer_id": 68016370,
"author": "Jack",
"author_id": 1654526,
"author_profile": "https://Stackoverflow.com/users/1654526",
"pm_score": 1,
"selected": false,
"text": "<p>Uff.. too many people linking socket concept to a two-endpoints communication, mostly on TCP/IP protocol. But:</p>\n<ul>\n<li><strong>NO</strong> - Socket is not related to a two-endpoint communication. It's the local endpoint, which can or cannot be connected on the other side (Think about a server socket listening for incoming connection)</li>\n<li><strong>NO</strong> - Socket it's not strictly related to TCP/IP. It is defined with a protcol, which can be TCP/IP, but can be anything else. For example you can have socket that communicates over files. You can also implement a new protocol yourself to have a communication over USB lamp which sends data by flashing: that would still be a socket from the application point of view.</li>\n</ul>\n<p>Regarding the port concept it's correct what you read on other answers. Port is mostly intended to be the number value (2 bytes, 0-65535) in TCP or UDP packet. Just let me stress that TCP or UPD not necessarily are used on top of IP. So:</p>\n<ul>\n<li><strong>NO</strong> - it's not correct saying that port is part of TCP/IP or UDP/IP. It's part of TCP or UDP, or any other protocol which define and use it. IP has no knowledge of what a port is.</li>\n</ul>\n"
},
{
"answer_id": 73326629,
"author": "Tom Lever",
"author_id": 10028567,
"author_profile": "https://Stackoverflow.com/users/10028567",
"pm_score": -1,
"selected": false,
"text": "<p>Definitions of Port</p>\n<p>Vinton G. Cerf and Robert E. Kahn (May 1974). A Protocol for Packet Network Intercommunication. IEEE Transactions on Communications, Volume 22, Number 5. IEEE.</p>\n<p>A port is a unit of a "pair of [entities that] will exchange one or more messages over a period of time.”</p>\n<p>“… We could view the sequence of messages produced by one port as if it were embedded in an infinitely long stream of bytes... We emphasise that the sequence number associated with a given packet is unique only to the pair of ports that are communicating... Arriving packets are examined to determine for which port they are intended... Provision should be made for a destination process to specify that it is willing to LISTEN to a specific port or 'any' port."</p>\n<p>A "port is simply a designator of one... duplex... message stream... [among one or more] message streams... associated with a process."</p>\n<p>Information Sciences Institute: University of Southern California (September 1981). RFC 793: Transmission Control Protocol: DARPA Internet Program Protocol Specification.</p>\n<p>A port is one entity of one or more entities through which a process communicates via one or more communication streams with one or more other processes.</p>\n<p>"Since a process may need to distinguish among several communication streams between itself and another process (or processes), we imagine that each process may have a number of ports through which it communicates with the ports of other processes.”</p>\n<p>“The intent is that connection be allowed only between ports operating with exactly the same security and compartment values and at the higher of the precedence level requested by the two ports.”\n“Note this check is placed following the sequence check to prevent a segment from an old connection between these ports with a different security or precedence from causing an abort of the current connection.”</p>\n<p>“A port is an address that specifies which logical input or output channel of a process is associated with [a stream of] data.”\n"To allow for many processes within a single Host to use TCP communication facilities simultaneously, the TCP provides a set of addresses or ports within each host.”</p>\n<p>“The portion of a socket that specifies which logical input or output channel of a process is associated with the data.”</p>\n<p> \nDefinitions of Socket</p>\n<p>Oracle (2020). Class Socket. Java Platform, Standard Edition 7\nAPI Specification.</p>\n<p>"A socket is an endpoint for communication between two machines."</p>\n<p>Information Sciences Institute: University of Southern California (September 1981). RFC 793: Transmission Control Protocol: DARPA Internet Program Protocol Specification.</p>\n<p>A socket is a string consisting of an Internet address [i.e., the first eight-bit number (e.g., 123) of a network address (e.g., 123.45.78.0), a period, the second eight-bit number (e.g., 45) of the network address, a period, the third eight-bit number (e.g., 78) of the network address, a period, and a host address (e.g., 90)], a colon, and a TCP port (e.g., 1234). A socket is a unit of “A pair of [entities that] uniquely identify [a] connection[, and that] may be simultaneously used in multiple connections.”</p>\n<p>"To allow for many processes within a single Host to use TCP communication facilities simultaneously, the TCP provides a set of addresses or ports within each host. Concatenated with the network and host addresses from the internet communication layer, this forms a socket. A pair of sockets uniquely identifies each connection. That is, a socket may be simultaneously used in multiple connections."\n“To provide for unique addresses within each TCP, we concatenate an internet address identifying the TCP with a port identifier to create a socket which will be unique throughout all networks connected together.”</p>\n<p>“The reliability and flow control mechanisms described above require that TCPs initialize and maintain certain status information for each data stream. The combination of this information, including sockets, sequence numbers, and window sizes, is called a connection. Each connection is uniquely specified by a pair of sockets identifying its two sides.”</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199234/"
] |
This was a question raised by one of the software engineers in my organisation. I'm interested in the broadest definition.
|
Summary
-------
**A TCP socket is an endpoint *instance*** defined by an IP address and a port in the context of either a particular TCP connection or the listening state.
**A port is a virtualisation identifier** defining a service endpoint (as distinct from a service *instance* endpoint aka session identifier).
**A TCP socket is *not* a connection**, it is the endpoint of a specific connection.
**There can be concurrent connections to a service endpoint**, because a connection is identified by *both its local and remote* endpoints, allowing traffic to be routed to a specific service instance.
**There can only be one listener socket for a given address/port combination**.
Exposition
----------
This was an interesting question that forced me to re-examine a number of things I thought I knew inside out. You'd think a name like "socket" would be self-explanatory: it was obviously chosen to evoke imagery of the endpoint into which you plug a network cable, there being strong functional parallels. Nevertheless, in network parlance the word "socket" carries so much baggage that a careful re-examination is necessary.
In the broadest possible sense, a port is a point of ingress or egress. Although not used in a networking context, the French word *porte* literally means *door or gateway*, further emphasising the fact that ports are transportation endpoints whether you ship data or big steel containers.
For the purpose of this discussion I will limit consideration to the context of TCP-IP networks. The OSI model is all very well but has never been completely implemented, much less widely deployed in high-traffic high-stress conditions.
The combination of an IP address and a port is strictly known as an endpoint and is sometimes called a socket. This usage originates with RFC793, the original TCP specification.
A TCP *connection* is defined by two endpoints aka *sockets*.
An endpoint (socket) is defined by the combination of a network address and a *port* identifier. Note that address/port does *not* completely identify a socket (more on this later).
The purpose of ports is to differentiate multiple endpoints on a given network address. You could say that a port is a virtualised endpoint. This virtualisation makes multiple concurrent connections on a single network interface possible.
>
> It is the socket pair (the 4-tuple
> consisting of the client IP address,
> client port number, server IP address,
> and server port number) that specifies
> the two endpoints that uniquely
> identifies each TCP connection in an
> internet. (*TCP-IP Illustrated Volume 1*, W. Richard Stevens)
>
>
>
In most C-derived languages, TCP connections are established and manipulated using methods on an instance of a Socket class. Although it is common to operate on a higher level of abstraction, typically an instance of a NetworkStream class, this generally exposes a reference to a socket object. To the coder this socket object appears to represent the connection because the connection is created and manipulated using methods of the socket object.
In C#, to establish a TCP connection (to an existing listener) first you create a *TcpClient*. If you don't specify an endpoint to the *TcpClient* constructor it uses defaults - one way or another the local endpoint is defined. Then you invoke the *Connect*
method on the instance you've created. This method requires a parameter describing the other endpoint.
All this is a bit confusing and leads you to believe that a socket is a connection, which is bollocks. I was labouring under this misapprehension until Richard Dorman asked the question.
Having done a lot of reading and thinking, I'm now convinced that it would make a lot more sense to have a class *TcpConnection* with a constructor that takes two arguments, *LocalEndpoint* and *RemoteEndpoint*. You could probably support a single argument *RemoteEndpoint* when defaults are acceptable for the local endpoint. This is ambiguous on multihomed computers, but the ambiguity can be resolved using the routing table by selecting the interface with the shortest route to the remote endpoint.
Clarity would be enhanced in other respects, too. A socket is *not* identified by the combination of IP address and port:
>
> [...]TCP demultiplexes incoming segments using all four values that comprise the local and foreign addresses: destination IP address, destination port number, source IP address, and source port number. TCP cannot determine which process gets an incoming segment by looking at the destination port only. Also, the only one of the [various] endpoints at [a given port number] that will receive incoming connection requests is the one in the listen state. (p255, *TCP-IP Illustrated Volume 1*, W. Richard Stevens)
>
>
>
As you can see, it is not just possible but quite likely for a network service to have numerous sockets with the same address/port, but only one listener socket on a particular address/port combination. Typical library implementations present a socket class, an instance of which is used to create and manage a connection. This is extremely unfortunate, since it causes confusion and has lead to widespread conflation of the two concepts.
Hagrawal doesn't believe me (see comments) so here's a real sample. I connected a web browser to <http://dilbert.com> and then ran `netstat -an -p tcp`. The last six lines of the output contain two examples of the fact that address and port are not enough to uniquely identify a socket. There are two distinct connections between 192.168.1.3 (my workstation) and 54.252.94.236:80 (the remote HTTP server)
```
TCP 192.168.1.3:63240 54.252.94.236:80 SYN_SENT
TCP 192.168.1.3:63241 54.252.94.236:80 SYN_SENT
TCP 192.168.1.3:63242 207.38.110.62:80 SYN_SENT
TCP 192.168.1.3:63243 207.38.110.62:80 SYN_SENT
TCP 192.168.1.3:64161 65.54.225.168:443 ESTABLISHED
```
Since a socket is the endpoint of a connection, there are two sockets with the address/port combination `207.38.110.62:80` and two more with the address/port combination `54.252.94.236:80`.
I think Hagrawal's misunderstanding arises from my very careful use of the word "identifies". I mean "completely, unambiguously and uniquely identifies". In the above sample there are two endpoints with the address/port combination `54.252.94.236:80`. If all you have is address and port, you don't have enough information to tell these sockets apart. It's not enough information to *identify* a socket.
Addendum
--------
Paragraph two of section 2.7 of RFC793 says
>
> A connection is fully specified by the pair of sockets at the ends. A
> local socket may participate in many connections to different foreign
> sockets.
>
>
>
This definition of socket is not helpful from a programming perspective because it is not the same as a socket *object*, which is the endpoint of a particular connection. To a programmer, and most of this question's audience are programmers, this is a vital functional difference.
@plugwash makes a salient observation.
>
> The fundamental problem is that the TCP RFC definition of socket is in conflict with the defintion of socket used by all major operating systems and libraries.
>
>
>
By definition the RFC is correct. When a library misuses terminology, this does not supersede the RFC. Instead, it imposes a burden of responsibility on users of that library to understand both interpretations and to be careful with words and context. Where RFCs do not agree, the most recent and most directly applicable RFC takes precedence.
References
----------
1. *TCP-IP Illustrated Volume 1 The Protocols*, W. Richard Stevens, 1994 Addison Wesley
2. *[RFC793](https://www.rfc-editor.org/rfc/rfc793)*, Information Sciences Institute, University of Southern California for DARPA
3. *[RFC147](https://www.rfc-editor.org/rfc/rfc147)*, The Definition of a Socket, Joel M. Winett, Lincoln Laboratory
|
152,462 |
<p>I need to run a Java application, which we are trying to port to Java 6, on an NT box.</p>
<p>I manage to run java 5 on it (although not officially supported), but when I try to run java 6 I get the following error:</p>
<pre><code>Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Program Files\Java\jre1.6.0_05\bin\awt.dll: The specified procedure could not be found
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(Unknown Source)
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.loadLibrary0(Unknown Source)
at java.lang.System.loadLibrary(Unknown Source)
at sun.security.action.LoadLibraryAction.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.awt.NativeLibLoader.loadLibraries(Unknown Source)
at sun.awt.DebugHelper.<clinit>(Unknown Source)
at java.awt.EventQueue.<clinit>(Unknown Source)
at javax.swing.SwingUtilities.invokeLater(Unknown Source)
at ui.sequencer.test.WindowTest.main(WindowTest.java:136)
</code></pre>
<p>Anybody has any idea how to solve this?</p>
<p>This persists even when I move the java executables to another directory with no spaces in its name.</p>
<p>p.s.
I know, I should upgrade, but it's not up to me or my company - this is a very very bug huge gigantic company we work with, and they intend to keep NT for another 5 years.</p>
|
[
{
"answer_id": 152495,
"author": "Jacek Szymański",
"author_id": 23242,
"author_profile": "https://Stackoverflow.com/users/23242",
"pm_score": 1,
"selected": false,
"text": "<p>Java SE 6 <a href=\"http://java.sun.com/javase/6/webnotes/install/system-configurations.html\" rel=\"nofollow noreferrer\">requires</a> at least Windows 2000.</p>\n"
},
{
"answer_id": 152607,
"author": "Roel Spilker",
"author_id": 12634,
"author_profile": "https://Stackoverflow.com/users/12634",
"pm_score": 1,
"selected": false,
"text": "<p>I you are not using a GUI, for instance AWT, Swing or SWT, you could try starting you application in headless mode. See <a href=\"http://java.sun.com/developer/technicalArticles/J2SE/Desktop/headless/\" rel=\"nofollow noreferrer\">http://java.sun.com/developer/technicalArticles/J2SE/Desktop/headless/</a> for more information. To start java in headless mode, use <code>java -Djava.awt.headless=true</code> </p>\n\n<p>It would take care of the UnsatisfiedLinkError. I don't know if that's the only obstacle though.</p>\n"
},
{
"answer_id": 166060,
"author": "Michael Bar-Sinai",
"author_id": 11699,
"author_profile": "https://Stackoverflow.com/users/11699",
"pm_score": 2,
"selected": false,
"text": "<p>OK, Thanks for all the viewers and to @Roel Spiker and @Partyzant for their answers.</p>\n\n<p><strong>It can't be done.</strong> Not unless you install windows2000 on the NT box. This is because awt.dll fr J6SE uses new methods in User32.dll, which is part of the windows OS (linked to kernel.dll et al). Use the dll dependency walker and see for yourself.\nAnother possible solution is to alter OpenJDK slightly to use other methods available in windows NT.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11699/"
] |
I need to run a Java application, which we are trying to port to Java 6, on an NT box.
I manage to run java 5 on it (although not officially supported), but when I try to run java 6 I get the following error:
```
Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Program Files\Java\jre1.6.0_05\bin\awt.dll: The specified procedure could not be found
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(Unknown Source)
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.loadLibrary0(Unknown Source)
at java.lang.System.loadLibrary(Unknown Source)
at sun.security.action.LoadLibraryAction.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.awt.NativeLibLoader.loadLibraries(Unknown Source)
at sun.awt.DebugHelper.<clinit>(Unknown Source)
at java.awt.EventQueue.<clinit>(Unknown Source)
at javax.swing.SwingUtilities.invokeLater(Unknown Source)
at ui.sequencer.test.WindowTest.main(WindowTest.java:136)
```
Anybody has any idea how to solve this?
This persists even when I move the java executables to another directory with no spaces in its name.
p.s.
I know, I should upgrade, but it's not up to me or my company - this is a very very bug huge gigantic company we work with, and they intend to keep NT for another 5 years.
|
OK, Thanks for all the viewers and to @Roel Spiker and @Partyzant for their answers.
**It can't be done.** Not unless you install windows2000 on the NT box. This is because awt.dll fr J6SE uses new methods in User32.dll, which is part of the windows OS (linked to kernel.dll et al). Use the dll dependency walker and see for yourself.
Another possible solution is to alter OpenJDK slightly to use other methods available in windows NT.
|
152,469 |
<p>I want to make a login system using ASP.NET (MVC).</p>
<p>On the internet, I found some bad examples that involved SQL in Click events. Other information pointed to the ASP.NET built-in membership provider.</p>
<p>However, I want to roll my own. I don't want to use the built-in membership provider, as it only seems to work on MS SQL, and I don't like the idea of having a few foreign tables in my database.</p>
<p>I could probably think of something, but I need a few pointers in the right direction. It does not have to be high-security, but just regular common-sense security.</p>
<p>And I have a few direct questions:</p>
<ol>
<li><p>A lot of systems seem to have the Session ID stored in a user table. I guess this is to tie a session to a user to prevent hijacking. Do check this every time a user enters a page? And what do I do if the session expires?</p></li>
<li><p>Hashing, salting, what does it do? I know of MD5 hashing and I have used it before. But not salting.</p></li>
<li><p>Best practices for cookies?</p></li>
</ol>
|
[
{
"answer_id": 152513,
"author": "Peter Marshall",
"author_id": 4692,
"author_profile": "https://Stackoverflow.com/users/4692",
"pm_score": -1,
"selected": false,
"text": "<p>I would avoid the whole issue and use openid. There is a library available that you can use directly. \n<a href=\"http://blog.wekeroad.com/blog/my-mvc-starter-template/\" rel=\"nofollow noreferrer\">Here is a link to a blog post about putting this in place</a></p>\n"
},
{
"answer_id": 152523,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 4,
"selected": true,
"text": "<p>I dont know about best practices but I can tell you what I do. Its not hitech security but it does the job.</p>\n\n<p>I use forms authentication. I receive the password secured with ssl via a textbox on the login page. I take that password and hash it. (Hashing is like one way encryption, you can get hash code that cant be reversed back to the password). I take that hash and compare it to the users hash in the database. If the hash's match i use asp.nets built in authentication handling, which handles cookies for me.</p>\n\n<p>The FormsAuthentication class has methods available to do this fo you, such as SetAuthCookie and RedirectFromLogin. they will set the cookie and mark them as authenticated. The cookie asp.net uses is encrypted. I cant speak for its security level though, but its in fairly common use.</p>\n\n<p>In my class i do the password check and use formsauth to handle the rest:</p>\n\n<pre><code>if(SecurityHelper.LoginUser(txtUsername.Text, txtPassword.Text))\n{ \n FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);\n}\n</code></pre>\n"
},
{
"answer_id": 152527,
"author": "axel_c",
"author_id": 20272,
"author_profile": "https://Stackoverflow.com/users/20272",
"pm_score": 2,
"selected": false,
"text": "<p>You can implement your own membership provider using the ASP.NET infrastructure, see <a href=\"http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider.aspx\" rel=\"nofollow noreferrer\">MSDN docs for MemberShipProvider class</a>.</p>\n"
},
{
"answer_id": 152590,
"author": "DaveF",
"author_id": 17579,
"author_profile": "https://Stackoverflow.com/users/17579",
"pm_score": 2,
"selected": false,
"text": "<p>The built in provider works well. It does actually work with MySQL, although I found it not to be as straight forward as the MS SQL version. If you can use then do, it'll save you hours of work. </p>\n\n<p>If you need to use another data store then I concur with axel_c, if I was going to roll my own then I'd write a membership provider as per MS specification. It will make the code more maintainable for any developers following you.</p>\n"
},
{
"answer_id": 152630,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": -1,
"selected": false,
"text": "<p>A disadvantage of the Membership Provider by microsoft is that you can't use it in a domain driven approach. If you want to, you can create your own user object with your own password hash and still use the authentication cookies provided by Microsoft. Using these authentication cookies means that you don't have to manage the session IDs yourself.</p>\n\n<pre><code>public void SignIn(User user)\n {\n FormsAuthentication.SignOut();\n var ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now.AddMinutes(30), expires, alse, null);\n var encryptedTicket = FormsAuthentication.Encrypt(ticket);\n var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)\n {\n Expires = ticket.Expiration\n };\n\n httpContextProvider.GetCurrentHttpContext().Response.Cookies.Add(authCookie);\n }\n\n public void SignOut()\n {\n FormsAuthentication.SignOut();\n }\n</code></pre>\n\n<p>I use my own user object and tables. \nI store my passwords hashed in the usertable with a unique salt per user.\nThis is secure, easy to implement and it will fit in your design.\nYour database table won't be polluted by Microsofts membership provider crap.</p>\n"
},
{
"answer_id": 152679,
"author": "Jarrett Meyer",
"author_id": 5834,
"author_profile": "https://Stackoverflow.com/users/5834",
"pm_score": 2,
"selected": false,
"text": "<p>Salting is the practice of adding a unqiue string of characters to whatever is being hashed. Suppose <code>mySalt = abc123</code> and my password is <code>passwd</code>. In PHP, I would use <code>hashResult = md5(mySalt + password)</code>.</p>\n\n<p>Suppose the string is intercepted. You try to match the string, but you end up matching gibberish because the password was salted before encrypted. Just remember that whatever you use for salt must be continuous throughout the application. If you salt the password before storage, you must compare the hashed, salted password to the DB.</p>\n"
},
{
"answer_id": 152928,
"author": "Ken Ray",
"author_id": 12253,
"author_profile": "https://Stackoverflow.com/users/12253",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the built in SQL membership provider - and you could set up a dedicated \"user access\" database if you don't want the .Net membership tables within your database - just specify that in the connection string.</p>\n\n<p>THe advantage with the provider model is at the application level, the code is independent of what particular authentication store you have used.</p>\n\n<p>There are a good series of tutirials on the asp.net site:</p>\n\n<p><a href=\"http://www.asp.net/learn/security/\" rel=\"nofollow noreferrer\" title=\"Security Tutorials\">link text</a></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to make a login system using ASP.NET (MVC).
On the internet, I found some bad examples that involved SQL in Click events. Other information pointed to the ASP.NET built-in membership provider.
However, I want to roll my own. I don't want to use the built-in membership provider, as it only seems to work on MS SQL, and I don't like the idea of having a few foreign tables in my database.
I could probably think of something, but I need a few pointers in the right direction. It does not have to be high-security, but just regular common-sense security.
And I have a few direct questions:
1. A lot of systems seem to have the Session ID stored in a user table. I guess this is to tie a session to a user to prevent hijacking. Do check this every time a user enters a page? And what do I do if the session expires?
2. Hashing, salting, what does it do? I know of MD5 hashing and I have used it before. But not salting.
3. Best practices for cookies?
|
I dont know about best practices but I can tell you what I do. Its not hitech security but it does the job.
I use forms authentication. I receive the password secured with ssl via a textbox on the login page. I take that password and hash it. (Hashing is like one way encryption, you can get hash code that cant be reversed back to the password). I take that hash and compare it to the users hash in the database. If the hash's match i use asp.nets built in authentication handling, which handles cookies for me.
The FormsAuthentication class has methods available to do this fo you, such as SetAuthCookie and RedirectFromLogin. they will set the cookie and mark them as authenticated. The cookie asp.net uses is encrypted. I cant speak for its security level though, but its in fairly common use.
In my class i do the password check and use formsauth to handle the rest:
```
if(SecurityHelper.LoginUser(txtUsername.Text, txtPassword.Text))
{
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
}
```
|
152,483 |
<p>Is there a way to print all methods of an object in JavaScript?</p>
|
[
{
"answer_id": 152499,
"author": "WalkingRandomly",
"author_id": 1856916,
"author_profile": "https://Stackoverflow.com/users/1856916",
"pm_score": 1,
"selected": false,
"text": "<p>From <a href=\"http://www.javascriptkit.com/jsref/looping.shtml\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<p>Example 1: This example writes out all the properties of the \"navigator\" object, plus their values:</p>\n\n<pre><code>for (var myprop in navigator){\n document.write(myprop+\": \"+navigator[myprop]+\"<br>\")\n}\n</code></pre>\n\n<p>Just replace 'navigator' with whatever object you are interested in and you should be good to go.</p>\n\n<p>As mentioned by Anthony in the comments section - This returns all attributes not just methods as the question asked for.</p>\n\n<p>Oops! That'll teach me to try and answer a question in a language I don't know. Still, I think the code is useful - just not what was required.</p>\n"
},
{
"answer_id": 152554,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 2,
"selected": false,
"text": "<p>Take a gander at this code:-</p>\n\n<pre><code>function writeLn(s)\n{\n //your code to write a line to stdout\n WScript.Echo(s)\n}\n\nfunction Base() {}\nBase.prototype.methodA = function() {}\nBase.prototype.attribA = \"hello\"\n\nvar derived = new Base()\nderived.methodB = function() {}\nderived.attribB = \"world\";\n\nfunction getMethods(obj)\n{\n var retVal = {}\n\n for (var candidate in obj)\n {\n if (typeof(obj[candidate]) == \"function\")\n retVal[candidate] = {func: obj[candidate], inherited: !obj.hasOwnProperty(candidate)}\n }\n return retVal\n}\n\nvar result = getMethods(derived)\nfor (var name in result)\n{\n writeLn(name + \" is \" + (result[name].inherited ? \"\" : \"not\") + \" inherited\")\n}\n</code></pre>\n\n<p>The getMethod function returns the set of methods along with whether the method is one that has been inherited from a prototype.</p>\n\n<p>Note that if you intend to use this on objects that are supplied from the context such as browser/DOM object then it won't work IE.</p>\n"
},
{
"answer_id": 152564,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 0,
"selected": false,
"text": "<p>Since methods in JavaScript are just properties that are functions, the for..in loop will enumerate them with an exception - it won't enumerate built-in methods. As far as I know, there is no way to enumerate built-in methods. And you can't declare your own methods or properties on an object that aren't enumerable this way.</p>\n"
},
{
"answer_id": 152573,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 8,
"selected": true,
"text": "<p>Sure:</p>\n\n<pre><code>function getMethods(obj) {\n var result = [];\n for (var id in obj) {\n try {\n if (typeof(obj[id]) == \"function\") {\n result.push(id + \": \" + obj[id].toString());\n }\n } catch (err) {\n result.push(id + \": inaccessible\");\n }\n }\n return result;\n}\n</code></pre>\n\n<p>Using it:</p>\n\n<pre><code>alert(getMethods(document).join(\"\\n\"));\n</code></pre>\n"
},
{
"answer_id": 38848631,
"author": "Gianluca Esposito",
"author_id": 843493,
"author_profile": "https://Stackoverflow.com/users/843493",
"pm_score": 3,
"selected": false,
"text": "<p>Here is an <code>ES6</code> sample.</p>\n\n<pre><code>// Get the Object's methods names:\nfunction getMethodsNames(obj = this) {\n return Object.keys(obj)\n .filter((key) => typeof obj[key] === 'function');\n}\n\n// Get the Object's methods (functions):\nfunction getMethods(obj = this) {\n return Object.keys(obj)\n .filter((key) => typeof obj[key] === 'function')\n .map((key) => obj[key]);\n}\n</code></pre>\n\n<p><code>obj = this</code> is an ES6 default parameter, you can pass in an Object or it will default to <code>this</code>.</p>\n\n<p><code>Object.keys</code> returns an Array of the <code>Object</code>'s own enumerable properties.\nOver the <code>window</code> Object it will return <code>[..., 'localStorage', ...'location']</code>.</p>\n\n<p><code>(param) => ...</code> is an ES6 arrow function, it's a shorthand for</p>\n\n<pre><code>function(param) {\n return ...\n}\n</code></pre>\n\n<p>with an implicit return.</p>\n\n<p><code>Array.filter</code> creates a new array with all elements that pass the test (<code>typeof obj[key] === 'function'</code>).</p>\n\n<p><code>Array.map</code> creates a new array with the results of calling a provided function on every element in this array (return <code>obj[key]</code>).</p>\n"
},
{
"answer_id": 46610382,
"author": "mrded",
"author_id": 1264409,
"author_profile": "https://Stackoverflow.com/users/1264409",
"pm_score": 4,
"selected": false,
"text": "<p>If you just want to look what is inside an object, you can print all object's keys. Some of them can be variables, some - methods.</p>\n\n<p>The method is not very accurate, however it's really quick:</p>\n\n<pre><code>console.log(Object.keys(obj));\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21132/"
] |
Is there a way to print all methods of an object in JavaScript?
|
Sure:
```
function getMethods(obj) {
var result = [];
for (var id in obj) {
try {
if (typeof(obj[id]) == "function") {
result.push(id + ": " + obj[id].toString());
}
} catch (err) {
result.push(id + ": inaccessible");
}
}
return result;
}
```
Using it:
```
alert(getMethods(document).join("\n"));
```
|
152,487 |
<p>There is a MSBuild script, that includes number if Delphi and C# projects, unit tests etc. </p>
<p>The problem is: how to mark build failed if warnings were raised (for testing purposes, not for release builds)? Using LogError instead of LogWarning in custom tasks seems to be not a good option, because the build should test as much as it's able (until real error) to report as much warnings as possible in a time (build project is using in CruiseControl.NET).</p>
<p>May be, the solution is to create my own logger that would store warnings flag inside, but I cannot find if there is a way to read this flag in the end of build?</p>
<p>P.S. There is no problem to fail the build immediately after receiving a warning (Delphi compiler output is processed by custom task, and /warnaserror could be used for C#), but the desired behavior is "build everything; collect all warnings; fail the build" to report about all warnings, not only about the first one.</p>
<p><strong>P.P.S. As far as I really need not number of warnings, but just flag of their presence, I decided to simplify signaling mechanism, and use trivial Mutex instead of shared memory. Code is below:</strong></p>
<pre><code>using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Threading;
namespace Intrahealth.Build.WarningLogger
{
public sealed class WarningLoggerCheck : Task
{
public override bool Execute()
{
Log.LogMessage("WarningLoggerCheck:" + mutexName + "...");
result = false;
Mutex m = null;
try
{
m = Mutex.OpenExisting(mutexName);
}
catch (WaitHandleCannotBeOpenedException)
{
result = true;
}
catch (Exception)
{
}
if (result)
Log.LogMessage("WarningLoggerCheck PASSED");
else
Log.LogError("Build log contains warnings. Build is FAILED");
return result;
}
private bool result = true;
[Output]
public bool Result
{
get { return result; }
}
private string mutexName = "WarningLoggerMutex";
public string MutexName
{
get { return mutexName; }
set { mutexName = value ?? "WarningLoggerMutex"; }
}
}
public class WarningLogger : Logger
{
internal static int warningsCount = 0;
private string mutexName = String.Empty;
private Mutex mutex = null;
public override void Initialize(IEventSource eventSource)
{
eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
}
private void SetMutex()
{
if (mutexName == String.Empty)
{
mutexName = "WarningLoggerMutex";
if (this.Parameters != null && this.Parameters != String.Empty)
{
mutexName = this.Parameters;
}
}
mutex = new Mutex(false, mutexName);
}
void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
{
if (e.Message != null && e.Message.Contains("MSB3146"))
return;
if (e.Code != null && e.Code.Equals("MSB3146"))
return;
if (warningsCount == 0)
SetMutex();
warningsCount++;
}
}
}
</code></pre>
|
[
{
"answer_id": 152524,
"author": "Jason Stangroome",
"author_id": 20819,
"author_profile": "https://Stackoverflow.com/users/20819",
"pm_score": 1,
"selected": false,
"text": "<p>The C# compiler (csc.exe) has a /warnaserror switch will will treat warnings as errors and fail the build. This is also available as a setting in the .csproj file. I assume Delphi has a similar ability.</p>\n"
},
{
"answer_id": 152538,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 1,
"selected": false,
"text": "<pre><code>msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release >> %MrB-BUILDLOG%\nfindstr /r /c:\"[1-9][0-9]* Error(s)\" >> %MrB-BUILDLOG%\nif not errorlevel 1 (\n echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-BUILDLOG%\n) else (\n findstr /r /c:\"[1-9][0-9]* Warning(s)\" >> %MrB-BUILDLOG%\n if not errorlevel 1 (\n echo ERROR: sending notification email for build warnings in '%~nx1'. >>\n</code></pre>\n\n<p>%MrB-BUILDLOG%\n ) else (\n echo Successful build of '%~nx1'. >> %MrB-BUILDLOG%\n )\n )</p>\n"
},
{
"answer_id": 152685,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 4,
"selected": true,
"text": "<p>AFAIK MSBuild has no built-in support to retrieve the warning count at a given point of the build script. You can however follow these steps to achieve this goal:</p>\n\n<ol>\n<li>Create a custom logger that listens for the warning event and counts the number of warnings</li>\n<li>Create a custom task that exposes an [Output] WarningCount property</li>\n<li>The custom task gets somehow the value of the warning count from the custom logger</li>\n</ol>\n\n<p>The most difficult step is step 3. For this there are several options and you can freely search them under IPC - Inter Process Comunication. Follows a working example of how you can achieve this. Each item is a different <em>Class Library</em>.</p>\n\n<p><strong>SharedMemory</strong></p>\n\n<p><a href=\"http://weblogs.asp.net/rosherove/archive/2003/05/01/6295.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/rosherove/archive/2003/05/01/6295.aspx</a></p>\n\n<blockquote>\n <p>I've created a wrapper for named\n shared memory that was part of a\n larger project. It basically allows\n serialized types and object graphs to\n be stored in and retrieved from shared\n memory (including as you'd expect\n cross process). Whether the larger\n project ever gets completed is another\n matter ;-).</p>\n</blockquote>\n\n<p><strong>SampleLogger</strong></p>\n\n<p>Implements the custom logger that keeps track of the warning count.</p>\n\n<pre><code>namespace SampleLogger\n{\n using System;\n using Microsoft.Build.Utilities;\n using Microsoft.Build.Framework;\n using DM.SharedMemory;\n\n public class MySimpleLogger : Logger\n {\n private Segment s;\n private int warningCount;\n\n public override void Initialize(IEventSource eventSource)\n {\n eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);\n\n this.s = new Segment(\"MSBuildMetadata\", SharedMemoryCreationFlag.Create, 65535);\n this.s.SetData(this.warningCount.ToString());\n }\n\n void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)\n {\n this.warningCount++;\n this.s.SetData(this.warningCount.ToString());\n }\n\n public override void Shutdown()\n {\n this.s.Dispose();\n base.Shutdown();\n }\n }\n}\n</code></pre>\n\n<p><strong>SampleTasks</strong></p>\n\n<p>Implements the custom task that reads the number of warnings raised in the MSbuild project. The custom task reads from the shared memory written by the custom logger implemented in class library <em>SampleLogger</em>.</p>\n\n<pre><code>namespace SampleTasks\n{\n using System;\n using Microsoft.Build.Utilities;\n using Microsoft.Build.Framework;\n using DM.SharedMemory;\n\n public class BuildMetadata : Task\n {\n public int warningCount;\n\n [Output]\n public int WarningCount\n {\n get\n {\n Segment s = new Segment(\"MSBuildMetadata\", SharedMemoryCreationFlag.Attach, 0);\n int warningCount = Int32.Parse(s.GetData() as string);\n return warningCount;\n }\n }\n\n public override bool Execute()\n {\n return true;\n }\n }\n}\n</code></pre>\n\n<p>Going for a spin.</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" DefaultTargets=\"Main\">\n <UsingTask TaskName=\"BuildMetadata\" AssemblyFile=\"F:\\temp\\SampleLogger\\bin\\debug\\SampleTasks.dll\" />\n\n <Target Name=\"Main\">\n <Warning Text=\"Sample warning #1\" />\n <Warning Text=\"Sample warning #2\" />\n\n <BuildMetadata>\n <Output\n TaskParameter=\"WarningCount\"\n PropertyName=\"WarningCount\" />\n </BuildMetadata>\n\n <Error Text=\"A total of $(WarningCount) warning(s) were raised.\" Condition=\"$(WarningCount) > 0\" />\n </Target>\n</Project>\n</code></pre>\n\n<p>If you run the following command:</p>\n\n<pre><code>c:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild test.xml /logger:SampleLogger.dll\n</code></pre>\n\n<p>This will be the output:</p>\n\n<pre><code>Microsoft (R) Build Engine Version 2.0.50727.3053\n[Microsoft .NET Framework, Version 2.0.50727.3053]\nCopyright (C) Microsoft Corporation 2005. All rights reserved.\n\nBuild started 30-09-2008 13:04:39.\n__________________________________________________\nProject \"F:\\temp\\SampleLogger\\bin\\debug\\test.xml\" (default targets):\n\nTarget Main:\n F:\\temp\\SampleLogger\\bin\\debug\\test.xml : warning : Sample warning #1\n F:\\temp\\SampleLogger\\bin\\debug\\test.xml : warning : Sample warning #2\n F:\\temp\\SampleLogger\\bin\\debug\\test.xml(15,3): error : A total of 2 warning(s) were raised.\nDone building target \"Main\" in project \"test.xml\" -- FAILED.\n\nDone building project \"test.xml\" -- FAILED.\n\nBuild FAILED.\nF:\\temp\\SampleLogger\\bin\\debug\\test.xml : warning : Sample warning #1\nF:\\temp\\SampleLogger\\bin\\debug\\test.xml : warning : Sample warning #2\nF:\\temp\\SampleLogger\\bin\\debug\\test.xml(15,3): error : A total of 2 warning(s) were raised.\n 2 Warning(s)\n 1 Error(s)\n\nTime Elapsed 00:00:00.01\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11391/"
] |
There is a MSBuild script, that includes number if Delphi and C# projects, unit tests etc.
The problem is: how to mark build failed if warnings were raised (for testing purposes, not for release builds)? Using LogError instead of LogWarning in custom tasks seems to be not a good option, because the build should test as much as it's able (until real error) to report as much warnings as possible in a time (build project is using in CruiseControl.NET).
May be, the solution is to create my own logger that would store warnings flag inside, but I cannot find if there is a way to read this flag in the end of build?
P.S. There is no problem to fail the build immediately after receiving a warning (Delphi compiler output is processed by custom task, and /warnaserror could be used for C#), but the desired behavior is "build everything; collect all warnings; fail the build" to report about all warnings, not only about the first one.
**P.P.S. As far as I really need not number of warnings, but just flag of their presence, I decided to simplify signaling mechanism, and use trivial Mutex instead of shared memory. Code is below:**
```
using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Threading;
namespace Intrahealth.Build.WarningLogger
{
public sealed class WarningLoggerCheck : Task
{
public override bool Execute()
{
Log.LogMessage("WarningLoggerCheck:" + mutexName + "...");
result = false;
Mutex m = null;
try
{
m = Mutex.OpenExisting(mutexName);
}
catch (WaitHandleCannotBeOpenedException)
{
result = true;
}
catch (Exception)
{
}
if (result)
Log.LogMessage("WarningLoggerCheck PASSED");
else
Log.LogError("Build log contains warnings. Build is FAILED");
return result;
}
private bool result = true;
[Output]
public bool Result
{
get { return result; }
}
private string mutexName = "WarningLoggerMutex";
public string MutexName
{
get { return mutexName; }
set { mutexName = value ?? "WarningLoggerMutex"; }
}
}
public class WarningLogger : Logger
{
internal static int warningsCount = 0;
private string mutexName = String.Empty;
private Mutex mutex = null;
public override void Initialize(IEventSource eventSource)
{
eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
}
private void SetMutex()
{
if (mutexName == String.Empty)
{
mutexName = "WarningLoggerMutex";
if (this.Parameters != null && this.Parameters != String.Empty)
{
mutexName = this.Parameters;
}
}
mutex = new Mutex(false, mutexName);
}
void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
{
if (e.Message != null && e.Message.Contains("MSB3146"))
return;
if (e.Code != null && e.Code.Equals("MSB3146"))
return;
if (warningsCount == 0)
SetMutex();
warningsCount++;
}
}
}
```
|
AFAIK MSBuild has no built-in support to retrieve the warning count at a given point of the build script. You can however follow these steps to achieve this goal:
1. Create a custom logger that listens for the warning event and counts the number of warnings
2. Create a custom task that exposes an [Output] WarningCount property
3. The custom task gets somehow the value of the warning count from the custom logger
The most difficult step is step 3. For this there are several options and you can freely search them under IPC - Inter Process Comunication. Follows a working example of how you can achieve this. Each item is a different *Class Library*.
**SharedMemory**
<http://weblogs.asp.net/rosherove/archive/2003/05/01/6295.aspx>
>
> I've created a wrapper for named
> shared memory that was part of a
> larger project. It basically allows
> serialized types and object graphs to
> be stored in and retrieved from shared
> memory (including as you'd expect
> cross process). Whether the larger
> project ever gets completed is another
> matter ;-).
>
>
>
**SampleLogger**
Implements the custom logger that keeps track of the warning count.
```
namespace SampleLogger
{
using System;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using DM.SharedMemory;
public class MySimpleLogger : Logger
{
private Segment s;
private int warningCount;
public override void Initialize(IEventSource eventSource)
{
eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
this.s = new Segment("MSBuildMetadata", SharedMemoryCreationFlag.Create, 65535);
this.s.SetData(this.warningCount.ToString());
}
void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
{
this.warningCount++;
this.s.SetData(this.warningCount.ToString());
}
public override void Shutdown()
{
this.s.Dispose();
base.Shutdown();
}
}
}
```
**SampleTasks**
Implements the custom task that reads the number of warnings raised in the MSbuild project. The custom task reads from the shared memory written by the custom logger implemented in class library *SampleLogger*.
```
namespace SampleTasks
{
using System;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using DM.SharedMemory;
public class BuildMetadata : Task
{
public int warningCount;
[Output]
public int WarningCount
{
get
{
Segment s = new Segment("MSBuildMetadata", SharedMemoryCreationFlag.Attach, 0);
int warningCount = Int32.Parse(s.GetData() as string);
return warningCount;
}
}
public override bool Execute()
{
return true;
}
}
}
```
Going for a spin.
```
<?xml version="1.0" encoding="UTF-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Main">
<UsingTask TaskName="BuildMetadata" AssemblyFile="F:\temp\SampleLogger\bin\debug\SampleTasks.dll" />
<Target Name="Main">
<Warning Text="Sample warning #1" />
<Warning Text="Sample warning #2" />
<BuildMetadata>
<Output
TaskParameter="WarningCount"
PropertyName="WarningCount" />
</BuildMetadata>
<Error Text="A total of $(WarningCount) warning(s) were raised." Condition="$(WarningCount) > 0" />
</Target>
</Project>
```
If you run the following command:
```
c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MSBuild test.xml /logger:SampleLogger.dll
```
This will be the output:
```
Microsoft (R) Build Engine Version 2.0.50727.3053
[Microsoft .NET Framework, Version 2.0.50727.3053]
Copyright (C) Microsoft Corporation 2005. All rights reserved.
Build started 30-09-2008 13:04:39.
__________________________________________________
Project "F:\temp\SampleLogger\bin\debug\test.xml" (default targets):
Target Main:
F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #1
F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #2
F:\temp\SampleLogger\bin\debug\test.xml(15,3): error : A total of 2 warning(s) were raised.
Done building target "Main" in project "test.xml" -- FAILED.
Done building project "test.xml" -- FAILED.
Build FAILED.
F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #1
F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #2
F:\temp\SampleLogger\bin\debug\test.xml(15,3): error : A total of 2 warning(s) were raised.
2 Warning(s)
1 Error(s)
Time Elapsed 00:00:00.01
```
|
152,514 |
<p>I have to rename a complete folder tree recursively so that no uppercase letter appears anywhere (it's C++ source code, but that shouldn't matter).</p>
<p>Bonus points for ignoring CVS and Subversion version control files/folders. The preferred way would be a shell script, since a shell should be available on any Linux box.</p>
<p>There were some valid arguments about details of the file renaming.</p>
<ol>
<li><p>I think files with the same lowercase names should be overwritten; it's the user's problem. When checked out on a case-ignoring file system, it would overwrite the first one with the latter, too.</p></li>
<li><p>I would consider A-Z characters and transform them to a-z, everything else is just calling for problems (at least with source code).</p></li>
<li><p>The script would be needed to run a build on a Linux system, so I think changes to CVS or Subversion version control files should be omitted. After all, it's just a scratch checkout. Maybe an "export" is more appropriate.</p></li>
</ol>
|
[
{
"answer_id": 152519,
"author": "vividos",
"author_id": 23740,
"author_profile": "https://Stackoverflow.com/users/23740",
"pm_score": 3,
"selected": false,
"text": "<p>Here's my suboptimal solution, using a Bash shell script:</p>\n\n<pre><code>#!/bin/bash\n# First, rename all folders\nfor f in `find . -depth ! -name CVS -type d`; do\n g=`dirname \"$f\"`/`basename \"$f\" | tr '[A-Z]' '[a-z]'`\n if [ \"xxx$f\" != \"xxx$g\" ]; then\n echo \"Renaming folder $f\"\n mv -f \"$f\" \"$g\"\n fi\ndone\n\n# Now, rename all files\nfor f in `find . ! -type d`; do\n g=`dirname \"$f\"`/`basename \"$f\" | tr '[A-Z]' '[a-z]'`\n if [ \"xxx$f\" != \"xxx$g\" ]; then\n echo \"Renaming file $f\"\n mv -f \"$f\" \"$g\"\n fi\ndone\n</code></pre>\n\n<p>Folders are all renamed correctly, and <code>mv</code> isn't asking questions when permissions don't match, and CVS folders are not renamed (CVS control files inside that folder are still renamed, unfortunately).</p>\n\n<p>Since \"find -depth\" and \"find | sort -r\" both return the folder list in a usable order for renaming, I preferred using \"-depth\" for searching folders.</p>\n"
},
{
"answer_id": 152531,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 7,
"selected": false,
"text": "<pre><code>for f in `find`; do mv -v \"$f\" \"`echo $f | tr '[A-Z]' '[a-z]'`\"; done\n</code></pre>\n"
},
{
"answer_id": 152560,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 3,
"selected": false,
"text": "<p>Using Larry Wall's filename fixer:</p>\n\n<pre><code>$op = shift or die $help;\nchomp(@ARGV = <STDIN>) unless @ARGV;\nfor (@ARGV) {\n $was = $_;\n eval $op;\n die $@ if $@;\n rename($was,$_) unless $was eq $_;\n}\n</code></pre>\n\n<p>It's as simple as</p>\n\n<pre><code>find | fix 'tr/A-Z/a-z/'\n</code></pre>\n\n<p>(where <code>fix</code> is of course the script above)</p>\n"
},
{
"answer_id": 152571,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "<p>This is a small shell script that does what you requested:</p>\n\n<pre><code>root_directory=\"${1?-please specify parent directory}\"\ndo_it () {\n awk '{ lc= tolower($0); if (lc != $0) print \"mv \\\"\" $0 \"\\\" \\\"\" lc \"\\\"\" }' | sh\n}\n# first the folders\nfind \"$root_directory\" -depth -type d | do_it\nfind \"$root_directory\" ! -type d | do_it\n</code></pre>\n\n<p>Note the -depth action in the first find.</p>\n"
},
{
"answer_id": 152598,
"author": "Ian Dickinson",
"author_id": 6716,
"author_profile": "https://Stackoverflow.com/users/6716",
"pm_score": 3,
"selected": false,
"text": "<p>The original question asked for ignoring SVN and CVS directories, which can be done by adding -prune to the find command. E.g to ignore CVS:</p>\n\n<pre><code>find . -name CVS -prune -o -exec mv '{}' `echo {} | tr '[A-Z]' '[a-z]'` \\; -print\n</code></pre>\n\n<p>[edit] I tried this out, and embedding the lower-case translation inside the find didn't work for reasons I don't actually understand. So, amend this to:</p>\n\n<pre><code>$> cat > tolower\n#!/bin/bash\nmv $1 `echo $1 | tr '[:upper:]' '[:lower:]'`\n^D\n$> chmod u+x tolower \n$> find . -name CVS -prune -o -exec tolower '{}' \\;\n</code></pre>\n\n<p>Ian</p>\n"
},
{
"answer_id": 152636,
"author": "pklausner",
"author_id": 22700,
"author_profile": "https://Stackoverflow.com/users/22700",
"pm_score": 0,
"selected": false,
"text": "<pre><code>( find YOURDIR -type d | sort -r;\n find yourdir -type f ) |\ngrep -v /CVS | grep -v /SVN |\nwhile read f; do mv -v $f `echo $f | tr '[A-Z]' '[a-z]'`; done\n</code></pre>\n\n<p>First rename the directories bottom up <em>sort -r</em> (where -depth is not available), then the files.\nThen <em>grep -v /CVS</em> instead of <em>find ...-prune</em> because it's simpler.\nFor large directories, <em>for f in ...</em> can overflow some shell buffers.\nUse <em>find ... | while read</em> to avoid that.</p>\n\n<p>And yes, this will clobber files which differ only in case...</p>\n"
},
{
"answer_id": 152741,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 9,
"selected": true,
"text": "<p>A concise version using the <code>\"rename\"</code> command:</p>\n\n<pre><code>find my_root_dir -depth -exec rename 's/(.*)\\/([^\\/]*)/$1\\/\\L$2/' {} \\;\n</code></pre>\n\n<p>This avoids problems with directories being renamed before files and trying to move files into non-existing directories (e.g. <code>\"A/A\"</code> into <code>\"a/a\"</code>).</p>\n\n<p>Or, a more verbose version without using <code>\"rename\"</code>.</p>\n\n<pre><code>for SRC in `find my_root_dir -depth`\ndo\n DST=`dirname \"${SRC}\"`/`basename \"${SRC}\" | tr '[A-Z]' '[a-z]'`\n if [ \"${SRC}\" != \"${DST}\" ]\n then\n [ ! -e \"${DST}\" ] && mv -T \"${SRC}\" \"${DST}\" || echo \"${SRC} was not renamed\"\n fi\ndone\n</code></pre>\n\n<h3>P.S.</h3>\n\n<p>The latter allows more flexibility with the move command (for example, <code>\"svn mv\"</code>).</p>\n"
},
{
"answer_id": 152836,
"author": "niXar",
"author_id": 19979,
"author_profile": "https://Stackoverflow.com/users/19979",
"pm_score": 4,
"selected": false,
"text": "<p>Most of the answers above are dangerous, because they do not deal with names containing odd characters. Your safest bet for this kind of thing is to use <code>find</code>'s <code>-print0</code> option, which will terminate filenames with ASCII NUL instead of \\n.</p>\n\n<p>Here is a script, which only alter files and not directory names so as not to confuse <code>find</code>:</p>\n\n<pre><code>find . -type f -print0 | xargs -0n 1 bash -c \\\n's=$(dirname \"$0\")/$(basename \"$0\");\nd=$(dirname \"$0\")/$(basename \"$0\"|tr \"[A-Z]\" \"[a-z]\"); mv -f \"$s\" \"$d\"'\n</code></pre>\n\n<p>I tested it, and it works with filenames containing spaces, all kinds of quotes, etc. This is important because if you run, as root, one of those other scripts on a tree that includes the file created by</p>\n\n<pre><code>touch \\;\\ echo\\ hacker::0:0:hacker:\\$\\'\\057\\'root:\\$\\'\\057\\'bin\\$\\'\\057\\'bash\n</code></pre>\n\n<p>... well guess what ...</p>\n"
},
{
"answer_id": 8167105,
"author": "tristanbailey",
"author_id": 6096,
"author_profile": "https://Stackoverflow.com/users/6096",
"pm_score": 8,
"selected": false,
"text": "<p>Smaller still I quite like:</p>\n\n<pre><code>rename 'y/A-Z/a-z/' *\n</code></pre>\n\n<p>On case insensitive filesystems such as OS X's <a href=\"https://en.wikipedia.org/wiki/HFS_Plus\" rel=\"noreferrer\">HFS+</a>, you will want to add the <code>-f</code> flag:</p>\n\n<pre><code>rename -f 'y/A-Z/a-z/' *\n</code></pre>\n"
},
{
"answer_id": 17730002,
"author": "benjwadams",
"author_id": 1914300,
"author_profile": "https://Stackoverflow.com/users/1914300",
"pm_score": 3,
"selected": false,
"text": "<p>Not portable, Zsh only, but pretty concise.</p>\n\n<p>First, make sure <code>zmv</code> is loaded.</p>\n\n<pre><code>autoload -U zmv\n</code></pre>\n\n<p>Also, make sure <code>extendedglob</code> is on:</p>\n\n<pre><code>setopt extendedglob\n</code></pre>\n\n<p>Then use:</p>\n\n<pre><code>zmv '(**/)(*)~CVS~**/CVS' '${1}${(L)2}'\n</code></pre>\n\n<p>To recursively lowercase files and directories where the name is not <em>CVS</em>.</p>\n"
},
{
"answer_id": 25590300,
"author": "Ginhing",
"author_id": 3209127,
"author_profile": "https://Stackoverflow.com/users/3209127",
"pm_score": 7,
"selected": false,
"text": "<p>Just simply try the following if you don't need to care about efficiency.</p>\n\n<pre><code>zip -r foo.zip foo/*\nunzip -LL foo.zip\n</code></pre>\n"
},
{
"answer_id": 27969656,
"author": "jacanterbury",
"author_id": 765827,
"author_profile": "https://Stackoverflow.com/users/765827",
"pm_score": 1,
"selected": false,
"text": "<p>I needed to do this on a Cygwin setup on Windows 7 and found that I got syntax errors with the suggestions from above that I tried (though I may have missed a working option). However, this solution straight from <a href=\"http://ubuntuforums.org/showthread.php?t=1336909\" rel=\"nofollow noreferrer\">Ubuntu forums</a> worked out of the can :-)</p>\n\n<pre><code>ls | while read upName; do loName=`echo \"${upName}\" | tr '[:upper:]' '[:lower:]'`; mv \"$upName\" \"$loName\"; done\n</code></pre>\n\n<p>(NB: I had previously replaced whitespace with underscores using:</p>\n\n<pre><code>for f in *\\ *; do mv \"$f\" \"${f// /_}\"; done\n</code></pre>\n\n<p>)</p>\n"
},
{
"answer_id": 28777455,
"author": "cwd",
"author_id": 288032,
"author_profile": "https://Stackoverflow.com/users/288032",
"pm_score": 1,
"selected": false,
"text": "<h3>Slugify Rename (regex)</h3>\n\n<p>It is not exactly what the OP asked for, but what I was hoping to find on this page:</p>\n\n<p>A \"slugify\" version for renaming files so they are similar to URLs (i.e. only include alphanumeric, dots, and dashes):</p>\n\n<pre><code>rename \"s/[^a-zA-Z0-9\\.]+/-/g\" filename\n</code></pre>\n"
},
{
"answer_id": 29248837,
"author": "Jonghee Park",
"author_id": 319911,
"author_profile": "https://Stackoverflow.com/users/319911",
"pm_score": 2,
"selected": false,
"text": "<p>In OS X, <code>mv -f</code> shows \"same file\" error, so I rename twice:</p>\n\n<pre><code>for i in `find . -name \"*\" -type f |grep -e \"[A-Z]\"`; do j=`echo $i | tr '[A-Z]' '[a-z]' | sed s/\\-1$//`; mv $i $i-1; mv $i-1 $j; done\n</code></pre>\n"
},
{
"answer_id": 33618314,
"author": "alemol",
"author_id": 1668293,
"author_profile": "https://Stackoverflow.com/users/1668293",
"pm_score": 4,
"selected": false,
"text": "<p>This works if you already have or set up the <strong>rename</strong> command (e.g. through <a href=\"https://en.wikipedia.org/wiki/Homebrew_%28package_management_software%29\" rel=\"noreferrer\">brew install</a> in Mac):</p>\n\n<pre><code>rename --lower-case --force somedir/*\n</code></pre>\n"
},
{
"answer_id": 35117352,
"author": "John Foley",
"author_id": 1057048,
"author_profile": "https://Stackoverflow.com/users/1057048",
"pm_score": 1,
"selected": false,
"text": "<p>I would reach for Python in this situation, to avoid optimistically assuming paths without spaces or slashes. I've also found that <code>python2</code> tends to be installed in more places than <code>rename</code>.</p>\n\n<pre><code>#!/usr/bin/env python2\nimport sys, os\n\ndef rename_dir(directory):\n print('DEBUG: rename('+directory+')')\n\n # Rename current directory if needed\n os.rename(directory, directory.lower())\n directory = directory.lower()\n\n # Rename children\n for fn in os.listdir(directory):\n path = os.path.join(directory, fn)\n os.rename(path, path.lower())\n path = path.lower()\n\n # Rename children within, if this child is a directory\n if os.path.isdir(path):\n rename_dir(path)\n\n# Run program, using the first argument passed to this Python script as the name of the folder\nrename_dir(sys.argv[1])\n</code></pre>\n"
},
{
"answer_id": 35561366,
"author": "Chris Schierkolk",
"author_id": 5964664,
"author_profile": "https://Stackoverflow.com/users/5964664",
"pm_score": 2,
"selected": false,
"text": "<pre><code>for f in `find -depth`; do mv ${f} ${f,,} ; done\n</code></pre>\n\n<p><code>find -depth</code> prints each file and directory, with a directory's contents printed before the directory itself. <code>${f,,}</code> lowercases the file name.</p>\n"
},
{
"answer_id": 36359928,
"author": "Pere",
"author_id": 1391963,
"author_profile": "https://Stackoverflow.com/users/1391963",
"pm_score": 4,
"selected": false,
"text": "<p>This works on <a href=\"http://en.wikipedia.org/wiki/CentOS\" rel=\"noreferrer\">CentOS</a>/<a href=\"http://en.wikipedia.org/wiki/Red_Hat_Linux\" rel=\"noreferrer\">Red Hat Linux</a> or other distributions without the <code>rename</code> Perl script:</p>\n\n<pre><code>for i in $( ls | grep [A-Z] ); do mv -i \"$i\" \"`echo $i | tr 'A-Z' 'a-z'`\"; done\n</code></pre>\n\n<p>Source: <em><a href=\"https://linuxconfig.org/rename-all-files-from-uppercase-to-lowercase-characters\" rel=\"noreferrer\">Rename all file names from uppercase to lowercase characters</a></em></p>\n\n<p>(In some distributions the default <code>rename</code> command comes from util-linux, and that is a different, incompatible tool.)</p>\n"
},
{
"answer_id": 42314201,
"author": "Stephen",
"author_id": 1018614,
"author_profile": "https://Stackoverflow.com/users/1018614",
"pm_score": 5,
"selected": false,
"text": "<p>One can simply use the following which is less complicated:</p>\n<pre><code>rename 'y/A-Z/a-z/' *\n</code></pre>\n"
},
{
"answer_id": 44709747,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>If you use <a href=\"https://www.archlinux.org/\" rel=\"nofollow noreferrer\">Arch Linux</a>, you can install <a href=\"https://fossies.org/linux/privat/old/rename-1.3.tar.gz/\" rel=\"nofollow noreferrer\"><code>rename</code></a>) package from <a href=\"https://aur.archlinux.org/packages/rename\" rel=\"nofollow noreferrer\"><code>AUR</code></a> that provides the <code>renamexm</code> command as <code>/usr/bin/renamexm</code> executable and <a href=\"https://fossies.org/linux/rename/rename.1\" rel=\"nofollow noreferrer\">a manual page</a> along with it.</p>\n\n<p>It is a really powerful tool to quickly rename files and directories.</p>\n\n<h3>Convert to lowercase</h3>\n\n<pre><code>rename -l Developers.mp3 # or --lowcase\n</code></pre>\n\n<h3>Convert to UPPER case</h3>\n\n<pre><code>rename -u developers.mp3 # or --upcase, long option\n</code></pre>\n\n<h3>Other options</h3>\n\n<pre><code>-R --recursive # directory and its children\n\n-t --test # Dry run, output but don't rename\n\n-o --owner # Change file owner as well to user specified\n\n-v --verbose # Output what file is renamed and its new name\n\n-s/str/str2 # Substitute string on pattern\n\n--yes # Confirm all actions\n</code></pre>\n\n<p>You can fetch the sample <em>Developers.mp3</em> file from <a href=\"http://www.youtube-mp3.org/\" rel=\"nofollow noreferrer\">here</a>, if needed ;)</p>\n"
},
{
"answer_id": 46492911,
"author": "Paul Hodges",
"author_id": 8656552,
"author_profile": "https://Stackoverflow.com/users/8656552",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"https://helpmanual.io/builtin/typeset/\" rel=\"nofollow noreferrer\">typeset</a>:</p>\n\n<pre><code>typeset -l new # Always lowercase\nfind $topPoint | # Not using xargs to make this more readable\n while read old\n do new=\"$old\" # $new is a lowercase version of $old\n mv \"$old\" \"$new\" # Quotes for those annoying embedded spaces\n done\n</code></pre>\n\n<p>On Windows, emulations, like <a href=\"https://superuser.com/questions/1053633\">Git Bash</a>, may fail because Windows isn't case-sensitive under the hood. For those, add a step that <code>mv</code>'s the file to another name first, like \"$old.tmp\", and then to <code>$new</code>.</p>\n"
},
{
"answer_id": 49705900,
"author": "akilesh raj",
"author_id": 4336570,
"author_profile": "https://Stackoverflow.com/users/4336570",
"pm_score": 2,
"selected": false,
"text": "<p>With MacOS,</p>\n\n<p>Install the <code>rename</code> package,</p>\n\n<pre><code>brew install rename\n</code></pre>\n\n<p>Use,</p>\n\n<pre><code>find . -iname \"*.py\" -type f | xargs -I% rename -c -f \"%\" \n</code></pre>\n\n<p>This command find all the files with a <code>*.py</code> extension and converts the filenames to lower case.</p>\n\n<pre><code>`f` - forces a rename\n</code></pre>\n\n<p>For example,</p>\n\n<pre><code>$ find . -iname \"*.py\" -type f\n./sample/Sample_File.py\n./sample_file.py\n$ find . -iname \"*.py\" -type f | xargs -I% rename -c -f \"%\"\n$ find . -iname \"*.py\" -type f\n./sample/sample_file.py\n./sample_file.py\n</code></pre>\n"
},
{
"answer_id": 52479152,
"author": "ndemou",
"author_id": 1011025,
"author_profile": "https://Stackoverflow.com/users/1011025",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Lengthy But <em>\"Works With No Surprises & No Installations\"</em></strong></p>\n\n<p>This script <strong>handles filenames with spaces, quotes, other <em>unusual</em> characters and Unicode, works on case insensitive filesystems and most Unix-y environments</strong> that have bash and awk installed (i.e. almost all). It also reports collisions if any (leaving the filename in uppercase) and of course renames both files & directories and works recursively. Finally it's highly adaptable: you can tweak the find command to target the files/dirs you wish and you can tweak awk to do other name manipulations. Note that by \"handles Unicode\" I mean that it will indeed convert their case (not ignore them like answers that use <code>tr</code>).</p>\n\n<pre><code># adapt the following command _IF_ you want to deal with specific files/dirs\nfind . -depth -mindepth 1 -exec bash -c '\n for file do\n # adapt the awk command if you wish to rename to something other than lowercase\n newname=$(dirname \"$file\")/$(basename \"$file\" | awk \"{print tolower(\\$0)}\")\n if [ \"$file\" != \"$newname\" ] ; then\n # the extra step with the temp filename is for case-insensitive filesystems\n if [ ! -e \"$newname\" ] && [ ! -e \"$newname.lcrnm.tmp\" ] ; then\n mv -T \"$file\" \"$newname.lcrnm.tmp\" && mv -T \"$newname.lcrnm.tmp\" \"$newname\" \n else\n echo \"ERROR: Name already exists: $newname\"\n fi\n fi \n done\n' sh {} +\n</code></pre>\n\n<hr>\n\n<p><strong>References</strong></p>\n\n<p>My script is based on these excellent answers:</p>\n\n<p><a href=\"https://unix.stackexchange.com/questions/9496/looping-through-files-with-spaces-in-the-names\">https://unix.stackexchange.com/questions/9496/looping-through-files-with-spaces-in-the-names</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/2264428/how-to-convert-a-string-to-lower-case-in-bash\">How to convert a string to lower case in Bash?</a></p>\n"
},
{
"answer_id": 53918698,
"author": "Chris",
"author_id": 59198,
"author_profile": "https://Stackoverflow.com/users/59198",
"pm_score": 2,
"selected": false,
"text": "<p>This works nicely on macOS too:</p>\n\n<pre><code>ruby -e \"Dir['*'].each { |p| File.rename(p, p.downcase) }\"\n</code></pre>\n"
},
{
"answer_id": 54694950,
"author": "oisyn",
"author_id": 8951473,
"author_profile": "https://Stackoverflow.com/users/8951473",
"pm_score": 0,
"selected": false,
"text": "<pre><code>find . -depth -name '*[A-Z]*'|sed -n 's/\\(.*\\/\\)\\(.*\\)/mv -n -v -T \\1\\2 \\1\\L\\2/p'|sh\n</code></pre>\n\n<p>I haven't tried the more elaborate scripts mentioned here, but none of the single commandline versions worked for me on my Synology NAS. <code>rename</code> is not available, and many of the variations of <code>find</code> fail because it seems to stick to the older name of the already renamed path (eg, if it finds <code>./FOO</code> followed by <code>./FOO/BAR</code>, renaming <code>./FOO</code> to <code>./foo</code> will still continue to list <code>./FOO/BAR</code> even though that path is no longer valid). Above command worked for me without any issues.</p>\n\n<p>What follows is an explanation of each part of the command:</p>\n\n<hr>\n\n<pre><code>find . -depth -name '*[A-Z]*'\n</code></pre>\n\n<p>This will find any file from the current directory (change <code>.</code> to whatever directory you want to process), using a depth-first search (eg., it will list <code>./foo/bar</code> before <code>./foo</code>), but only for files that contain an uppercase character. The <code>-name</code> filter only applies to the base file name, not the full path. So this will list <code>./FOO/BAR</code> but not <code>./FOO/bar</code>. This is ok, as we don't want to rename <code>./FOO/bar</code>. We want to rename <code>./FOO</code> though, but that one is listed later on (this is why <code>-depth</code> is important).</p>\n\n<p>This comand in itself is particularly useful to finding the files that you want to rename in the first place. Use this after the complete rename command to search for files that still haven't been replaced because of file name collisions or errors.</p>\n\n<hr>\n\n<pre><code>sed -n 's/\\(.*\\/\\)\\(.*\\)/mv -n -v -T \\1\\2 \\1\\L\\2/p'\n</code></pre>\n\n<p>This part reads the files outputted by <code>find</code> and formats them in a <code>mv</code> command using a regular expression. The <code>-n</code> option stops <code>sed</code> from printing the input, and the <code>p</code> command in the search-and-replace regex outputs the replaced text.</p>\n\n<p>The regex itself consists of two captures: the part up until the last / (which is the directory of the file), and the filename itself. The directory is left intact, but the filename is transformed to lowercase. So, if <code>find</code> outputs <code>./FOO/BAR</code>, it will become <code>mv -n -v -T ./FOO/BAR ./FOO/bar</code>. The <code>-n</code> option of <code>mv</code> makes sure existing lowercase files are not overwritten. The <code>-v</code> option makes <code>mv</code> output every change that it makes (or doesn't make - if <code>./FOO/bar</code> already exists, it outputs something like <code>./FOO/BAR -> ./FOO/BAR</code>, noting that no change has been made). The <code>-T</code> is very important here - it treats the target file as a directory. This will make sure that <code>./FOO/BAR</code> isn't moved into <code>./FOO/bar</code> if that directory happens to exist.</p>\n\n<p>Use this together with <code>find</code> to generate a list of commands that will be executed (handy to verify what will be done without actually doing it)</p>\n\n<hr>\n\n<pre><code>sh\n</code></pre>\n\n<p>This pretty self-explanatory. It routes all the generated <code>mv</code> commands to the shell interpreter. You can replace it with <code>bash</code> or any shell of your liking.</p>\n"
},
{
"answer_id": 56063878,
"author": "Kim T",
"author_id": 2068766,
"author_profile": "https://Stackoverflow.com/users/2068766",
"pm_score": 4,
"selected": false,
"text": "<p>The simplest approach I found on Mac OS X was to use the rename package from <a href=\"http://plasmasturm.org/code/rename/\" rel=\"noreferrer\">http://plasmasturm.org/code/rename/</a>:</p>\n\n<pre><code>brew install rename\nrename --force --lower-case --nows *\n</code></pre>\n\n<blockquote>\n <p>--force Rename even when a file with the destination name already exists.</p>\n \n <p>--lower-case Convert file names to all lower case.</p>\n \n <p>--nows Replace all sequences of whitespace in the filename with single underscore characters.</p>\n</blockquote>\n"
},
{
"answer_id": 63917612,
"author": "Sebastian Schmied",
"author_id": 7563639,
"author_profile": "https://Stackoverflow.com/users/7563639",
"pm_score": 1,
"selected": false,
"text": "<p>None of the solutions here worked for me because I was on a system that didn't have access to the perl rename script, plus some of the files included spaces. However, I found a variant that works:</p>\n<pre><code>find . -depth -exec sh -c '\n t=${0%/*}/$(printf %s "${0##*/}" | tr "[:upper:]" "[:lower:]");\n [ "$t" = "$0" ] || mv -i "$0" "$t"\n' {} \\;\n</code></pre>\n<p>Credit goes to "Gilles 'SO- stop being evil'", see <a href=\"https://unix.stackexchange.com/a/20232/266760\">this answer on the similar question "change entire directory tree to lower-case names" on the Unix & Linux StackExchange</a>.</p>\n"
},
{
"answer_id": 64899100,
"author": "Eduardo",
"author_id": 9823,
"author_profile": "https://Stackoverflow.com/users/9823",
"pm_score": 3,
"selected": false,
"text": "<p>One-liner:</p>\n<pre><code>for F in K*; do NEWNAME=$(echo "$F" | tr '[:upper:]' '[:lower:]'); mv "$F" "$NEWNAME"; done\n</code></pre>\n<p>Or even:</p>\n<pre><code>for F in K*; do mv "$F" "${F,,}"; done\n</code></pre>\n<p>Note that this will convert only files/directories starting with letter K, so adjust accordingly.</p>\n"
},
{
"answer_id": 71063134,
"author": "TransferOrbit",
"author_id": 4943071,
"author_profile": "https://Stackoverflow.com/users/4943071",
"pm_score": 1,
"selected": false,
"text": "<p>I believe the one-liners can be simplified:</p>\n<p><code>for f in **/*; do mv "$f" "${f:l}"; done</code></p>\n"
},
{
"answer_id": 74678376,
"author": "Felix",
"author_id": 3803047,
"author_profile": "https://Stackoverflow.com/users/3803047",
"pm_score": 0,
"selected": false,
"text": "<p>Using bash, without <code>rename</code>:</p>\n<pre><code>find . -exec bash -c 'mv $0 ${0,,}' {} \\;\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23740/"
] |
I have to rename a complete folder tree recursively so that no uppercase letter appears anywhere (it's C++ source code, but that shouldn't matter).
Bonus points for ignoring CVS and Subversion version control files/folders. The preferred way would be a shell script, since a shell should be available on any Linux box.
There were some valid arguments about details of the file renaming.
1. I think files with the same lowercase names should be overwritten; it's the user's problem. When checked out on a case-ignoring file system, it would overwrite the first one with the latter, too.
2. I would consider A-Z characters and transform them to a-z, everything else is just calling for problems (at least with source code).
3. The script would be needed to run a build on a Linux system, so I think changes to CVS or Subversion version control files should be omitted. After all, it's just a scratch checkout. Maybe an "export" is more appropriate.
|
A concise version using the `"rename"` command:
```
find my_root_dir -depth -exec rename 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \;
```
This avoids problems with directories being renamed before files and trying to move files into non-existing directories (e.g. `"A/A"` into `"a/a"`).
Or, a more verbose version without using `"rename"`.
```
for SRC in `find my_root_dir -depth`
do
DST=`dirname "${SRC}"`/`basename "${SRC}" | tr '[A-Z]' '[a-z]'`
if [ "${SRC}" != "${DST}" ]
then
[ ! -e "${DST}" ] && mv -T "${SRC}" "${DST}" || echo "${SRC} was not renamed"
fi
done
```
### P.S.
The latter allows more flexibility with the move command (for example, `"svn mv"`).
|
152,537 |
<p>I need to add the ability for users of my software to select records by character ranges.<br>
How can I write a query that returns all widgets from a table whose name falls in the range Ba-Bi for example?</p>
<p>Currently I'm using greater than and less than operators, so the above example would become:</p>
<pre><code>select * from widget
where name >= 'ba' and name < 'bj'
</code></pre>
<p>Notice how I have "incremented" the last character of the upper bound from i to j so that "bike" would not be left out.</p>
<p>Is there a generic way to find the next character after a given character based on the field's collation or would it be safer to create a second condition?</p>
<pre><code>select * from widget
where name >= 'ba'
and (name < 'bi' or name like 'bi%')
</code></pre>
<p>My application needs to support localization. How sensitive is this kind of query to different character sets?</p>
<p>I also need to support both MSSQL and Oracle. What are my options for ensuring that character casing is ignored no matter what language appears in the data?</p>
|
[
{
"answer_id": 152608,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 0,
"selected": false,
"text": "<p>For MSSQL see this thread: <a href=\"http://bytes.com/forum/thread483570.html\" rel=\"nofollow noreferrer\">http://bytes.com/forum/thread483570.html</a> .</p>\n\n<p>For Oracle, it depends on your Oracle version, as Oracle 10 now supports regex(p) like queries: <a href=\"http://www.psoug.org/reference/regexp.html\" rel=\"nofollow noreferrer\">http://www.psoug.org/reference/regexp.html</a> (search for regexp_like ) and see this article: <a href=\"http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/rischert_regexp_pt1.html\" rel=\"nofollow noreferrer\">http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/rischert_regexp_pt1.html</a></p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 152728,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "<p>Frustratingly, the Oracle substring function is SUBSTR(), whilst it SQL-Server it's SUBSTRING().</p>\n\n<p>You could write a simple wrapper around one or both of them so that they share the same function name + prototype.</p>\n\n<p>Then you can just use</p>\n\n<pre><code>MY_SUBSTRING(name, 2) >= 'ba' AND MY_SUBSTRING(name, 2) <= 'bi'\n</code></pre>\n\n<p>or similar.</p>\n"
},
{
"answer_id": 152786,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 0,
"selected": false,
"text": "<p>You could use this...</p>\n\n<pre><code>select * from widget\nwhere name Like 'b[a-i]%'\n</code></pre>\n\n<p>This will match any row where the name starts with b, the second character is in the range a to i, and any other characters follow.</p>\n"
},
{
"answer_id": 152879,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 0,
"selected": false,
"text": "<p>I think that I'd go with something simple like appending a high-sorting string to the end of the upper bound. Something like:</p>\n\n<pre><code>select * from widgetwhere name >= 'ba' and name <= 'bi'||'~'\n</code></pre>\n\n<p>I'm not sure that would survive EBCDIC conversion though</p>\n"
},
{
"answer_id": 153101,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 3,
"selected": true,
"text": "<p>Let's skip directly to localization. Would you say \"aa\" >= \"ba\" ? Probably not, but that is where it sorts in Sweden. Also, you simply can't assume that you can ignore casing in any language. Casing is explicitly language-dependent, with the most common example being Turkish: uppercase i is İ. Lowercase I is ı.</p>\n\n<p>Now, your SQL DB defines the result of <, == etc by a \"collation order\". This is definitely language specific. So, you should explicitly control this, for every query. A Turkish collation order will put those i's where they belong (in Turkish). You can't rely on the default collation.</p>\n\n<p>As for the \"increment part\", don't bother. Stick to >= and <=.</p>\n"
},
{
"answer_id": 153190,
"author": "Carlton Jenke",
"author_id": 1215,
"author_profile": "https://Stackoverflow.com/users/1215",
"pm_score": 0,
"selected": false,
"text": "<p>You could also do it like this:</p>\n\n<pre><code>select * from widget\nwhere left(name, 2) between 'ba' and 'bi'\n</code></pre>\n\n<p>If your criteria length changes (as you seemed to indicate in a comment you left), the query would need to have the length as an input also:</p>\n\n<pre><code>declare @CriteriaLength int\nset @CriteriaLength = 4\nselect * from widget\nwhere left(name, @CriteriaLength) between 'baaa' and 'bike'\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8799/"
] |
I need to add the ability for users of my software to select records by character ranges.
How can I write a query that returns all widgets from a table whose name falls in the range Ba-Bi for example?
Currently I'm using greater than and less than operators, so the above example would become:
```
select * from widget
where name >= 'ba' and name < 'bj'
```
Notice how I have "incremented" the last character of the upper bound from i to j so that "bike" would not be left out.
Is there a generic way to find the next character after a given character based on the field's collation or would it be safer to create a second condition?
```
select * from widget
where name >= 'ba'
and (name < 'bi' or name like 'bi%')
```
My application needs to support localization. How sensitive is this kind of query to different character sets?
I also need to support both MSSQL and Oracle. What are my options for ensuring that character casing is ignored no matter what language appears in the data?
|
Let's skip directly to localization. Would you say "aa" >= "ba" ? Probably not, but that is where it sorts in Sweden. Also, you simply can't assume that you can ignore casing in any language. Casing is explicitly language-dependent, with the most common example being Turkish: uppercase i is İ. Lowercase I is ı.
Now, your SQL DB defines the result of <, == etc by a "collation order". This is definitely language specific. So, you should explicitly control this, for every query. A Turkish collation order will put those i's where they belong (in Turkish). You can't rely on the default collation.
As for the "increment part", don't bother. Stick to >= and <=.
|
152,541 |
<p>I have a stored procedure that looks like:</p>
<pre><code>CREATE PROCEDURE dbo.usp_TestFilter
@AdditionalFilter BIT = 1
AS
SELECT *
FROM dbo.SomeTable T
WHERE
T.Column1 IS NOT NULL
AND CASE WHEN @AdditionalFilter = 1 THEN
T.Column2 IS NOT NULL
</code></pre>
<p>Needless to say, this doesn't work. How can I activate the additional where clause that checks for the @AdditionalFilter parameter? Thanks for any help.</p>
|
[
{
"answer_id": 152551,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 1,
"selected": false,
"text": "<pre><code>CREATE PROCEDURE dbo.usp_TestFilter\n @AdditionalFilter BIT = 1\nAS\n SELECT *\n FROM dbo.SomeTable T\n WHERE\n T.Column1 IS NOT NULL\n AND (NOT @AdditionalFilter OR T.Column2 IS NOT NULL)\n</code></pre>\n"
},
{
"answer_id": 152552,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select *\nfrom SomeTable t\nwhere t.Column1 is null\nand (@AdditionalFilter = 0 or t.Column2 is not null)\n</code></pre>\n"
},
{
"answer_id": 152553,
"author": "Johan",
"author_id": 11347,
"author_profile": "https://Stackoverflow.com/users/11347",
"pm_score": 4,
"selected": true,
"text": "<pre><code>CREATE PROCEDURE dbo.usp_TestFilter\n @AdditionalFilter BIT = 1\nAS\n SELECT *\n FROM dbo.SomeTable T\n WHERE\n T.Column1 IS NOT NULL\n AND (@AdditionalFilter = 0 OR\n T.Column2 IS NOT NULL)\n</code></pre>\n\n<p>If @AdditionalFilter is 0, the column won't be evaluated since it can't affect the outcome of the part between brackets. If it's anything other than 0, the column condition will be evaluated.</p>\n"
},
{
"answer_id": 152748,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 2,
"selected": false,
"text": "<p>This practice tends to confuse the query optimizer. I've seen SQL Server 2000 build the execution plan exactly the opposite way round and use an index on Column1 when the flag was set and vice-versa. SQL Server 2005 seemed to at least get the execution plan right on first compilation, but you then have a new problem. The system caches compiled execution plans and tries to reuse them. If you first use the query one way, it will still execute the query that way even if the extra parameter changes, and different indexes would be more appropriate.</p>\n\n<p>You can force a stored procedure to be recompiled on this execution by using <code>WITH RECOMPILE</code> in the <code>EXEC</code> statement, or every time by specifying <code>WITH RECOMPILE</code> on the <code>CREATE PROCEDURE</code> statement. There will be a penalty as SQL Server re-parses and optimizes the query each time.</p>\n\n<p>In general, if the form of your query is going to change, use dynamic SQL generation <strong>with parameters</strong>. SQL Server will also cache execution plans for parameterized queries and auto-parameterized queries (where it tries to deduce which arguments are parameters), and even regular queries, but it gives most weight to stored procedure execution plans, then parameterized, auto-parameterized and regular queries in that order. The higher the weight, the longer it can stay in RAM before the plan is discarded, if the server needs the memory for something else.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6651/"
] |
I have a stored procedure that looks like:
```
CREATE PROCEDURE dbo.usp_TestFilter
@AdditionalFilter BIT = 1
AS
SELECT *
FROM dbo.SomeTable T
WHERE
T.Column1 IS NOT NULL
AND CASE WHEN @AdditionalFilter = 1 THEN
T.Column2 IS NOT NULL
```
Needless to say, this doesn't work. How can I activate the additional where clause that checks for the @AdditionalFilter parameter? Thanks for any help.
|
```
CREATE PROCEDURE dbo.usp_TestFilter
@AdditionalFilter BIT = 1
AS
SELECT *
FROM dbo.SomeTable T
WHERE
T.Column1 IS NOT NULL
AND (@AdditionalFilter = 0 OR
T.Column2 IS NOT NULL)
```
If @AdditionalFilter is 0, the column won't be evaluated since it can't affect the outcome of the part between brackets. If it's anything other than 0, the column condition will be evaluated.
|
152,580 |
<p>How do I check if an object is of a given type, or if it inherits from a given type?</p>
<p>How do I check if the object <code>o</code> is of type <code>str</code>?</p>
<hr />
<p><sub>Beginners often wrongly expect the string to <em>already be</em> "a number" - either expecting Python 3.x <code>input</code> to convert type, or expecting that a string like <code>'1'</code> is <em>also simultaneously</em> an integer. This is the wrong canonical for those questions. Please carefully read the question and then use <a href="https://stackoverflow.com/questions/354038">How do I check if a string represents a number (float or int)?</a>, <a href="https://stackoverflow.com/questions/20449427/">How can I read inputs as numbers?</a> and/or <a href="https://stackoverflow.com/questions/23294658/">Asking the user for input until they give a valid response</a> as appropriate.</sub></p>
|
[
{
"answer_id": 152583,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 4,
"selected": false,
"text": "<pre><code>isinstance(o, str)\n</code></pre>\n\n<p><a href=\"https://docs.python.org/2/library/functions.html#isinstance\" rel=\"nofollow noreferrer\">Link to docs</a></p>\n"
},
{
"answer_id": 152592,
"author": "Herge",
"author_id": 14102,
"author_profile": "https://Stackoverflow.com/users/14102",
"pm_score": 6,
"selected": false,
"text": "<p><code>isinstance(o, str)</code> will return <code>True</code> if <code>o</code> is an <code>str</code> or is of a type that inherits from <code>str</code>.</p>\n\n<p><code>type(o) is str</code> will return <code>True</code> if and only if <code>o</code> is a str. It will return <code>False</code> if <code>o</code> is of a type that inherits from <code>str</code>.</p>\n"
},
{
"answer_id": 152596,
"author": "Fredrik Johansson",
"author_id": 1163767,
"author_profile": "https://Stackoverflow.com/users/1163767",
"pm_score": 12,
"selected": true,
"text": "<p>Use <a href=\"https://docs.python.org/library/functions.html#isinstance\" rel=\"noreferrer\"><code>isinstance</code></a> to check if <code>o</code> is an instance of <code>str</code> or any subclass of <code>str</code>:</p>\n<pre><code>if isinstance(o, str):\n</code></pre>\n<p>To check if the type of <code>o</code> is exactly <code>str</code>, <em>excluding subclasses of <code>str</code></em>:</p>\n<pre><code>if type(o) is str:\n</code></pre>\n<p>Another alternative to the above:</p>\n<pre><code>if issubclass(type(o), str):\n</code></pre>\n<p>See <a href=\"http://docs.python.org/library/functions.html\" rel=\"noreferrer\">Built-in Functions</a> in the Python Library Reference for relevant information.</p>\n<hr />\n<h4>Checking for strings in Python 2</h4>\n<p>For Python 2, this is a better way to check if <code>o</code> is a string:</p>\n<pre><code>if isinstance(o, basestring):\n</code></pre>\n<p>because this will also catch Unicode strings. <a href=\"https://docs.python.org/2/library/functions.html#unicode\" rel=\"noreferrer\"><code>unicode</code></a> is not a subclass of <code>str</code>; whereas, both <code>str</code> and <code>unicode</code> are subclasses of <a href=\"https://docs.python.org/2/library/functions.html#basestring\" rel=\"noreferrer\"><code>basestring</code></a>. In Python 3, <code>basestring</code> no longer exists since there's <a href=\"https://docs.python.org/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit\" rel=\"noreferrer\">a strict separation</a> of strings (<a href=\"https://docs.python.org/3/library/functions.html#func-str\" rel=\"noreferrer\"><code>str</code></a>) and binary data (<a href=\"https://docs.python.org/3/library/functions.html#func-bytes\" rel=\"noreferrer\"><code>bytes</code></a>).</p>\n<p>Alternatively, <code>isinstance</code> accepts a tuple of classes. This will return <code>True</code> if <code>o</code> is an instance of any subclass of any of <code>(str, unicode)</code>:</p>\n<pre><code>if isinstance(o, (str, unicode)):\n</code></pre>\n"
},
{
"answer_id": 153032,
"author": "Will Harding",
"author_id": 23508,
"author_profile": "https://Stackoverflow.com/users/23508",
"pm_score": 3,
"selected": false,
"text": "<p>I think the cool thing about using a dynamic language like Python is you really shouldn't have to check something like that.</p>\n\n<p>I would just call the required methods on your object and catch an <code>AttributeError</code>. Later on this will allow you to call your methods with other (seemingly unrelated) objects to accomplish different tasks, such as mocking an object for testing.</p>\n\n<p>I've used this a lot when getting data off the web with <code>urllib2.urlopen()</code> which returns a <em>file like</em> object. This can in turn can be passed to almost any method that reads from a file, because it implements the same <code>read()</code> method as a real file.</p>\n\n<p>But I'm sure there is a time and place for using <code>isinstance()</code>, otherwise it probably wouldn't be there :)</p>\n"
},
{
"answer_id": 154156,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 8,
"selected": false,
"text": "<p>The <strong>most</strong> Pythonic way to check the type of an object is... not to check it.</p>\n\n<p>Since Python encourages <a href=\"http://wikipedia.org/wiki/Duck_typing\" rel=\"noreferrer\">Duck Typing</a>, you should just <code>try...except</code> to use the object's methods the way you want to use them. So if your function is looking for a writable file object, <em>don't</em> check that it's a subclass of <code>file</code>, just try to use its <code>.write()</code> method!</p>\n\n<p>Of course, sometimes these nice abstractions break down and <code>isinstance(obj, cls)</code> is what you need. But use sparingly.</p>\n"
},
{
"answer_id": 11763264,
"author": "Chris Barker",
"author_id": 1569130,
"author_profile": "https://Stackoverflow.com/users/1569130",
"pm_score": 3,
"selected": false,
"text": "<p>To Hugo:</p>\n\n<p>You probably mean <code>list</code> rather than <code>array</code>, but that points to the whole problem with type checking - you don't want to know if the object in question is a list, you want to know if it's some kind of sequence or if it's a single object. So try to use it like a sequence.</p>\n\n<p>Say you want to add the object to an existing sequence, or if it's a sequence of objects, add them all</p>\n\n<pre><code>try:\n my_sequence.extend(o)\nexcept TypeError:\n my_sequence.append(o)\n</code></pre>\n\n<p>One trick with this is if you are working with strings and/or sequences of strings - that's tricky, as a string is often thought of as a single object, but it's also a sequence of characters. Worse than that, as it's really a sequence of single-length strings.</p>\n\n<p>I usually choose to design my API so that it only accepts either a single value or a sequence - it makes things easier. It's not hard to put a <code>[ ]</code> around your single value when you pass it in if need be.</p>\n\n<p>(Though this can cause errors with strings, as they do look like (are) sequences.)</p>\n"
},
{
"answer_id": 37076991,
"author": "Praxeolitic",
"author_id": 1128289,
"author_profile": "https://Stackoverflow.com/users/1128289",
"pm_score": 5,
"selected": false,
"text": "<p>After the question was asked and answered, <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"noreferrer\">type hints were added to Python</a>. Type hints in Python allow types to be checked but in a very different way from statically typed languages. Type hints in Python associate the expected types of arguments with functions as runtime accessible data associated with functions and this <em>allows</em> for types to be checked. Example of type hint syntax:</p>\n\n<pre><code>def foo(i: int):\n return i\n\nfoo(5)\nfoo('oops')\n</code></pre>\n\n<p>In this case we want an error to be triggered for <code>foo('oops')</code> since the annotated type of the argument is <code>int</code>. The added type hint does not <em>cause</em> an error to occur when the script is run normally. However, it adds attributes to the function describing the expected types that other programs can query and use to check for type errors.</p>\n\n<p>One of these other programs that can be used to find the type error is <code>mypy</code>:</p>\n\n<pre><code>mypy script.py\nscript.py:12: error: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\n</code></pre>\n\n<p>(You might need to install <code>mypy</code> from your package manager. I don't think it comes with CPython but seems to have some level of \"officialness\".)</p>\n\n<p>Type checking this way is different from type checking in statically typed compiled languages. Because types are dynamic in Python, type checking must be done at runtime, which imposes a cost -- even on correct programs -- if we insist that it happen at every chance. Explicit type checks may also be more restrictive than needed and cause unnecessary errors (e.g. does the argument really need to be of exactly <code>list</code> type or is anything iterable sufficient?).</p>\n\n<p>The upside of explicit type checking is that it can catch errors earlier and give clearer error messages than duck typing. The exact requirements of a duck type can only be expressed with external documentation (hopefully it's thorough and accurate) and errors from incompatible types can occur far from where they originate.</p>\n\n<p>Python's type hints are meant to offer a compromise where types can be specified and checked but there is no additional cost during usual code execution.</p>\n\n<p>The <code>typing</code> package offers type variables that can be used in type hints to express needed behaviors without requiring particular types. For example, it includes variables such as <code>Iterable</code> and <code>Callable</code> for hints to specify the need for any type with those behaviors.</p>\n\n<p>While type hints are the most Pythonic way to check types, it's often even more Pythonic to not check types at all and rely on duck typing. Type hints are relatively new and the jury is still out on when they're the most Pythonic solution. A relatively uncontroversial but very general comparison: Type hints provide a form of documentation that can be enforced, allow code to generate earlier and easier to understand errors, can catch errors that duck typing can't, and can be checked statically (in an unusual sense but it's still outside of runtime). On the other hand, duck typing has been the Pythonic way for a long time, doesn't impose the cognitive overhead of static typing, is less verbose, and will accept all viable types and then some.</p>\n"
},
{
"answer_id": 54720728,
"author": "Granitosaurus",
"author_id": 3737009,
"author_profile": "https://Stackoverflow.com/users/3737009",
"pm_score": 3,
"selected": false,
"text": "<p>For more complex type validations I like <a href=\"https://github.com/agronholm/typeguard\" rel=\"noreferrer\">typeguard</a>'s approach of validating based on python type hint annotations:</p>\n\n<pre><code>from typeguard import check_type\nfrom typing import List\n\ntry:\n check_type('mylist', [1, 2], List[int])\nexcept TypeError as e:\n print(e)\n</code></pre>\n\n<p>You can perform very complex validations in very clean and readable fashion.</p>\n\n<pre><code>check_type('foo', [1, 3.14], List[Union[int, float]])\n# vs\nisinstance(foo, list) and all(isinstance(a, (int, float)) for a in foo) \n</code></pre>\n"
},
{
"answer_id": 57099789,
"author": "Yerramsetty Rohit",
"author_id": 10548228,
"author_profile": "https://Stackoverflow.com/users/10548228",
"pm_score": 4,
"selected": false,
"text": "<p>You can check for type of a variable using __name__ of a type.</p>\n\n<p>Ex:</p>\n\n<pre><code>>>> a = [1,2,3,4] \n>>> b = 1 \n>>> type(a).__name__\n'list'\n>>> type(a).__name__ == 'list'\nTrue\n>>> type(b).__name__ == 'list'\nFalse\n>>> type(b).__name__\n'int'\n</code></pre>\n"
},
{
"answer_id": 59466517,
"author": "cherah30",
"author_id": 4887530,
"author_profile": "https://Stackoverflow.com/users/4887530",
"pm_score": -1,
"selected": false,
"text": "<p>I think the best way is to typing well your variables. You can do this by using the "typing" library.</p>\n<p>Example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import NewType\nUserId = NewType ('UserId', int)\nsome_id = UserId (524313`)\n</code></pre>\n<p>See <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/typing.html</a>.</p>\n"
},
{
"answer_id": 62122230,
"author": "Ultrablendz",
"author_id": 5006125,
"author_profile": "https://Stackoverflow.com/users/5006125",
"pm_score": -1,
"selected": false,
"text": "<p>A simple way to check type is to compare it with something whose type you know.</p>\n\n<pre><code>>>> a = 1\n>>> type(a) == type(1)\nTrue\n>>> b = 'abc'\n>>> type(b) == type('')\nTrue\n</code></pre>\n"
},
{
"answer_id": 67462404,
"author": "Simply Beautiful Art",
"author_id": 7741591,
"author_profile": "https://Stackoverflow.com/users/7741591",
"pm_score": 3,
"selected": false,
"text": "<p>The accepted answer answers the question in that it provides the answers to the asked questions.</p>\n<blockquote>\n<p>Q: What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?</p>\n</blockquote>\n<blockquote>\n<p>A: Use <code>isinstance, issubclass, type</code> to check based on types.</p>\n</blockquote>\n<p>As other answers and comments are quick to point out however, there's a lot more to the idea of "type-checking" than that in python. Since the addition of Python 3 and <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"noreferrer\">type hints</a>, much has changed as well. Below, I go over some of the difficulties with type checking, duck typing, and exception handling. For those that think type checking isn't what is needed (it usually isn't, but we're here), I also point out how type hints can be used instead.</p>\n<h3>Type Checking</h3>\n<p>Type checking is not always an appropriate thing to do in python. Consider the following example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def sum(nums):\n """Expect an iterable of integers and return the sum."""\n result = 0\n for n in nums:\n result += n\n return result\n</code></pre>\n<p>To check if the input is an iterable of integers, we run into a major issue. The only way to check if every element is an integer would be to loop through to check each element. But if we loop through the entire iterator, then there will be nothing left for intended code. We have two options in this kind of situation.</p>\n<ol>\n<li><p>Check as we loop.</p>\n</li>\n<li><p>Check beforehand but store everything as we check.</p>\n</li>\n</ol>\n<p>Option 1 has the downside of complicating our code, especially if we need to perform similar checks in many places. It forces us to move type checking from the top of the function to <em>everywhere</em> we use the iterable in our code.</p>\n<p>Option 2 has the obvious downside that it destroys the entire purpose of iterators. The entire point is to not store the data because we shouldn't need to.</p>\n<p>One might also think that checking if checking all of the elements is too much then perhaps we can just check if the input itself is of the type iterable, but there isn't actually any iterable base class. Any type implementing <code>__iter__</code> is iterable.</p>\n<h3>Exception Handling and Duck Typing</h3>\n<p>An alternative approach would be to forgo type checking altogether and focus on exception handling and duck typing instead. That is to say, wrap your code in a try-except block and catch any errors that occur. Alternatively, don't do anything and let exceptions rise naturally from your code.</p>\n<p>Here's one way to go about catching an exception.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def sum(nums):\n """Try to catch exceptions?"""\n try:\n result = 0\n for n in nums:\n result += n\n return result\n except TypeError as e:\n print(e)\n</code></pre>\n<p>Compared to the options before, this is certainly better. We're checking as we run the code. If there's a <code>TypeError</code> anywhere, we'll know. We don't have to place a check everywhere that we loop through the input. And we don't have to store the input as we iterate over it.</p>\n<p>Furthermore, this approach enables duck typing. Rather than checking for <code>specific types</code>, we have moved to checking for <code>specific behaviors</code> and look for when the input fails to behave as expected (in this case, looping through <code>nums</code> and being able to add <code>n</code>).</p>\n<p>However, the exact reasons which make exception handling nice can also be their downfall.</p>\n<ol>\n<li><p>A <code>float</code> isn't an <code>int</code>, but it satisfies the <em>behavioral</em> requirements to work.</p>\n</li>\n<li><p>It is also bad practice to wrap the entire code with a try-except block.</p>\n</li>\n</ol>\n<p>At first these may not seem like issues, but here's some reasons that may change your mind.</p>\n<ol>\n<li><p>A user can no longer expect our function to return an <code>int</code> as intended. This may break code elsewhere.</p>\n</li>\n<li><p>Since exceptions can come from a wide variety of sources, using the try-except on the whole code block may end up catching exceptions you didn't intend to. We only wanted to check if <code>nums</code> was iterable and had integer elements.</p>\n</li>\n<li><p>Ideally we'd like to catch exceptions our code generators and raise, in their place, more informative exceptions. It's not fun when an exception is raised from someone else's code with no explanation other than a line you didn't write and that some <code>TypeError</code> occured.</p>\n</li>\n</ol>\n<p>In order to fix the exception handling in response to the above points, our code would then become this... abomination.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def sum(nums):\n """\n Try to catch all of our exceptions only.\n Re-raise them with more specific details.\n """\n result = 0\n\n try:\n iter(nums)\n except TypeError as e:\n raise TypeError("nums must be iterable")\n\n for n in nums:\n try:\n result += int(n)\n except TypeError as e:\n raise TypeError("stopped mid iteration since a non-integer was found")\n\n return result\n</code></pre>\n<p>You can kinda see where this is going. The more we try to "properly" check things, the worse our code is looking. Compared to the original code, this isn't readable at all.</p>\n<p>We could argue perhaps this is a bit extreme. But on the other hand, this is only a very simple example. In practice, your code is probably much more complicated than this.</p>\n<h3>Type Hints</h3>\n<p>We've seen what happens when we try to modify our small example to "enable type checking". Rather than focusing on trying to force specific types, type hinting allows for a way to make types clear to users.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Iterable\n\ndef sum(nums: Iterable[int]) -> int:\n result = 0\n for n in nums:\n result += n\n return result\n</code></pre>\n<p>Here are some advantages to using type-hints.</p>\n<ul>\n<li><p>The code actually looks good now!</p>\n</li>\n<li><p>Static type analysis may be performed by your editor if you use type hints!</p>\n</li>\n<li><p>They are stored on the function/class, making them dynamically usable e.g. <a href=\"https://github.com/agronholm/typeguard\" rel=\"noreferrer\"><code>typeguard</code></a> and <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"noreferrer\"><code>dataclasses</code></a>.</p>\n</li>\n<li><p>They show up for functions when using <code>help(...)</code>.</p>\n</li>\n<li><p>No need to sanity check if your input type is right based on a description or worse lack thereof.</p>\n</li>\n<li><p>You can "type" hint based on <a href=\"https://www.python.org/dev/peps/pep-0544/\" rel=\"noreferrer\">structure</a> e.g. "does it have this attribute?" without requiring subclassing by the user.</p>\n</li>\n</ul>\n<p>The downside to type hinting?</p>\n<ul>\n<li>Type hints are nothing more than syntax and special text on their own. <em>It isn't the same as type checking</em>.</li>\n</ul>\n<p>In other words, it doesn't actually answer the question because it doesn't provide type checking. Regardless, however, if you are here for type checking, then you <em>should</em> be type hinting as well. Of course, if you've come to the conclusion that type checking isn't actually necessary but you want some semblance of typing, then type hints are for you.</p>\n"
},
{
"answer_id": 68052807,
"author": "SuperNova",
"author_id": 3464971,
"author_profile": "https://Stackoverflow.com/users/3464971",
"pm_score": 5,
"selected": false,
"text": "<p>In <a href=\"https://www.python.org/dev/peps/pep-0604/\" rel=\"noreferrer\">Python 3.10</a>, you can use <code>|</code> in <code>isinstance</code>:</p>\n<pre><code>>>> isinstance('1223', int | str) \nTrue\n\n>>> isinstance('abcd', int | str) \nTrue\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14102/"
] |
How do I check if an object is of a given type, or if it inherits from a given type?
How do I check if the object `o` is of type `str`?
---
Beginners often wrongly expect the string to *already be* "a number" - either expecting Python 3.x `input` to convert type, or expecting that a string like `'1'` is *also simultaneously* an integer. This is the wrong canonical for those questions. Please carefully read the question and then use [How do I check if a string represents a number (float or int)?](https://stackoverflow.com/questions/354038), [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/) and/or [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/) as appropriate.
|
Use [`isinstance`](https://docs.python.org/library/functions.html#isinstance) to check if `o` is an instance of `str` or any subclass of `str`:
```
if isinstance(o, str):
```
To check if the type of `o` is exactly `str`, *excluding subclasses of `str`*:
```
if type(o) is str:
```
Another alternative to the above:
```
if issubclass(type(o), str):
```
See [Built-in Functions](http://docs.python.org/library/functions.html) in the Python Library Reference for relevant information.
---
#### Checking for strings in Python 2
For Python 2, this is a better way to check if `o` is a string:
```
if isinstance(o, basestring):
```
because this will also catch Unicode strings. [`unicode`](https://docs.python.org/2/library/functions.html#unicode) is not a subclass of `str`; whereas, both `str` and `unicode` are subclasses of [`basestring`](https://docs.python.org/2/library/functions.html#basestring). In Python 3, `basestring` no longer exists since there's [a strict separation](https://docs.python.org/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit) of strings ([`str`](https://docs.python.org/3/library/functions.html#func-str)) and binary data ([`bytes`](https://docs.python.org/3/library/functions.html#func-bytes)).
Alternatively, `isinstance` accepts a tuple of classes. This will return `True` if `o` is an instance of any subclass of any of `(str, unicode)`:
```
if isinstance(o, (str, unicode)):
```
|
152,585 |
<p>What is the simplest way to identify and separate GET and POST parameters from a controller in Ruby on Rails, which will be equivalent to $_GET and $_POST variables in PHP?</p>
|
[
{
"answer_id": 152599,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 6,
"selected": false,
"text": "<p>You can use the <code>request.get?</code> and <code>request.post?</code> methods to distinguish between HTTP Gets and Posts.</p>\n\n<ul>\n<li>See <a href=\"http://api.rubyonrails.org/classes/ActionDispatch/Request.html\" rel=\"noreferrer\">http://api.rubyonrails.org/classes/ActionDispatch/Request.html</a></li>\n</ul>\n"
},
{
"answer_id": 152609,
"author": "Toby Hede",
"author_id": 14971,
"author_profile": "https://Stackoverflow.com/users/14971",
"pm_score": 1,
"selected": false,
"text": "<p>I think what you want to do isn't very \"Rails\", if you know what I mean. Your GET requests should be <strong>idempotent</strong> - you should be able to issue the same GET request many times and get the same result each time. </p>\n"
},
{
"answer_id": 152652,
"author": "Ben Scofield",
"author_id": 6478,
"author_profile": "https://Stackoverflow.com/users/6478",
"pm_score": 6,
"selected": true,
"text": "<p>I don't know of any convenience methods in Rails for this, but you can access the querystring directly to parse out parameters that are set there. Something like the following:</p>\n\n<pre><code>request.query_string.split(/&/).inject({}) do |hash, setting|\n key, val = setting.split(/=/)\n hash[key.to_sym] = val\n hash\nend\n</code></pre>\n"
},
{
"answer_id": 152872,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to check the type of request in order to prevent doing anything when the wrong method is used, be aware that you can also specify it in your routes.rb file:</p>\n\n<pre><code>map.connect '/posts/:post_id', :controller => 'posts', :action => 'update', :conditions => {:method => :post} \n</code></pre>\n\n<p>or </p>\n\n<pre><code>map.resources :posts, :conditions => {:method => :post} \n</code></pre>\n\n<p>Your PostsController's update method will now only be called when you effectively had a post. Check out the doc for <a href=\"http://www.railsbrain.com/api/rails-2.1.0/doc/index.html?a=M000354&name=resources\" rel=\"nofollow noreferrer\">resources</a>. </p>\n"
},
{
"answer_id": 152922,
"author": "domgblackwell",
"author_id": 16954,
"author_profile": "https://Stackoverflow.com/users/16954",
"pm_score": 1,
"selected": false,
"text": "<p>You don't need to know that level of detail in the controller. Your routes and forms will cause appropriate items to be added to the params hash. Then in the controller you just access say <code>params[:foo]</code> to get the foo parameter and do whatever you need to with it.</p>\n\n<p>The mapping between GET and POST (and PUT and DELETE) and controller actions is set up in <code>config/routes.rb</code> in most modern Rails code.</p>\n"
},
{
"answer_id": 5505704,
"author": "jesse reiss",
"author_id": 654332,
"author_profile": "https://Stackoverflow.com/users/654332",
"pm_score": 3,
"selected": false,
"text": "<p>There is a difference between GET and POST params. A POST HTTP request can still have GET params.</p>\n\n<p>GET parameters are URL query parameters.</p>\n\n<p>POST parameters are parameters in the body of the HTTP request.</p>\n\n<p>you can access these separately from the request.GET and request.POST hashes.</p>\n"
},
{
"answer_id": 8364866,
"author": "wiseland",
"author_id": 1078483,
"author_profile": "https://Stackoverflow.com/users/1078483",
"pm_score": 4,
"selected": false,
"text": "<p>You can do it using:</p>\n\n<p><code>request.POST</code> </p>\n\n<p>and</p>\n\n<p><code>request.GET</code></p>\n"
},
{
"answer_id": 9586443,
"author": "Ryan Barton",
"author_id": 204148,
"author_profile": "https://Stackoverflow.com/users/204148",
"pm_score": 4,
"selected": false,
"text": "<p>There are three very-lightly-documented hash accessors on the request object for this:</p>\n\n<ul>\n<li><code>request.query_parameters</code> - sent as part of the query string, i.e. after a ?</li>\n<li><code>request.path_parameters</code> - decoded from the URL via routing, i.e. controller, action, id</li>\n<li><code>request.request_parameters</code> - All params, including above as well as any sent as part of the POST body</li>\n</ul>\n\n<p>You can use <code>Hash#reject</code> to get to the POST-only params as needed.</p>\n\n<p>Source: <a href=\"http://guides.rubyonrails.org/v2.3.8/action_controller_overview.html\" rel=\"noreferrer\">http://guides.rubyonrails.org/v2.3.8/action_controller_overview.html</a> section 9.1.1</p>\n\n<p>I looked in an old Rails 1.2.6 app and these accessors existed back then as well.</p>\n"
},
{
"answer_id": 13389109,
"author": "Rod McLaughlin",
"author_id": 1495955,
"author_profile": "https://Stackoverflow.com/users/1495955",
"pm_score": 0,
"selected": false,
"text": "<p>I think what Jesse Reiss is talking about is a situation where in your <code>routes.rb</code> file you have</p>\n\n<pre><code>post 'ctrllr/:a/:b' => 'ctrllr#an_action'\n</code></pre>\n\n<p>and you POST to <strong>\"/ctrllr/foo/bar?a=not_foo\"</strong> POST values <strong>{'a' => 'still_not_foo'}</strong>, you will have three different values of 'a': 'foo', 'not_foo', and 'still_not_foo'</p>\n\n<p>'params' in the controller will have 'a' set to 'foo'. To find 'a' set to 'not_foo' and 'still_not_foo', you need to examine <code>request.GET</code> and <code>request.POST</code></p>\n\n<p>I wrote a gem which distinguishes between these different key=>value pairs at <a href=\"https://github.com/pdxrod/routesfordummies\" rel=\"nofollow\">https://github.com/pdxrod/routesfordummies</a>.</p>\n"
},
{
"answer_id": 16123963,
"author": "betoharres",
"author_id": 1254111,
"author_profile": "https://Stackoverflow.com/users/1254111",
"pm_score": 0,
"selected": false,
"text": "<pre><code>if request.query_parameters().to_a.empty?\n</code></pre>\n"
},
{
"answer_id": 39448933,
"author": "Navin",
"author_id": 3522082,
"author_profile": "https://Stackoverflow.com/users/3522082",
"pm_score": 3,
"selected": false,
"text": "<p><code>request.get?</code> will return boolean true if it is GET method,</p>\n\n<p><code>request.post?</code> will return boolean true if it is POST method,</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18768/"
] |
What is the simplest way to identify and separate GET and POST parameters from a controller in Ruby on Rails, which will be equivalent to $\_GET and $\_POST variables in PHP?
|
I don't know of any convenience methods in Rails for this, but you can access the querystring directly to parse out parameters that are set there. Something like the following:
```
request.query_string.split(/&/).inject({}) do |hash, setting|
key, val = setting.split(/=/)
hash[key.to_sym] = val
hash
end
```
|
152,602 |
<p>Which of theese two alternatives do you find yourself using most often, and which is more "idiomatic"?</p>
<ol>
<li>f arg (obj.DoStuff())</li>
<li>f arg <| obj.DoStuff()</li>
</ol>
|
[
{
"answer_id": 152637,
"author": "Rayne",
"author_id": 21734,
"author_profile": "https://Stackoverflow.com/users/21734",
"pm_score": 0,
"selected": false,
"text": "<p>I use () much much more often, but thats just preference, I'm pretty sure that <| is more idomatic, but I use () by habit.</p>\n"
},
{
"answer_id": 152860,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 0,
"selected": false,
"text": "<p>Whenever possible, I much prefer |> because it reads from left to right.</p>\n"
},
{
"answer_id": 152933,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 4,
"selected": true,
"text": "<p>Overall, I don't know that one or the other is more idiomatic.</p>\n\n<p>Personally, the only time I use <| is with \"raise\":</p>\n\n<pre><code>raise <| new FooException(\"blah\")\n</code></pre>\n\n<p>Apart from that, I always use parens. Note that since most F# code uses curried functions, this does not typically imply any \"extra\" parens:</p>\n\n<pre><code>f arg (g x y)\n</code></pre>\n\n<p>It's when you get into non-curried functions and constructors and whatnot that it starts getting less pretty:</p>\n\n<pre><code>f arg (g(x,y))\n</code></pre>\n\n<p>We will probably at least <em>consider</em> changing the F# languages rules so that high-precedence applications bind even more tightly; right now</p>\n\n<pre><code>f g()\n</code></pre>\n\n<p>parses like</p>\n\n<pre><code>f g ()\n</code></pre>\n\n<p>but a lot of people would like it to parse as</p>\n\n<pre><code>f (g())\n</code></pre>\n\n<p>(the motivating case in the original question). If you have a strong opinion about this, leave a comment on this response.</p>\n"
},
{
"answer_id": 300465,
"author": "namin",
"author_id": 34596,
"author_profile": "https://Stackoverflow.com/users/34596",
"pm_score": 2,
"selected": false,
"text": "<p>Because type inference works from left to right, a bonus of using <code>|></code> is that it allows F# to infer the type of the argument of the function.</p>\n\n<p>As a contrived example, </p>\n\n<pre><code>[1; 2; 3] |> (fun x -> x.Length*2)\n</code></pre>\n\n<p>works just fine, but</p>\n\n<pre><code>(fun x -> x.Length*2) [1; 2; 3]\n</code></pre>\n\n<p>complains of \"lookup on object of indeterminate type\".</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21182/"
] |
Which of theese two alternatives do you find yourself using most often, and which is more "idiomatic"?
1. f arg (obj.DoStuff())
2. f arg <| obj.DoStuff()
|
Overall, I don't know that one or the other is more idiomatic.
Personally, the only time I use <| is with "raise":
```
raise <| new FooException("blah")
```
Apart from that, I always use parens. Note that since most F# code uses curried functions, this does not typically imply any "extra" parens:
```
f arg (g x y)
```
It's when you get into non-curried functions and constructors and whatnot that it starts getting less pretty:
```
f arg (g(x,y))
```
We will probably at least *consider* changing the F# languages rules so that high-precedence applications bind even more tightly; right now
```
f g()
```
parses like
```
f g ()
```
but a lot of people would like it to parse as
```
f (g())
```
(the motivating case in the original question). If you have a strong opinion about this, leave a comment on this response.
|
152,613 |
<p>I have a specialized list that holds items of type <code>IThing</code>:</p>
<pre><code>public class ThingList : IList<IThing>
{...}
public interface IThing
{
Decimal Weight { get; set; }
Decimal Velocity { get; set; }
Decimal Distance { get; set; }
Decimal Age { get; set; }
Decimal AnotherValue { get; set; }
[...even more properties and methods...]
}
</code></pre>
<p>Sometimes I need to know the maximum or minimum of a certain property of all the things in the list. Because of "Tell don't ask" we let the List figure it out:</p>
<pre><code>public class ThingList : IList<IThing>
{
public Decimal GetMaximumWeight()
{
Decimal result = 0;
foreach (IThing thing in this) {
result = Math.Max(result, thing.Weight);
}
return result;
}
}
</code></pre>
<p>Thats very nice. But sometimes I need the minimum weight, sometimes the maximum velocity and so on. I don't want a <code>GetMaximum*()/GetMinimum*()</code> pair for every single property.</p>
<p>One solution would be reflection. Something like (hold your nose, strong code smell!):</p>
<pre><code>Decimal GetMaximum(String propertyName);
Decimal GetMinimum(String propertyName);
</code></pre>
<p>Are there any better, less smelly ways to accomplish this?</p>
<p>Thanks,
Eric</p>
<p>Edit: @Matt: .Net 2.0</p>
<p><strike>Conclusion: There is no better way for .Net 2.0 (with Visual Studio 2005). Maybe we should move to .Net 3.5 and Visual Studio 2008 sometime soon. Thanks, guys.</strike></p>
<p>Conclusion: There are diffent ways that are far better than reflection. Depending on runtime and C# version. Have a look at Jon Skeets answer for the differences. All answers are are very helpful.</p>
<p>I will go for Sklivvz suggestion (anonymous methods). There are several code snippets from other people (Konrad Rudolph, Matt Hamilton and Coincoin) which implement Sklivvz idea. I can only "accept" one answer, unfortunately.</p>
<p>Thank you very much. You can all feel "accepted", altough only Sklivvz gets the credits ;-)</p>
|
[
{
"answer_id": 152619,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": false,
"text": "<p>If you were you using .NET 3.5 and LINQ:</p>\n\n<pre><code>Decimal result = myThingList.Max(i => i.Weight);\n</code></pre>\n\n<p>That would make the calculation of Min and Max fairly trivial.</p>\n"
},
{
"answer_id": 152624,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>If using .NET 3.5, why not use lambdas?</p>\n\n<pre><code>public Decimal GetMaximum(Func<IThing, Decimal> prop) {\n Decimal result = Decimal.MinValue;\n foreach (IThing thing in this)\n result = Math.Max(result, prop(thing));\n\n return result;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Decimal result = list.GetMaximum(x => x.Weight);\n</code></pre>\n\n<p>This is strongly typed and efficient. There are also extension methods that already do exactly this.</p>\n"
},
{
"answer_id": 152625,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "<p>(Edited to reflect .NET 2.0 answer, and LINQBridge in VS2005...)</p>\n\n<p>There are three situations here - although the OP only has .NET 2.0, other people facing the same problem may not...</p>\n\n<p>1) Using .NET 3.5 and C# 3.0: use LINQ to Objects like this:</p>\n\n<pre><code>decimal maxWeight = list.Max(thing => thing.Weight);\ndecimal minWeight = list.Min(thing => thing.Weight);\n</code></pre>\n\n<p>2) Using .NET 2.0 and C# 3.0: use <a href=\"http://www.albahari.com/nutshell/linqbridge.aspx\" rel=\"noreferrer\">LINQBridge</a> and the same code</p>\n\n<p>3) Using .NET 2.0 and C# 2.0: use <a href=\"http://www.albahari.com/nutshell/linqbridge.aspx\" rel=\"noreferrer\">LINQBridge</a> and anonymous methods:</p>\n\n<pre><code>decimal maxWeight = Enumerable.Max(list, delegate(IThing thing) \n { return thing.Weight; }\n);\ndecimal minWeight = Enumerable.Min(list, delegate(IThing thing)\n { return thing.Weight; }\n);\n</code></pre>\n\n<p>(I don't have a C# 2.0 compiler to hand to test the above - if it complains about an ambiguous conversion, cast the delegate to Func<IThing,decimal>.)</p>\n\n<p>LINQBridge will work with VS2005, but you don't get extension methods, lambda expressions, query expressions etc. Clearly migrating to C# 3 is a nicer option, but I'd prefer using LINQBridge to implementing the same functionality myself.</p>\n\n<p>All of these suggestions involve walking the list twice if you need to get both the max and min. If you've got a situation where you're loading from disk lazily or something like that, and you want to calculate several aggregates in one go, you might want to look at my <a href=\"http://msmvps.com/blogs/jon_skeet/archive/2008/01/04/quot-push-quot-linq-revisited-next-attempt-at-an-explanation.aspx\" rel=\"noreferrer\">\"Push LINQ\"</a> code in <a href=\"http://pobox.com/~skeet/csharp/miscutil\" rel=\"noreferrer\">MiscUtil</a>. (That works with .NET 2.0 as well.)</p>\n"
},
{
"answer_id": 152626,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, you should use a delegate and anonymous methods.</p>\n<p>For an example see <a href=\"http://encodo.com/en/blogs.php?entry_id=76\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Basically you need to implement something similar to the <a href=\"http://msdn.microsoft.com/en-us/library/x0b5b5bc(VS.80).aspx\" rel=\"nofollow noreferrer\">Find method of Lists</a>.</p>\n<p>Here is a sample implementation</p>\n<pre><code>public class Thing\n{\n public int theInt;\n public char theChar;\n public DateTime theDateTime;\n \n public Thing(int theInt, char theChar, DateTime theDateTime)\n {\n this.theInt = theInt;\n this.theChar = theChar;\n this.theDateTime = theDateTime;\n }\n \n public string Dump()\n {\n return string.Format("I: {0}, S: {1}, D: {2}", \n theInt, theChar, theDateTime);\n }\n}\n\npublic class ThingCollection: List<Thing>\n{\n public delegate Thing AggregateFunction(Thing Best, \n Thing Candidate);\n \n public Thing Aggregate(Thing Seed, AggregateFunction Func)\n {\n Thing res = Seed;\n foreach (Thing t in this) \n {\n res = Func(res, t);\n }\n return res;\n }\n}\n\nclass MainClass\n{\n public static void Main(string[] args)\n {\n Thing a = new Thing(1,'z',DateTime.Now);\n Thing b = new Thing(2,'y',DateTime.Now.AddDays(1));\n Thing c = new Thing(3,'x',DateTime.Now.AddDays(-1));\n Thing d = new Thing(4,'w',DateTime.Now.AddDays(2));\n Thing e = new Thing(5,'v',DateTime.Now.AddDays(-2));\n \n ThingCollection tc = new ThingCollection();\n \n tc.AddRange(new Thing[]{a,b,c,d,e});\n \n Thing result;\n\n //Max by date\n result = tc.Aggregate(tc[0], \n delegate (Thing Best, Thing Candidate) \n { \n return (Candidate.theDateTime.CompareTo(\n Best.theDateTime) > 0) ? \n Candidate : \n Best; \n }\n );\n Console.WriteLine("Max by date: {0}", result.Dump());\n \n //Min by char\n result = tc.Aggregate(tc[0], \n delegate (Thing Best, Thing Candidate) \n { \n return (Candidate.theChar < Best.theChar) ? \n Candidate : \n Best; \n }\n );\n Console.WriteLine("Min by char: {0}", result.Dump()); \n }\n}\n</code></pre>\n<p>The results:</p>\n<p><code>Max by date: I: 4, S: w, D: 10/3/2008 12:44:07 AM</code><br />\n<code>Min by char: I: 5, S: v, D: 9/29/2008 12:44:07 AM</code></p>\n"
},
{
"answer_id": 152756,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p><del>Conclusion: There is no better way for .Net 2.0 (with Visual Studio 2005).</del></p>\n</blockquote>\n\n<p><del>You seem to have misunderstood the answers (especially Jon's). You can use option 3 from his answer.</del> If you don't want to use LinqBridge you can still use a delegate and implement the <code>Max</code> method yourself, similar to the method I've posted:</p>\n\n<pre><code>delegate Decimal PropertyValue(IThing thing);\n\npublic class ThingList : IList<IThing> {\n public Decimal Max(PropertyValue prop) {\n Decimal result = Decimal.MinValue;\n foreach (IThing thing in this) {\n result = Math.Max(result, prop(thing));\n }\n return result;\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>ThingList lst;\nlst.Max(delegate(IThing thing) { return thing.Age; });\n</code></pre>\n"
},
{
"answer_id": 152763,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 2,
"selected": false,
"text": "<p>For C# 2.0 and .Net 2.0 you can do the following for Max:</p>\n\n<pre><code>public delegate Decimal GetProperty<TElement>(TElement element);\n\npublic static Decimal Max<TElement>(IEnumerable<TElement> enumeration, \n GetProperty<TElement> getProperty)\n{\n Decimal max = Decimal.MinValue;\n\n foreach (TElement element in enumeration)\n {\n Decimal propertyValue = getProperty(element);\n max = Math.Max(max, propertyValue);\n }\n\n return max;\n}\n</code></pre>\n\n<p>And here is how you would use it:</p>\n\n<pre><code>string[] array = new string[] {\"s\",\"sss\",\"ddsddd\",\"333\",\"44432333\"};\n\nMax(array, delegate(string e) { return e.Length;});\n</code></pre>\n\n<p>Here is how you would do it with C# 3.0, .Net 3.5 and Linq, without the function above:</p>\n\n<pre><code>string[] array = new string[] {\"s\",\"sss\",\"ddsddd\",\"333\",\"44432333\"};\narray.Max( e => e.Length);\n</code></pre>\n"
},
{
"answer_id": 152778,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an attempt, using C# 2.0, at Skilwz's idea.</p>\n\n<pre><code>public delegate T GetPropertyValueDelegate<T>(IThing t);\n\npublic T GetMaximum<T>(GetPropertyValueDelegate<T> getter)\n where T : IComparable\n{\n if (this.Count == 0) return default(T);\n\n T max = getter(this[0]);\n for (int i = 1; i < this.Count; i++)\n {\n T ti = getter(this[i]);\n if (max.CompareTo(ti) < 0) max = ti;\n }\n return max;\n}\n</code></pre>\n\n<p>You'd use it like this:</p>\n\n<pre><code>ThingList list;\nDecimal maxWeight = list.GetMaximum(delegate(IThing t) { return t.Weight; });\n</code></pre>\n"
},
{
"answer_id": 152976,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "<p>How about a generalised .Net 2 solution?</p>\n\n<pre><code>public delegate A AggregateAction<A, B>( A prevResult, B currentElement );\n\npublic static Tagg Aggregate<Tcoll, Tagg>( \n IEnumerable<Tcoll> source, Tagg seed, AggregateAction<Tagg, Tcoll> func )\n{\n Tagg result = seed;\n\n foreach ( Tcoll element in source ) \n result = func( result, element );\n\n return result;\n}\n\n//this makes max easy\npublic static int Max( IEnumerable<int> source )\n{\n return Aggregate<int,int>( source, 0, \n delegate( int prev, int curr ) { return curr > prev ? curr : prev; } );\n}\n\n//but you could also do sum\npublic static int Sum( IEnumerable<int> source )\n{\n return Aggregate<int,int>( source, 0, \n delegate( int prev, int curr ) { return curr + prev; } );\n}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8976/"
] |
I have a specialized list that holds items of type `IThing`:
```
public class ThingList : IList<IThing>
{...}
public interface IThing
{
Decimal Weight { get; set; }
Decimal Velocity { get; set; }
Decimal Distance { get; set; }
Decimal Age { get; set; }
Decimal AnotherValue { get; set; }
[...even more properties and methods...]
}
```
Sometimes I need to know the maximum or minimum of a certain property of all the things in the list. Because of "Tell don't ask" we let the List figure it out:
```
public class ThingList : IList<IThing>
{
public Decimal GetMaximumWeight()
{
Decimal result = 0;
foreach (IThing thing in this) {
result = Math.Max(result, thing.Weight);
}
return result;
}
}
```
Thats very nice. But sometimes I need the minimum weight, sometimes the maximum velocity and so on. I don't want a `GetMaximum*()/GetMinimum*()` pair for every single property.
One solution would be reflection. Something like (hold your nose, strong code smell!):
```
Decimal GetMaximum(String propertyName);
Decimal GetMinimum(String propertyName);
```
Are there any better, less smelly ways to accomplish this?
Thanks,
Eric
Edit: @Matt: .Net 2.0
Conclusion: There is no better way for .Net 2.0 (with Visual Studio 2005). Maybe we should move to .Net 3.5 and Visual Studio 2008 sometime soon. Thanks, guys.
Conclusion: There are diffent ways that are far better than reflection. Depending on runtime and C# version. Have a look at Jon Skeets answer for the differences. All answers are are very helpful.
I will go for Sklivvz suggestion (anonymous methods). There are several code snippets from other people (Konrad Rudolph, Matt Hamilton and Coincoin) which implement Sklivvz idea. I can only "accept" one answer, unfortunately.
Thank you very much. You can all feel "accepted", altough only Sklivvz gets the credits ;-)
|
Yes, you should use a delegate and anonymous methods.
For an example see [here](http://encodo.com/en/blogs.php?entry_id=76).
Basically you need to implement something similar to the [Find method of Lists](http://msdn.microsoft.com/en-us/library/x0b5b5bc(VS.80).aspx).
Here is a sample implementation
```
public class Thing
{
public int theInt;
public char theChar;
public DateTime theDateTime;
public Thing(int theInt, char theChar, DateTime theDateTime)
{
this.theInt = theInt;
this.theChar = theChar;
this.theDateTime = theDateTime;
}
public string Dump()
{
return string.Format("I: {0}, S: {1}, D: {2}",
theInt, theChar, theDateTime);
}
}
public class ThingCollection: List<Thing>
{
public delegate Thing AggregateFunction(Thing Best,
Thing Candidate);
public Thing Aggregate(Thing Seed, AggregateFunction Func)
{
Thing res = Seed;
foreach (Thing t in this)
{
res = Func(res, t);
}
return res;
}
}
class MainClass
{
public static void Main(string[] args)
{
Thing a = new Thing(1,'z',DateTime.Now);
Thing b = new Thing(2,'y',DateTime.Now.AddDays(1));
Thing c = new Thing(3,'x',DateTime.Now.AddDays(-1));
Thing d = new Thing(4,'w',DateTime.Now.AddDays(2));
Thing e = new Thing(5,'v',DateTime.Now.AddDays(-2));
ThingCollection tc = new ThingCollection();
tc.AddRange(new Thing[]{a,b,c,d,e});
Thing result;
//Max by date
result = tc.Aggregate(tc[0],
delegate (Thing Best, Thing Candidate)
{
return (Candidate.theDateTime.CompareTo(
Best.theDateTime) > 0) ?
Candidate :
Best;
}
);
Console.WriteLine("Max by date: {0}", result.Dump());
//Min by char
result = tc.Aggregate(tc[0],
delegate (Thing Best, Thing Candidate)
{
return (Candidate.theChar < Best.theChar) ?
Candidate :
Best;
}
);
Console.WriteLine("Min by char: {0}", result.Dump());
}
}
```
The results:
`Max by date: I: 4, S: w, D: 10/3/2008 12:44:07 AM`
`Min by char: I: 5, S: v, D: 9/29/2008 12:44:07 AM`
|
152,618 |
<p>Probably a long question for a simple solution, but here goes...</p>
<p>I have a custom made silverlight control for selecting multiple files and sending them to the server. It sends files to a general handler (FileReciever.ashx) using the OpenWriteAsync method of a WebCLient control.</p>
<p>Basically, the silverlight code does something like this for each file:</p>
<pre><code>WebClient client = new WebClient();
client.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
client.OpenWriteAsync(handlerUri);
</code></pre>
<p>The server side handler simply reads the incoming stream, and then does some more processing with the resulting byte array.</p>
<p>THE PROBLEM is that client side OpenWriteCompleted is done as soon as all the data has been sent over the wire. My code will then contine with the next file. What I really want is to wait until the ASHX handler has finished with all it's processing of that request. How do I do that? Any wait mechanism on WebClient? Any callback I can do on the HttpContext in the handler? Should I use some other kind of transfer technique? Please advice!</p>
|
[
{
"answer_id": 152632,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 1,
"selected": true,
"text": "<p>Hrm, maybe a simple solutioin could be to tag the url with a GUID(the guid being unique per file, or transfer, whatever makes sense to your situatuation). Then you can have another simple web service that is capable of checking on the status of the other service, based on the guid, and have your silverlight client query that new service for its processing status(by passing the new web service the guid of the past transfer).</p>\n"
},
{
"answer_id": 152648,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 0,
"selected": false,
"text": "<p>I'm assuming that you're concerned that the data being returned from the handler is taking a long time to transfer and the server is not being utilized during that time. There isn't a way to tell when the server is done processing, so I don't think you can do this without changing your architecture.</p>\n\n<p>I would have your handler only an identifier of some sort (like a GUID or int) that can be used to retrieve the result of the handler in another request. So the page would call the handler, the handler would store the result and return the identifier, the page would call the handler the second time and call another handler to get the result of the first call. This would keep your server in use while your data was transferring.</p>\n"
},
{
"answer_id": 152970,
"author": "ANaimi",
"author_id": 2721,
"author_profile": "https://Stackoverflow.com/users/2721",
"pm_score": 0,
"selected": false,
"text": "<p>Or you can probably do it with JavaScript (jQuery)... if you don't mind using JavaScript that is.</p>\n"
},
{
"answer_id": 154173,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 0,
"selected": false,
"text": "<p>If files are not very big, and is feasible to keep each of them in memory, an ugly yet effective solution is converting them to strings and sending them using the UploadStringAsync method. </p>\n\n<p>Avoid this approach if file size is unbounded, but if you can now that they will be relatively small, it is possible to use this approach.</p>\n"
},
{
"answer_id": 8324714,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 1,
"selected": false,
"text": "<p>The same question has been asked in Silverlight <a href=\"http://forums.silverlight.net/t/20144.aspx/1/10\" rel=\"nofollow\">forums</a>. The Microsoft endorsed answer was that you can't do that with WebClient and OpenWriteAsync. You need to either user UploadStringAsync or an HttpWebRequest.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22621/"
] |
Probably a long question for a simple solution, but here goes...
I have a custom made silverlight control for selecting multiple files and sending them to the server. It sends files to a general handler (FileReciever.ashx) using the OpenWriteAsync method of a WebCLient control.
Basically, the silverlight code does something like this for each file:
```
WebClient client = new WebClient();
client.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
client.OpenWriteAsync(handlerUri);
```
The server side handler simply reads the incoming stream, and then does some more processing with the resulting byte array.
THE PROBLEM is that client side OpenWriteCompleted is done as soon as all the data has been sent over the wire. My code will then contine with the next file. What I really want is to wait until the ASHX handler has finished with all it's processing of that request. How do I do that? Any wait mechanism on WebClient? Any callback I can do on the HttpContext in the handler? Should I use some other kind of transfer technique? Please advice!
|
Hrm, maybe a simple solutioin could be to tag the url with a GUID(the guid being unique per file, or transfer, whatever makes sense to your situatuation). Then you can have another simple web service that is capable of checking on the status of the other service, based on the guid, and have your silverlight client query that new service for its processing status(by passing the new web service the guid of the past transfer).
|
152,643 |
<p>For an <code>std::map<std::string, std::string> variables</code>, I'd like to do this:</p>
<pre><code>BOOST_CHECK_EQUAL(variables["a"], "b");
</code></pre>
<p>The only problem is, in this context <code>variables</code> is <code>const</code>, so <code>operator[]</code> won't work :(</p>
<p>Now, there are several workarounds to this; casting away the <code>const</code>, using <code>variables.count("a") ? variables.find("a")->second : std::string()</code> or even making a function wrapping that. None of these seem to me to be as nice as <code>operator[]</code>. What should I do? Is there a standard way of doing this (beautifully)?</p>
<p><strong>Edit:</strong> Just to state the answer that none of you want to give: No, there is no convenient, beautiful, standard way of doing this in C++. I will have to implement a support function.</p>
|
[
{
"answer_id": 152658,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p><code>find</code> is the idiomatic form. Casting away <code>const</code> is almost always a bad idea. You'd have to guarantee that no write operation is performed. While this can be reasonably expected of a read access on a map, the specification doesn't say anything about this.</p>\n\n<p>If you <em>know</em> that the value exists you can of course forego the test using <code>count</code> (which is quite inefficient, anyway, since it means traversing the map twice. Even if you don't know whether the element exists I wouldn't use this. Use the following instead:</p>\n\n<pre><code>T const& item(map<TKey, T> const& m, TKey const& key, T const& def = T()) {\n map<TKey, T>::const_iterator i = m.find(key);\n return i == m.end() ? def : i->second;\n}\n</code></pre>\n\n<p>/EDIT: As Chris has correctly pointed out, default-construction of objects of type <code>T</code> <em>might</em> be expensive, especially since this is done even if this object isn't actually needed (because the entry exists). If this is the case, don't use the default value for the <code>def</code> argument in the above case.</p>\n"
},
{
"answer_id": 152660,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 1,
"selected": false,
"text": "<p>Indeed, operator[] is a non-const one on std::map, since it automatically inserts a key-value pair in the map if it weren't there. (Oooh side-effects!)</p>\n\n<p>The right way is using <code>map::find</code> and, if the returned iterator is valid (<code>!= map.end()</code>), returning the <code>second</code>, as you showed.</p>\n\n<pre><code>map<int, int> m;\nm[1]=5; m[2]=6; // fill in some couples\n...\nmap<int,int>::const_iterator it = m.find( 3 );\nif( it != m.end() ) {\n int value = it->second;\n // ... do stuff with value\n}\n</code></pre>\n\n<p>You <em>could</em> add a <code>map::operator[]( const key_type& key ) const</code> in a subclass of the std::map you're using, and assert the key to be found, after which you return the <code>it->second</code>.</p>\n"
},
{
"answer_id": 152665,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "<pre><code>template <typename K, typename V>\nV get(std::map<K, V> const& map, K const& key)\n{\n std::map<K, V>::const_iterator iter(map.find(key));\n return iter != map.end() ? iter->second : V();\n}\n</code></pre>\n\n<p>Improved implementation based on comments:</p>\n\n<pre><code>template <typename T>\ntypename T::mapped_type get(T const& map, typename T::key_type const& key)\n{\n typename T::const_iterator iter(map.find(key));\n return iter != map.end() ? iter->second : typename T::mapped_type();\n}\n</code></pre>\n"
},
{
"answer_id": 152680,
"author": "janm",
"author_id": 7256,
"author_profile": "https://Stackoverflow.com/users/7256",
"pm_score": 4,
"selected": false,
"text": "<p>Casting away const is wrong, because operator[] on map<> will create the entry if it isn't present with a default constructed string. If the map is actually in immutable storage then it will fail. This must be so because operator[] returns a non-const reference to allow assignment. (eg. m[1] = 2)</p>\n\n<p>A quick free function to implement the comparison:</p>\n\n<pre><code>template<typename CONT>\nbool check_equal(const CONT& m, const typename CONT::key_type& k,\n const typename CONT::mapped_type& v)\n{\n CONT::const_iterator i(m.find(k));\n if (i == m.end()) return false;\n return i->second == v;\n}\n</code></pre>\n\n<p>I'll think about syntactic sugar and update if I think of something.</p>\n\n<p>...</p>\n\n<p>The immediate syntactic sugar involved a free function that does a map<>::find() and returns a special class that wraps map<>::const_iterator, and then has overloaded operator==() and operator!=() to allow comparison with the mapped type. So you can do something like:</p>\n\n<pre><code>if (nonmutating_get(m, \"key\") == \"value\") { ... }\n</code></pre>\n\n<p>I'm not convinced that is much better than:</p>\n\n<pre><code>if (check_equal(m, \"key\", \"value\")) { ... }\n</code></pre>\n\n<p>And it is certainly much more complex and what is going on is much less obvious.</p>\n\n<p>The purpose of the object wrapping the iterator is to stop having default constructed data objects. If you don't care, then just use the \"get\" answer.</p>\n\n<p>In response to the comment about the get being preferred over a comparison in the hope of finding some future use, I have these comments:</p>\n\n<ul>\n<li><p>Say what you mean: calling a function called \"check_equal\" makes it clear that you are doing an equality comparison without object creation.</p></li>\n<li><p>I recommend only implementing functionality once you have a need. Doing something before then is often a mistake.</p></li>\n<li><p>Depending on the situation, a default constructor might have side-effects. If you are comparing, why do anything extra?</p></li>\n<li><p>The SQL argument: NULL is not equivalent to an empty string. Is the absence of a key from your container really the same as the key being present in your container with a default constructed value?</p></li>\n</ul>\n\n<p>Having said all that, a default constructed object is equivalent to using map<>::operator[] on a non-const container. And perhaps you have a current requirement for a get function that returns a default constructed object; I know I have had that requirement in the past.</p>\n"
},
{
"answer_id": 153145,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 3,
"selected": false,
"text": "<p>An interesting aside, there are two ways do the template type discovery in the get implementation that was accepted (the one that gets the value or returns a default constructed object). One, you can do what was accepted and have:</p>\n\n<pre><code>template <typename K, typename V>\nV get1(const std::map<K, V>& theMap, const K const key)\n{\n std::map<K, V>::const_iterator iter(theMap.find(key));\n return iter != theMap.end() ? iter->second : V();\n}\n</code></pre>\n\n<p>or you can use the map type and get the types off of that:</p>\n\n<pre><code>template<typename T>\ntypename T::mapped_type\nget2(const T& theMap, const typename T::key_type& key)\n{\n typename T::const_iterator itr = theMap.find(key);\n return itr != theMap.end() ? itr->second : typename T::mapped_type();\n}\n</code></pre>\n\n<p>The advantage of this is that the type of the key being passed in doesn't play in the type discovery and it can be something that can be implicitly converted to a key. For example:</p>\n\n<pre><code>std::map<std::string, int> data;\nget1(data, \"hey\"); // doesn't compile because the key type is ambiguous\nget2(data, \"hey\"); // just fine, a const char* can be converted to a string\n</code></pre>\n"
},
{
"answer_id": 153913,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 0,
"selected": false,
"text": "<pre><code>std::map<std::string, std::string>::const_iterator it( m.find(\"a\") );\nBOOST_CHECK_EQUAL( \n ( it == m.end() ? std::string(\"\") : it->second ), \n \"b\" \n );\n</code></pre>\n\n<p>That doesn't look too bad to me... I probably wouldn't write a function for this. </p>\n"
},
{
"answer_id": 1000076,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Following up xtofl's idea of specializing the map container. Will the following work well?</p>\n\n<pre><code>template <typename K,typename V> \nstruct Dictionary:public std::map<K,V> \n{ \n const V& operator[] (const K& key) const \n { \n std::map<K,V>::const_iterator iter(this->find(key)); \n BOOST_VERIFY(iter!=this->end()); \n return iter->second; \n } \n}; \n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2971/"
] |
For an `std::map<std::string, std::string> variables`, I'd like to do this:
```
BOOST_CHECK_EQUAL(variables["a"], "b");
```
The only problem is, in this context `variables` is `const`, so `operator[]` won't work :(
Now, there are several workarounds to this; casting away the `const`, using `variables.count("a") ? variables.find("a")->second : std::string()` or even making a function wrapping that. None of these seem to me to be as nice as `operator[]`. What should I do? Is there a standard way of doing this (beautifully)?
**Edit:** Just to state the answer that none of you want to give: No, there is no convenient, beautiful, standard way of doing this in C++. I will have to implement a support function.
|
```
template <typename K, typename V>
V get(std::map<K, V> const& map, K const& key)
{
std::map<K, V>::const_iterator iter(map.find(key));
return iter != map.end() ? iter->second : V();
}
```
Improved implementation based on comments:
```
template <typename T>
typename T::mapped_type get(T const& map, typename T::key_type const& key)
{
typename T::const_iterator iter(map.find(key));
return iter != map.end() ? iter->second : typename T::mapped_type();
}
```
|
152,664 |
<p>I have many items inside a list control. I want each item to have a different item template depending on the type of the item. So the first item in the list is a ObjectA type and so I want it to be rendered with ItemTemplateA. Second item is a ObjectB type and so I want it to have ItemTemplateB for rendering. At the moment I can only use the ItemTemplate setting to define one template for them all. Any way to achieve this?</p>
|
[
{
"answer_id": 152672,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "<p>Have a look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemtemplateselector.aspx\" rel=\"noreferrer\">ItemTemplateSelector</a> property of your list control. You can point it to a custom TemplateSelector and decide which template to use in code.</p>\n\n<p>Here's a blog post describing TemplateSelectors:</p>\n\n<p><a href=\"http://blogs.interknowlogy.com/johnbowen/archive/2007/06/21/20463.aspx\" rel=\"noreferrer\">http://blogs.interknowlogy.com/johnbowen/archive/2007/06/21/20463.aspx</a></p>\n\n<p>Edit: Here's a better post:</p>\n\n<p><a href=\"http://blog.paranoidferret.com/index.php/2008/07/16/wpf-tutorial-how-to-use-a-datatemplateselector/\" rel=\"noreferrer\">http://blog.paranoidferret.com/index.php/2008/07/16/wpf-tutorial-how-to-use-a-datatemplateselector/</a></p>\n"
},
{
"answer_id": 152779,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 5,
"selected": true,
"text": "<p>the <code>ItemTemplateSelector</code> will work but I think it is easier to create multiple <code>DataTemplate</code>s in your resource section and then just giving each one a <code>DataType</code>. This will automatically then use this <code>DataTemplate</code> if the items generator detects the matching data type?</p>\n\n<pre><code><DataTemplate DataType={x:Type local:ObjectA}>\n ...\n</DataTemplate>\n</code></pre>\n\n<p>Also make sure that you have no <code>x:Key</code> set for the <code>DataTemplate</code>.<br>\nRead more about this approach <a href=\"http://www.zagstudio.com/blog/361#.Us6JPJG-3nc\" rel=\"nofollow noreferrer\">here</a> </p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6276/"
] |
I have many items inside a list control. I want each item to have a different item template depending on the type of the item. So the first item in the list is a ObjectA type and so I want it to be rendered with ItemTemplateA. Second item is a ObjectB type and so I want it to have ItemTemplateB for rendering. At the moment I can only use the ItemTemplate setting to define one template for them all. Any way to achieve this?
|
the `ItemTemplateSelector` will work but I think it is easier to create multiple `DataTemplate`s in your resource section and then just giving each one a `DataType`. This will automatically then use this `DataTemplate` if the items generator detects the matching data type?
```
<DataTemplate DataType={x:Type local:ObjectA}>
...
</DataTemplate>
```
Also make sure that you have no `x:Key` set for the `DataTemplate`.
Read more about this approach [here](http://www.zagstudio.com/blog/361#.Us6JPJG-3nc)
|
152,670 |
<p>Is it possible to prevent the Windows Installer from running every time Access 2003 and Access 2007 are started, when they are both installed on the same machine at the same time..?</p>
<p>Like many developers I need to run more than 1 version of MS Access. I have just installed Access 2007. If I open Access 2003 and then open Access 2007 I have to wait 3mins for the 'Configuring Microsoft Office Enterprise 2007..." dialog. Then if I open Access 2003 again it takes another 30secs or so to configure that. </p>
<p>PLEASE NOTE: I am using shortcuts to open the files that include the full path to Access. Eg to open Access 2007:</p>
<pre><code> "C:\program files\microsoft office 12\office12\msaccess.exe" "C:\test.accdb"
</code></pre>
<p>and for 2003:</p>
<pre><code> "C:\program files\microsoft office 11\office11\msaccess.exe" "C:\test.mdb"
</code></pre>
|
[
{
"answer_id": 152875,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 2,
"selected": false,
"text": "<p>This is caused by Windows Installer, which is used by both installers. Advertised shortcuts as used by both Office 2003 and Office 2007 invoke Windows Installer to check that the entire feature is installed properly; the installer detects that something else (in this case the other product) has registered the file extensions used by Access (possibly the ProgIds as well) and decides that a repair is necessary, so it invokes the 'Configuring Office' dialog and proceeds to reinstall various components.</p>\n\n<p>To avoid this, run Access from Program Files directly; create shortcuts if you'll be doing this frequently.</p>\n"
},
{
"answer_id": 156079,
"author": "Chris OC",
"author_id": 11041,
"author_profile": "https://Stackoverflow.com/users/11041",
"pm_score": 1,
"selected": false,
"text": "<p>Want to cut it down to about 20 seconds to reconfigure Access 2007 after opening Access 2003? Download and install Office 2007 sp1:</p>\n\n<p><a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=9EC51594-992C-4165-A997-25DA01F388F5&displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?FamilyId=9EC51594-992C-4165-A997-25DA01F388F5&displaylang=en</a></p>\n\n<p>Btw, you can't avoid the reconfiguration between Access 2007 and earlier versions. Access 2007 uses some of the same registry keys as earlier versions and they have to be rewritten when opening Access 2007.</p>\n"
},
{
"answer_id": 160498,
"author": "Tim Lara",
"author_id": 3469,
"author_profile": "https://Stackoverflow.com/users/3469",
"pm_score": 0,
"selected": false,
"text": "<p>The best workaround I've found for this is to use VMWare Thinapp to virtualize one (or more) of the offending versions of Access:</p>\n\n<p><a href=\"http://www.vmware.com/products/thinapp/\" rel=\"nofollow noreferrer\">http://www.vmware.com/products/thinapp/</a></p>\n\n<p>It's a little more lightweight than a full Virtual PC / VMWare / etc installation, but unfortunately still a bit of a hassle to set up and not free.</p>\n"
},
{
"answer_id": 1450798,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The fix to the problem is very simple as it turns out - \nsimply run the following commands (by pressing the Windows Key+R or typing it into the Start/Run command box. \n Use the line with Office\\11.0 if you have Office 2003 installed and Office\\12.0 if you have Office 2007 installed. \n You can use both if you have both installed :</p>\n\n<pre><code>reg add HKCU\\Software\\Microsoft\\Office\\11.0\\Word\\Options /v NoReReg /t REG_DWORD /d 1\n\nreg add HKCU\\Software\\Microsoft\\Office\\12.0\\Word\\Options /v NoReReg /t REG_DWORD /d 1\n</code></pre>\n\n<p>That is it. Office 2007 might want to have one more spin round the block with it's configuration dialog box, but that should be it. </p>\n\n<p>C: \\Program Files>Common Files>microsoft shared>OFFICE12>Office Setup Controller>SETUP.exe change to SETUPold.exe</p>\n\n<p>[HKEY_CURRENT_USER\\Software\\Classes\\Access.Application]</p>\n\n<p>This key will cause the config screen to constantly cycle everytime you open Access 2007.<br>\nBy deleting the key and everything under it, it fixes the cycling problem and Access 2007 opens right away.</p>\n"
},
{
"answer_id": 1947415,
"author": "master",
"author_id": 236995,
"author_profile": "https://Stackoverflow.com/users/236995",
"pm_score": 0,
"selected": false,
"text": "<p>Just Install Office 2007 Sp2, that works.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10422/"
] |
Is it possible to prevent the Windows Installer from running every time Access 2003 and Access 2007 are started, when they are both installed on the same machine at the same time..?
Like many developers I need to run more than 1 version of MS Access. I have just installed Access 2007. If I open Access 2003 and then open Access 2007 I have to wait 3mins for the 'Configuring Microsoft Office Enterprise 2007..." dialog. Then if I open Access 2003 again it takes another 30secs or so to configure that.
PLEASE NOTE: I am using shortcuts to open the files that include the full path to Access. Eg to open Access 2007:
```
"C:\program files\microsoft office 12\office12\msaccess.exe" "C:\test.accdb"
```
and for 2003:
```
"C:\program files\microsoft office 11\office11\msaccess.exe" "C:\test.mdb"
```
|
This is caused by Windows Installer, which is used by both installers. Advertised shortcuts as used by both Office 2003 and Office 2007 invoke Windows Installer to check that the entire feature is installed properly; the installer detects that something else (in this case the other product) has registered the file extensions used by Access (possibly the ProgIds as well) and decides that a repair is necessary, so it invokes the 'Configuring Office' dialog and proceeds to reinstall various components.
To avoid this, run Access from Program Files directly; create shortcuts if you'll be doing this frequently.
|
152,675 |
<p>There is probably is simple fix for this but I currently have code similar to </p>
<pre><code>dim dr as dbDataReader
try
dr = connection.getDataReader(sql_str)
Catch ex as sqlClientException
log.error(ex)
finally
if not IsNothing(dr) then
dr.close
end if
end try
</code></pre>
<p>However Visual Studio still warns me that the </p>
<pre><code>if not IsNothing(dr) then
dr.close
end if
</code></pre>
<p>Can cause a NullReferenceException. What is the best way to mitigate this? I can't move the declaration into the try block.</p>
|
[
{
"answer_id": 152715,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 0,
"selected": false,
"text": "<p>Your code is correct. In the <code>finally</code> statement, as long as you check to make sure your objects are not null, it won't throw a null reference exception based on what happens in your code.</p>\n"
},
{
"answer_id": 152718,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 0,
"selected": false,
"text": "<p>I don't remember exactly, how VB.NET initialize variable, but in C# you must set \"dr\" some value/reference before you use them somewhere.</p>\n\n<p>I think this should work:</p>\n\n<pre><code>dim dr as dbDataReader\n\ntry\n dr = connection.getDataReader(sql_str)\nCatch ex as sqlClientException\n log.error(ex)\n dr = Nothing ' there is the change '\n' finaly block is not necesary '\nend try\n\nif not IsNothing(dr) then\n dr.close\nend if\n</code></pre>\n"
},
{
"answer_id": 152719,
"author": "Jason Stangroome",
"author_id": 20819,
"author_profile": "https://Stackoverflow.com/users/20819",
"pm_score": 4,
"selected": true,
"text": "<p>Explicitly initialize the dr declaration to Nothing as such:</p>\n\n<pre><code>Dim dr As DbDataReader = Nothing\n</code></pre>\n\n<p>And the warning will disappear.</p>\n"
},
{
"answer_id": 152862,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 2,
"selected": false,
"text": "<p>If <code>GetDataReader</code> throws, <code>dr</code> will not be assigned and will still have its initial value. VB.NET does initialise references to <code>Nothing</code>, but the compiler will not let you rely on that.</p>\n\n<p>If using .NET 2.0, I would recommend a <code>Using</code> statement:</p>\n\n<pre><code>Using dr As DbDataReader = connection.GetDataReader(sql_str)\n Try\n ' Do something with dr '\n Catch ex As SqlClientException\n log.error(ex)\n End Try\nEnd Using\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11802/"
] |
There is probably is simple fix for this but I currently have code similar to
```
dim dr as dbDataReader
try
dr = connection.getDataReader(sql_str)
Catch ex as sqlClientException
log.error(ex)
finally
if not IsNothing(dr) then
dr.close
end if
end try
```
However Visual Studio still warns me that the
```
if not IsNothing(dr) then
dr.close
end if
```
Can cause a NullReferenceException. What is the best way to mitigate this? I can't move the declaration into the try block.
|
Explicitly initialize the dr declaration to Nothing as such:
```
Dim dr As DbDataReader = Nothing
```
And the warning will disappear.
|
152,693 |
<p>I have an <strong>if</strong> condition which checks for value and the it throws new <strong>NumberFormatException</strong></p>
<p>Is there any other way to code this</p>
<pre><code>if (foo)
{
throw new NumberFormatException
}
// ..
catch (NumberFormatException exc)
{
// some msg...
}
</code></pre>
|
[
{
"answer_id": 152709,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 2,
"selected": false,
"text": "<p>If your aim is to avoid to throw a new exception:</p>\n\n<pre><code>if(foo)\n{\n //some msg...\n} else\n{\n //do something else\n}\n</code></pre>\n"
},
{
"answer_id": 152716,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>In Java, you can try parsing a string with regular expressions before trying to convert it to a number.</p>\n\n<p>If you're trying to catch your own exception (why???) you could do this:</p>\n\n<pre><code>try { if (foo) throw new NumberFormatException(); }\ncatch(NumberFormatexception) {/* ... */}\n</code></pre>\n"
},
{
"answer_id": 152720,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 2,
"selected": false,
"text": "<p>If you are doing something such as this:</p>\n\n<pre><code>try\n{\n // some stuff\n if (foo)\n {\n throw new NumberFormatException();\n }\n}\ncatch (NumberFormatException exc)\n{\n do something;\n}\n</code></pre>\n\n<p>Then sure, you could avoid the exception completely and do the 'do something' part inside the conditional block.</p>\n"
},
{
"answer_id": 152725,
"author": "dice",
"author_id": 22100,
"author_profile": "https://Stackoverflow.com/users/22100",
"pm_score": 0,
"selected": false,
"text": "<p>if you are trying to replace the throwing of an exception with some other error handling mechanism your only option is to return or set an error code - the problem is that you then have to go and ensure it is checked elsewhere.</p>\n\n<p>the exception is best.</p>\n"
},
{
"answer_id": 152751,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 1,
"selected": false,
"text": "<p>Don't throw exceptions if you can handle them in another, more elegant manner. Exceptions are expensive and should only be used for cases where there is something going on beyond your control (e.g. a database server is not responding).</p>\n\n<p>If you are trying to ensure that a value is set, and formatted correctly, you should try to handle failure of these conditions in a more graceful manner. For example...</p>\n\n<pre><code>if(myObject.value != null && Checkformat(myObject.Value)\n{\n // good to go\n}\nelse\n{\n // not a good place to be. Prompt the user rather than raise an exception?\n}\n</code></pre>\n"
},
{
"answer_id": 152813,
"author": "Nate",
"author_id": 21108,
"author_profile": "https://Stackoverflow.com/users/21108",
"pm_score": 0,
"selected": false,
"text": "<p>If you know the flow that will cause you to throw a NumberFormatException, code to handle that case. You shouldn't use Exception hierarchies as a program flow mechanism.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11114/"
] |
I have an **if** condition which checks for value and the it throws new **NumberFormatException**
Is there any other way to code this
```
if (foo)
{
throw new NumberFormatException
}
// ..
catch (NumberFormatException exc)
{
// some msg...
}
```
|
If your aim is to avoid to throw a new exception:
```
if(foo)
{
//some msg...
} else
{
//do something else
}
```
|
152,699 |
<p>In Python, you can do this:</p>
<pre><code>import webbrowser
webbrowser.open_new("http://example.com/")
</code></pre>
<p>It will open the passed in url in the default browser</p>
<p>Is there a ruby equivalent?</p>
|
[
{
"answer_id": 152765,
"author": "Ken",
"author_id": 20621,
"author_profile": "https://Stackoverflow.com/users/20621",
"pm_score": 2,
"selected": false,
"text": "<p>Windows Only Solution:</p>\n\n<pre><code>require 'win32ole'\nshell = WIN32OLE.new('Shell.Application')\nshell.ShellExecute(...)\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb774148.aspx\" rel=\"nofollow noreferrer\">Shell Execute on MSDN</a></p>\n"
},
{
"answer_id": 152775,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 0,
"selected": false,
"text": "<p>If it's windows and it's IE, try this: <a href=\"http://rubyonwindows.blogspot.com/search/label/watir\" rel=\"nofollow noreferrer\">http://rubyonwindows.blogspot.com/search/label/watir</a> also check out Selenium ruby: <a href=\"http://selenium.rubyforge.org/getting-started.html\" rel=\"nofollow noreferrer\">http://selenium.rubyforge.org/getting-started.html</a></p>\n\n<p>HTH </p>\n"
},
{
"answer_id": 152951,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 5,
"selected": false,
"text": "<p>Mac-only solution:</p>\n\n<pre><code>system(\"open\", \"http://stackoverflow.com/\")\n</code></pre>\n\n<p>or</p>\n\n<pre><code>`open http://stackoverflow.com/`\n</code></pre>\n"
},
{
"answer_id": 152996,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 8,
"selected": true,
"text": "<h2>Cross-platform solution:</h2>\n\n<p>First, install the <a href=\"http://www.copiousfreetime.org/projects/launchy/\" rel=\"noreferrer\">Launchy</a> gem:</p>\n\n<pre><code>$ gem install launchy\n</code></pre>\n\n<p>Then, you can run this:</p>\n\n<pre><code>require 'launchy'\n\nLaunchy.open(\"http://stackoverflow.com\")\n</code></pre>\n"
},
{
"answer_id": 153558,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 2,
"selected": false,
"text": "<p>This also works:</p>\n\n<pre><code>system(\"start #{link}\")\n</code></pre>\n"
},
{
"answer_id": 155154,
"author": "James Baker",
"author_id": 9365,
"author_profile": "https://Stackoverflow.com/users/9365",
"pm_score": 3,
"selected": false,
"text": "<p>Simplest Win solution:</p>\n\n<pre>`start http://www.example.com`</pre>\n"
},
{
"answer_id": 12702115,
"author": "damage3025",
"author_id": 1656173,
"author_profile": "https://Stackoverflow.com/users/1656173",
"pm_score": 3,
"selected": false,
"text": "<p>Linux-only solution</p>\n\n<pre><code>system(\"xdg-open\", \"http://stackoverflow.com/\")\n</code></pre>\n"
},
{
"answer_id": 14053693,
"author": "user1931928",
"author_id": 1931928,
"author_profile": "https://Stackoverflow.com/users/1931928",
"pm_score": 5,
"selected": false,
"text": "<p>This should work on most platforms:</p>\n\n<pre><code>link = \"Insert desired link location here\"\nif RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/\n system \"start #{link}\"\nelsif RbConfig::CONFIG['host_os'] =~ /darwin/\n system \"open #{link}\"\nelsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/\n system \"xdg-open #{link}\"\nend\n</code></pre>\n"
},
{
"answer_id": 58855763,
"author": "Felix",
"author_id": 1680728,
"author_profile": "https://Stackoverflow.com/users/1680728",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the 'os' gem: <a href=\"https://github.com/rdp/os\" rel=\"nofollow noreferrer\">https://github.com/rdp/os</a> to let your operating system (in the best case you own your OS, meaning not OS X) decide what to do with an URL.</p>\n<p>Typically this will be a good choice.</p>\n<pre><code>require 'os'\n\nsystem(OS.open_file_command, 'https://stackoverflow.com')\n# ~ like `xdg-open stackoverflow.com` on most modern unixoids,\n# but should work on most other operating systems, too.\n</code></pre>\n<p><strong>Note</strong> On windows, the argument(s?) to <code>system</code> need to be escaped, see comment section. There should be a function in Rubys stdlib for that, feel free to add it to the comments and I will update the answer.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147/"
] |
In Python, you can do this:
```
import webbrowser
webbrowser.open_new("http://example.com/")
```
It will open the passed in url in the default browser
Is there a ruby equivalent?
|
Cross-platform solution:
------------------------
First, install the [Launchy](http://www.copiousfreetime.org/projects/launchy/) gem:
```
$ gem install launchy
```
Then, you can run this:
```
require 'launchy'
Launchy.open("http://stackoverflow.com")
```
|
152,708 |
<p>I needed to find all the files that contained a specific string pattern. The first solution that comes to mind is using <em>find</em> piped with <em>xargs grep</em>:</p>
<pre><code>find . -iname '*.py' | xargs grep -e 'YOUR_PATTERN'
</code></pre>
<p>But if I need to find patterns that spans on more than one line, I'm stuck because vanilla grep can't find multiline patterns.</p>
|
[
{
"answer_id": 152711,
"author": "Oli",
"author_id": 22035,
"author_profile": "https://Stackoverflow.com/users/22035",
"pm_score": 8,
"selected": true,
"text": "<p>So I discovered <a href=\"http://www.pcre.org/\" rel=\"nofollow noreferrer\"><em><strong>pcregrep</strong></em></a> which stands for <strong>Perl Compatible Regular Expressions GREP</strong>.</p>\n<blockquote>\n<p>the -M option makes it possible to search for patterns that span line boundaries.</p>\n</blockquote>\n<p>For example, you need to find files where the '<em>_name</em>' variable is followed on the next line by the '<em>_description</em>' variable:</p>\n<pre><code>find . -iname '*.py' | xargs pcregrep -M '_name.*\\n.*_description'\n</code></pre>\n<p>Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\\n', \\r', '\\r\\n', ...</p>\n"
},
{
"answer_id": 152755,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": 7,
"selected": false,
"text": "<p>Here is the example using <a href=\"https://www.gnu.org/software/grep/\" rel=\"nofollow noreferrer\">GNU <code>grep</code></a>:</p>\n<pre><code>grep -Pzo '_name.*\\n.*_description'\n</code></pre>\n<blockquote>\n<p><code>-z</code>/<code>--null-data</code> Treat the input as a set of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline.</p>\n</blockquote>\n<p>Which has the effect of treating the whole file as one large line.\nSee <code>-z</code> description <a href=\"https://stackoverflow.com/questions/3717772/regex-grep-for-multi-line-search-needed/7167115#7167115\">on grep's manual</a> and also <a href=\"https://www.gnu.org/software/grep/manual/html_node/Usage.html\" rel=\"nofollow noreferrer\">common question no 14 on grep's manual usage page</a></p>\n"
},
{
"answer_id": 152848,
"author": "Oli",
"author_id": 22035,
"author_profile": "https://Stackoverflow.com/users/22035",
"pm_score": 5,
"selected": false,
"text": "<p>Here is a more useful example:</p>\n\n<pre><code>pcregrep -Mi \"<title>(.*\\n){0,5}</title>\" afile.html\n</code></pre>\n\n<p>It searches the title tag in a html file even if it spans up to 5 lines.</p>\n\n<p>Here is an example of unlimited lines:</p>\n\n<pre><code>pcregrep -Mi \"(?s)<title>.*</title>\" example.html \n</code></pre>\n"
},
{
"answer_id": 3718035,
"author": "Amit",
"author_id": 448436,
"author_profile": "https://Stackoverflow.com/users/448436",
"pm_score": 7,
"selected": false,
"text": "<p>Why don't you go for <a href=\"http://www.gnu.org/software/gawk/manual/gawk.html\" rel=\"noreferrer\">awk</a>:</p>\n\n<pre><code>awk '/Start pattern/,/End pattern/' filename\n</code></pre>\n"
},
{
"answer_id": 7170065,
"author": "albfan",
"author_id": 848072,
"author_profile": "https://Stackoverflow.com/users/848072",
"pm_score": 2,
"selected": false,
"text": "<p>This answer might be useful:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/3717772/regex-grep-for-multi-line-search-needed/7167115#7167115\">Regex (grep) for multi-line search needed</a></p>\n\n<p>To find recursively you can use flags -R (recursive) and --include (GLOB pattern). See:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/221921/grep-exclude-include-syntax-do-not-grep-through-certain-files/221929#221929\">Use grep --exclude/--include syntax to not grep through certain files</a></p>\n"
},
{
"answer_id": 11676024,
"author": "bukzor",
"author_id": 146821,
"author_profile": "https://Stackoverflow.com/users/146821",
"pm_score": 5,
"selected": false,
"text": "<p><code>grep -P</code> also uses libpcre, but is <em>much</em> more widely installed. To find a complete <code>title</code> section of an html document, even if it spans multiple lines, you can use this:</p>\n\n<pre><code>grep -P '(?s)<title>.*</title>' example.html\n</code></pre>\n\n<p>Since <a href=\"http://www.pcre.org/\" rel=\"noreferrer\">the PCRE project</a> implements to the perl standard, use the perl documentation for reference:</p>\n\n<ul>\n<li><a href=\"http://perldoc.perl.org/perlre.html#Modifiers\" rel=\"noreferrer\">http://perldoc.perl.org/perlre.html#Modifiers</a></li>\n<li><a href=\"http://perldoc.perl.org/perlre.html#Extended-Patterns\" rel=\"noreferrer\">http://perldoc.perl.org/perlre.html#Extended-Patterns</a></li>\n</ul>\n"
},
{
"answer_id": 27931490,
"author": "Shwaydogg",
"author_id": 722738,
"author_profile": "https://Stackoverflow.com/users/722738",
"pm_score": 4,
"selected": false,
"text": "<p>With <a href=\"https://github.com/ggreer/the_silver_searcher\">silver searcher</a>:</p>\n\n<pre><code>ag 'abc.*(\\n|.)*efg'\n</code></pre>\n\n<p>Speed optimizations of silver searcher could possibly shine here.</p>\n"
},
{
"answer_id": 28664303,
"author": "svent",
"author_id": 4535174,
"author_profile": "https://Stackoverflow.com/users/4535174",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the grep alternative <a href=\"http://sift-tool.org\" rel=\"noreferrer\">sift</a> here (disclaimer: I am the author).</p>\n\n<p>It support multiline matching and limiting the search to specific file types out of the box:</p>\n\n<pre>sift -m --files '*.py' 'YOUR_PATTERN'</pre>\n\n<p>(search all *.py files for the specified multiline regex pattern)</p>\n\n<p>It is available for all major operating systems. Take a look at the <a href=\"http://sift-tool.org/samples.html\" rel=\"noreferrer\">samples page</a> to see how it can be used to to extract multiline values from an XML file.</p>\n"
},
{
"answer_id": 31589471,
"author": "Martin",
"author_id": 5148382,
"author_profile": "https://Stackoverflow.com/users/5148382",
"pm_score": 3,
"selected": false,
"text": "<p>@Marcin:\nawk example non-greedy:</p>\n\n<pre><code>awk '{if ($0 ~ /Start pattern/) {triggered=1;}if (triggered) {print; if ($0 ~ /End pattern/) { exit;}}}' filename\n</code></pre>\n"
},
{
"answer_id": 33180874,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 2,
"selected": false,
"text": "<p>Using <code>ex</code>/<code>vi</code> editor and <a href=\"http://wiki.bash-hackers.org/internals/shell_options#globstar\" rel=\"nofollow noreferrer\">globstar option</a> (syntax similar to <code>awk</code> and <code>sed</code>):</p>\n\n<pre><code>ex +\"/string1/,/string3/p\" -R -scq! file.txt\n</code></pre>\n\n<p>where <code>aaa</code> is your starting point, and <code>bbb</code> is your ending text.</p>\n\n<p>To search recursively, try:</p>\n\n<pre><code>ex +\"/aaa/,/bbb/p\" -scq! **/*.py\n</code></pre>\n\n<p><sup>Note: To enable <code>**</code> syntax, run <code>shopt -s globstar</code> (Bash 4 or zsh).</sup></p>\n"
},
{
"answer_id": 36393093,
"author": "pbal",
"author_id": 5905959,
"author_profile": "https://Stackoverflow.com/users/5905959",
"pm_score": 2,
"selected": false,
"text": "<pre><code>perl -ne 'print if (/begin pattern/../end pattern/)' filename\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22035/"
] |
I needed to find all the files that contained a specific string pattern. The first solution that comes to mind is using *find* piped with *xargs grep*:
```
find . -iname '*.py' | xargs grep -e 'YOUR_PATTERN'
```
But if I need to find patterns that spans on more than one line, I'm stuck because vanilla grep can't find multiline patterns.
|
So I discovered [***pcregrep***](http://www.pcre.org/) which stands for **Perl Compatible Regular Expressions GREP**.
>
> the -M option makes it possible to search for patterns that span line boundaries.
>
>
>
For example, you need to find files where the '*\_name*' variable is followed on the next line by the '*\_description*' variable:
```
find . -iname '*.py' | xargs pcregrep -M '_name.*\n.*_description'
```
Tip: you need to include the line break character in your pattern. Depending on your platform, it could be '\n', \r', '\r\n', ...
|
152,714 |
<p>I am relatively new to matchers. I am toying around with <a href="http://code.google.com/p/hamcrest/" rel="noreferrer">hamcrest</a> in combination with JUnit and I kinda like it.</p>
<p>Is there a way, to state that one of multiple choices is correct?</p>
<p>Something like</p>
<pre><code>assertThat( result, is( either( 1, or( 2, or( 3 ) ) ) ) ) //does not work in hamcrest
</code></pre>
<p>The method I am testing returns one element of a collection. The list may contain multiple candidates. My current implementation returns the first hit, but that is not a requirement. I would like my testcase to succeed, if any of the possible candidates is returned. How would you express this in Java?</p>
<p>(I am open to hamcrest-alternatives)</p>
|
[
{
"answer_id": 153198,
"author": "marcospereira",
"author_id": 4600,
"author_profile": "https://Stackoverflow.com/users/4600",
"pm_score": 8,
"selected": true,
"text": "<pre><code>assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3)))\n</code></pre>\n<p>From <a href=\"http://hamcrest.org/JavaHamcrest/tutorial#logical\" rel=\"noreferrer\">Hamcrest tutorial</a>:</p>\n<blockquote>\n<p><code>anyOf</code> - matches if any matchers match, short circuits (like Java ||)</p>\n</blockquote>\n<p>See also <a href=\"http://hamcrest.org/JavaHamcrest/javadoc/2.2/org/hamcrest/core/AnyOf.html\" rel=\"noreferrer\">Javadoc</a>.</p>\n<p>Moreover, you could write your own Matcher, which is quite easy to do.</p>\n"
},
{
"answer_id": 6554732,
"author": "Tyler",
"author_id": 65977,
"author_profile": "https://Stackoverflow.com/users/65977",
"pm_score": 6,
"selected": false,
"text": "<p>marcos is right, but you have a couple other options as well. First of all, there <em>is</em> an either/or:</p>\n\n<pre><code>assertThat(result, either(is(1)).or(is(2)));\n</code></pre>\n\n<p>but if you have more than two items it would probably get unwieldy. Plus, the typechecker gets weird on stuff like that sometimes. For your case, you could do:</p>\n\n<pre><code>assertThat(result, isOneOf(1, 2, 3))\n</code></pre>\n\n<p>or if you already have your options in an array/Collection:</p>\n\n<pre><code>assertThat(result, isIn(theCollection))\n</code></pre>\n\n<p>See also <a href=\"http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html\">Javadoc</a>.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] |
I am relatively new to matchers. I am toying around with [hamcrest](http://code.google.com/p/hamcrest/) in combination with JUnit and I kinda like it.
Is there a way, to state that one of multiple choices is correct?
Something like
```
assertThat( result, is( either( 1, or( 2, or( 3 ) ) ) ) ) //does not work in hamcrest
```
The method I am testing returns one element of a collection. The list may contain multiple candidates. My current implementation returns the first hit, but that is not a requirement. I would like my testcase to succeed, if any of the possible candidates is returned. How would you express this in Java?
(I am open to hamcrest-alternatives)
|
```
assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3)))
```
From [Hamcrest tutorial](http://hamcrest.org/JavaHamcrest/tutorial#logical):
>
> `anyOf` - matches if any matchers match, short circuits (like Java ||)
>
>
>
See also [Javadoc](http://hamcrest.org/JavaHamcrest/javadoc/2.2/org/hamcrest/core/AnyOf.html).
Moreover, you could write your own Matcher, which is quite easy to do.
|
152,729 |
<p>If you use Image.Save Method to save an image to a EMF/WMF, you get an exception (<a href="http://msdn.microsoft.com/en-us/library/ktx83wah.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ktx83wah.aspx</a>)</p>
<p>Is there another way to save the image to an EMF/WMF?
Are there any encoders available?</p>
|
[
{
"answer_id": 152830,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 2,
"selected": false,
"text": "<p>A metafile is a file which records a sequence of GDI operations. It is scalable because the original sequence of operations that generated the picture are captured, and therefore the co-ordinates that were recorded can be scaled.</p>\n\n<p>I think, in .NET, that you should create a <code>Metafile</code> object, create a <code>Graphics</code> object using <code>Graphics.FromImage</code>, then perform your drawing steps. The file is automatically updated as you draw on it. You can find a small sample in the documentation for <a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.graphics.addmetafilecomment.aspx\" rel=\"nofollow noreferrer\">Graphics.AddMetafileComment</a>.</p>\n\n<p>If you really want to store a bitmap in a metafile, use these steps then use <code>Graphics.DrawImage</code> to paint the bitmap. However, when it is scaled it will be stretched using <code>StretchBlt</code>.</p>\n"
},
{
"answer_id": 688593,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The question was: \"Is there another way to save the image to an EMF/WMF?\" Not \"what is metafile\" or \"how to create metafile\" or \"how to use metafile with Graphics\".</p>\n\n<p>I also look for answer for this question \"how to save EMF/WMF\"\nIn fact if you use:</p>\n\n<pre><code> Graphics grfx = CreateGraphics();\n MemoryStream ms = new MemoryStream();\n IntPtr ipHdc = grfx.GetHdc();\n\n Metafile mf = new Metafile(ms, ipHdc);\n\n grfx.ReleaseHdc(ipHdc);\n grfx.Dispose();\n grfx = Graphics.FromImage(mf);\n\n grfx.FillEllipse(Brushes.Gray, 0, 0, 100, 100);\n grfx.DrawEllipse(Pens.Black, 0, 0, 100, 100);\n grfx.DrawArc(new Pen(Color.Red, 10), 20, 20, 60, 60, 30, 120);\n grfx.Dispose();\n\n mf.Save(@\"C:\\file.emf\", ImageFormat.Emf);\n mf.Save(@\"C:\\file.png\", ImageFormat.Png);\n</code></pre>\n\n<p>In both cases image is saved as format png. And this is the problem which I cannot solve :/</p>\n"
},
{
"answer_id": 733465,
"author": "erikkallen",
"author_id": 47161,
"author_profile": "https://Stackoverflow.com/users/47161",
"pm_score": 4,
"selected": false,
"text": "<p>If I remember correctly, it can be done with a combination of the Metafile.GetHenhmetafile(), the API GetEnhMetaFileBits() and Stream.Write(), something like</p>\n\n<pre><code>[DllImport(\"gdi32\")] static extern uint GetEnhMetaFileBits(IntPtr hemf, uint cbBuffer, byte[] lpbBuffer);\n\n\nIntPtr h = metafile.GetHenhMetafile();\nint size = GetEnhMetaFileBits(h, 0, null);\nbyte[] data = new byte[size];\nGetEnhMetaFileBits(h, size, data);\nusing (FileStream w = File.Create(\"out.emf\")) {\n w.Write(data, 0, size);\n}\n// TODO: I don't remember whether the handle needs to be closed, but I guess not.\n</code></pre>\n\n<p>I think this is how I solved the problem when I had it.</p>\n"
},
{
"answer_id": 895204,
"author": "Han",
"author_id": 6473,
"author_profile": "https://Stackoverflow.com/users/6473",
"pm_score": 2,
"selected": false,
"text": "<p>The answer by erikkallen is correct. I tried this from VB.NET, and had to use 2 different DllImports to get it to work:</p>\n\n<pre><code><System.Runtime.InteropServices.DllImportAttribute(\"gdi32.dll\", EntryPoint:=\"GetEnhMetaFileBits\")> _\n Public Shared Function GetEnhMetaFileBits(<System.Runtime.InteropServices.InAttribute()> ByVal hEMF As System.IntPtr, ByVal nSize As UInteger, ByVal lpData As IntPtr) As UInteger\nEnd Function\n\n <System.Runtime.InteropServices.DllImportAttribute(\"gdi32.dll\", EntryPoint:=\"GetEnhMetaFileBits\")> _\n Public Shared Function GetEnhMetaFileBits(<System.Runtime.InteropServices.InAttribute()> ByVal hEMF As System.IntPtr, ByVal nSize As UInteger, ByVal lpData() As Byte) As UInteger\nEnd Function\n</code></pre>\n\n<p>The first import is used for the first call to get the emf size. The second import to get the actual bits.\nAlternatively you could use:</p>\n\n<pre><code>Dim h As IntPtr = mf.GetHenhmetafile()\nCopyEnhMetaFileW(h, FileName)\n</code></pre>\n\n<p>This copies the emf bits directly to the named file.</p>\n"
},
{
"answer_id": 978346,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p><code>Image</code> is an abstract class: what you want to do depends on whether you are dealing with a <code>Metafile</code> or a <code>Bitmap</code>.</p>\n\n<p>Creating an image with GDI+ and saving it as an EMF is simple with <code>Metafile</code>. Per Mike's <a href=\"https://stackoverflow.com/questions/152729/gdi-c-how-to-save-an-image-as-emf/152830#152830\">post</a>:</p>\n\n<pre><code>var path = @\"c:\\foo.emf\"\nvar g = CreateGraphics(); // get a graphics object from your form, or wherever\nvar img = new Metafile(path, g.GetHdc()); // file is created here\nvar ig = Graphics.FromImage(img);\n// call drawing methods on ig, causing writes to the file\nig.Dispose(); img.Dispose(); g.ReleaseHdc(); g.Dispose();\n</code></pre>\n\n<p>This is what you want to do most of the time, since that is what EMF is for: saving vector images in the form of GDI+ drawing commands.</p>\n\n<p>You can save a <code>Bitmap</code> to an EMF file by using the above method and calling <code>ig.DrawImage(your_bitmap)</code>, but be aware that this does not magically covert your raster data into a vector image.</p>\n"
},
{
"answer_id": 5180149,
"author": "BZ1",
"author_id": 563545,
"author_profile": "https://Stackoverflow.com/users/563545",
"pm_score": 1,
"selected": false,
"text": "<p>I was looking for a way to save the GDI instructions in a Metafile object to a EMF file. Han's post helped me solve the problem. This was before I joined SOF. Thank you, Han. Here is what <a href=\"http://www.gnostice.com/nl_article.asp?id=188&t=How_To_Convert_PDF_to_EMF_In_NET\" rel=\"nofollow\">I tried</a>.</p>\n\n<pre>\n [DllImport(\"gdi32.dll\")]\n static extern IntPtr CopyEnhMetaFile( // Copy EMF to file\n IntPtr hemfSrc, // Handle to EMF\n String lpszFile // File\n );\n\n [DllImport(\"gdi32.dll\")]\n static extern int DeleteEnhMetaFile( // Delete EMF\n IntPtr hemf // Handle to EMF\n );\n\n // Code that creates the metafile \n // Metafile metafile = ...\n\n // Get a handle to the metafile\n IntPtr iptrMetafileHandle = metafile.GetHenhmetafile();\n\n // Export metafile to an image file\n CopyEnhMetaFile(\n iptrMetafileHandle, \n \"image.emf\");\n\n // Delete the metafile from memory\n DeleteEnhMetaFile(iptrMetafileHandle);\n\n</pre>\n"
},
{
"answer_id": 5514430,
"author": "Roger",
"author_id": 687715,
"author_profile": "https://Stackoverflow.com/users/687715",
"pm_score": 0,
"selected": false,
"text": "<p>It appears there is much confusion over vector vs. bitmap. All of the code in this thread generates bitmap (non-vector) files - it does not preserve the vector GDI calls. To prove this to yourself, download the \"EMF Parser\" tool and inspect the output files: <a href=\"http://downloads.zdnet.com/abstract.aspx?docid=749645\" rel=\"nofollow\">http://downloads.zdnet.com/abstract.aspx?docid=749645</a>.</p>\n\n<p>This issue has caused many developers considering anguish. Sure would be nice if Microsoft would fix this and properly support their own EMF format.</p>\n"
},
{
"answer_id": 10509475,
"author": "Alex",
"author_id": 1383581,
"author_profile": "https://Stackoverflow.com/users/1383581",
"pm_score": 2,
"selected": false,
"text": "<p>You also need to close the <code>CopyEnhMetaFile</code> handler:</p>\n\n<pre><code>IntPtr ptr2 = CopyEnhMetaFile(iptrMetafileHandle, \"image.emf\");\nDeleteEnhMetaFile(ptr2);\n\n// Delete the metafile from memory\nDeleteEnhMetaFile(iptrMetafileHandle);\n</code></pre>\n\n<p>Otherwise, you cannot delete the file because it's still used by the process.</p>\n"
},
{
"answer_id": 12008528,
"author": "Brian Kennedy",
"author_id": 968565,
"author_profile": "https://Stackoverflow.com/users/968565",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend avoiding such extern's and unmanaged cruft in a managed .NET app.\nInstead, I'd recommend something a bit more like the managed solution given in this thread:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/5270763/convert-an-image-into-wmf-with-net\">Convert an image into WMF with .NET?</a></p>\n\n<p>P.S. I am answering this old thread because this was the best answer I had found, but then ended up developing a managed solution, which then lead me to the link above. So, to save others that time, I figured I'd point this one to that one.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12192/"
] |
If you use Image.Save Method to save an image to a EMF/WMF, you get an exception (<http://msdn.microsoft.com/en-us/library/ktx83wah.aspx>)
Is there another way to save the image to an EMF/WMF?
Are there any encoders available?
|
`Image` is an abstract class: what you want to do depends on whether you are dealing with a `Metafile` or a `Bitmap`.
Creating an image with GDI+ and saving it as an EMF is simple with `Metafile`. Per Mike's [post](https://stackoverflow.com/questions/152729/gdi-c-how-to-save-an-image-as-emf/152830#152830):
```
var path = @"c:\foo.emf"
var g = CreateGraphics(); // get a graphics object from your form, or wherever
var img = new Metafile(path, g.GetHdc()); // file is created here
var ig = Graphics.FromImage(img);
// call drawing methods on ig, causing writes to the file
ig.Dispose(); img.Dispose(); g.ReleaseHdc(); g.Dispose();
```
This is what you want to do most of the time, since that is what EMF is for: saving vector images in the form of GDI+ drawing commands.
You can save a `Bitmap` to an EMF file by using the above method and calling `ig.DrawImage(your_bitmap)`, but be aware that this does not magically covert your raster data into a vector image.
|
152,745 |
<p>I need a way to represent a 2-D array (a dense matrix) of doubles in C++, with absolute minimum accessing overhead. </p>
<p>I've done some timing on various linux/unix machines and gcc versions. An STL vector of vectors, declared as:</p>
<pre><code>vector<vector<double> > matrix(n,vector<double>(n));
</code></pre>
<p>and accessed through <code>matrix[i][j]</code> is between 5% and 100% slower to access than an array declared as:</p>
<pre><code>double *matrix = new double[n*n];
</code></pre>
<p>accessed through an inlined index function <code>matrix[index(i,j)]</code>, where <code>index(i,j)</code> evaluates to i+n*j. Other ways of arranging a 2-D array without STL - an array of n pointers to the start of each row, or defining the whole thing on the stack as a constant size <code>matrix[n][n]</code> - run at almost exactly the same speed as the index function method.</p>
<p>Recent GCC versions (> 4.0) seem to be able to compile the STL vector-of-vectors to nearly the same efficiency as the non-STL code when optimisations are turned on, but this is somewhat machine-dependent.</p>
<p>I'd like to use STL if possible, but will have to choose the fastest solution. Does anyone have any experience in optimising STL with GCC?</p>
|
[
{
"answer_id": 152761,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 3,
"selected": false,
"text": "<p>My guess would be the fastest is, for a matrix, to use 1D STL array and override the () operator to use it as 2D matrix.</p>\n\n<p>However, the STL also defines a type specifically for non-resizeable numerical arrays: valarray. You also have various optimisations for in-place operations.</p>\n\n<p>valarray accept as argument a numerical type: </p>\n\n<pre><code>valarray<double> a;\n</code></pre>\n\n<p>Then, you can use slices, indirect arrays, ... and of course, you can inherit the valarray and define your own operator()(int i, int j) for 2D arrays ...</p>\n"
},
{
"answer_id": 152762,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 3,
"selected": false,
"text": "<p>My recommendation would be to use Boost.UBLAS, which provides fast matrix/vector classes.</p>\n"
},
{
"answer_id": 152776,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 3,
"selected": false,
"text": "<p>Very likely this is a locality-of-reference issue. <code>vector</code> uses <code>new</code> to allocate its internal array, so each row will be at least a little apart in memory due to each block's header; it could be a long distance apart if memory is already fragmented when you allocate them. Different rows of the array are likely to at least incur a cache-line fault and could incur a page fault; if you're really unlucky two adjacent rows could be on memory lines that share a TLB slot and accessing one will evict the other.</p>\n\n<p>In contrast your other solutions guarantee that all the data is adjacent. It could help your performance if you align the structure so it crosses as few cache lines as possible.</p>\n\n<p><code>vector</code> is designed for <em>resizable</em> arrays. If you don't need to resize the arrays, use a regular C++ array. STL operations can generally operate on C++ arrays.</p>\n\n<p>Do be sure to walk the array in the correct direction, i.e. across (consecutive memory addresses) rather than down. This will reduce cache faults.</p>\n"
},
{
"answer_id": 152784,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 4,
"selected": true,
"text": "<p>If you're using GCC the compiler can analyze your matrix accesses and change the order in memory in certain cases. The magic compiler flag is defined as:</p>\n\n<pre><code>-fipa-matrix-reorg\n</code></pre>\n\n<blockquote>\n <p>Perform matrix flattening and\n transposing. Matrix flattening tries\n to replace a m-dimensional matrix with\n its equivalent n-dimensional matrix,\n where n < m. This reduces the level of\n indirection needed for accessing the\n elements of the matrix. The second\n optimization is matrix transposing\n that attemps to change the order of\n the matrix's dimensions in order to\n improve cache locality. Both\n optimizations need fwhole-program\n flag. Transposing is enabled only if\n profiling information is avaliable.</p>\n</blockquote>\n\n<p>Note that this option is not enabled by -O2 or -O3. You have to pass it yourself.</p>\n"
},
{
"answer_id": 152881,
"author": "OldMan",
"author_id": 23415,
"author_profile": "https://Stackoverflow.com/users/23415",
"pm_score": 1,
"selected": false,
"text": "<p>To be fair depends on the algorithms you are using upon the matrix.</p>\n\n<p>The double name[n*m] format is very fast when you are accessing data by rows both because has almost no overhead besides a multiplication and addition and because your rows are packed data that will be coherent in cache.</p>\n\n<p>If your algorithms access column ordered data then other layouts might have much better cache coherence. If your algorithm access data in quadrants of the matrix even other layouts might be better. </p>\n\n<p>Try to make some research directed at the type of usage and algorithms you are using. That is specially important if the matrix are very large, since cache misses may hurt your performance way more than needing 1 or 2 extra math operations to access each address.</p>\n"
},
{
"answer_id": 154141,
"author": "tfinniga",
"author_id": 9042,
"author_profile": "https://Stackoverflow.com/users/9042",
"pm_score": 1,
"selected": false,
"text": "<p>You could just as easily do vector< double >( n*m );</p>\n"
},
{
"answer_id": 154423,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 0,
"selected": false,
"text": "<p>There is the uBLAS implementation in Boost. It is worth a look.</p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/matrix.htm\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/matrix.htm</a></p>\n"
},
{
"answer_id": 351226,
"author": "lothar",
"author_id": 44434,
"author_profile": "https://Stackoverflow.com/users/44434",
"pm_score": 1,
"selected": false,
"text": "<p>You may want to look at the Eigen C++ template library at <a href=\"http://eigen.tuxfamily.org/\" rel=\"nofollow noreferrer\">http://eigen.tuxfamily.org/</a> . It generates AltiVec or sse2 code to optimize the vector/matrix calculations.</p>\n"
},
{
"answer_id": 431897,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Another related library is Blitz++: <a href=\"http://www.oonumerics.org/blitz/docs/blitz.html\" rel=\"nofollow noreferrer\">http://www.oonumerics.org/blitz/docs/blitz.html</a></p>\n\n<p>Blitz++ is designed to optimize array manipulation.</p>\n"
},
{
"answer_id": 3464760,
"author": "hookenz",
"author_id": 134702,
"author_profile": "https://Stackoverflow.com/users/134702",
"pm_score": 0,
"selected": false,
"text": "<p>I have done this some time back for raw images by declaring my own 2 dimensional array classes.</p>\n\n<p>In a normal 2D array, you access the elements like:</p>\n\n<p>array[2][3]. Now to get that effect, you'd have a class array with an overloaded\n[] array accessor. But, this would essentially return another array, thereby giving\nyou the second dimension.</p>\n\n<p>The problem with this approach is that it has a double function call overhead.</p>\n\n<p>The way I did it was to use the () style overload.</p>\n\n<p>So instead of\narray[2][3], change I had it do this style array(2,3).</p>\n\n<p>That () function was very tiny and I made sure it was inlined.</p>\n\n<p>See this link for the general concept of that:\n<a href=\"http://www.learncpp.com/cpp-tutorial/99-overloading-the-parenthesis-operator/\" rel=\"nofollow noreferrer\">http://www.learncpp.com/cpp-tutorial/99-overloading-the-parenthesis-operator/</a></p>\n\n<p>You can template the type if you need to.<br>\nThe difference I had was that my array was dynamic. I had a block of char memory I'd declare. And I employed a column cache, so I knew where in my sequence of bytes the next row began. Access was optimized for accessing neighbouring values, because I was using it for image processing.</p>\n\n<p>It's hard to explain without the code but essentially the result was as fast as C, and much easier to understand and use.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23732/"
] |
I need a way to represent a 2-D array (a dense matrix) of doubles in C++, with absolute minimum accessing overhead.
I've done some timing on various linux/unix machines and gcc versions. An STL vector of vectors, declared as:
```
vector<vector<double> > matrix(n,vector<double>(n));
```
and accessed through `matrix[i][j]` is between 5% and 100% slower to access than an array declared as:
```
double *matrix = new double[n*n];
```
accessed through an inlined index function `matrix[index(i,j)]`, where `index(i,j)` evaluates to i+n\*j. Other ways of arranging a 2-D array without STL - an array of n pointers to the start of each row, or defining the whole thing on the stack as a constant size `matrix[n][n]` - run at almost exactly the same speed as the index function method.
Recent GCC versions (> 4.0) seem to be able to compile the STL vector-of-vectors to nearly the same efficiency as the non-STL code when optimisations are turned on, but this is somewhat machine-dependent.
I'd like to use STL if possible, but will have to choose the fastest solution. Does anyone have any experience in optimising STL with GCC?
|
If you're using GCC the compiler can analyze your matrix accesses and change the order in memory in certain cases. The magic compiler flag is defined as:
```
-fipa-matrix-reorg
```
>
> Perform matrix flattening and
> transposing. Matrix flattening tries
> to replace a m-dimensional matrix with
> its equivalent n-dimensional matrix,
> where n < m. This reduces the level of
> indirection needed for accessing the
> elements of the matrix. The second
> optimization is matrix transposing
> that attemps to change the order of
> the matrix's dimensions in order to
> improve cache locality. Both
> optimizations need fwhole-program
> flag. Transposing is enabled only if
> profiling information is avaliable.
>
>
>
Note that this option is not enabled by -O2 or -O3. You have to pass it yourself.
|
152,757 |
<p>I am wondering whether it is safe to mix jdk 1.5 and 1.6 (Java 6) object serialization (biderctional communication). I searched for an explicit statement from sun concerning this question but did not succeed. So, besides the technical feasability I am searching for an "official" statement concerning the problem.</p>
|
[
{
"answer_id": 152789,
"author": "GavinCattell",
"author_id": 21644,
"author_profile": "https://Stackoverflow.com/users/21644",
"pm_score": 2,
"selected": false,
"text": "<p>After testing with a serialized object written to a file using the ObjectOutputStream in a Java 1.5 program, then running a read with a ObjectInputStream in a Java 1.6 program I can say this worked without any issue.</p>\n"
},
{
"answer_id": 152792,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 4,
"selected": false,
"text": "<p>The serialization mechanism itself has not changed. For individual classes it will depend on the specific class. If a class has a serialVersionUID field, this is supposed to indicate serialization compatiblity. </p>\n\n<p>Something like:</p>\n\n<pre><code>private static final long serialVersionUID = 8683452581122892189L;\n</code></pre>\n\n<p>If it is unchanged, the serialized versions are compatible. For JDK classes this is guaranteed, but of course it is always possible to forget to update the serialVersionUID after making a breaking change.</p>\n\n<p>When JDK classes are not guaranteed to be compatible, this is usually mentioned in the Javadoc.</p>\n\n<blockquote>\n <p>Warning: Serialized objects of this class will not be compatible with future Swing releases</p>\n</blockquote>\n"
},
{
"answer_id": 152811,
"author": "Alan",
"author_id": 17205,
"author_profile": "https://Stackoverflow.com/users/17205",
"pm_score": 2,
"selected": false,
"text": "<p>I would quickly add that it is possible to change the class but <em>forget</em> to change the serialVersionUID. So it is incorrect that \"If the class defines a serialVersionUID, and this does not change, the class is guaranteed to be compatible.\" Rather, having the same serialVersionUID is the way an API promises backward compatibility.</p>\n"
},
{
"answer_id": 152826,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>Unless otherwise stated, this should be part of binary compatibility. Swing classes are explicitly not compatible between versions. If you find a problem with other classes, report a bug on <a href=\"http://bugs.sun.com/\" rel=\"nofollow noreferrer\">bugs.sun.com</a>.</p>\n"
},
{
"answer_id": 152895,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 2,
"selected": false,
"text": "<p>Have you read the <a href=\"http://java.sun.com/javase/6/docs/platform/serialization/spec/serialTOC.html\" rel=\"nofollow noreferrer\">Java Object Serialization Specification</a>? There is a topic on <a href=\"http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html\" rel=\"nofollow noreferrer\">versioning</a>. There is also an article for class implementers: <a href=\"http://java.sun.com/developer/technicalArticles/Programming/serialization/\" rel=\"nofollow noreferrer\">Discover the secrets of the Java Serialization API</a>. Each release of Java is accompanied by <a href=\"http://java.sun.com/javase/6/webnotes/compatibility.html\" rel=\"nofollow noreferrer\">compatibility notes</a>.</p>\n\n<p>From the Java 6 spec on serialization:</p>\n\n<hr>\n\n<p>The goals are to:</p>\n\n<ul>\n<li>Support bidirectional communication between different versions of a class operating in different virtual machines by:\n\n<ul>\n<li>Defining a mechanism that allows JavaTM classes to read streams written by older versions of the same class.</li>\n<li>Defining a mechanism that allows JavaTM classes to write streams intended to be read by older versions of the same class.</li>\n</ul></li>\n<li>Provide default serialization for persistence and for RMI.</li>\n<li>Perform well and produce compact streams in simple cases, so that RMI can use serialization.</li>\n<li>Be able to identify and load classes that match the exact class used to write the stream.</li>\n<li>Keep the overhead low for nonversioned classes.</li>\n<li>Use a stream format that allows the traversal of the stream without having to invoke methods specific to the objects saved in the stream.</li>\n</ul>\n\n<hr>\n"
},
{
"answer_id": 152943,
"author": "VoidPointer",
"author_id": 23424,
"author_profile": "https://Stackoverflow.com/users/23424",
"pm_score": 2,
"selected": false,
"text": "<p>The serialization mechanism in 1.5 and 1.6 is compatible. Thus, the same code compiled/running in a 1.5 and 1.6 context can exchange serialized objects. Whether the two VM instances have the same/compatible version of the class (as may be indicated by the serialVersionUID field) is a different question not related to the JDK version.</p>\n\n<p>If you have one serializable Foo.java and use this in a 1.5 and 1.6 JDK/VM, serialized instances of Foo created by one V; can be deserialized by the other.</p>\n"
},
{
"answer_id": 155521,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 0,
"selected": false,
"text": "<p>Note that the Java Beans specification details a version-independent serialization method which allows for strong backwards-compatibility. It also results in readable \"serialized\" forms. In fact a serialized object can be created pretty easily using the mechanism.</p>\n\n<p>Look up the documentation to the <code>XMLEncoder</code> and <code>XMLDecoder</code> classes.</p>\n\n<p>I wouldn't use this for passing an object over the wire necessarily (though if high performance is a requirement,I wouldn't use serialization either) but it's invaluable for persistent object storage. </p>\n"
},
{
"answer_id": 359336,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It is not safe to mix Java 1.5 and 1.6. For example, I have a Java 1.5 object serialized into a file and tried opening it in Java 1.6 but it came up with the error below.</p>\n\n<pre><code>java.io.InvalidClassException: javax.swing.JComponent; local class incompatible: stream classdesc serialVersionUID = 7917968344860800289, local class serialVersionUID = -1030230214076481435\n at java.io.ObjectStreamClass.initNonProxy(Unknown Source)\n at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)\n at java.io.ObjectInputStream.readClassDesc(Unknown Source)\n at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)\n at java.io.ObjectInputStream.readClassDesc(Unknown Source)\n at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)\n at java.io.ObjectInputStream.readClassDesc(Unknown Source)\n at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.readArray(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.defaultReadFields(Unknown Source)\n at java.io.ObjectInputStream.readSerialData(Unknown Source)\n at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.defaultReadFields(Unknown Source)\n at java.io.ObjectInputStream.readSerialData(Unknown Source)\n at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.readArray(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.defaultReadFields(Unknown Source)\n at java.io.ObjectInputStream.readSerialData(Unknown Source)\n at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.readObject(Unknown Source)\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am wondering whether it is safe to mix jdk 1.5 and 1.6 (Java 6) object serialization (biderctional communication). I searched for an explicit statement from sun concerning this question but did not succeed. So, besides the technical feasability I am searching for an "official" statement concerning the problem.
|
The serialization mechanism itself has not changed. For individual classes it will depend on the specific class. If a class has a serialVersionUID field, this is supposed to indicate serialization compatiblity.
Something like:
```
private static final long serialVersionUID = 8683452581122892189L;
```
If it is unchanged, the serialized versions are compatible. For JDK classes this is guaranteed, but of course it is always possible to forget to update the serialVersionUID after making a breaking change.
When JDK classes are not guaranteed to be compatible, this is usually mentioned in the Javadoc.
>
> Warning: Serialized objects of this class will not be compatible with future Swing releases
>
>
>
|
152,770 |
<p>Is there any facility of transposing rows to columns in SQL Server (it is possible in MS-Access)?
I was befuddled because this facility is available in MS-Access but not in SQL Server. Is it by design that this feature has not been included in SQL Server?</p>
|
[
{
"answer_id": 152963,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 3,
"selected": true,
"text": "<p>The example at <a href=\"http://jdixon.dotnetdevelopersjournal.com/pivot_table_data_in_sql_server_2000_and_2005.htm\" rel=\"nofollow noreferrer\">http://jdixon.dotnetdevelopersjournal.com/pivot_table_data_in_sql_server_2000_and_2005.htm</a> only works if you know in advance what the row values can be. For example, let's say you have an entity with custom attributes and the custom attributes are implemented as rows in a child table, where the child table is basically variable/value pairs, and those variable/value pairs are configurable. </p>\n\n<pre><code>color red\nsize big\ncity Chicago\n</code></pre>\n\n<p>I'm going to describe a technique that works. I've used it. I'm NOT promoting it, but it works.</p>\n\n<p>To pivot the data where you don't know what the values can be in advance, create a temp table on the fly with no columns. Then use a cursor to loop through your rows, issuing a dynamically built \"alter table\" for each variable, so that in the end your temp table has the columns, color, size, city.</p>\n\n<p>Then you insert one row in your temp table, update it via another cursor through the variable, value pairs, and then select it, usually joined with its parent entity, in effect making it seem like those custom variable/value pairs were like built-in columns in the original parent entity.</p>\n"
},
{
"answer_id": 169412,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 2,
"selected": false,
"text": "<p>The cursor method described is probably the least SQL-like to use. As mentioned, SQL 2005 and on has PIVOT which works great. But for older versions and non-MS SQL servers, the Rozenshtein method from \"Optimzing Transact-SQL\" (edit: out of print, but avail. from Amazon: <a href=\"https://rads.stackoverflow.com/amzn/click/com/0964981203\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">http://www.amazon.com/Optimizing-Transact-SQL-Advanced-Programming-Techniques/dp/0964981203</a>), is excellent for pivoting and unpivoting data.\nIt uses point characteristics to turn row based data into columns. Rozenshtein describes several cases, here's one example:</p>\n\n<pre><code>SELECT\n RowValueNowAColumn = \n CONVERT(varchar,\n MAX(\n SUBSTRING(myTable.MyVarCharColumn,1,DATALENGTH(myTable.MyVarCharColumn)\n * CHARINDEX(sa.SearchAttributeName,'MyRowValue'))))\nFROM\n myTable\n</code></pre>\n\n<p>This method is a lot more efficient than using case statements and works for a variety of data types and SQL implementations (not just MS SQL). </p>\n"
},
{
"answer_id": 792435,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>For UNPIVOT in sql server 2005, I have found a good article</p>\n\n<p><a href=\"http://www.logiclabz.com/sql-server/transpose-columns-to-rows-in-sql-server-2005-using-unpivot.aspx\" rel=\"nofollow noreferrer\">columns-to-rows-in-sql-server</a></p>\n"
},
{
"answer_id": 2520747,
"author": "SimonH_UK",
"author_id": 302228,
"author_profile": "https://Stackoverflow.com/users/302228",
"pm_score": 1,
"selected": false,
"text": "<p>Best to limit to small scale for this sort of thing. If you're using SQL 2k though and don't have PIVOT features available, I've drafted a stored proc that should do the job for you. Bit of a botch rush job so pull it apart as much as you like. Paste the below into a sql window and edit the EXEC at the bottom as preferred. If you want to see what's being generated, remove the --s in the middle:</p>\n\n<pre><code>IF EXISTS (SELECT * FROM SYSOBJECTS WHERE XTYPE = 'P' AND NAME = 'USP_LIST_CONCAT')\nDROP PROCEDURE USP_LIST_CONCAT\nGO\n\nCREATE PROCEDURE USP_LIST_CONCAT (@SourceTable NVARCHAR(1000) = '' ,@SplitColumn NVARCHAR(1000) = '' , @Deli NVARCHAR(10) = '', @KeyColumns NVARCHAR(2000) = '' , @Condition NVARCHAR(1000) = '')\nAS\nBEGIN\nSET NOCOUNT ON\n\n/* PROCEDURE CREATED 2010 FOR SQL SERVER 2000. SIMON HUGHES. */\n/* NOTES: REMOVE --'s BELOW TO LIST GENERATED SQL. */\n\nIF @SourceTable = '' OR @SourceTable = '?' OR @SourceTable = '/?' OR @SplitColumn = '' OR @KeyColumns = ''\nBEGIN\nPRINT 'Format for use:'\nPRINT ' USP_LIST_CONCAT ''SourceTable'', ''SplitColumn'', ''Deli'', ''KeyColumn1,...'', ''Column1 = 12345 AND ...'''\nPRINT ''\nPRINT 'Description:'\nPRINT 'The SourceTable should contain a number of records acting as a list of values.'\nPRINT 'The SplitColumn should be the name of the column holding the values wanted.'\nPRINT 'The Delimiter may be any single character or string ie ''/'''\nPRINT 'The KeyColumn may contain a comma separated list of columns that will be returned before the concatenated list.'\nPRINT 'The optional Conditions may be left blank or may include the following as examples:'\nPRINT ' ''Column1 = 12334 AND (Column2 = ''ABC'' OR Column3 = ''DEF'')'''\nPRINT ''\nPRINT 'A standard list in the format:'\nPRINT ' Store1, Employee1, Rabbits'\nPRINT ' Store1, Employee1, Dogs'\nPRINT ' Store1, Employee1, Cats'\nPRINT ' Store1, Employee2, Dogs'\nPRINT ''\nPRINT 'Will be returned as:'\nPRINT ' Store1, Employee1, Cats/Dogs/Rabbits'\nPRINT ' Store1, Employee2, Dogs'\nPRINT ''\nPRINT 'A full ORDER BY and DISTINCT is included'\nRETURN -1\nEND\n\n\nDECLARE @SQLStatement NVARCHAR(4000)\n\nSELECT @SQLStatement = '\nDECLARE @DynamicSQLStatement NVARCHAR(4000)\n\nSELECT @DynamicSQLStatement = ''SELECT '+@KeyColumns+', SUBSTRING(''\n\nSELECT @DynamicSQLStatement = @DynamicSQLStatement + '' + '' + CHAR(10) +\n'' MAX(CASE WHEN '+@SplitColumn+' = ''''''+RTRIM('+@SplitColumn+')+'''''' THEN '''''+@Deli+'''+RTRIM('+@SplitColumn+')+'''''' ELSE '''''''' END)''\nFROM '+ @SourceTable +' ORDER BY '+@SplitColumn+'\n\nSELECT @DynamicSQLStatement = @DynamicSQLStatement + '' ,2,7999) List'' + CHAR(10) + ''FROM '+ @SourceTable+''' + CHAR(10) +'''+CASE WHEN @Condition = '' THEN '/* WHERE */' ELSE 'WHERE '+@Condition END+ '''+ CHAR(10) + ''GROUP BY '+@KeyColumns+'''\n\nSELECT @DynamicSQLStatement = REPLACE(@DynamicSQLStatement,''( +'',''('')\n\n-- SELECT @DynamicSQLStatement -- DEBUG ONLY\nEXEC (@DynamicSQLStatement)'\n\nEXEC (@SQLStatement)\n\nEND\nGO\n\nEXEC USP_LIST_CONCAT 'MyTableName', 'ColumnForListing', 'Delimiter', 'KeyCol1, KeyCol2', 'Column1 = 123456'\n</code></pre>\n"
},
{
"answer_id": 2894501,
"author": "Vikas Baweja",
"author_id": 348617,
"author_profile": "https://Stackoverflow.com/users/348617",
"pm_score": 0,
"selected": false,
"text": "<p>I have Data in following format </p>\n\n<p><strong>Survey_question_ID</strong></p>\n\n<p><strong>Email (User</strong>)</p>\n\n<p><strong>Answer</strong></p>\n\n<p>for 1 survey there are 13 question and answers\nthe desired output i wanted was</p>\n\n<p><strong>User</strong> ---<strong>Survey_question_ID1</strong>---<strong>Survey_question_ID2</strong></p>\n\n<p><strong>email</strong>---<strong>answers</strong>---<strong>answer</strong> ........<strong>so on</strong> </p>\n\n<p>Here is the solution for <b>SQL Server 2000</b>, Cause field data type is <b>TEXT</b>.</p>\n\n<pre><code>DROP TABLE #tmp\n\nDECLARE @tmpTable TABLE\n(\nemailno NUMERIC,\nquestion1 VARCHAR(80),\nquestion2 VARCHAR(80),\nquestion3 VARCHAR(80),\nquestion4 VARCHAR(80),\nquestion5 VARCHAR(80),\nquestion6 VARCHAR(80),\nquestion7 VARCHAR(80),\nquestion8 VARCHAR(80),\nquestion9 VARCHAR(80),\nquestion10 VARCHAR(80),\nquestion11 VARCHAR(80),\nquestion12 VARCHAR(80),\nquestion13 VARCHAR(8000)\n)\n\nDECLARE @tmpTable2 TABLE\n(\nemailNumber NUMERIC\n)\n\nDECLARE @counter INT\nDECLARE @Email INT\n\nSELECT @counter =COUNT(DISTINCT ans.email) FROM answers ans WHERE ans.surveyname=100430 AND ans.qnpkey BETWEEN 233702 AND 233714\nSELECT * INTO #tmp FROM @tmpTable\nINSERT INTO @tmpTable2 (emailNumber) SELECT DISTINCT CAST(ans.email AS NUMERIC) FROM answers ans WHERE ans.surveyname=100430 AND ans.qnpkey BETWEEN 233702 AND 233714\n\nWHILE @counter >0\n\nBEGIN\n\n SELECT TOP 1 @Email= emailNumber FROM @tmpTable2\n INSERT INTO @tmpTable (emailno) VALUES (@Email )\n\n\n Update @tmpTable set question1=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233702 and ans.email=@Email\n Update @tmpTable set question2=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233703 and email=@email\n Update @tmpTable set question3=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233704 and email=@email\n Update @tmpTable set question4=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233705 and email=@email\n Update @tmpTable set question5=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233706 and email=@email\n Update @tmpTable set question6=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233707 and email=@email\n Update @tmpTable set question7=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233708 and email=@email\n Update @tmpTable set question8=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233709 and email=@email\n Update @tmpTable set question9=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233710 and email=@email\n Update @tmpTable set question10=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233711 and email=@email\n Update @tmpTable set question11=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233712 and email=@email\n Update @tmpTable set question12=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233713 and email=@email\n Update @tmpTable set question13=CAST(answer as VARCHAR(8000)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233714 and email=@email\n\n insert into #tmp select * from @tmpTable \n\n DELETE FROM @tmpTable \n DELETE FROM @tmpTable2 WHERE emailNumber= @Email\n\n set @counter =@counter -1\n\nEnd\n\nselect * from #tmp\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4021/"
] |
Is there any facility of transposing rows to columns in SQL Server (it is possible in MS-Access)?
I was befuddled because this facility is available in MS-Access but not in SQL Server. Is it by design that this feature has not been included in SQL Server?
|
The example at <http://jdixon.dotnetdevelopersjournal.com/pivot_table_data_in_sql_server_2000_and_2005.htm> only works if you know in advance what the row values can be. For example, let's say you have an entity with custom attributes and the custom attributes are implemented as rows in a child table, where the child table is basically variable/value pairs, and those variable/value pairs are configurable.
```
color red
size big
city Chicago
```
I'm going to describe a technique that works. I've used it. I'm NOT promoting it, but it works.
To pivot the data where you don't know what the values can be in advance, create a temp table on the fly with no columns. Then use a cursor to loop through your rows, issuing a dynamically built "alter table" for each variable, so that in the end your temp table has the columns, color, size, city.
Then you insert one row in your temp table, update it via another cursor through the variable, value pairs, and then select it, usually joined with its parent entity, in effect making it seem like those custom variable/value pairs were like built-in columns in the original parent entity.
|
152,774 |
<p>What's the best way to trim a DateTime object to a specific precision? For instance, if I have a DateTime with a value of '2008-09-29 09:41:43', but I only want it's precision to be to the minute, is there any better way to do it than this?</p>
<pre><code>private static DateTime TrimDateToMinute(DateTime date)
{
return new DateTime(
date.Year,
date.Month,
date.Day,
date.Hour,
date.Minute,
0);
}
</code></pre>
<p>What I would really want is to make it variable so that I could set its precision to the second, minute, hour, or day.</p>
|
[
{
"answer_id": 152803,
"author": "Rikalous",
"author_id": 4271,
"author_profile": "https://Stackoverflow.com/users/4271",
"pm_score": 3,
"selected": false,
"text": "<p>You could use an enumeration</p>\n\n<pre><code>public enum DateTimePrecision\n{\n Hour, Minute, Second\n}\n\npublic static DateTime TrimDate(DateTime date, DateTimePrecision precision)\n{\n switch (precision)\n {\n case DateTimePrecision.Hour:\n return new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);\n case DateTimePrecision.Minute:\n return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0);\n case DateTimePrecision.Second:\n return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);\n default:\n break;\n }\n}\n</code></pre>\n\n<p>and expand as required.</p>\n"
},
{
"answer_id": 153014,
"author": "Bartek Szabat",
"author_id": 23774,
"author_profile": "https://Stackoverflow.com/users/23774",
"pm_score": 8,
"selected": true,
"text": "<pre><code>static class Program\n{\n //using extension method:\n static DateTime Trim(this DateTime date, long roundTicks)\n {\n return new DateTime(date.Ticks - date.Ticks % roundTicks, date.Kind);\n }\n\n //sample usage:\n static void Main(string[] args)\n {\n Console.WriteLine(DateTime.Now);\n Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerDay));\n Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerHour));\n Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMillisecond));\n Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMinute));\n Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerSecond));\n Console.ReadLine();\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 10848875,
"author": "Gunarathinam",
"author_id": 885942,
"author_profile": "https://Stackoverflow.com/users/885942",
"pm_score": -1,
"selected": false,
"text": "<pre><code>DateTime dt = new DateTime()\ndt = dt.AddSeconds(-dt.Second)\n</code></pre>\n\n<p>Above code will trim seconds.</p>\n"
},
{
"answer_id": 15751093,
"author": "rocketsarefast",
"author_id": 544958,
"author_profile": "https://Stackoverflow.com/users/544958",
"pm_score": 3,
"selected": false,
"text": "<p>I like this method. Someone mentioned it was good to preserve the Date Kind, etc. This accomplishes that because you dont have to make a new DateTime. The DateTime is properly cloned from the original DateTime and it simply subtracts the remainder ticks.</p>\n\n<pre><code>public static DateTime FloorTime(DateTime dt, TimeSpan interval) \n{\n return dt.AddTicks(-1 * (dt.Ticks % interval.Ticks));\n}\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>dt = FloorTime(dt, TimeSpan.FromMinutes(5)); // floor to the nearest 5min interval\ndt = FloorTime(dt, TimeSpan.FromSeconds(1)); // floor to the nearest second\ndt = FloorTime(dt, TimeSpan.FromDays(1)); // floor to the nearest day\n</code></pre>\n"
},
{
"answer_id": 26807751,
"author": "Marcos Arruda",
"author_id": 2479173,
"author_profile": "https://Stackoverflow.com/users/2479173",
"pm_score": 1,
"selected": false,
"text": "<p>There are some good solutions presented here, but when I need to do this, I simply do:</p>\n\n<pre><code>DateTime truncDate;\ntruncDate = date.Date; // trim to day\ntruncDate = date.Date + TimeSpan.Parse(string.Format(\"{0:HH:00:00}\", date)); // trim to hour\ntruncDate = date.Date + TimeSpan.Parse(string.Format(\"{0:HH:mm}\", date)); // trim to minute\ntruncDate = date.Date + TimeSpan.Parse(string.Format(\"{0:HH:mm:ss}\", date)); // trim to second\n</code></pre>\n\n<p>Hope it helps.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21807/"
] |
What's the best way to trim a DateTime object to a specific precision? For instance, if I have a DateTime with a value of '2008-09-29 09:41:43', but I only want it's precision to be to the minute, is there any better way to do it than this?
```
private static DateTime TrimDateToMinute(DateTime date)
{
return new DateTime(
date.Year,
date.Month,
date.Day,
date.Hour,
date.Minute,
0);
}
```
What I would really want is to make it variable so that I could set its precision to the second, minute, hour, or day.
|
```
static class Program
{
//using extension method:
static DateTime Trim(this DateTime date, long roundTicks)
{
return new DateTime(date.Ticks - date.Ticks % roundTicks, date.Kind);
}
//sample usage:
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now);
Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerDay));
Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerHour));
Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMillisecond));
Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMinute));
Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerSecond));
Console.ReadLine();
}
}
```
|
152,807 |
<p><strong>UPDATE:</strong> i updated the code and problem description to reflect my changes. </p>
<p>I know now that i'm trying a Socket operation on nonsocket. or that my fd_set is not valid since:</p>
<p><code>select</code> returns -1 and
<code>WSAGetLastError()</code>returns 10038. </p>
<p>But i can't seem to figure out what it is. Platform is Windows. I have not posted the <code>WSAStartup</code> part.</p>
<pre><code>int loop = 0;
FILE *output
int main()
{
fd_set fd;
output = _popen("tail -f test.txt","r");
while(forceExit == 0)
{
FD_ZERO(&fd);
FD_SET(_fileno(output),&fd);
int returncode = select(_fileno(output)+1,&fd,NULL,NULL,NULL);
if(returncode == 0)
{
printf("timed out");
}
else if (returncode < 0)
{
printf("returncode: %d\n",returncode);
printf("Last Error: %d\n",WSAGetLastError());
}
else
{
if(FD_ISSET(_fileno(output),&fd))
{
if(fgets(buff, sizeof(buff), output) != NULL )
{
printf("Output: %s\n", buff);
}
}
else
{
printf(".");
}
}
Sleep(500);
}
return 0;
}
</code></pre>
<p>The new outcome now is of course the print out of the returncode and the last error.</p>
|
[
{
"answer_id": 152831,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 0,
"selected": false,
"text": "<p>The first argument to select needs to be the highest-numbered file descriptor in any of the three sets, plus 1:</p>\n\n<pre><code> int select(int nfds, fd_set *readfds, fd_set *writefds,\n fd_set *exceptfds, struct timeval *timeout);\n</code></pre>\n\n<p>Also:</p>\n\n<pre><code> if(FD_ISSET(filePointer,&exceptfds))\n {\n printf(\"i have data\\n\");\n }\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code> if(FD_ISSET(filePointer,&fd))\n {\n printf(\"i have data\\n\");\n }\n</code></pre>\n\n<p>You should check the return code from select().</p>\n\n<p>You also need to reset the fdsets each time you call select().</p>\n\n<p>You don't need timeout since you're not using it.</p>\n\n<p>Edit:</p>\n\n<p>Apparently on Windows, nfds is ignored, but should probably be set correctly, just so the code is more portable.</p>\n\n<p>If you want to use a timeout, you need to pass it into the select call as the last argument:</p>\n\n<pre><code>// Reset fd, exceptfds, and timeout before each select()...\nint result = select(maxFDPlusOne, &fd, NULL, &exceptfds, &timeout);\n\nif (result == 0)\n{\n // timeout\n}\nelse if (result < 0)\n{\n // error\n}\nelse\n{\n // something happened\n if (FD_ISSET(filePointer,&fd))\n {\n // Need to read the data, otherwise you'll get notified each time.\n }\n}\n</code></pre>\n"
},
{
"answer_id": 152876,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 0,
"selected": false,
"text": "<p>The first thing that I notice is wrong is that you are calling FD_ISSET on your exceptfds in each conditional. I think that you want something like this:</p>\n\n<pre><code>if (FD_ISSET(filePointer,&fd))\n{\n printf(\"i have data\\n\");\n}\nelse ....\n</code></pre>\n\n<p>The except field in the select is typically used to report errors or out-of-band data on a socket. When one of the descriptors of your exception is set, it doesn't mean an error necessarily, but rather some \"message\" (i.e. out-of-band data). I suspect that for your application, you can probably get by without putting your file descriptor inside of an exception set. If you truly want to check for errors, you need to be checking the return value of select and doing something if it returns -1 (or SOCKET_ERROR on Windows). I'm not sure of your platform so I can't be more specific about the return code.</p>\n"
},
{
"answer_id": 152937,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 2,
"selected": false,
"text": "<p>You have some data ready to be read, but you are not actually reading anything. When you poll the descriptor next time, the data will still be there. Drain the pipe before you continue to poll.</p>\n"
},
{
"answer_id": 153029,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li><p><code>select()</code> first argument is the highest number file descriptor in your set, plus 1. (i.e. output+1)</p>\n\n<p>select(output+1, &fd, NULL, &exceptfds, NULL);</p></li>\n<li><p>The first <code>FD_ISSET(...)</code> should be on the <code>fd_set</code> fd. </p>\n\n<p>if (FD_ISSET(filePointer, &fd))</p></li>\n<li><p>Your data stream has data, then you need to read that data stream. Use fgets(...) or similar to read from the data source.</p>\n\n<p>char buf[1024];\n...\nfgets(buf, sizeof(buf) * sizeof(char), output);</p></li>\n</ol>\n"
},
{
"answer_id": 153574,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I can tell, Windows anonymous pipes cannot be used with non-blocking calls like select. So, while your _popen and select code looks good independently, you can't join the two together.</p>\n\n<p><a href=\"http://www.perlmonks.org/?node_id=621058\" rel=\"nofollow noreferrer\">Here's a similar thread elsewhere.</a></p>\n\n<p>It's possible that calling <a href=\"http://msdn.microsoft.com/en-us/library/aa365787.aspx\" rel=\"nofollow noreferrer\">SetNamedPipeHandleState</a> with the PIPE_NOWAIT flag might work for you, but MSDN is more than a little cryptic on the subject.</p>\n\n<p>So, I think you need to look at other ways of achieving this. I'd suggest having the reading in a separate thread, and use normal blocking I/O. </p>\n"
},
{
"answer_id": 157988,
"author": "SinisterDex",
"author_id": 10010,
"author_profile": "https://Stackoverflow.com/users/10010",
"pm_score": 0,
"selected": false,
"text": "<p>since <code>select</code> doesn't work i used threads, specifically <a href=\"http://msdn.microsoft.com/en-us/library/kdzttdcb(VS.80).aspx\" rel=\"nofollow noreferrer\"><code>_beginthread</code> , <code>_beginthreadex</code></a>.</p>\n"
},
{
"answer_id": 160420,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 1,
"selected": false,
"text": "<p>First of all, as yourself and others have pointed out, <code>select()</code> is only valid for sockets under Windows. <code>select()</code> does not work on streams which is what <code>_popen()</code> returns. Error 10038 clearly identifies this.</p>\n\n<p>I don't get what the purpose of your example is. If you simply want to spawn a process and collect it's stdout, just do this (which comes directly from the MSDN _popen page):</p>\n\n<pre><code>int main( void )\n{\n\n char psBuffer[128];\n FILE *pPipe;\n\n if( (pPipe = _popen(\"tail -f test.txt\", \"rt\" )) == NULL )\n exit( 1 );\n\n /* Read pipe until end of file, or an error occurs. */\n\n while(fgets(psBuffer, 128, pPipe))\n {\n printf(psBuffer);\n }\n\n\n /* Close pipe and print return value of pPipe. */\n if (feof( pPipe))\n {\n printf( \"\\nProcess returned %d\\n\", _pclose( pPipe ) );\n }\n else\n {\n printf( \"Error: Failed to read the pipe to the end.\\n\");\n }\n}\n</code></pre>\n\n<p>That's it. No select required.</p>\n\n<p>And I'm not sure how threads will help you here, this will just complicate your problem.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10010/"
] |
**UPDATE:** i updated the code and problem description to reflect my changes.
I know now that i'm trying a Socket operation on nonsocket. or that my fd\_set is not valid since:
`select` returns -1 and
`WSAGetLastError()`returns 10038.
But i can't seem to figure out what it is. Platform is Windows. I have not posted the `WSAStartup` part.
```
int loop = 0;
FILE *output
int main()
{
fd_set fd;
output = _popen("tail -f test.txt","r");
while(forceExit == 0)
{
FD_ZERO(&fd);
FD_SET(_fileno(output),&fd);
int returncode = select(_fileno(output)+1,&fd,NULL,NULL,NULL);
if(returncode == 0)
{
printf("timed out");
}
else if (returncode < 0)
{
printf("returncode: %d\n",returncode);
printf("Last Error: %d\n",WSAGetLastError());
}
else
{
if(FD_ISSET(_fileno(output),&fd))
{
if(fgets(buff, sizeof(buff), output) != NULL )
{
printf("Output: %s\n", buff);
}
}
else
{
printf(".");
}
}
Sleep(500);
}
return 0;
}
```
The new outcome now is of course the print out of the returncode and the last error.
|
You have some data ready to be read, but you are not actually reading anything. When you poll the descriptor next time, the data will still be there. Drain the pipe before you continue to poll.
|
152,822 |
<p>I want something like this:</p>
<pre><code><msxsl:script language="C#">
??? getNodes() { ... return ... }
</msxsl:script>
<xsl:for-each select="user:getNodes()">
...
</xsl:for-each>
</code></pre>
<p>What return type should i use for <code>getNodes()</code> and what should i put in it's body?</p>
|
[
{
"answer_id": 153141,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 2,
"selected": false,
"text": "<p>A quick google for C# xslt msxml revealed a link to the following page which gives many examples of extending XSLT in microsoft environments. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/magazine/cc302079.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc302079.aspx</a></p>\n\n<p>Specifically the section on Mapping Types between XSLT and .Net gives you exactly the information you need:</p>\n\n<p>W3C XPath Type - Equivalent .NET Class (Type)</p>\n\n<ul>\n<li>String - System.String</li>\n<li>Boolean - System.Boolean</li>\n<li>Number - System.Double</li>\n<li>Result Tree Fragment - System.Xml.XPath.XPathNavigator</li>\n<li>Node Set - System.Xml.XPath.XPathNodeIterator</li>\n</ul>\n\n<p>So in your example I would try XPathNodeLiterator. </p>\n"
},
{
"answer_id": 414009,
"author": "Boaz",
"author_id": 2892,
"author_profile": "https://Stackoverflow.com/users/2892",
"pm_score": 4,
"selected": true,
"text": "<p>In principle you need to use the XPathNodeIterator to return node sets (as Samjudson says). I take it that the example you gave is a degenerated function, as you do not supply it with any parameters. However, I think it is instructive the see how you <em>could</em> fabricate nodes out of thin air. </p>\n\n<pre><code><msxsl:script language=\"C#\">\n XPathNodeIterator getNodes() \n { \n XmlDocument doc = new XmlDocument();\n doc.PreserveWhitespace = true;\n doc.LoadXml(\"<root><fld>val</fld><fld>val2</fld></root>\");\n return doc.CreateNavigator().Select(\"/root/fld\");\n }\n</msxsl:script>\n</code></pre>\n\n<p>However, typically you would want to do something in your function that is not possible in xslt, like filtering a node set based on some criteria. A criteria that is better implemented through code or depends om some external data structure. Another option is just that you would to simplify a wordy expression (as in the example bellow). Then you would pass some parameters to you getNodes function. For simplicity I use a XPath based filtering but it could be anything:</p>\n\n<pre><code> <msxsl:script language=\"C#\">\n XPathNodeIterator getNodes(XPathNodeIterator NodesToFilter, string Criteria)\n {\n XPathNodeIterator x = NodesToFilter.Current.Select(\"SOMEVERYCOMPLEXPATH[\"+Criteria+\"]\");\n return x;\n }\n </msxsl:script>\n <xsl:for-each select=\"user:getNodes(values/val,'SomeCriteria')\">\n ...\n </xsl:for-each>\n</code></pre>\n\n<p>Hopes this helps,\nBoaz</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310/"
] |
I want something like this:
```
<msxsl:script language="C#">
??? getNodes() { ... return ... }
</msxsl:script>
<xsl:for-each select="user:getNodes()">
...
</xsl:for-each>
```
What return type should i use for `getNodes()` and what should i put in it's body?
|
In principle you need to use the XPathNodeIterator to return node sets (as Samjudson says). I take it that the example you gave is a degenerated function, as you do not supply it with any parameters. However, I think it is instructive the see how you *could* fabricate nodes out of thin air.
```
<msxsl:script language="C#">
XPathNodeIterator getNodes()
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml("<root><fld>val</fld><fld>val2</fld></root>");
return doc.CreateNavigator().Select("/root/fld");
}
</msxsl:script>
```
However, typically you would want to do something in your function that is not possible in xslt, like filtering a node set based on some criteria. A criteria that is better implemented through code or depends om some external data structure. Another option is just that you would to simplify a wordy expression (as in the example bellow). Then you would pass some parameters to you getNodes function. For simplicity I use a XPath based filtering but it could be anything:
```
<msxsl:script language="C#">
XPathNodeIterator getNodes(XPathNodeIterator NodesToFilter, string Criteria)
{
XPathNodeIterator x = NodesToFilter.Current.Select("SOMEVERYCOMPLEXPATH["+Criteria+"]");
return x;
}
</msxsl:script>
<xsl:for-each select="user:getNodes(values/val,'SomeCriteria')">
...
</xsl:for-each>
```
Hopes this helps,
Boaz
|
152,823 |
<p>XAMPP makes configuring a local LAMP stack for windows a breeze. So it's quite disappointing that enabling <code>.htaccess</code> files is such a nightmare.</p>
<p>My problem:
I've got a PHP application that requires apache/php to search for an <code>/includes/</code> directory contained within the application. To do this, <code>.htaccess</code> files must be allowed in Apache and the <code>.htaccess</code> file must specify exactly where the includes directory is.</p>
<p>Problem is, I can't get my Apache config to view these <code>.htaccess</code> files. I had major hassles installing this app at uni and getting the admins there to help with the setup. This shouldn't be so hard but for some reason I just can't get Apache to play nice.</p>
<p>This is my setup:</p>
<p><code>c:\xampp</code>
<code>c:\xampp\htdocs</code>
<code>c:\xampp\apache\conf\httpd.conf</code> - where I've made the changes listed below
<code>c:\xampp\apache\bin\php.ini</code> - where changes to this file affect the PHP installation
It is interesting to note that <code>c:\xampp\php\php.ini</code> changes mean nothing - this is NOT the ini that affects the PHP installation.</p>
<p>The following lines are additions I've made to the <code>httpd.conf</code> file</p>
<pre><code>#AccessFileName .htaccess
AccessFileName htaccess.txt
#
# The following lines prevent .htaccess and .htpasswd
# files from being viewed by Web clients.
#
#<Files ~ "^\.ht">
<Files ~ "^htaccess\.">
Order allow,deny
Deny from all
</Files>
<Directory "c:/xampp/htdocs">
#
# AllowOverride controls what directives may be placed in
# .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
</code></pre>
<p>The following is the entire <code>.htaccess</code> file contained in:
<code>c:\xampp\htdocs\application\htaccess.txt</code></p>
<pre><code><Files ~ "\.inc$">
Order deny,allow
Deny from all
</Files>
php_value default_charset "UTF-8"
php_value include_path ".;c:\xampp\htdocs\application\includes"
php_value register_globals 0
php_value magic_quotes_gpc 0
php_value magic_quotes_runtime 0
php_value magic_quotes_sybase 0
php_value session.use_cookies 1
php_value session.use_only_cookies 0
php_value session.use_trans_sid 1
php_value session.gc_maxlifetime 3600
php_value arg_separator.output "&amp;"
php_value url_rewriter.tags "a=href,area=href,frame=src,input=src,fieldset="
</code></pre>
<p>The includes directory exists at the location specified.</p>
<p>When I try to access the application I receive the following error:</p>
<pre><code>Warning: require(include.general.inc) [function.require]: failed to open stream: No such file or directory in C:\xampp\htdocs\application\menu\logon.php on line 21
</code></pre>
<p>Fatal error: require() [function.require]: Failed opening required <code>include.general.inc</code> (include_path='.;C:\xampp\php\pear\random') in <code>C:\xampp\htdocs\application\menu\logon.php</code> on line 21</p>
<p>The include path <code>c..\random\</code> is specified in the <code>php.ini</code> file listed above. The XAMPP install fails to allow another include path as specified in the <code>htaccess.txt</code> file.</p>
<p>I'm guessing there's probably an error with the <code>httpd.conf</code> OR the <code>htaccess.txt</code> file.. but it doesn't seem to be reading the <code>.htaccess</code> file. I've tried to be as thorough as possible so forgive the verbosity of the post.</p>
<p>Now I know a workaround could be to simply add the include_path to the PHP file, but I'm not going to have access to the <code>php.ini</code> file on the location I plan to deploy my app. I will, however, be able to request the server admin allows <code>.htaccess</code> files.</p>
<p>renamed <code>htacces.txt</code> to <code>.htaccess</code> and ammended the appropriate directives in the <code>httpd.conf</code> file and all seems to work. The application suggested the naming of <code>htaccess.txt</code> and the ammended directives in the httpd. These are obviously wrong (at least for a XAMPP stack).</p>
<p>By the way, using ini_set() is a much friendlier way if the app needs to be deployed to multiple locations so thanks especially for that pointer.</p>
|
[
{
"answer_id": 152851,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 2,
"selected": false,
"text": "<p>You can alter the include_path on each request using ini_set(). This would avoid having to use htaccess at all.</p>\n"
},
{
"answer_id": 152861,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 4,
"selected": true,
"text": "<ol>\n<li>Why do you need to rename .htaccess to htaccess.txt </li>\n<li>Try setting the include_path using <a href=\"http://php.net/set_include_path()\" rel=\"noreferrer\">set_include_path()</a> and see if that helps (as an intermediate fix)</li>\n<li>Verify which php.ini to use through a <a href=\"http://php.net/phpinfo\" rel=\"noreferrer\">phpinfo()</a></li>\n</ol>\n"
},
{
"answer_id": 152927,
"author": "Rich Bradshaw",
"author_id": 16511,
"author_profile": "https://Stackoverflow.com/users/16511",
"pm_score": 1,
"selected": false,
"text": "<p>My htaccess works under XAMPP fine - though some modules are disabled by default - are you sure that the modules you want are enabled? </p>\n"
},
{
"answer_id": 153071,
"author": "SchizoDuckie",
"author_id": 18077,
"author_profile": "https://Stackoverflow.com/users/18077",
"pm_score": 1,
"selected": false,
"text": "<p>I think the searchprase you are looking for is:</p>\n\n<p><a href=\"http://www.google.com/search?site=&hl=en&q=allowoverride+all\" rel=\"nofollow noreferrer\">AllowOverride All</a></p>\n\n<p>My guess is that within xampp you need to enable AllowOverride (through an .htaccess) in httpd.conf. It's a simple security measure that prevents newbies from installing a hackable platform :P</p>\n"
},
{
"answer_id": 154981,
"author": "f13o",
"author_id": 20288,
"author_profile": "https://Stackoverflow.com/users/20288",
"pm_score": 1,
"selected": false,
"text": "<p>You need to enable AllowOverride All in main http.conf file. Look inside XAMPP_DIR/apache/conf/http.conf)</p>\n"
},
{
"answer_id": 32487080,
"author": "Deepak",
"author_id": 4490437,
"author_profile": "https://Stackoverflow.com/users/4490437",
"pm_score": 1,
"selected": false,
"text": "<p>Simply Do this:</p>\n\n<pre><code>open file ...\\xampp\\apache\\conf\\httpd.conf\n\nfind line \"LoadModule rewrite_module modules/mod_rewrite.so\"\n\nif here is a # before this line remove it.(remove comment)\n</code></pre>\n\n<p>its working</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583/"
] |
XAMPP makes configuring a local LAMP stack for windows a breeze. So it's quite disappointing that enabling `.htaccess` files is such a nightmare.
My problem:
I've got a PHP application that requires apache/php to search for an `/includes/` directory contained within the application. To do this, `.htaccess` files must be allowed in Apache and the `.htaccess` file must specify exactly where the includes directory is.
Problem is, I can't get my Apache config to view these `.htaccess` files. I had major hassles installing this app at uni and getting the admins there to help with the setup. This shouldn't be so hard but for some reason I just can't get Apache to play nice.
This is my setup:
`c:\xampp`
`c:\xampp\htdocs`
`c:\xampp\apache\conf\httpd.conf` - where I've made the changes listed below
`c:\xampp\apache\bin\php.ini` - where changes to this file affect the PHP installation
It is interesting to note that `c:\xampp\php\php.ini` changes mean nothing - this is NOT the ini that affects the PHP installation.
The following lines are additions I've made to the `httpd.conf` file
```
#AccessFileName .htaccess
AccessFileName htaccess.txt
#
# The following lines prevent .htaccess and .htpasswd
# files from being viewed by Web clients.
#
#<Files ~ "^\.ht">
<Files ~ "^htaccess\.">
Order allow,deny
Deny from all
</Files>
<Directory "c:/xampp/htdocs">
#
# AllowOverride controls what directives may be placed in
# .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
```
The following is the entire `.htaccess` file contained in:
`c:\xampp\htdocs\application\htaccess.txt`
```
<Files ~ "\.inc$">
Order deny,allow
Deny from all
</Files>
php_value default_charset "UTF-8"
php_value include_path ".;c:\xampp\htdocs\application\includes"
php_value register_globals 0
php_value magic_quotes_gpc 0
php_value magic_quotes_runtime 0
php_value magic_quotes_sybase 0
php_value session.use_cookies 1
php_value session.use_only_cookies 0
php_value session.use_trans_sid 1
php_value session.gc_maxlifetime 3600
php_value arg_separator.output "&"
php_value url_rewriter.tags "a=href,area=href,frame=src,input=src,fieldset="
```
The includes directory exists at the location specified.
When I try to access the application I receive the following error:
```
Warning: require(include.general.inc) [function.require]: failed to open stream: No such file or directory in C:\xampp\htdocs\application\menu\logon.php on line 21
```
Fatal error: require() [function.require]: Failed opening required `include.general.inc` (include\_path='.;C:\xampp\php\pear\random') in `C:\xampp\htdocs\application\menu\logon.php` on line 21
The include path `c..\random\` is specified in the `php.ini` file listed above. The XAMPP install fails to allow another include path as specified in the `htaccess.txt` file.
I'm guessing there's probably an error with the `httpd.conf` OR the `htaccess.txt` file.. but it doesn't seem to be reading the `.htaccess` file. I've tried to be as thorough as possible so forgive the verbosity of the post.
Now I know a workaround could be to simply add the include\_path to the PHP file, but I'm not going to have access to the `php.ini` file on the location I plan to deploy my app. I will, however, be able to request the server admin allows `.htaccess` files.
renamed `htacces.txt` to `.htaccess` and ammended the appropriate directives in the `httpd.conf` file and all seems to work. The application suggested the naming of `htaccess.txt` and the ammended directives in the httpd. These are obviously wrong (at least for a XAMPP stack).
By the way, using ini\_set() is a much friendlier way if the app needs to be deployed to multiple locations so thanks especially for that pointer.
|
1. Why do you need to rename .htaccess to htaccess.txt
2. Try setting the include\_path using [set\_include\_path()](http://php.net/set_include_path()) and see if that helps (as an intermediate fix)
3. Verify which php.ini to use through a [phpinfo()](http://php.net/phpinfo)
|
152,837 |
<p>How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database.</p>
<p>I'm not sure if it makes a difference, but I'm using Oracle 9i.</p>
|
[
{
"answer_id": 152849,
"author": "stjohnroe",
"author_id": 2985,
"author_profile": "https://Stackoverflow.com/users/2985",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using sql plus then I think that you need to issue the command </p>\n\n<pre><code>SET SCAN OFF\n</code></pre>\n"
},
{
"answer_id": 152852,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 4,
"selected": false,
"text": "<p>If you are doing it from SQLPLUS use </p>\n\n<pre><code>SET DEFINE OFF \n</code></pre>\n\n<p>to stop it treading & as a special case</p>\n"
},
{
"answer_id": 152856,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SET ESCAPE ON;\nINSERT VALUES(\"J\\&J Construction\") INTO custnames;\n</code></pre>\n\n<p>(Untested, don't have an Oracle box at hand and it has been a while)</p>\n"
},
{
"answer_id": 152859,
"author": "Andrew Hampton",
"author_id": 466,
"author_profile": "https://Stackoverflow.com/users/466",
"pm_score": 2,
"selected": false,
"text": "<p>I've found that using either of the following options works:</p>\n\n<p><code>SET DEF OFF</code> </p>\n\n<p>or</p>\n\n<p><code>SET SCAN OFF</code></p>\n\n<p>I don't know enough about databases to know if one is better or \"more right\" than the other. Also, if there's something better than either of these, please let me know.</p>\n"
},
{
"answer_id": 152864,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 2,
"selected": false,
"text": "<p>SET SCAN OFF is obsolete\n<a href=\"http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a90842/apc.htm\" rel=\"nofollow noreferrer\">http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a90842/apc.htm</a></p>\n"
},
{
"answer_id": 152884,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 2,
"selected": false,
"text": "<p>In a program, always use a parameterized query. It avoids SQL Injection attacks as well as any other characters that are special to the SQL parser.</p>\n"
},
{
"answer_id": 152971,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 3,
"selected": false,
"text": "<p>The correct syntax is</p>\n\n<pre><code>set def off;\ninsert into tablename values( 'J&J');\n</code></pre>\n"
},
{
"answer_id": 175922,
"author": "Osama Al-Maadeed",
"author_id": 25544,
"author_profile": "https://Stackoverflow.com/users/25544",
"pm_score": 0,
"selected": false,
"text": "<p>Stop using SQL/Plus, I highly recommend <a href=\"http://www.allroundautomations.nl/plsqldev.html\" rel=\"nofollow noreferrer\">PL/SQL Developer</a> it's much more than an SQL tool.</p>\n\n<p>p.s. Some people prefer <a href=\"http://www.toadsoft.com/\" rel=\"nofollow noreferrer\">TOAD</a>.</p>\n"
},
{
"answer_id": 410490,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 7,
"selected": true,
"text": "<p>I keep on forgetting this and coming back to it again! I think the best answer is a combination of the responses provided so far.</p>\n\n<p>Firstly, & is the variable prefix in sqlplus/sqldeveloper, hence the problem - when it appears, it is expected to be part of a variable name.</p>\n\n<p>SET DEFINE OFF will stop sqlplus interpreting & this way.</p>\n\n<p>But what if you need to use sqlplus variables <em>and</em> literal & characters? </p>\n\n<ul>\n<li>You need SET DEFINE ON to make variables work</li>\n<li>And SET ESCAPE ON to escape uses of &.</li>\n</ul>\n\n<p>e.g.</p>\n\n<pre><code>set define on\nset escape on\n\ndefine myvar=/forth\n\nselect 'back\\\\ \\& &myvar' as swing from dual;\n</code></pre>\n\n<p>Produces:</p>\n\n<pre><code>old 1: select 'back\\\\ \\& &myvar' from dual\nnew 1: select 'back\\ & /forth' from dual\n\nSWING\n--------------\nback\\ & /forth\n</code></pre>\n\n<p>If you want to use a different escape character:</p>\n\n<pre><code>set define on\nset escape '#'\n\ndefine myvar=/forth\n\nselect 'back\\ #& &myvar' as swing from dual;\n</code></pre>\n\n<p>When you set a specific escape character, you may see 'SP2-0272: escape character cannot be alphanumeric or whitespace'. This probably means you already have the escape character defined, and things get horribly self-referential. The clean way of avoiding this problem is to set escape off first:</p>\n\n<pre><code>set escape off\nset escape '#'\n</code></pre>\n"
},
{
"answer_id": 410612,
"author": "Hans",
"author_id": 51334,
"author_profile": "https://Stackoverflow.com/users/51334",
"pm_score": 3,
"selected": false,
"text": "<p>There's always the chr() function, which converts an ascii code to string.</p>\n\n<p>ie. something like:\nINSERT INTO\n table\nVALUES (\n CONCAT( 'J', CHR(38), 'J' )\n)</p>\n"
},
{
"answer_id": 15975677,
"author": "C. J.",
"author_id": 2275117,
"author_profile": "https://Stackoverflow.com/users/2275117",
"pm_score": 4,
"selected": false,
"text": "<p>An alternate solution, use concatenation and the chr function:</p>\n\n<pre><code>select 'J' || chr(38) || 'J Construction' from dual;\n</code></pre>\n"
},
{
"answer_id": 36443549,
"author": "lokesh kumar",
"author_id": 4506183,
"author_profile": "https://Stackoverflow.com/users/4506183",
"pm_score": 3,
"selected": false,
"text": "<p>You can insert such an string as <strong>'J'||'&'||'Construction'</strong>.\nIt works fine.</p>\n\n<pre><code>insert into table_name (col_name) values('J'||'&'||'Construction');\n</code></pre>\n"
},
{
"answer_id": 45959353,
"author": "Alberto Cerqueira",
"author_id": 5004526,
"author_profile": "https://Stackoverflow.com/users/5004526",
"pm_score": 0,
"selected": false,
"text": "<p>Look, Andrew:</p>\n\n<p><strong>\"J&J Construction\"</strong>:</p>\n\n<pre><code>SELECT CONCAT('J', CONCAT(CHR(38), 'J Construction')) FROM DUAL;\n</code></pre>\n"
},
{
"answer_id": 48382464,
"author": "aemre",
"author_id": 4582867,
"author_profile": "https://Stackoverflow.com/users/4582867",
"pm_score": 3,
"selected": false,
"text": "<pre><code>INSERT INTO TEST_TABLE VALUES('Jonhy''s Sport &'||' Fitness')\n</code></pre>\n\n<p>This query's output : <strong>Jonhy's Sport & Fitness</strong> </p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/466/"
] |
How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database.
I'm not sure if it makes a difference, but I'm using Oracle 9i.
|
I keep on forgetting this and coming back to it again! I think the best answer is a combination of the responses provided so far.
Firstly, & is the variable prefix in sqlplus/sqldeveloper, hence the problem - when it appears, it is expected to be part of a variable name.
SET DEFINE OFF will stop sqlplus interpreting & this way.
But what if you need to use sqlplus variables *and* literal & characters?
* You need SET DEFINE ON to make variables work
* And SET ESCAPE ON to escape uses of &.
e.g.
```
set define on
set escape on
define myvar=/forth
select 'back\\ \& &myvar' as swing from dual;
```
Produces:
```
old 1: select 'back\\ \& &myvar' from dual
new 1: select 'back\ & /forth' from dual
SWING
--------------
back\ & /forth
```
If you want to use a different escape character:
```
set define on
set escape '#'
define myvar=/forth
select 'back\ #& &myvar' as swing from dual;
```
When you set a specific escape character, you may see 'SP2-0272: escape character cannot be alphanumeric or whitespace'. This probably means you already have the escape character defined, and things get horribly self-referential. The clean way of avoiding this problem is to set escape off first:
```
set escape off
set escape '#'
```
|
152,866 |
<p>For simplicity, I generally split a lot of my configuration (i.e. the contents of app.config and web.config) out into separate .config files, and then reference them from the main config file using the 'configSource' attribute. For example:</p>
<pre><code><appSettings configSource="appSettings.config"/>
</code></pre>
<p>and then placing all of the key/value pairs in that appSettings.config file instead of having this in-line in the main config file:</p>
<pre><code><appSettings>
<add key="FirstKey" value="FirstValue"/>
<add key="SecondKey" value="SecondValue"/>
...
</appSettings>
</code></pre>
<p>This typically works great with the application itself, but I run into problems when attempting to write unit tests that, for whatever reason, need to get at some value from a configuration section that is stored in one of these external files. (I understand that most of these would likley be considered "integration tests", as they are relying on the Configuration system, and I do have "pure unit tests" as well, but those are the not the problem. I'm really looking to test that these configuration values are retrieved correctly and impact behavior in the correct way).</p>
<p>Due to how MSTest compiles and copies the output to obfuscated-looking folders that are different from every test run (rather than to the 'bin' folder like you might think), it never seems to be able to find those external files while the tests are executing. I've tried messing around with post build actions to make this work but with no luck. Is there a way to have these external files copied over into the correct output folder at run time?</p>
|
[
{
"answer_id": 152873,
"author": "Jesse Taber",
"author_id": 1680,
"author_profile": "https://Stackoverflow.com/users/1680",
"pm_score": 5,
"selected": true,
"text": "<p>Found it:</p>\n\n<p>If you edit the test run configuration (by double clicking the .testrunconfig file that gets put into the 'Solution Items' solution folder when you add a new unit test), you get a test run configuration dialog. There's a section there called 'Deployment' where you can specifiy files or whole folders from anywhere in the solution that can be copied out with the compiled assemblies at run time to the correct folder.</p>\n\n<p>In this way, I can now actually just define most of my configuration in one set of external .config files and have them automatically copied out at the run of each test.</p>\n"
},
{
"answer_id": 638298,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Test run configurations are a bit awkward when trying to run tests outside of Visual Studio.</p>\n\n<p>For command line execution using MSTest they become quite cumbersome to keep \"clean\".\nThey are also \"global\" to the solution so external files will be copied for every test project.</p>\n\n<p>I much prefer the <code>DeploymentItem</code> attribute.</p>\n\n<pre><code>[TestMethod]\n[DeploymentItem(@\"test_data.file\")]\npublic void FooTest()\n{...}\n</code></pre>\n\n<p>Makes the tests independent of the .testrunconfig files.</p>\n"
},
{
"answer_id": 42199914,
"author": "Ghebrehiywet",
"author_id": 4915864,
"author_profile": "https://Stackoverflow.com/users/4915864",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li><p>write this in your connectionString. First <strong>ConnectionString.config</strong> is not exists. </p>\n\n<p><\"connectionStrings configSource=\"ConnectionString.config\"> \"</p></li>\n<li><p>open command prompt (CMD) in administrator privileged.</p></li>\n<li>Create a symbolic links with the name of <strong>ConnectionString.config</strong> at bin/debug folder.</li>\n</ol>\n\n<p>C:\\Windows\\Systems32> <code>mklink \"C:\\Link To Folder\\....\\ConnectionString.config\" \"C:\\Users\\Name\\Original Folder\\.....\\...\\Secure ConnectionString.config\"</code></p>\n\n<p>finally it creates ConnectionString configuration file at the specified location. and works successfully.</p>\n\n<p><a href=\"https://i.stack.imgur.com/K0JLb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/K0JLb.png\" alt=\"enter image description here\"></a></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1680/"
] |
For simplicity, I generally split a lot of my configuration (i.e. the contents of app.config and web.config) out into separate .config files, and then reference them from the main config file using the 'configSource' attribute. For example:
```
<appSettings configSource="appSettings.config"/>
```
and then placing all of the key/value pairs in that appSettings.config file instead of having this in-line in the main config file:
```
<appSettings>
<add key="FirstKey" value="FirstValue"/>
<add key="SecondKey" value="SecondValue"/>
...
</appSettings>
```
This typically works great with the application itself, but I run into problems when attempting to write unit tests that, for whatever reason, need to get at some value from a configuration section that is stored in one of these external files. (I understand that most of these would likley be considered "integration tests", as they are relying on the Configuration system, and I do have "pure unit tests" as well, but those are the not the problem. I'm really looking to test that these configuration values are retrieved correctly and impact behavior in the correct way).
Due to how MSTest compiles and copies the output to obfuscated-looking folders that are different from every test run (rather than to the 'bin' folder like you might think), it never seems to be able to find those external files while the tests are executing. I've tried messing around with post build actions to make this work but with no luck. Is there a way to have these external files copied over into the correct output folder at run time?
|
Found it:
If you edit the test run configuration (by double clicking the .testrunconfig file that gets put into the 'Solution Items' solution folder when you add a new unit test), you get a test run configuration dialog. There's a section there called 'Deployment' where you can specifiy files or whole folders from anywhere in the solution that can be copied out with the compiled assemblies at run time to the correct folder.
In this way, I can now actually just define most of my configuration in one set of external .config files and have them automatically copied out at the run of each test.
|
152,869 |
<p>It is easy to highlight a selected datagrid row, by for example using toggleClass in the tr's click event. But how best to later remove the highlight after a different row has been selected? Iterating over all the rows to unhighlight them could become expensive for larger datagrids. I'd be interested in the simplest solution, as well as the most performant.</p>
<p>Thanks,<br>
Mike </p>
|
[
{
"answer_id": 152877,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want to find items that have <strong>toggledClass</strong> and turn that off using jQuery:</p>\n\n<pre><code>$('.toggledClass').removeClass('toggledClass');\n</code></pre>\n"
},
{
"answer_id": 152886,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 0,
"selected": false,
"text": "<p>For faster performance, you could push your selected element's ID into a var (or an array for multiples), and then use that var/iterate over that array when toggling the classes off.</p>\n"
},
{
"answer_id": 153102,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": true,
"text": "<p>This method stores the active row into a variable. The $ at the start of the variable is just my own hungarian notation for jQuery objects.</p>\n\n<pre><code>var $activeRow;\n\n$('#myGrid tr').click(function() {\n if ($activeRow) $activeRow.removeClass('active');\n $activeRow = $(this).addClass('active');\n});\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/785/"
] |
It is easy to highlight a selected datagrid row, by for example using toggleClass in the tr's click event. But how best to later remove the highlight after a different row has been selected? Iterating over all the rows to unhighlight them could become expensive for larger datagrids. I'd be interested in the simplest solution, as well as the most performant.
Thanks,
Mike
|
This method stores the active row into a variable. The $ at the start of the variable is just my own hungarian notation for jQuery objects.
```
var $activeRow;
$('#myGrid tr').click(function() {
if ($activeRow) $activeRow.removeClass('active');
$activeRow = $(this).addClass('active');
});
```
|
152,893 |
<p>We have a form that allows a user to dynamically add inputs for fields. For example if you have a form for tracking projects, you want to dynamically add tasks to that project. Just to clarify my language: you dynamically add inputs for the task field. The problem is, we have 50 of those fields. Our current solution presents all 50 fields with a plus (+) next to the field to allow them to add another input box for that field. The labels for the field are to the left of the field and each input box that is added goes below the current input box. </p>
<p>Please trust that dynamically adding inputs is the right solution, please trust that it has been thought out, please trust that this is what the users wants, please trust that we have gone down various other roads and this is the best solution. </p>
<p>My question is about presentation: How would you do it?</p>
<p>Please keep the answers to UI design. We already have the database schema figured out.</p>
<hr>
<p><strong>Update</strong></p>
<p><em>Current Solution is a web based application that uses JavaScript to dynamically add new inputs and looks very similar to Corey Trager's drawing:</em></p>
<pre><code>Task [.............] +
[.............] +
[.............] +
[.............] +
Foo [.............] +
[.............] +
[.............] +
Repeat 50 times...
</code></pre>
|
[
{
"answer_id": 152904,
"author": "zackola",
"author_id": 321427,
"author_profile": "https://Stackoverflow.com/users/321427",
"pm_score": 0,
"selected": false,
"text": "<p>Little + icon somewhere near the last task field with a link that says \"Add new task\". When clicked, new task field appears below current last task.</p>\n"
},
{
"answer_id": 152906,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 0,
"selected": false,
"text": "<p>I would use a drag-and-drop approach, allowing the user flexibility in positioning. This is possible even using a web-application. See, for example, Dropthings (<a href=\"http://www.dropthings.com/\" rel=\"nofollow noreferrer\">http://www.dropthings.com/</a>). This provides all the code you'd need to implement drag-n-drop in an ASP.NET environment.</p>\n\n<p>What environment are you using?</p>\n"
},
{
"answer_id": 152930,
"author": "FryHard",
"author_id": 231,
"author_profile": "https://Stackoverflow.com/users/231",
"pm_score": 1,
"selected": false,
"text": "<p>Thinking on from what @zachary suggested:</p>\n\n<p>Display the form as it was designed to the user with the default/ last saved number of fields. At the bottom of the form place a DropDownButton that has a + icon and the words Add Field (<strong>+ Add Field</strong>). </p>\n\n<p>Dropping down this button will show the list of all fields that are available. When the user selects one of these the form will grow (enough to house the new field) the new field with label will be displayed at the bottom of the form and the add field button will show below the new field.</p>\n\n<p><hr/>\n<strong>Edit:</strong></p>\n\n<p>To follow on the theme of ASCII diagrams this was is what I think my suggesting would look like.</p>\n\n<p>Task [......................]<br/>\n [ + Add Task ▼] </p>\n\n<p>Foo [......................]<br/>\n [ + Add Foo ▼] </p>\n"
},
{
"answer_id": 152931,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 1,
"selected": false,
"text": "<p>So, what you described can look something like this? If not, can you try \"drawing\" it please?</p>\n\n<pre><code>Task [.............] + \n [.............] + \n [.............] + \n [.............] +\n\nFoo [.............] +\n [.............] +\n [.............] +\n</code></pre>\n\n<p>Is this a web page or other technology?</p>\n"
},
{
"answer_id": 152934,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 0,
"selected": false,
"text": "<p>If this is a web app then you could use Javascript to dynamically manage the additional fields. Depending on whether you can process the form asynchronously, you could use Ajax which would simplify some aspects of the form management.</p>\n\n<p>Basically, each task would need an individually named and then you would need to append a new uniquely named form input element for each new field that they choose to append. Then you would have to loop through the form using Javascript before submitting the form or you would loop through the POST data after its submitted.</p>\n\n<p>Of course, this introduces Javascript as a requirement for your web app which isn't always viable.</p>\n"
},
{
"answer_id": 153299,
"author": "garrow",
"author_id": 21095,
"author_profile": "https://Stackoverflow.com/users/21095",
"pm_score": 1,
"selected": false,
"text": "<p>This may be completely off the mark, but depending on the requirements for the fields, and if this is the configuration or the data entry interface.</p>\n\n<p>If the fields <strong>do</strong> need to be open for data entry, you could leave have them defined as a list of fieldnames and values, and use click-to-edit to dynamically place input boxes on each element as needed.</p>\n\n<p>This solution could <strong>reduce visual noise</strong> as well as save <strong>vertical space</strong>. As you can see the form input takes up more space than plain text. You can cater for keyboard users by capturing tab events and triggering the next field's click to edit functionality.</p>\n\n<p>It could look something like this. ( having just clicked on Foo to edit the content)</p>\n\n<pre><code>Name : Joe Blogs\nPhone : 555-1234\nCheese : Stilton\n -----------\nFoo | SNAFU | \n -----------\nBar : fubar\nFifty : Whatever\n\n(+) Add new field...\n</code></pre>\n\n<hr>\n\n<p>OR </p>\n\n<p>If this is a configuration page, ie where you add new fields to be filled in on another screen or stage in the process, you could define a list of fields sequentially, which are then displayed to the user for data entry.</p>\n\n<pre><code> -------------------------------------------------\nDefine Fields | name, phone, cheese, foo, bar ..(etc).. fifty |\n -------------------------------------------------\n</code></pre>\n\n<p>Then the fields are displayed in a huge grid as per the current UI.</p>\n"
},
{
"answer_id": 156080,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, now that you've added my diagram to your question, my answer is....</p>\n\n<p>I'm not saying this is better, but it's an alternative. Here's a different way that replaces horizontal scrolling with clicking. Instead of navigating from \"tasks\" to \"foo\" to \"bar\" by vertical scrolling, use \"tabs\", even if you have to stack them several rows high. It does make it easier to navigate in a random order. You could even switch back and forth from this tabbed view to your current \"show all\" view.</p>\n\n<pre><code>[task][foo][another tab][another tab][etc][etc][etc][etc][etc][etc]\n[row2][fred][another tab][etc][etc][etc][etc][etc][etc][etc]\n[row3][another tab][wilma][etc][etc][etc][etc][etc][etc][etc]\n\n[task1 ]+\n[task2 }+\n[task3 ]+ \n</code></pre>\n"
},
{
"answer_id": 1112903,
"author": "jsnfwlr",
"author_id": 124085,
"author_profile": "https://Stackoverflow.com/users/124085",
"pm_score": 0,
"selected": false,
"text": "<p>Could you not use a system similar to that implemented by face book, that has a single textbox, but allows multiple items to be added to it? There are pre-coded solutions, such as <a href=\"http://ajaxian.com/archives/facebook-style-input-box\" rel=\"nofollow noreferrer\">this one</a>, which is for mootools v1.2, or <a href=\"http://loopj.com/2009/04/25/jquery-plugin-tokenizing-autocomplete-text-entry/\" rel=\"nofollow noreferrer\">this one</a> which is for jQuery. And you could even allow auto-complete of the tasks already in the system.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681/"
] |
We have a form that allows a user to dynamically add inputs for fields. For example if you have a form for tracking projects, you want to dynamically add tasks to that project. Just to clarify my language: you dynamically add inputs for the task field. The problem is, we have 50 of those fields. Our current solution presents all 50 fields with a plus (+) next to the field to allow them to add another input box for that field. The labels for the field are to the left of the field and each input box that is added goes below the current input box.
Please trust that dynamically adding inputs is the right solution, please trust that it has been thought out, please trust that this is what the users wants, please trust that we have gone down various other roads and this is the best solution.
My question is about presentation: How would you do it?
Please keep the answers to UI design. We already have the database schema figured out.
---
**Update**
*Current Solution is a web based application that uses JavaScript to dynamically add new inputs and looks very similar to Corey Trager's drawing:*
```
Task [.............] +
[.............] +
[.............] +
[.............] +
Foo [.............] +
[.............] +
[.............] +
Repeat 50 times...
```
|
Thinking on from what @zachary suggested:
Display the form as it was designed to the user with the default/ last saved number of fields. At the bottom of the form place a DropDownButton that has a + icon and the words Add Field (**+ Add Field**).
Dropping down this button will show the list of all fields that are available. When the user selects one of these the form will grow (enough to house the new field) the new field with label will be displayed at the bottom of the form and the add field button will show below the new field.
---
**Edit:**
To follow on the theme of ASCII diagrams this was is what I think my suggesting would look like.
Task [......................]
[ + Add Task ▼]
Foo [......................]
[ + Add Foo ▼]
|
152,900 |
<p>When loading XML into an XmlDocument, i.e.</p>
<pre>
XmlDocument document = new XmlDocument();
document.LoadXml(xmlData);
</pre>
<p>is there any way to stop the process from replacing entities? I've got a strange problem where I've got a TM symbol (stored as the entity #8482) in the xml being converted into the TM character. As far as I'm concerned this shouldn't happen as the XML document has the encoding ISO-8859-1 (which doesn't have the TM symbol)</p>
<p>Thanks</p>
|
[
{
"answer_id": 152923,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>I confess things get a little confusing with XML documents and encodings, but I'd hope that it would get set appropriate when you save it again, if you're still using ISO-8859-1 - but that if you save with UTF-8, it wouldn't need to. In some ways, logically the document really contains the symbol rather the entity reference - the latter is just an encoding matter. (I'm thinking aloud here - please don't take this as authoritative information.)</p>\n\n<p>What are you doing with the document after loading it?</p>\n"
},
{
"answer_id": 152935,
"author": "Andy",
"author_id": 3585,
"author_profile": "https://Stackoverflow.com/users/3585",
"pm_score": 0,
"selected": false,
"text": "<p>I beleive if you enclose the entity contents in the CDATA section it should leave it all alone e.g.</p>\n\n<pre><code><root>\n<testnode>\n<![CDATA[some text &#8482;]]>\n</testnode>\n</root>\n</code></pre>\n"
},
{
"answer_id": 152936,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>What are you writing it to? A TextWriter? a Stream? what?</p>\n\n<p>The following keeps the entity (well, it replaces it with the hex equivalent) - but if you do the same with a StringWriter it detects the unicode and uses that instead:</p>\n\n<pre><code> XmlDocument doc = new XmlDocument();\n doc.LoadXml(@\"<xml>&#8482;</xml>\");\n using (MemoryStream ms = new MemoryStream())\n {\n XmlWriterSettings settings = new XmlWriterSettings();\n settings.Encoding = Encoding.GetEncoding(\"ISO-8859-1\");\n XmlWriter xw = XmlWriter.Create(ms, settings);\n doc.Save(xw);\n xw.Close();\n Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));\n }\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code> <?xml version=\"1.0\" encoding=\"iso-8859-1\"?><xml>&#x2122;</xml>\n</code></pre>\n"
},
{
"answer_id": 152956,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 0,
"selected": false,
"text": "<p>Entity references are not encoding specific. According to the <a href=\"http://www.w3.org/TR/2006/REC-xml-20060816/#sec-references\" rel=\"nofollow noreferrer\">W3C XML 1.0 Recommendation</a>:</p>\n\n<blockquote>\n <p>If the character reference begins with\n \"&#x\", the digits and letters up to\n the terminating ; provide a\n hexadecimal representation of the\n character's code point in ISO/IEC\n 10646.</p>\n</blockquote>\n"
},
{
"answer_id": 153013,
"author": "Simon Gibbs",
"author_id": 13935,
"author_profile": "https://Stackoverflow.com/users/13935",
"pm_score": 3,
"selected": true,
"text": "<p>This is a standard misunderstanding of the XML toolset. The whole business with \"&#x\", is a syntactic feature designed to cope with character encodings. Your XmlDocument isn't a stream of characters - it has been freed of character encoding issues - instead it contains an abstract model of XML type data. Words for this include DOM and InfoSet, I'm not sure exactly which is accurate. </p>\n\n<p>The \"&#x\" gubbins won't exist in this model because the whole issue is irrelevant, it will return - if appropriate - when you transform the Info Set back into a character stream in some specific encoding.</p>\n\n<p>This misunderstanding is sufficiently common to have made it into academic literature as part of a collection of similar quirks. Take a look at \"Xml Fever\" at this location: <a href=\"http://doi.acm.org/10.1145/1364782.1364795\" rel=\"nofollow noreferrer\">http://doi.acm.org/10.1145/1364782.1364795</a></p>\n"
},
{
"answer_id": 153022,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 0,
"selected": false,
"text": "<p>The &#xxxx; entities are considered to be the character they represent. All XML is converted to unicode on reading and any such entities are removed in favor of the unicode character they represent. This includes any occurance for them in unicode source such as the string passed to LoadXML.</p>\n\n<p>Similarly on writing any character that cannot be represented by the stream being written to is converted to a &#xxxx; entity. There is little point trying to preserve them.</p>\n\n<p>A common mistake is expect to get a String from a DOM by some means that uses an encoding other then unicode. That just doesn't happen regardless of what the \n"
},
{
"answer_id": 153810,
"author": "Gordon Thompson",
"author_id": 21299,
"author_profile": "https://Stackoverflow.com/users/21299",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for all of the help.</p>\n\n<p>I've fixed my problem by writing a HtmlEncode function which actually replaces all of the characters before it spits them out to the webpage (instead of relying on the somewhat broken HtmlEncode() .NET function which only seems to encode a small subset of the characters necessary)</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21299/"
] |
When loading XML into an XmlDocument, i.e.
```
XmlDocument document = new XmlDocument();
document.LoadXml(xmlData);
```
is there any way to stop the process from replacing entities? I've got a strange problem where I've got a TM symbol (stored as the entity #8482) in the xml being converted into the TM character. As far as I'm concerned this shouldn't happen as the XML document has the encoding ISO-8859-1 (which doesn't have the TM symbol)
Thanks
|
This is a standard misunderstanding of the XML toolset. The whole business with "&#x", is a syntactic feature designed to cope with character encodings. Your XmlDocument isn't a stream of characters - it has been freed of character encoding issues - instead it contains an abstract model of XML type data. Words for this include DOM and InfoSet, I'm not sure exactly which is accurate.
The "&#x" gubbins won't exist in this model because the whole issue is irrelevant, it will return - if appropriate - when you transform the Info Set back into a character stream in some specific encoding.
This misunderstanding is sufficiently common to have made it into academic literature as part of a collection of similar quirks. Take a look at "Xml Fever" at this location: <http://doi.acm.org/10.1145/1364782.1364795>
|
152,968 |
<p>Do you know an easy and straight-forward method/sub/module which allows me to convert a number (say 1234567.89) to an easily readable form - something like 1.23M?</p>
<p>Right now I can do this by making several comparisons, but I'm not happy with my method:</p>
<pre><code>if($bytes > 1000000000){
$bytes = ( sprintf( "%0.2f", $bytes/1000000000 )). " Gb/s";
}
elsif ($bytes > 1000000){
$bytes = ( sprintf( "%0.2f", $bytes/1000000 )). " Mb/s";
}
elsif ($bytes > 1000){
$bytes = ( sprintf( "%0.2f", $bytes/1000 )). " Kb/s";
}
else{
$bytes = sprintf( "%0.2f", $bytes ). "b/s";
}
</code></pre>
<p>Thank you for your help!</p>
|
[
{
"answer_id": 152978,
"author": "WalkingRandomly",
"author_id": 1856916,
"author_profile": "https://Stackoverflow.com/users/1856916",
"pm_score": 5,
"selected": true,
"text": "<p>The <a href=\"http://search.cpan.org/dist/Number-Bytes-Human\" rel=\"noreferrer\">Number::Bytes::Human</a> module should be able to help you out.</p>\n\n<p>An example of how to use it can be found in its synopsis:</p>\n\n<pre><code> use Number::Bytes::Human qw(format_bytes);\n\n $size = format_bytes(0); # '0'\n $size = format_bytes(2*1024); # '2.0K'\n\n $size = format_bytes(1_234_890, bs => 1000); # '1.3M'\n $size = format_bytes(1E9, bs => 1000); # '1.0G'\n\n # the OO way\n $human = Number::Bytes::Human->new(bs => 1000, si => 1);\n $size = $human->format(1E7); # '10MB'\n $human->set_options(zero => '-');\n $size = $human->format(0); # '-'\n</code></pre>\n"
},
{
"answer_id": 152982,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://search.cpan.org/perldoc?Number::Bytes::Human\" rel=\"nofollow noreferrer\">Number::Bytes::Human</a> seems to do exactly what you want.</p>\n"
},
{
"answer_id": 153017,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 2,
"selected": false,
"text": "<p>In pure Perl form, I've done this with a nested ternary operator to cut on verbosity:</p>\n\n<pre><code>sub BytesToReadableString($) {\n my $c = shift;\n $c >= 1073741824 ? sprintf(\"%0.2fGB\", $c/1073741824)\n : $c >= 1048576 ? sprintf(\"%0.2fMB\", $c/1048576)\n : $c >= 1024 ? sprintf(\"%0.2fKB\", $c/1024)\n : $c . \"bytes\";\n}\n\nprint BytesToReadableString(225939) . \"/s\\n\";\n</code></pre>\n\n<p>Outputs:</p>\n\n<pre>220.64KB/s</pre>\n"
},
{
"answer_id": 153026,
"author": "Mnebuerquo",
"author_id": 5114,
"author_profile": "https://Stackoverflow.com/users/5114",
"pm_score": 0,
"selected": false,
"text": "<p>This snippet is in PHP, and it's loosely based on some example someone else had on their website somewhere (sorry buddy, I can't remember).</p>\n\n<p>The basic concept is instead of using if, use a loop.</p>\n\n<pre><code>function formatNumberThousands($a,$dig)\n{\n $unim = array(\"\",\"k\",\"m\",\"g\");\n $c = 0;\n while ($a>=1000 && $c<=3) {\n $c++;\n $a = $a/1000;\n }\n $d = $dig-ceil(log10($a));\n return number_format($a,($c ? $d : 0)).\"\".$unim[$c];\n}\n</code></pre>\n\n<p>The number_format() call is a PHP library function which returns a string with commas between the thousands groups. I'm not sure if something like it exists in perl.</p>\n\n<p>The $dig parameter sets a limit on the number of digits to show. If $dig is 2, it will give you 1.2k from 1237.</p>\n\n<p>To format bytes, just divide by 1024 instead.</p>\n\n<p>This function is in use in some production code to this day.</p>\n"
},
{
"answer_id": 153268,
"author": "Michael Cramer",
"author_id": 1496728,
"author_profile": "https://Stackoverflow.com/users/1496728",
"pm_score": 2,
"selected": false,
"text": "<pre><code>sub magnitudeformat {\n my $val = shift;\n my $expstr;\n\n my $exp = log($val) / log(10);\n if ($exp < 3) { return $val; }\n elsif ($exp < 6) { $exp = 3; $expstr = \"K\"; }\n elsif ($exp < 9) { $exp = 6; $expstr = \"M\"; }\n elsif ($exp < 12) { $exp = 9; $expstr = \"G\"; } # Or \"B\".\n else { $exp = 12; $expstr = \"T\"; }\n\n return sprintf(\"%0.1f%s\", $val/(10**$exp), $expstr);\n}\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23780/"
] |
Do you know an easy and straight-forward method/sub/module which allows me to convert a number (say 1234567.89) to an easily readable form - something like 1.23M?
Right now I can do this by making several comparisons, but I'm not happy with my method:
```
if($bytes > 1000000000){
$bytes = ( sprintf( "%0.2f", $bytes/1000000000 )). " Gb/s";
}
elsif ($bytes > 1000000){
$bytes = ( sprintf( "%0.2f", $bytes/1000000 )). " Mb/s";
}
elsif ($bytes > 1000){
$bytes = ( sprintf( "%0.2f", $bytes/1000 )). " Kb/s";
}
else{
$bytes = sprintf( "%0.2f", $bytes ). "b/s";
}
```
Thank you for your help!
|
The [Number::Bytes::Human](http://search.cpan.org/dist/Number-Bytes-Human) module should be able to help you out.
An example of how to use it can be found in its synopsis:
```
use Number::Bytes::Human qw(format_bytes);
$size = format_bytes(0); # '0'
$size = format_bytes(2*1024); # '2.0K'
$size = format_bytes(1_234_890, bs => 1000); # '1.3M'
$size = format_bytes(1E9, bs => 1000); # '1.0G'
# the OO way
$human = Number::Bytes::Human->new(bs => 1000, si => 1);
$size = $human->format(1E7); # '10MB'
$human->set_options(zero => '-');
$size = $human->format(0); # '-'
```
|
152,975 |
<p>I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.</p>
<p>Is something like this possible with jQuery?</p>
<pre><code>$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
</code></pre>
|
[
{
"answer_id": 152992,
"author": "Chris MacDonald",
"author_id": 18146,
"author_profile": "https://Stackoverflow.com/users/18146",
"pm_score": 5,
"selected": false,
"text": "<p>Check the window click event target (it should propagate to the window, as long as it's not captured anywhere else), and ensure that it's not any of the menu elements. If it's not, then you're outside your menu.</p>\n\n<p>Or check the position of the click, and see if it's contained within the menu area.</p>\n"
},
{
"answer_id": 153047,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 12,
"selected": true,
"text": "<blockquote>\n<p>Note: Using <code>stopPropagation</code> is something that should be avoided as it breaks normal event flow in the DOM. See <a href=\"https://css-tricks.com/dangers-stopping-event-propagation/\" rel=\"noreferrer\">this CSS Tricks article</a> for more information. Consider using <a href=\"https://stackoverflow.com/a/3028037/561309\">this method</a> instead.</p>\n</blockquote>\n<p>Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body.</p>\n<pre class=\"lang-js prettyprint-override\"><code>$(window).click(function() {\n //Hide the menus if visible\n});\n\n$('#menucontainer').click(function(event){\n event.stopPropagation();\n});\n</code></pre>\n"
},
{
"answer_id": 154268,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 7,
"selected": false,
"text": "<p>I have an application that works similarly to Eran's example, except I attach the click event to the body when I open the menu... Kinda like this:</p>\n\n<pre><code>$('#menucontainer').click(function(event) {\n $('html').one('click',function() {\n // Hide the menus\n });\n\n event.stopPropagation();\n});\n</code></pre>\n\n<p>More information on <a href=\"http://docs.jquery.com/Events/one\" rel=\"noreferrer\">jQuery's <code>one()</code> function</a></p>\n"
},
{
"answer_id": 1089622,
"author": "Dennis",
"author_id": 81976,
"author_profile": "https://Stackoverflow.com/users/81976",
"pm_score": 7,
"selected": false,
"text": "<p>The other solutions here didn't work for me so I had to use:</p>\n<pre><code>if(!$(event.target).is('#foo'))\n{\n // hide menu\n}\n</code></pre>\n<h2>Edit: Plain Javascript variant (2021-03-31)</h2>\n<p>I used this method to handle closing a drop down menu when clicking outside of it.</p>\n<p>First, I created a custom class name for all the elements of the component. This class name will be added to all elements that make up the menu widget.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const className = `dropdown-${Date.now()}-${Math.random() * 100}`;\n</code></pre>\n<p>I create a function to check for clicks and the class name of the clicked element. If clicked element does not contain the custom class name I generated above, it should set the <code>show</code> flag to <code>false</code> and the menu will close.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const onClickOutside = (e) => {\n if (!e.target.className.includes(className)) {\n show = false;\n }\n};\n</code></pre>\n<p>Then I attached the click handler to the window object.</p>\n<pre class=\"lang-js prettyprint-override\"><code>// add when widget loads\nwindow.addEventListener("click", onClickOutside);\n</code></pre>\n<p>... and finally some housekeeping</p>\n<pre class=\"lang-js prettyprint-override\"><code>// remove listener when destroying the widget\nwindow.removeEventListener("click", onClickOutside);\n</code></pre>\n"
},
{
"answer_id": 1278068,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>If you are scripting for IE and FF 3.* and you just want to know if the click occured within a certain box area, you could also use something like:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>this.outsideElementClick = function(objEvent, objElement) {\n var objCurrentElement = objEvent.target || objEvent.srcElement;\n var blnInsideX = false;\n var blnInsideY = false;\n\n if (objCurrentElement.getBoundingClientRect().left >= objElement.getBoundingClientRect().left && objCurrentElement.getBoundingClientRect().right <= objElement.getBoundingClientRect().right)\n blnInsideX = true;\n\n if (objCurrentElement.getBoundingClientRect().top >= objElement.getBoundingClientRect().top && objCurrentElement.getBoundingClientRect().bottom <= objElement.getBoundingClientRect().bottom)\n blnInsideY = true;\n\n if (blnInsideX && blnInsideY)\n return false;\n else\n return true;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 1746926,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<pre><code>$(\"#menuscontainer\").click(function() {\n $(this).focus();\n});\n$(\"#menuscontainer\").blur(function(){\n $(this).hide();\n});\n</code></pre>\n\n<p>Works for me just fine.</p>\n"
},
{
"answer_id": 2577818,
"author": "Wolfram",
"author_id": 95033,
"author_profile": "https://Stackoverflow.com/users/95033",
"pm_score": 5,
"selected": false,
"text": "<p>Now there is a plugin for that: <a href=\"https://github.com/cowboy/jquery-outside-events\" rel=\"noreferrer\">outside events</a> (<a href=\"http://benalman.com/projects/jquery-outside-events-plugin/\" rel=\"noreferrer\">blog post</a>)</p>\n\n<p>The following happens when a <em>clickoutside</em> handler (WLOG) is bound to an element:</p>\n\n<ul>\n<li>the element is added to an array which holds all elements with <em>clickoutside</em> handlers</li>\n<li>a (<a href=\"http://docs.jquery.com/Namespaced_Events\" rel=\"noreferrer\">namespaced</a>) <em>click</em> handler is bound to the document (if not already there)</li>\n<li>on any <em>click</em> in the document, the <em>clickoutside</em> event is triggered for those elements in that array that are not equal to or a parent of the <em>click</em>-events target</li>\n<li>additionally, the event.target for the <em>clickoutside</em> event is set to the element the user clicked on (so you even know what the user clicked, not just that he clicked outside)</li>\n</ul>\n\n<p>So no events are stopped from propagation and additional <em>click</em> handlers may be used \"above\" the element with the outside-handler.</p>\n"
},
{
"answer_id": 2960848,
"author": "govind",
"author_id": 356804,
"author_profile": "https://Stackoverflow.com/users/356804",
"pm_score": 2,
"selected": false,
"text": "<p>This worked perfectly fine in time for me:</p>\n\n<pre><code>$('body').click(function() {\n // Hide the menus if visible.\n});\n</code></pre>\n"
},
{
"answer_id": 3028037,
"author": "Art",
"author_id": 62194,
"author_profile": "https://Stackoverflow.com/users/62194",
"pm_score": 11,
"selected": false,
"text": "<p>You can listen for a <strong>click</strong> event on <code>document</code> and then make sure <code>#menucontainer</code> is not an ancestor or the target of the clicked element by using <a href=\"http://api.jquery.com/closest/\" rel=\"noreferrer\"><code>.closest()</code></a>.</p>\n<p>If it is not, then the clicked element is outside of the <code>#menucontainer</code> and you can safely hide it.</p>\n<pre class=\"lang-js prettyprint-override\"><code>$(document).click(function(event) { \n var $target = $(event.target);\n if(!$target.closest('#menucontainer').length && \n $('#menucontainer').is(":visible")) {\n $('#menucontainer').hide();\n } \n});\n</code></pre>\n<h3>Edit – 2017-06-23</h3>\n<p>You can also clean up after the event listener if you plan to dismiss the menu and want to stop listening for events. This function will clean up only the newly created listener, preserving any other click listeners on <code>document</code>. With ES2015 syntax:</p>\n<pre class=\"lang-js prettyprint-override\"><code>export function hideOnClickOutside(selector) {\n const outsideClickListener = (event) => {\n const $target = $(event.target);\n if (!$target.closest(selector).length && $(selector).is(':visible')) {\n $(selector).hide();\n removeClickListener();\n }\n }\n\n const removeClickListener = () => {\n document.removeEventListener('click', outsideClickListener);\n }\n\n document.addEventListener('click', outsideClickListener);\n}\n</code></pre>\n<h3>Edit – 2018-03-11</h3>\n<p>For those who don't want to use jQuery. Here's the above code in plain vanillaJS (ECMAScript6).</p>\n<pre class=\"lang-js prettyprint-override\"><code>function hideOnClickOutside(element) {\n const outsideClickListener = event => {\n if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null\n element.style.display = 'none';\n removeClickListener();\n }\n }\n\n const removeClickListener = () => {\n document.removeEventListener('click', outsideClickListener);\n }\n\n document.addEventListener('click', outsideClickListener);\n}\n\nconst isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js \n</code></pre>\n<p><strong>NOTE:</strong>\nThis is based on Alex comment to just use <code>!element.contains(event.target)</code> instead of the jQuery part.</p>\n<p>But <code>element.closest()</code> is now also available in all major browsers (the W3C version differs a bit from the jQuery one).\nPolyfills can be found here: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/closest\" rel=\"noreferrer\">Element.closest()</a></p>\n<h3>Edit – 2020-05-21</h3>\n<p>In the case where you want the user to be able to click-and-drag inside the element, then release the mouse outside the element, without closing the element:</p>\n<pre><code> ...\n let lastMouseDownX = 0;\n let lastMouseDownY = 0;\n let lastMouseDownWasOutside = false;\n\n const mouseDownListener = (event: MouseEvent) => {\n lastMouseDownX = event.offsetX;\n lastMouseDownY = event.offsetY;\n lastMouseDownWasOutside = !$(event.target).closest(element).length;\n }\n document.addEventListener('mousedown', mouseDownListener);\n</code></pre>\n<p>And in <code>outsideClickListener</code>:</p>\n<pre><code>const outsideClickListener = event => {\n const deltaX = event.offsetX - lastMouseDownX;\n const deltaY = event.offsetY - lastMouseDownY;\n const distSq = (deltaX * deltaX) + (deltaY * deltaY);\n const isDrag = distSq > 3;\n const isDragException = isDrag && !lastMouseDownWasOutside;\n\n if (!element.contains(event.target) && isVisible(element) && !isDragException) { // or use: event.target.closest(selector) === null\n element.style.display = 'none';\n removeClickListener();\n document.removeEventListener('mousedown', mouseDownListener); // Or add this line to removeClickListener()\n }\n }\n</code></pre>\n"
},
{
"answer_id": 3062825,
"author": "Neco",
"author_id": 369448,
"author_profile": "https://Stackoverflow.com/users/369448",
"pm_score": 2,
"selected": false,
"text": "<p>Function:</p>\n\n<pre><code>$(function() {\n $.fn.click_inout = function(clickin_handler, clickout_handler) {\n var item = this;\n var is_me = false;\n item.click(function(event) {\n clickin_handler(event);\n is_me = true;\n });\n $(document).click(function(event) {\n if (is_me) {\n is_me = false;\n } else {\n clickout_handler(event);\n }\n });\n return this;\n }\n});\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>this.input = $('<input>')\n .click_inout(\n function(event) { me.ShowTree(event); },\n function() { me.Hide(); }\n )\n .appendTo(this.node);\n</code></pre>\n\n<p>And functions are very simple:</p>\n\n<pre><code>ShowTree: function(event) {\n this.data_span.show();\n}\nHide: function() {\n this.data_span.hide();\n}\n</code></pre>\n"
},
{
"answer_id": 4333616,
"author": "Chu Yeow",
"author_id": 25226,
"author_profile": "https://Stackoverflow.com/users/25226",
"pm_score": 4,
"selected": false,
"text": "<p>I've had success with something like this:</p>\n\n<pre><code>var $menuscontainer = ...;\n\n$('#trigger').click(function() {\n $menuscontainer.show();\n\n $('body').click(function(event) {\n var $target = $(event.target);\n\n if ($target.parents('#menuscontainer').length == 0) {\n $menuscontainer.hide();\n }\n });\n});\n</code></pre>\n\n<p>The logic is: when <code>#menuscontainer</code> is shown, bind a click handler to the body that hides <code>#menuscontainer</code> only if the target (of the click) isn't a child of it.</p>\n"
},
{
"answer_id": 4642622,
"author": "webenformasyon",
"author_id": 550597,
"author_profile": "https://Stackoverflow.com/users/550597",
"pm_score": 3,
"selected": false,
"text": "<p>Use:</p>\n\n<pre><code>var go = false;\n$(document).click(function(){\n if(go){\n $('#divID').hide();\n go = false;\n }\n})\n\n$(\"#divID\").mouseover(function(){\n go = false;\n});\n\n$(\"#divID\").mouseout(function (){\n go = true;\n});\n\n$(\"btnID\").click( function(){\n if($(\"#divID:visible\").length==1)\n $(\"#divID\").hide(); // Toggle\n $(\"#divID\").show();\n});\n</code></pre>\n"
},
{
"answer_id": 6051126,
"author": "34m0",
"author_id": 342783,
"author_profile": "https://Stackoverflow.com/users/342783",
"pm_score": 5,
"selected": false,
"text": "<p>I don't think what you really need is to close the menu when the user clicks outside; what you need is for the menu to close when the user clicks anywhere at all on the page. If you click on the menu, or off the menu it should close right? </p>\n\n<p>Finding no satisfactory answers above prompted me to write <a href=\"http://programming34m0.blogspot.com/2011/05/simplifying-javascript-jump-menu.html\">this blog post</a> the other day. For the more pedantic, there are a number of gotchas to take note of: </p>\n\n<ol>\n<li>If you attach a click event handler to the body element at click time be sure to wait for the 2nd click before closing the menu, and unbinding the event. Otherwise the click event that opened the menu will bubble up to the listener that has to close the menu.</li>\n<li>If you use event.stopPropogation() on a click event, no other elements in your page can have a click-anywhere-to-close feature.</li>\n<li>Attaching a click event handler to the body element indefinitely is not a performant solution</li>\n<li>Comparing the target of the event, and its parents to the handler's creator assumes that what you want is to close the menu when you click off it, when what you really want is to close it when you click anywhere on the page.</li>\n<li>Listening for events on the body element will make your code more brittle. Styling as innocent as this would break it: <code>body { margin-left:auto; margin-right: auto; width:960px;}</code></li>\n</ol>\n"
},
{
"answer_id": 6860287,
"author": "nazar kuliyev",
"author_id": 386073,
"author_profile": "https://Stackoverflow.com/users/386073",
"pm_score": 4,
"selected": false,
"text": "<p>I found this method in some jQuery calendar plugin.</p>\n\n<pre><code>function ClickOutsideCheck(e)\n{\n var el = e.target;\n var popup = $('.popup:visible')[0];\n if (popup==undefined)\n return true;\n\n while (true){\n if (el == popup ) {\n return true;\n } else if (el == document) {\n $(\".popup\").hide();\n return false;\n } else {\n el = $(el).parent()[0];\n }\n }\n};\n\n$(document).bind('mousedown.popup', ClickOutsideCheck);\n</code></pre>\n"
},
{
"answer_id": 7490132,
"author": "Rowan",
"author_id": 933754,
"author_profile": "https://Stackoverflow.com/users/933754",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$(document).click(function() {\n $(\".overlay-window\").hide();\n});\n$(\".overlay-window\").click(function() {\n return false;\n});\n</code></pre>\n\n<p>If you click on the document, hide a given element, unless you click on that same element.</p>\n"
},
{
"answer_id": 8400851,
"author": "Satya Prakash",
"author_id": 192545,
"author_profile": "https://Stackoverflow.com/users/192545",
"pm_score": 3,
"selected": false,
"text": "<p>I did it like this in <a href=\"http://en.wikipedia.org/wiki/Yahoo!_UI_Library\" rel=\"nofollow\">YUI</a> 3:</p>\n\n<pre><code>// Detect the click anywhere other than the overlay element to close it.\nY.one(document).on('click', function (e) {\n if (e.target.ancestor('#overlay') === null && e.target.get('id') != 'show' && overlay.get('visible') == true) {\n overlay.hide();\n }\n});\n</code></pre>\n\n<p>I am checking if ancestor is not the widget element container, <br/>\nif target is not which open the widget/element, <br/>\nif widget/element I want to close is already open (not that important).</p>\n"
},
{
"answer_id": 8603563,
"author": "benb",
"author_id": 473101,
"author_profile": "https://Stackoverflow.com/users/473101",
"pm_score": 5,
"selected": false,
"text": "<p>As another poster said there are a lot of gotchas, especially if the element you are displaying (in this case a menu) has interactive elements.\nI've found the following method to be fairly robust:</p>\n\n<pre><code>$('#menuscontainer').click(function(event) {\n //your code that shows the menus fully\n\n //now set up an event listener so that clicking anywhere outside will close the menu\n $('html').click(function(event) {\n //check up the tree of the click target to check whether user has clicked outside of menu\n if ($(event.target).parents('#menuscontainer').length==0) {\n // your code to hide menu\n\n //this event listener has done its job so we can unbind it.\n $(this).unbind(event);\n }\n\n })\n});\n</code></pre>\n"
},
{
"answer_id": 9584414,
"author": "netdjw",
"author_id": 972828,
"author_profile": "https://Stackoverflow.com/users/972828",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my code:</p>\n\n<pre><code>// Listen to every click\n$('html').click(function(event) {\n if ( $('#mypopupmenu').is(':visible') ) {\n if (event.target.id != 'click_this_to_show_mypopupmenu') {\n $('#mypopupmenu').hide();\n }\n }\n});\n\n// Listen to selector's clicks\n$('#click_this_to_show_mypopupmenu').click(function() {\n\n // If the menu is visible, and you clicked the selector again we need to hide\n if ( $('#mypopupmenu').is(':visible') {\n $('#mypopupmenu').hide();\n return true;\n }\n\n // Else we need to show the popup menu\n $('#mypopupmenu').show();\n});\n</code></pre>\n"
},
{
"answer_id": 9808743,
"author": "Spencer Fry",
"author_id": 1088642,
"author_profile": "https://Stackoverflow.com/users/1088642",
"pm_score": 2,
"selected": false,
"text": "<p>This is my solution to this problem:</p>\n\n<pre><code>$(document).ready(function() {\n $('#user-toggle').click(function(e) {\n $('#user-nav').toggle();\n e.stopPropagation();\n });\n\n $('body').click(function() {\n $('#user-nav').hide(); \n });\n\n $('#user-nav').click(function(e){\n e.stopPropagation();\n });\n});\n</code></pre>\n"
},
{
"answer_id": 10074361,
"author": "Toogy",
"author_id": 1322001,
"author_profile": "https://Stackoverflow.com/users/1322001",
"pm_score": 2,
"selected": false,
"text": "<pre><code>jQuery().ready(function(){\n $('#nav').click(function (event) {\n $(this).addClass('activ');\n event.stopPropagation();\n });\n\n $('html').click(function () {\n if( $('#nav').hasClass('activ') ){\n $('#nav').removeClass('activ');\n }\n });\n});\n</code></pre>\n"
},
{
"answer_id": 10428503,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 3,
"selected": false,
"text": "<p>Hook a click event listener on the document. Inside the event listener, you can look at the <a href=\"http://api.jquery.com/category/events/event-object/\" rel=\"noreferrer\">event object</a>, in particular, the <a href=\"http://api.jquery.com/event.target/\" rel=\"noreferrer\">event.target</a> to see what element was clicked:</p>\n\n<pre><code>$(document).click(function(e){\n if ($(e.target).closest(\"#menuscontainer\").length == 0) {\n // .closest can help you determine if the element \n // or one of its ancestors is #menuscontainer\n console.log(\"hide\");\n }\n});\n</code></pre>\n"
},
{
"answer_id": 10882727,
"author": "srinath",
"author_id": 490962,
"author_profile": "https://Stackoverflow.com/users/490962",
"pm_score": 5,
"selected": false,
"text": "<p>This worked for me perfectly!!</p>\n\n<pre><code>$('html').click(function (e) {\n if (e.target.id == 'YOUR-DIV-ID') {\n //do something\n } else {\n //do something\n }\n});\n</code></pre>\n"
},
{
"answer_id": 13555176,
"author": "Alexandre T.",
"author_id": 1093596,
"author_profile": "https://Stackoverflow.com/users/1093596",
"pm_score": 2,
"selected": false,
"text": "<p>To be honest, I didn't like any of previous the solutions.</p>\n\n<p>The best way to do this, is binding the \"click\" event to the document, and comparing if that click is really outside the element (just like Art said in his suggestion).</p>\n\n<p>However, you'll have some problems there: You'll never be able to unbind it, and you cannot have an external button to open/close that element.</p>\n\n<p>That's why I wrote <a href=\"http://www.imaginacom.com/eval.php?exec=29\" rel=\"nofollow\">this small plugin (click here to link)</a>, to simplify these tasks. Could it be simpler?</p>\n\n<pre><code><a id='theButton' href=\"#\">Toggle the menu</a><br/>\n<div id='theMenu'>\n I should be toggled when the above menu is clicked,\n and hidden when user clicks outside.\n</div>\n\n<script>\n$('#theButton').click(function(){\n $('#theMenu').slideDown();\n});\n$(\"#theMenu\").dClickOutside({ ignoreList: $(\"#theButton\") }, function(clickedObj){\n $(this).slideUp();\n});\n</script>\n</code></pre>\n"
},
{
"answer_id": 13877279,
"author": "mlangenberg",
"author_id": 587208,
"author_profile": "https://Stackoverflow.com/users/587208",
"pm_score": 0,
"selected": false,
"text": "<p>Just a warning that using this:</p>\n\n<pre><code>$('html').click(function() {\n // Hide the menus if visible\n});\n\n$('#menucontainer').click(function(event){\n event.stopPropagation();\n});\n</code></pre>\n\n<p>It <strong>prevents</strong> the <a href=\"http://en.wikipedia.org/wiki/Ruby_on_Rails\" rel=\"nofollow\">Ruby on Rails</a> UJS driver from working properly. For example, <code>link_to 'click', '/url', :method => :delete</code> will not work.</p>\n\n<p>This might be a workaround:</p>\n\n<pre><code>$('html').click(function() {\n // Hide the menus if visible\n});\n\n$('#menucontainer').click(function(event){\n if (!$(event.target).data('method')) {\n event.stopPropagation();\n }\n});\n</code></pre>\n"
},
{
"answer_id": 14293001,
"author": "Bilal Berjawi",
"author_id": 1972286,
"author_profile": "https://Stackoverflow.com/users/1972286",
"pm_score": 2,
"selected": false,
"text": "<p>This should work:</p>\n\n<pre><code>$('body').click(function (event) {\n var obj = $(event.target);\n obj = obj['context']; // context : clicked element inside body\n if ($(obj).attr('id') != \"menuscontainer\" && $('#menuscontainer').is(':visible') == true) {\n //hide menu\n }\n});\n</code></pre>\n"
},
{
"answer_id": 14967514,
"author": "constrictus",
"author_id": 2088813,
"author_profile": "https://Stackoverflow.com/users/2088813",
"pm_score": -1,
"selected": false,
"text": "<pre><code> <div class=\"feedbackCont\" onblur=\"hidefeedback();\">\n <div class=\"feedbackb\" onclick=\"showfeedback();\" ></div>\n <div class=\"feedbackhide\" tabindex=\"1\"> </div>\n </div>\n\nfunction hidefeedback(){\n $j(\".feedbackhide\").hide();\n}\n\nfunction showfeedback(){\n $j(\".feedbackhide\").show();\n $j(\".feedbackCont\").attr(\"tabindex\",1).focus();\n}\n</code></pre>\n\n<p>This is the simplest solution I came up with. </p>\n"
},
{
"answer_id": 16842824,
"author": "teynon",
"author_id": 697477,
"author_profile": "https://Stackoverflow.com/users/697477",
"pm_score": 2,
"selected": false,
"text": "<p>One more solution is here:</p>\n\n<p><a href=\"http://jsfiddle.net/zR76D/\" rel=\"nofollow\">http://jsfiddle.net/zR76D/</a></p>\n\n<p>Usage:</p>\n\n<pre><code><div onClick=\"$('#menu').toggle();$('#menu').clickOutside(function() { $(this).hide(); $(this).clickOutside('disable'); });\">Open / Close Menu</div>\n<div id=\"menu\" style=\"display: none; border: 1px solid #000000; background: #660000;\">I am a menu, whoa is me.</div>\n</code></pre>\n\n<p>Plugin:</p>\n\n<pre><code>(function($) {\n var clickOutsideElements = [];\n var clickListener = false;\n\n $.fn.clickOutside = function(options, ignoreFirstClick) {\n var that = this;\n if (ignoreFirstClick == null) ignoreFirstClick = true;\n\n if (options != \"disable\") {\n for (var i in clickOutsideElements) {\n if (clickOutsideElements[i].element[0] == $(this)[0]) return this;\n }\n\n clickOutsideElements.push({ element : this, clickDetected : ignoreFirstClick, fnc : (typeof(options) != \"function\") ? function() {} : options });\n\n $(this).on(\"click.clickOutside\", function(event) {\n for (var i in clickOutsideElements) {\n if (clickOutsideElements[i].element[0] == $(this)[0]) {\n clickOutsideElements[i].clickDetected = true;\n }\n }\n });\n\n if (!clickListener) {\n if (options != null && typeof(options) == \"function\") {\n $('html').click(function() {\n for (var i in clickOutsideElements) {\n if (!clickOutsideElements[i].clickDetected) {\n clickOutsideElements[i].fnc.call(that);\n }\n if (clickOutsideElements[i] != null) clickOutsideElements[i].clickDetected = false;\n }\n });\n clickListener = true;\n }\n }\n }\n else {\n $(this).off(\"click.clickoutside\");\n for (var i = 0; i < clickOutsideElements.length; ++i) {\n if (clickOutsideElements[i].element[0] == $(this)[0]) {\n clickOutsideElements.splice(i, 1);\n }\n }\n }\n\n return this;\n }\n})(jQuery);\n</code></pre>\n"
},
{
"answer_id": 16861422,
"author": "maday",
"author_id": 2441120,
"author_profile": "https://Stackoverflow.com/users/2441120",
"pm_score": 2,
"selected": false,
"text": "<p>The broadest way to do this is to select everything on the web page except the element where you don't want clicks detected and bind the click event those when the menu is opened. </p>\n\n<p>Then when the menu is closed remove the binding.</p>\n\n<p>Use .stopPropagation to prevent the event from affecting any part of the menuscontainer.</p>\n\n<pre><code>$(\"*\").not($(\"#menuscontainer\")).bind(\"click.OutsideMenus\", function ()\n{\n // hide the menus\n\n //then remove all of the handlers\n $(\"*\").unbind(\".OutsideMenus\");\n});\n\n$(\"#menuscontainer\").bind(\"click.OutsideMenus\", function (event) \n{\n event.stopPropagation(); \n});\n</code></pre>\n"
},
{
"answer_id": 16863056,
"author": "kboom",
"author_id": 1130975,
"author_profile": "https://Stackoverflow.com/users/1130975",
"pm_score": 2,
"selected": false,
"text": "<p>The solutions here work fine <strong>when only one element is to be managed</strong>. If there are multiple elements, however, the problem is much more complicated. Tricks with e.stopPropagation() and all the others will not work.</p>\n\n<p>I came up with a <strong>solution</strong>, and maybe it is not so easy, but it's better than nothing. Have a look:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>$view.on(\"click\", function(e) {\n\n if(model.isActivated()) return;\n\n var watchUnclick = function() {\n rootView.one(\"mouseleave\", function() {\n $(document).one(\"click\", function() {\n model.deactivate();\n });\n rootView.one(\"mouseenter\", function() {\n watchUnclick();\n });\n });\n };\n watchUnclick();\n model.activate();\n });\n</code></pre>\n"
},
{
"answer_id": 16943381,
"author": "mems",
"author_id": 470117,
"author_profile": "https://Stackoverflow.com/users/470117",
"pm_score": 3,
"selected": false,
"text": "<p>Instead using flow interruption, blur/focus event or any other tricky technics, simply match event flow with element's kinship:</p>\n\n<pre><code>$(document).on(\"click.menu-outside\", function(event){\n // Test if target and it's parent aren't #menuscontainer\n // That means the click event occur on other branch of document tree\n if(!$(event.target).parents().andSelf().is(\"#menuscontainer\")){\n // Click outisde #menuscontainer\n // Hide the menus (but test if menus aren't already hidden)\n }\n});\n</code></pre>\n\n<p>To remove click outside event listener, simply:</p>\n\n<pre><code>$(document).off(\"click.menu-outside\");\n</code></pre>\n"
},
{
"answer_id": 17169887,
"author": "Anders",
"author_id": 548048,
"author_profile": "https://Stackoverflow.com/users/548048",
"pm_score": 2,
"selected": false,
"text": "<p>The answer marked as the accepted answer does not take into account that you can have overlays over the element, like dialogs, popovers, datepickers, etc. Clicks in these should not hide the element.</p>\n\n<p>I have made my own version that does take this into account. It's created as a <a href=\"http://en.wikipedia.org/wiki/KnockoutJS\" rel=\"nofollow\">KnockoutJS</a> binding, but it can easily be converted to jQuery-only.</p>\n\n<p>It works by the first query for all elements with either z-index or absolute position that are visible. It then hit tests those elements against the element I want to hide if click outside. If it's a hit I calculate a new bound rectangle which takes into account the overlay bounds.</p>\n\n<pre><code>ko.bindingHandlers.clickedIn = (function () {\n function getBounds(element) {\n var pos = element.offset();\n return {\n x: pos.left,\n x2: pos.left + element.outerWidth(),\n y: pos.top,\n y2: pos.top + element.outerHeight()\n };\n }\n\n function hitTest(o, l) {\n function getOffset(o) {\n for (var r = { l: o.offsetLeft, t: o.offsetTop, r: o.offsetWidth, b: o.offsetHeight };\n o = o.offsetParent; r.l += o.offsetLeft, r.t += o.offsetTop);\n return r.r += r.l, r.b += r.t, r;\n }\n\n for (var b, s, r = [], a = getOffset(o), j = isNaN(l.length), i = (j ? l = [l] : l).length; i;\n b = getOffset(l[--i]), (a.l == b.l || (a.l > b.l ? a.l <= b.r : b.l <= a.r))\n && (a.t == b.t || (a.t > b.t ? a.t <= b.b : b.t <= a.b)) && (r[r.length] = l[i]));\n return j ? !!r.length : r;\n }\n\n return {\n init: function (element, valueAccessor) {\n var target = valueAccessor();\n $(document).click(function (e) {\n if (element._clickedInElementShowing === false && target()) {\n var $element = $(element);\n var bounds = getBounds($element);\n\n var possibleOverlays = $(\"[style*=z-index],[style*=absolute]\").not(\":hidden\");\n $.each(possibleOverlays, function () {\n if (hitTest(element, this)) {\n var b = getBounds($(this));\n bounds.x = Math.min(bounds.x, b.x);\n bounds.x2 = Math.max(bounds.x2, b.x2);\n bounds.y = Math.min(bounds.y, b.y);\n bounds.y2 = Math.max(bounds.y2, b.y2);\n }\n });\n\n if (e.clientX < bounds.x || e.clientX > bounds.x2 ||\n e.clientY < bounds.y || e.clientY > bounds.y2) {\n\n target(false);\n }\n }\n element._clickedInElementShowing = false;\n });\n\n $(element).click(function (e) {\n e.stopPropagation();\n });\n },\n update: function (element, valueAccessor) {\n var showing = ko.utils.unwrapObservable(valueAccessor());\n if (showing) {\n element._clickedInElementShowing = true;\n }\n }\n };\n})();\n</code></pre>\n"
},
{
"answer_id": 19091957,
"author": "Roei Bahumi",
"author_id": 1283063,
"author_profile": "https://Stackoverflow.com/users/1283063",
"pm_score": 1,
"selected": false,
"text": "<p>This is a more general solution that <strong>allows multiple elements to be watched, and dynamically adding and removing elements from the queue</strong>.</p>\n\n<p>It holds a global queue (<strong>autoCloseQueue</strong>) - an object container for elements that should be closed on outside clicks. </p>\n\n<p>Each queue object key should be the DOM Element id, and the value should be an object with 2 callback functions: </p>\n\n<pre><code> {onPress: someCallbackFunction, onOutsidePress: anotherCallbackFunction}\n</code></pre>\n\n<p>Put this in your document ready callback:</p>\n\n<pre><code>window.autoCloseQueue = {} \n\n$(document).click(function(event) {\n for (id in autoCloseQueue){\n var element = autoCloseQueue[id];\n if ( ($(e.target).parents('#' + id).length) > 0) { // This is a click on the element (or its child element)\n console.log('This is a click on an element (or its child element) with id: ' + id);\n if (typeof element.onPress == 'function') element.onPress(event, id);\n } else { //This is a click outside the element\n console.log('This is a click outside the element with id: ' + id);\n if (typeof element.onOutsidePress == 'function') element.onOutsidePress(event, id); //call the outside callback\n delete autoCloseQueue[id]; //remove the element from the queue\n }\n }\n});\n</code></pre>\n\n<p>Then, when the DOM element with id '<strong>menuscontainer</strong>' is created, just add this object to the queue: </p>\n\n<pre><code>window.autoCloseQueue['menuscontainer'] = {onOutsidePress: clickOutsideThisElement}\n</code></pre>\n"
},
{
"answer_id": 20061566,
"author": "Webmaster G",
"author_id": 1582942,
"author_profile": "https://Stackoverflow.com/users/1582942",
"pm_score": 2,
"selected": false,
"text": "<p>I ended up doing something like this:</p>\n\n<pre><code>$(document).on('click', 'body, #msg_count_results .close',function() {\n $(document).find('#msg_count_results').remove();\n});\n$(document).on('click','#msg_count_results',function(e) {\n e.preventDefault();\n return false;\n});\n</code></pre>\n\n<p>I have a close button within the new container for end users friendly UI purposes. I had to use return false in order to not go through. Of course, having an A HREF on there to take you somewhere would be nice, or you could call some ajax stuff instead. Either way, it works ok for me. Just what I wanted.</p>\n"
},
{
"answer_id": 21826584,
"author": "lan.ta",
"author_id": 1076974,
"author_profile": "https://Stackoverflow.com/users/1076974",
"pm_score": -1,
"selected": false,
"text": "<p>Try this code:</p>\n\n<pre><code>if ($(event.target).parents().index($('#searchFormEdit')) == -1 &&\n $(event.target).parents().index($('.DynarchCalendar-topCont')) == -1 &&\n (_x < os.left || _x > (os.left + 570) || _y < os.top || _y > (os.top + 155)) &&\n isShowEditForm) {\n\n setVisibleEditForm(false);\n}\n</code></pre>\n"
},
{
"answer_id": 22387244,
"author": "Yacine Zalouani",
"author_id": 1214294,
"author_profile": "https://Stackoverflow.com/users/1214294",
"pm_score": -1,
"selected": false,
"text": "<p>You can set a tabindex to the <a href=\"http://en.wikipedia.org/wiki/Document_Object_Model\" rel=\"nofollow\">DOM</a> element. This will trigger a blur event when the user click outside the DOM element.</p>\n\n<p><a href=\"http://jsbin.com/fuloqixe/5\" rel=\"nofollow\">Demo</a></p>\n\n<pre><code><div tabindex=\"1\">\n Focus me\n</div>\n\ndocument.querySelector(\"div\").onblur = function(){\n console.log('clicked outside')\n}\ndocument.querySelector(\"div\").onfocus = function(){\n console.log('clicked inside')\n}\n</code></pre>\n"
},
{
"answer_id": 23398102,
"author": "Awena",
"author_id": 3003977,
"author_profile": "https://Stackoverflow.com/users/3003977",
"pm_score": 0,
"selected": false,
"text": "<p>This will toggle the Nav menu when you click on/off the element.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(document).on('click', function(e) {\n var elem = $(e.target).closest('#menu'),\n box = $(e.target).closest('#nav');\n if (elem.length) {\n e.preventDefault();\n $('#nav').toggle();\n } else if (!box.length) {\n $('#nav').hide();\n }\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<li id=\"menu\">\n <a></a>\n</li>\n<ul id=\"nav\">\n <!--Nav will toggle when you Click on Menu(it can be an icon in this example)-->\n <li class=\"page\"><a>Page1</a></li>\n <li class=\"page\"><a>Page2</a></li>\n <li class=\"page\"><a>Page3</a></li>\n <li class=\"page\"><a>Page4</a></li>\n</ul></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 24141571,
"author": "Grim",
"author_id": 843943,
"author_profile": "https://Stackoverflow.com/users/843943",
"pm_score": -1,
"selected": false,
"text": "<p>Standard HTML:</p>\n\n<p>Surround the menus by a <code><label></code> and fetch focus state changes.</p>\n\n<p><a href=\"http://jsfiddle.net/bK3gL/\" rel=\"nofollow\">http://jsfiddle.net/bK3gL/</a></p>\n\n<p>Plus: you can unfold the menu by <kbd>Tab</kbd>.</p>\n"
},
{
"answer_id": 24612659,
"author": "KyleMit",
"author_id": 1366033,
"author_profile": "https://Stackoverflow.com/users/1366033",
"pm_score": -1,
"selected": false,
"text": "<p>As a <a href=\"https://stackoverflow.com/a/3028037/1366033\">wrapper to this great answer from Art</a>, and to use the syntax originally requested by OP, here's a jQuery extension that can record wether a click occured outside of a set element.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>$.fn.clickOutsideThisElement = function (callback) {\n return this.each(function () {\n var self = this;\n $(document).click(function (e) {\n if (!$(e.target).closest(self).length) {\n callback.call(self, e)\n }\n })\n });\n};\n</code></pre>\n\n<p>Then you can call like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>$(\"#menuscontainer\").clickOutsideThisElement(function() {\n // handle menu toggle\n});\n</code></pre>\n\n<h2><a href=\"http://jsfiddle.net/KyleMit/Fv2fY/\" rel=\"nofollow noreferrer\">Here's a demo in fiddle</a></h2>\n"
},
{
"answer_id": 24930263,
"author": "Bohdan Lyzanets",
"author_id": 223750,
"author_profile": "https://Stackoverflow.com/users/223750",
"pm_score": 4,
"selected": false,
"text": "<p>As a variant:</p>\n\n<pre><code>var $menu = $('#menucontainer');\n$(document).on('click', function (e) {\n\n // If element is opened and click target is outside it, hide it\n if ($menu.is(':visible') && !$menu.is(e.target) && !$menu.has(e.target).length) {\n $menu.hide();\n }\n});\n</code></pre>\n\n<p>It has no problem with <a href=\"http://css-tricks.com/dangers-stopping-event-propagation/\" rel=\"noreferrer\">stopping event propagation</a> and better supports multiple menus on the same page where clicking on a second menu while a first is open will leave the first open in the stopPropagation solution.</p>\n"
},
{
"answer_id": 26258171,
"author": "Manish Shrivastava",
"author_id": 1133932,
"author_profile": "https://Stackoverflow.com/users/1133932",
"pm_score": 2,
"selected": false,
"text": "<p>For touch devices like iPad and iPhone we can use this code:</p>\n\n<pre><code>$(document).on('touchstart', function (event) {\n var container = $(\"YOUR CONTAINER SELECTOR\");\n\n if (!container.is(e.target) && // If the target of the click isn't the container...\n container.has(e.target).length === 0) // ... nor a descendant of the container\n {\n container.hide();\n }\n});\n</code></pre>\n"
},
{
"answer_id": 26276051,
"author": "shiv",
"author_id": 2520033,
"author_profile": "https://Stackoverflow.com/users/2520033",
"pm_score": -1,
"selected": false,
"text": "<p>Using not():</p>\n\n<pre><code>$(\"#id\").not().click(function() {\n alert('Clicked other that #id');\n});\n</code></pre>\n"
},
{
"answer_id": 26629746,
"author": "Mahesh Gaikwad",
"author_id": 2724353,
"author_profile": "https://Stackoverflow.com/users/2724353",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$(\"body > div:not(#dvid)\").click(function (e) {\n //your code\n}); \n</code></pre>\n"
},
{
"answer_id": 27537666,
"author": "aroykos",
"author_id": 3019696,
"author_profile": "https://Stackoverflow.com/users/3019696",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$(\"html\").click(function(){\n if($('#info').css(\"opacity\")>0.9) {\n $('#info').fadeOut('fast');\n }\n});\n</code></pre>\n"
},
{
"answer_id": 28198524,
"author": "Iman Sedighi",
"author_id": 2716838,
"author_profile": "https://Stackoverflow.com/users/2716838",
"pm_score": 5,
"selected": false,
"text": "<h2><strong>Solution1</strong></h2>\n\n<p>Instead of using event.stopPropagation() which can have some side affects, just define a simple flag variable and add one <code>if</code> condition. I tested this and worked properly without any side affects of stopPropagation:</p>\n\n<pre><code>var flag = \"1\";\n$('#menucontainer').click(function(event){\n flag = \"0\"; // flag 0 means click happened in the area where we should not do any action\n});\n\n$('html').click(function() {\n if(flag != \"0\"){\n // Hide the menus if visible\n }\n else {\n flag = \"1\";\n }\n});\n</code></pre>\n\n<h2><strong>Solution2</strong></h2>\n\n<p>With just a simple <code>if</code> condition:</p>\n\n<pre><code>$(document).on('click', function(event){\n var container = $(\"#menucontainer\");\n if (!container.is(event.target) && // If the target of the click isn't the container...\n container.has(event.target).length === 0) // ... nor a descendant of the container\n {\n // Do whatever you want to do when click is outside the element\n }\n});\n</code></pre>\n"
},
{
"answer_id": 30337498,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the vanilla JavaScript solution for future viewers.</p>\n\n<p>Upon clicking any element within the document, if the clicked element's id is toggled, or the hidden element is not hidden and the hidden element does not contain the clicked element, toggle the element.</p>\n\n<pre><code>(function () {\n \"use strict\";\n var hidden = document.getElementById('hidden');\n document.addEventListener('click', function (e) {\n if (e.target.id == 'toggle' || (hidden.style.display != 'none' && !hidden.contains(e.target))) hidden.style.display = hidden.style.display == 'none' ? 'block' : 'none';\n }, false);\n})();\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(function () {\r\n \"use strict\";\r\n var hidden = document.getElementById('hidden');\r\n document.addEventListener('click', function (e) {\r\n if (e.target.id == 'toggle' || (hidden.style.display != 'none' && !hidden.contains(e.target))) hidden.style.display = hidden.style.display == 'none' ? 'block' : 'none';\r\n }, false);\r\n})();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><a href=\"javascript:void(0)\" id=\"toggle\">Toggle Hidden Div</a>\r\n<div id=\"hidden\" style=\"display: none;\">This content is normally hidden. click anywhere other than this content to make me disappear</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>If you are going to have multiple toggles on the same page you can use something like this:</p>\n\n<ol>\n<li>Add the class name <code>hidden</code> to the collapsible item.</li>\n<li>Upon document click, close all hidden elements which do not contain the clicked element and are not hidden</li>\n<li>If the clicked element is a toggle, toggle the specified element.</li>\n</ol>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(function () {\r\n \"use strict\";\r\n var hiddenItems = document.getElementsByClassName('hidden'), hidden;\r\n document.addEventListener('click', function (e) {\r\n for (var i = 0; hidden = hiddenItems[i]; i++) {\r\n if (!hidden.contains(e.target) && hidden.style.display != 'none')\r\n hidden.style.display = 'none';\r\n }\r\n if (e.target.getAttribute('data-toggle')) {\r\n var toggle = document.querySelector(e.target.getAttribute('data-toggle'));\r\n toggle.style.display = toggle.style.display == 'none' ? 'block' : 'none';\r\n }\r\n }, false);\r\n})();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><a href=\"javascript:void(0)\" data-toggle=\"#hidden1\">Toggle Hidden Div</a>\r\n<div class=\"hidden\" id=\"hidden1\" style=\"display: none;\" data-hidden=\"true\">This content is normally hidden</div>\r\n<a href=\"javascript:void(0)\" data-toggle=\"#hidden2\">Toggle Hidden Div</a>\r\n<div class=\"hidden\" id=\"hidden2\" style=\"display: none;\" data-hidden=\"true\">This content is normally hidden</div>\r\n<a href=\"javascript:void(0)\" data-toggle=\"#hidden3\">Toggle Hidden Div</a>\r\n<div class=\"hidden\" id=\"hidden3\" style=\"display: none;\" data-hidden=\"true\">This content is normally hidden</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 31281896,
"author": "Scott Richardson",
"author_id": 981280,
"author_profile": "https://Stackoverflow.com/users/981280",
"pm_score": 3,
"selected": false,
"text": "<p>We implemented a solution, partly based off a comment from a user above, which works perfectly for us. We use it to hide a search box / results when clicking outside those elements, excluding the element that originally.</p>\n\n<pre><code>// HIDE SEARCH BOX IF CLICKING OUTSIDE\n$(document).click(function(event){ \n // IF NOT CLICKING THE SEARCH BOX OR ITS CONTENTS OR SEARCH ICON \n if ($(\"#search-holder\").is(\":visible\") && !$(event.target).is(\"#search-holder *, #search\")) {\n $(\"#search-holder\").fadeOut('fast');\n $(\"#search\").removeClass('active');\n }\n});\n</code></pre>\n\n<p>It checks if the search box is already visible first also, and in our case, it's also removing an active class on the hide/show search button.</p>\n"
},
{
"answer_id": 31631355,
"author": "bbe",
"author_id": 4582452,
"author_profile": "https://Stackoverflow.com/users/4582452",
"pm_score": 3,
"selected": false,
"text": "<p>Upvote for the most popular answer, but add </p>\n\n<pre><code>&& (e.target != $('html').get(0)) // ignore the scrollbar\n</code></pre>\n\n<p>so, a click on a scroll bar does not [hide or whatever] your target element.</p>\n"
},
{
"answer_id": 31813540,
"author": "martinedwards",
"author_id": 1485447,
"author_profile": "https://Stackoverflow.com/users/1485447",
"pm_score": -1,
"selected": false,
"text": "<p>This is a classic case of where a tweak to the HTML would be a better solution. Why not set the click on the elements which don't contain the menu item? Then you don't need to add the propagation.</p>\n\n<pre><code>$('.header, .footer, .main-content').click(function() {\n//Hide the menus if visible\n});\n</code></pre>\n"
},
{
"answer_id": 31868754,
"author": "Daniel Tonon",
"author_id": 1611058,
"author_profile": "https://Stackoverflow.com/users/1611058",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Outside click plugin!</strong></p>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>$('.target-element').outsideClick(function(event){\n //code that fires when user clicks outside the element\n //event = the click event\n //$(this) = the '.target-element' that is firing this function \n}, '.excluded-element')\n</code></pre>\n\n<p><strong>The code for it:</strong></p>\n\n<pre><code>(function($) {\n\n//when the user hits the escape key, it will trigger all outsideClick functions\n$(document).on(\"keyup\", function (e) {\n if (e.which == 27) $('body').click(); //escape key\n});\n\n//The actual plugin\n$.fn.outsideClick = function(callback, exclusions) {\n var subject = this;\n\n //test if exclusions have been set\n var hasExclusions = typeof exclusions !== 'undefined';\n\n //switches click event with touch event if on a touch device\n var ClickOrTouchEvent = \"ontouchend\" in document ? \"touchend\" : \"click\";\n\n $('body').on(ClickOrTouchEvent, function(event) {\n //click target does not contain subject as a parent\n var clickedOutside = !$(event.target).closest(subject).length;\n\n //click target was on one of the excluded elements\n var clickedExclusion = $(event.target).closest(exclusions).length;\n\n var testSuccessful;\n\n if (hasExclusions) {\n testSuccessful = clickedOutside && !clickedExclusion;\n } else {\n testSuccessful = clickedOutside;\n }\n\n if(testSuccessful) {\n callback.call(subject, event);\n }\n });\n\n return this;\n};\n\n}(jQuery));\n</code></pre>\n\n<p>Adapted from this answer <a href=\"https://stackoverflow.com/a/3028037/1611058\">https://stackoverflow.com/a/3028037/1611058</a></p>\n"
},
{
"answer_id": 33473515,
"author": "Rameez Rami",
"author_id": 2251701,
"author_profile": "https://Stackoverflow.com/users/2251701",
"pm_score": 6,
"selected": false,
"text": "<p>After research I have found three working solutions (I forgot the page links for reference)</p>\n\n<h2>First solution</h2>\n\n<pre><code><script>\n //The good thing about this solution is it doesn't stop event propagation.\n\n var clickFlag = 0;\n $('body').on('click', function () {\n if(clickFlag == 0) {\n console.log('hide element here');\n /* Hide element here */\n }\n else {\n clickFlag=0;\n }\n });\n $('body').on('click','#testDiv', function (event) {\n clickFlag = 1;\n console.log('showed the element');\n /* Show the element */\n });\n</script>\n</code></pre>\n\n<h2>Second solution</h2>\n\n<pre><code><script>\n $('body').on('click', function(e) {\n if($(e.target).closest('#testDiv').length == 0) {\n /* Hide dropdown here */\n }\n });\n</script>\n</code></pre>\n\n<h2>Third solution</h2>\n\n<pre><code><script>\n var specifiedElement = document.getElementById('testDiv');\n document.addEventListener('click', function(event) {\n var isClickInside = specifiedElement.contains(event.target);\n if (isClickInside) {\n console.log('You clicked inside')\n }\n else {\n console.log('You clicked outside')\n }\n });\n</script>\n</code></pre>\n"
},
{
"answer_id": 34218425,
"author": "Nitekurs",
"author_id": 4827540,
"author_profile": "https://Stackoverflow.com/users/4827540",
"pm_score": -1,
"selected": false,
"text": "<pre><code> $('#menucontainer').click(function(e){\n e.stopPropagation();\n });\n\n $(document).on('click', function(e){\n // code\n });\n</code></pre>\n"
},
{
"answer_id": 34280828,
"author": "Jitendra Damor",
"author_id": 4686674,
"author_profile": "https://Stackoverflow.com/users/4686674",
"pm_score": 5,
"selected": false,
"text": "<p>A simple solution for the situation is:</p>\n\n<pre><code>$(document).mouseup(function (e)\n{\n var container = $(\"YOUR SELECTOR\"); // Give you class or ID\n\n if (!container.is(e.target) && // If the target of the click is not the desired div or section\n container.has(e.target).length === 0) // ... nor a descendant-child of the container\n {\n container.hide();\n }\n});\n</code></pre>\n\n<p>The above script will hide the <code>div</code> if outside of the <code>div</code> click event is triggered.</p>\n\n<p>You can see the following blog for more information : <a href=\"http://www.codecanal.com/detect-click-outside-div-using-javascript/\" rel=\"noreferrer\">http://www.codecanal.com/detect-click-outside-div-using-javascript/</a></p>\n"
},
{
"answer_id": 35055176,
"author": "wsc",
"author_id": 5824173,
"author_profile": "https://Stackoverflow.com/users/5824173",
"pm_score": 0,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$('html').click(function() {\r\n//Hide the menus if visible\r\n});\r\n\r\n$('#menucontainer').click(function(event){\r\n event.stopPropagation();\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\r\n<html>\r\n <button id='#menucontainer'>Ok</button> \r\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 35846430,
"author": "Yishu Fang",
"author_id": 1253826,
"author_profile": "https://Stackoverflow.com/users/1253826",
"pm_score": 0,
"selected": false,
"text": "<p>Have a try of this:</p>\n\n<pre><code>$('html').click(function(e) {\n if($(e.target).parents('#menuscontainer').length == 0) {\n $('#menuscontainer').hide();\n }\n});\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/4cj4jxy0/\" rel=\"nofollow\">https://jsfiddle.net/4cj4jxy0/</a></p>\n\n<p>But note that this cannot work if the click event cannot reach the <code>html</code> tag. (Maybe other elements have <code>stopPropagation()</code>).</p>\n"
},
{
"answer_id": 36549967,
"author": "Qwertiy",
"author_id": 4928642,
"author_profile": "https://Stackoverflow.com/users/4928642",
"pm_score": 0,
"selected": false,
"text": "<p>Subscribe <em>capturing phase</em> of click to handle click on elements which call <code>preventDefault</code>.<br>\nRetrigger it on document element using the other name <code>click-anywhere</code>.</p>\n\n<pre><code>document.addEventListener('click', function (event) {\n event = $.event.fix(event);\n event.type = 'click-anywhere';\n $document.trigger(event);\n}, true);\n</code></pre>\n\n<p>Then where you need click outside functionality subscribe on <code>click-anywhere</code> event on <code>document</code> and check if the click was outside of the element you are interested in:</p>\n\n<pre><code>$(document).on('click-anywhere', function (event) {\n if (!$(event.target).closest('#smth').length) {\n // Do anything you need here\n }\n});\n</code></pre>\n\n<p>Some notes:</p>\n\n<ul>\n<li><p>You have to use <code>document</code> as it would be a perfomance fault to trigger event on all elements outside of which the click occured.</p></li>\n<li><p>This functionality can be wrapped into special plugin, which calls some callback on outside click.</p></li>\n<li><p>You can't subscribe capturing phase using jQuery itself.</p></li>\n<li><p>You don't need document load to subscribe as subscription is on <code>document</code>, even not on its <code>body</code>, so it exists always independently ащкь script placement and load status.</p></li>\n</ul>\n"
},
{
"answer_id": 36779401,
"author": "Matthew Goodwin",
"author_id": 2030888,
"author_profile": "https://Stackoverflow.com/users/2030888",
"pm_score": 3,
"selected": false,
"text": "<p>For easier use, and more expressive code, I created a jQuery plugin for this:</p>\n\n<pre><code>$('div.my-element').clickOut(function(target) { \n //do something here... \n});\n</code></pre>\n\n<p>Note: <strong>target</strong> is the element the user actually clicked. But callback is still executed in the context of the original element, so you can utilize <strong>this</strong> as you'd expect in a jQuery callback.</p>\n\n<p>Plugin:</p>\n\n<pre><code>$.fn.clickOut = function (parent, fn) {\n var context = this;\n fn = (typeof parent === 'function') ? parent : fn;\n parent = (parent instanceof jQuery) ? parent : $(document);\n\n context.each(function () {\n var that = this;\n parent.on('click', function (e) {\n var clicked = $(e.target);\n if (!clicked.is(that) && !clicked.parents().is(that)) {\n if (typeof fn === 'function') {\n fn.call(that, clicked);\n }\n }\n });\n\n });\n return context;\n};\n</code></pre>\n\n<p>By default, the click event listener is placed on the document. However, if you want to limit the event listener scope, you can pass in a jQuery object representing a parent level element that will be the top parent at which clicks will be listened to. This prevents unnecessary document level event listeners. Obviously, it won't work unless the parent element supplied is a parent of your initial element. </p>\n\n<p>Use like so:</p>\n\n<pre><code>$('div.my-element').clickOut($('div.my-parent'), function(target) { \n //do something here...\n});\n</code></pre>\n"
},
{
"answer_id": 37173398,
"author": "FDisk",
"author_id": 175404,
"author_profile": "https://Stackoverflow.com/users/175404",
"pm_score": 0,
"selected": false,
"text": "\n\n<pre class=\"lang-js prettyprint-override\"><code>$(document).on('click.menu.hide', function(e){\n if ( !$(e.target).closest('#my_menu').length ) {\n $('#my_menu').find('ul').toggleClass('active', false);\n }\n});\n\n$(document).on('click.menu.show', '#my_menu li', function(e){\n $(this).find('ul').toggleClass('active');\n});\n</code></pre>\n\n<pre class=\"lang-css prettyprint-override\"><code>div {\n float: left;\n}\n\nul {\n padding: 0;\n position: relative;\n}\nul li {\n padding: 5px 25px 5px 10px;\n border: 1px solid silver;\n cursor: pointer;\n list-style: none;\n margin-top: -1px;\n white-space: nowrap;\n}\nul li ul:before {\n margin-right: -20px;\n position: absolute;\n top: -17px;\n right: 0;\n content: \"\\25BC\";\n}\nul li ul li {\n visibility: hidden;\n height: 0;\n padding-top: 0;\n padding-bottom: 0;\n border-width: 0 0 1px 0;\n}\nul li ul li:last-child {\n border: none;\n}\nul li ul.active:before {\n content: \"\\25B2\";\n}\nul li ul.active li {\n display: list-item;\n visibility: visible;\n height: inherit;\n padding: 5px 25px 5px 10px;\n}\n</code></pre>\n\n<pre class=\"lang-html prettyprint-override\"><code><script src=\"https://code.jquery.com/jquery-2.1.4.js\"></script>\n<div>\n <ul id=\"my_menu\">\n <li>Menu 1\n <ul>\n <li>subMenu 1</li>\n <li>subMenu 2</li>\n <li>subMenu 3</li>\n <li>subMenu 4</li>\n </ul>\n </li>\n <li>Menu 2\n <ul>\n <li>subMenu 1</li>\n <li>subMenu 2</li>\n <li>subMenu 3</li>\n <li>subMenu 4</li>\n </ul>\n </li>\n <li>Menu 3</li>\n <li>Menu 4</li>\n <li>Menu 5</li>\n <li>Menu 6</li>\n </ul>\n</div>\n</code></pre>\n\n\n\n<p>Here is jsbin version <a href=\"http://jsbin.com/xopacadeni/edit?html,css,js,output\" rel=\"nofollow\">http://jsbin.com/xopacadeni/edit?html,css,js,output</a></p>\n"
},
{
"answer_id": 38317768,
"author": "zzzzBov",
"author_id": 497418,
"author_profile": "https://Stackoverflow.com/users/497418",
"pm_score": 9,
"selected": false,
"text": "<blockquote>\n<p>How to detect a click outside an element?</p>\n</blockquote>\n<p>The reason that this question is so popular and has so many answers is that it is deceptively complex. After almost eight years and dozens of answers, I am genuinely surprised to see how little care has been given to accessibility.</p>\n<blockquote>\n<p>I would like to hide these elements when the user clicks outside the menus' area.</p>\n</blockquote>\n<p>This is a noble cause and is the <em>actual</em> issue. The title of the question—which is what most answers appear to attempt to address—contains an unfortunate red herring.</p>\n<p><strong>Hint: it's the word <em>"click"</em>!</strong></p>\n<h1>You don't actually want to bind click handlers.</h1>\n<p>If you're binding click handlers to close the dialog, you've already failed. The reason you've failed is that not everyone triggers <code>click</code> events. Users not using a mouse will be able to escape your dialog (and your pop-up menu is arguably a type of dialog) by pressing <kbd>Tab</kbd>, and they then won't be able to read the content behind the dialog without subsequently triggering a <code>click</code> event.</p>\n<p>So let's rephrase the question.</p>\n<blockquote>\n<p>How does one close a dialog when a user is finished with it?</p>\n</blockquote>\n<p>This is the goal. Unfortunately, now we need to bind the <code>userisfinishedwiththedialog</code> event, and that binding isn't so straightforward.</p>\n<p>So how can we detect that a user has finished using a dialog?</p>\n<h2><code>focusout</code> event</h2>\n<p>A good start is to determine if focus has left the dialog.</p>\n<p><strong>Hint: be careful with the <code>blur</code> event, <code>blur</code> doesn't propagate if the event was bound to the bubbling phase!</strong></p>\n<p>jQuery's <a href=\"http://api.jquery.com/focusout/\" rel=\"noreferrer\"><code>focusout</code></a> will do just fine. If you can't use jQuery, then you can use <code>blur</code> during the capturing phase:</p>\n<pre><code>element.addEventListener('blur', ..., true);\n// use capture: ^^^^\n</code></pre>\n<p>Also, for many dialogs you'll need to allow the container to gain focus. Add <code>tabindex="-1"</code> to allow the dialog to receive focus dynamically without otherwise interrupting the tabbing flow.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$('a').on('click', function () {\n $(this.hash).toggleClass('active').focus();\n});\n\n$('div').on('focusout', function () {\n $(this).removeClass('active');\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div {\n display: none;\n}\n.active {\n display: block;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<a href=\"#example\">Example</a>\n<div id=\"example\" tabindex=\"-1\">\n Lorem ipsum <a href=\"http://example.com\">dolor</a> sit amet.\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<p>If you play with that demo for more than a minute you should quickly start seeing issues.</p>\n<p>The first is that the link in the dialog isn't clickable. Attempting to click on it or tab to it will lead to the dialog closing before the interaction takes place. This is because focusing the inner element triggers a <code>focusout</code> event before triggering a <code>focusin</code> event again.</p>\n<p>The fix is to queue the state change on the event loop. This can be done by using <code>setImmediate(...)</code>, or <code>setTimeout(..., 0)</code> for browsers that don't support <code>setImmediate</code>. Once queued it can be cancelled by a subsequent <code>focusin</code>:</p>\n<pre><code>$('.submenu').on({\n focusout: function (e) {\n $(this).data('submenuTimer', setTimeout(function () {\n $(this).removeClass('submenu--active');\n }.bind(this), 0));\n },\n focusin: function (e) {\n clearTimeout($(this).data('submenuTimer'));\n }\n});\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$('a').on('click', function () {\n $(this.hash).toggleClass('active').focus();\n});\n\n$('div').on({\n focusout: function () {\n $(this).data('timer', setTimeout(function () {\n $(this).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this).data('timer'));\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div {\n display: none;\n}\n.active {\n display: block;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<a href=\"#example\">Example</a>\n<div id=\"example\" tabindex=\"-1\">\n Lorem ipsum <a href=\"http://example.com\">dolor</a> sit amet.\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The second issue is that the dialog won't close when the link is pressed again. This is because the dialog loses focus, triggering the close behavior, after which the link click triggers the dialog to reopen.</p>\n<p>Similar to the previous issue, the focus state needs to be managed. Given that the state change has already been queued, it's just a matter of handling focus events on the dialog triggers:</p>\n<sub>This should look familiar</sub>\n<pre><code>$('a').on({\n focusout: function () {\n $(this.hash).data('timer', setTimeout(function () {\n $(this.hash).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this.hash).data('timer')); \n }\n});\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$('a').on('click', function () {\n $(this.hash).toggleClass('active').focus();\n});\n\n$('div').on({\n focusout: function () {\n $(this).data('timer', setTimeout(function () {\n $(this).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this).data('timer'));\n }\n});\n\n$('a').on({\n focusout: function () {\n $(this.hash).data('timer', setTimeout(function () {\n $(this.hash).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this.hash).data('timer')); \n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div {\n display: none;\n}\n.active {\n display: block;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<a href=\"#example\">Example</a>\n<div id=\"example\" tabindex=\"-1\">\n Lorem ipsum <a href=\"http://example.com\">dolor</a> sit amet.\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h2><kbd>Esc</kbd> key</h2>\n<p>If you thought you were done by handling the focus states, there's more you can do to simplify the user experience.</p>\n<p>This is often a "nice to have" feature, but it's common that when you have a modal or popup of any sort that the <kbd>Esc</kbd> key will close it out.</p>\n<pre><code>keydown: function (e) {\n if (e.which === 27) {\n $(this).removeClass('active');\n e.preventDefault();\n }\n}\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$('a').on('click', function () {\n $(this.hash).toggleClass('active').focus();\n});\n\n$('div').on({\n focusout: function () {\n $(this).data('timer', setTimeout(function () {\n $(this).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this).data('timer'));\n },\n keydown: function (e) {\n if (e.which === 27) {\n $(this).removeClass('active');\n e.preventDefault();\n }\n }\n});\n\n$('a').on({\n focusout: function () {\n $(this.hash).data('timer', setTimeout(function () {\n $(this.hash).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this.hash).data('timer')); \n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div {\n display: none;\n}\n.active {\n display: block;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<a href=\"#example\">Example</a>\n<div id=\"example\" tabindex=\"-1\">\n Lorem ipsum <a href=\"http://example.com\">dolor</a> sit amet.\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<p>If you know you have focusable elements within the dialog, you won't need to focus the dialog directly. If you're building a menu, you could focus the first menu item instead.</p>\n<pre><code>click: function (e) {\n $(this.hash)\n .toggleClass('submenu--active')\n .find('a:first')\n .focus();\n e.preventDefault();\n}\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$('.menu__link').on({\n click: function (e) {\n $(this.hash)\n .toggleClass('submenu--active')\n .find('a:first')\n .focus();\n e.preventDefault();\n },\n focusout: function () {\n $(this.hash).data('submenuTimer', setTimeout(function () {\n $(this.hash).removeClass('submenu--active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this.hash).data('submenuTimer')); \n }\n});\n\n$('.submenu').on({\n focusout: function () {\n $(this).data('submenuTimer', setTimeout(function () {\n $(this).removeClass('submenu--active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this).data('submenuTimer'));\n },\n keydown: function (e) {\n if (e.which === 27) {\n $(this).removeClass('submenu--active');\n e.preventDefault();\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.menu {\n list-style: none;\n margin: 0;\n padding: 0;\n}\n.menu:after {\n clear: both;\n content: '';\n display: table;\n}\n.menu__item {\n float: left;\n position: relative;\n}\n\n.menu__link {\n background-color: lightblue;\n color: black;\n display: block;\n padding: 0.5em 1em;\n text-decoration: none;\n}\n.menu__link:hover,\n.menu__link:focus {\n background-color: black;\n color: lightblue;\n}\n\n.submenu {\n border: 1px solid black;\n display: none;\n left: 0;\n list-style: none;\n margin: 0;\n padding: 0;\n position: absolute;\n top: 100%;\n}\n.submenu--active {\n display: block;\n}\n\n.submenu__item {\n width: 150px;\n}\n\n.submenu__link {\n background-color: lightblue;\n color: black;\n display: block;\n padding: 0.5em 1em;\n text-decoration: none;\n}\n\n.submenu__link:hover,\n.submenu__link:focus {\n background-color: black;\n color: lightblue;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<ul class=\"menu\">\n <li class=\"menu__item\">\n <a class=\"menu__link\" href=\"#menu-1\">Menu 1</a>\n <ul class=\"submenu\" id=\"menu-1\" tabindex=\"-1\">\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#1\">Example 1</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#2\">Example 2</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#3\">Example 3</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#4\">Example 4</a></li>\n </ul>\n </li>\n <li class=\"menu__item\">\n <a class=\"menu__link\" href=\"#menu-2\">Menu 2</a>\n <ul class=\"submenu\" id=\"menu-2\" tabindex=\"-1\">\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#1\">Example 1</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#2\">Example 2</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#3\">Example 3</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#4\">Example 4</a></li>\n </ul>\n </li>\n</ul>\nlorem ipsum <a href=\"http://example.com/\">dolor</a> sit amet.</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h1>WAI-ARIA Roles and Other Accessibility Support</h1>\n<p>This answer hopefully covers the basics of accessible keyboard and mouse support for this feature, but as it's already quite sizable I'm going to avoid any discussion of <a href=\"https://www.w3.org/TR/wai-aria/\" rel=\"noreferrer\">WAI-ARIA roles and attributes</a>, however I <em>highly</em> recommend that implementers refer to the spec for details on what roles they should use and any other appropriate attributes.</p>\n"
},
{
"answer_id": 38997381,
"author": "Thamaraiselvam",
"author_id": 2975952,
"author_profile": "https://Stackoverflow.com/users/2975952",
"pm_score": 1,
"selected": false,
"text": "<p>To hide <code>fileTreeClass</code> if clicked outside of it </p>\n\n<pre><code> jQuery(document).mouseup(function (e) {\n var container = $(\".fileTreeClass\");\n if (!container.is(e.target) // if the target of the click isn't the container...\n && container.has(e.target).length === 0) // ... nor a descendant of the container\n {\n container.hide();\n }\n });\n</code></pre>\n"
},
{
"answer_id": 39418566,
"author": "froilanq",
"author_id": 1895877,
"author_profile": "https://Stackoverflow.com/users/1895877",
"pm_score": 1,
"selected": false,
"text": "<p>Simple plugin:</p>\n\n<pre><code>$.fn.clickOff = function(callback, selfDestroy) {\n var clicked = false;\n var parent = this;\n var destroy = selfDestroy || true;\n\n parent.click(function() {\n clicked = true;\n });\n\n $(document).click(function(event) {\n if (!clicked && parent.is(':visible')) {\n if(callback) callback.call(parent, event)\n }\n if (destroy) {\n //parent.clickOff = function() {};\n //parent.off(\"click\");\n //$(document).off(\"click\");\n parent.off(\"clickOff\");\n }\n clicked = false;\n });\n};\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>$(\"#myDiv\").clickOff(function() {\n alert('clickOff');\n});\n</code></pre>\n"
},
{
"answer_id": 40357679,
"author": "Waheed",
"author_id": 225796,
"author_profile": "https://Stackoverflow.com/users/225796",
"pm_score": 2,
"selected": false,
"text": "<p>This might be a better fix for some people. </p>\n\n<pre><code>$(\".menu_link\").click(function(){\n // show menu code\n});\n\n$(\".menu_link\").mouseleave(function(){\n //hide menu code, you may add a timer for 3 seconds before code to be run\n});\n</code></pre>\n\n<p>I know mouseleave does not only mean a click outside, it also means leaving that element's area.</p>\n\n<p>Once the menu itself is inside the <code>menu_link</code> element then the menu itself should not be a problem to click on or move on.</p>\n"
},
{
"answer_id": 40563576,
"author": "Waltur Buerk",
"author_id": 3601474,
"author_profile": "https://Stackoverflow.com/users/3601474",
"pm_score": 2,
"selected": false,
"text": "<p>I believe the best way of doing it is something like this. </p>\n\n<pre><code>$(document).on(\"click\", function(event) {\n clickedtarget = $(event.target).closest('#menuscontainer');\n $(\"#menuscontainer\").not(clickedtarget).hide();\n});\n</code></pre>\n\n<p>This type of solution could easily be made to work for multiple menus and also menus that are dynamically added through javascript. Basically it just allows you to click anywhere in your document, and checks which element you clicked in, and selects it's closest \"#menuscontainer\". Then it hides all menuscontainers but excludes the one you clicked in. </p>\n\n<p>Not sure about exactly how your menus are built, but feel free to copy my code in the JSFiddle. It's a very simple but thoroughly functional menu/modal system. All you need to do is build the html-menus and the code will do the work for you.</p>\n\n<p><a href=\"https://jsfiddle.net/zs6anrn7/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/zs6anrn7/</a></p>\n"
},
{
"answer_id": 42126292,
"author": "Lucas",
"author_id": 2005787,
"author_profile": "https://Stackoverflow.com/users/2005787",
"pm_score": 2,
"selected": false,
"text": "<p>I know there are a million answers to this question, but I've always been a fan of using HTML and CSS to do most of the work. In this case, z-index and positioning. The simplest way that I have found to do this is as follows:</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>$(\"#show-trigger\").click(function(){\r\n $(\"#element\").animate({width: 'toggle'});\r\n $(\"#outside-element\").show();\r\n});\r\n$(\"#outside-element\").click(function(){\r\n $(\"#element\").hide();\r\n $(\"#outside-element\").hide();\r\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#outside-element {\r\n position:fixed;\r\n width:100%;\r\n height:100%;\r\n z-index:1;\r\n display:none;\r\n}\r\n#element {\r\n display:none;\r\n padding:20px;\r\n background-color:#ccc;\r\n width:300px;\r\n z-index:2;\r\n position:relative;\r\n}\r\n#show-trigger {\r\n padding:20px;\r\n background-color:#ccc;\r\n margin:20px auto;\r\n z-index:2;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\r\n<div id=\"outside-element\"></div>\r\n<div id=\"element\">\r\n <div class=\"menu-item\"><a href=\"#1\">Menu Item 1</a></div>\r\n <div class=\"menu-item\"><a href=\"#2\">Menu Item 1</a></div>\r\n <div class=\"menu-item\"><a href=\"#3\">Menu Item 1</a></div>\r\n <div class=\"menu-item\"><a href=\"#4\">Menu Item 1</a></div>\r\n</div>\r\n<div id=\"show-trigger\">Show Menu</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This creates a safe environment, since nothing is going to get triggered unless the menu is actually open and the z-index protects any of the content within the element from creating any misfires upon being clicked.</p>\n\n<p>Additionally, you're not requiring jQuery to cover all of your bases with propagation calls and having to purge all of the inner elements from misfires.</p>\n"
},
{
"answer_id": 42448663,
"author": "Karthikeyan Ganesan",
"author_id": 3462686,
"author_profile": "https://Stackoverflow.com/users/3462686",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$(document).on(\"click\",function (event) \n { \n console.log(event);\n if ($(event.target).closest('.element').length == 0)\n {\n //your code here\n if ($(\".element\").hasClass(\"active\"))\n {\n $(\".element\").removeClass(\"active\");\n }\n }\n });\n</code></pre>\n\n<p>Try this coding for getting the solution.</p>\n"
},
{
"answer_id": 43405204,
"author": "Dan Philip Bejoy",
"author_id": 6412847,
"author_profile": "https://Stackoverflow.com/users/6412847",
"pm_score": 4,
"selected": false,
"text": "<p>The event has a property called event.path of the element which is a <em>\"static ordered list of all its ancestors in tree order\"</em>. To check if an event originated from a specific DOM element or one of its children, just check the path for that specific DOM element. It can also be used to check multiple elements by logically <code>OR</code>ing the element check in the <code>some</code> function.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(\"body\").click(function() {\r\n target = document.getElementById(\"main\");\r\n flag = event.path.some(function(el, i, arr) {\r\n return (el == target)\r\n })\r\n if (flag) {\r\n console.log(\"Inside\")\r\n } else {\r\n console.log(\"Outside\")\r\n }\r\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#main {\r\n display: inline-block;\r\n background:yellow;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\r\n<div id=\"main\">\r\n <ul>\r\n <li>Test-Main</li>\r\n <li>Test-Main</li>\r\n <li>Test-Main</li>\r\n <li>Test-Main</li>\r\n <li>Test-Main</li>\r\n </ul>\r\n</div>\r\n<div id=\"main2\">\r\n Outside Main\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>So for your case It should be </p>\n\n<pre><code>$(\"body\").click(function() {\n target = $(\"#menuscontainer\")[0];\n flag = event.path.some(function(el, i, arr) {\n return (el == target)\n });\n if (!flag) {\n // Hide the menus\n }\n});\n</code></pre>\n"
},
{
"answer_id": 45155703,
"author": "Walt",
"author_id": 6562729,
"author_profile": "https://Stackoverflow.com/users/6562729",
"pm_score": 3,
"selected": false,
"text": "<p>If someone curious here is javascript solution(es6):</p>\n\n<pre><code>window.addEventListener('mouseup', e => {\n if (e.target != yourDiv && e.target.parentNode != yourDiv) {\n yourDiv.classList.remove('show-menu');\n //or yourDiv.style.display = 'none';\n }\n })\n</code></pre>\n\n<p>and es5, just in case:</p>\n\n<pre><code>window.addEventListener('mouseup', function (e) {\nif (e.target != yourDiv && e.target.parentNode != yourDiv) {\n yourDiv.classList.remove('show-menu'); \n //or yourDiv.style.display = 'none';\n}\n</code></pre>\n\n<p>});</p>\n"
},
{
"answer_id": 45353059,
"author": "Fabian",
"author_id": 7033353,
"author_profile": "https://Stackoverflow.com/users/7033353",
"pm_score": 2,
"selected": false,
"text": "<p>Here is what I do to solve to problem.</p>\n\n<pre><code>$(window).click(function (event) {\n //To improve performance add a checklike \n //if(myElement.isClosed) return;\n var isClickedElementChildOfMyBox = isChildOfElement(event,'#id-of-my-element');\n\n if (isClickedElementChildOfMyBox)\n return;\n\n //your code to hide the element \n});\n\nvar isChildOfElement = function (event, selector) {\n if (event.originalEvent.path) {\n return event.originalEvent.path[0].closest(selector) !== null;\n }\n\n return event.originalEvent.originalTarget.closest(selector) !== null;\n}\n</code></pre>\n"
},
{
"answer_id": 46187785,
"author": "hienbt88",
"author_id": 1431934,
"author_profile": "https://Stackoverflow.com/users/1431934",
"pm_score": 2,
"selected": false,
"text": "<p>This works for me</p>\n\n<pre><code>$(\"body\").mouseup(function(e) {\n var subject = $(\".main-menu\");\n if(e.target.id != subject.attr('id') && !subject.has(e.target).length) {\n $('.sub-menu').hide();\n }\n});\n</code></pre>\n"
},
{
"answer_id": 47090854,
"author": "Duannx",
"author_id": 4254681,
"author_profile": "https://Stackoverflow.com/users/4254681",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a simple solution by pure javascript. It is <strong>up-to-date with ES6</strong>:</p>\n\n<pre><code>var isMenuClick = false;\nvar menu = document.getElementById('menuscontainer');\ndocument.addEventListener('click',()=>{\n if(!isMenuClick){\n //Hide the menu here\n }\n //Reset isMenuClick \n isMenuClick = false;\n})\nmenu.addEventListener('click',()=>{\n isMenuClick = true;\n})\n</code></pre>\n"
},
{
"answer_id": 47729165,
"author": "Aominé",
"author_id": 7731859,
"author_profile": "https://Stackoverflow.com/users/7731859",
"pm_score": 0,
"selected": false,
"text": "<p>if you just want to display a window when you click on a button and undisp this window when you click outside.( or on the button again ) this bellow work good</p>\n\n<pre><code>document.body.onclick = function() { undisp_menu(); };\nvar menu_on = 0;\n\nfunction menu_trigger(event){\n\n if (menu_on == 0)\n {\n // otherwise u will call the undisp on body when \n // click on the button\n event.stopPropagation(); \n\n disp_menu();\n }\n\n else{\n undisp_menu();\n }\n\n}\n\n\nfunction disp_menu(){\n\n menu_on = 1;\n var e = document.getElementsByClassName(\"menu\")[0];\n e.className = \"menu on\";\n\n}\n\nfunction undisp_menu(){\n\n menu_on = 0;\n var e = document.getElementsByClassName(\"menu\")[0];\n e.className = \"menu\";\n\n}\n</code></pre>\n\n<p>don't forget this for the button</p>\n\n<pre><code><div class=\"button\" onclick=\"menu_trigger(event)\">\n\n<div class=\"menu\">\n</code></pre>\n\n<p>and the css:</p>\n\n<pre><code>.menu{\n display: none;\n}\n\n.on {\n display: inline-block;\n}\n</code></pre>\n"
},
{
"answer_id": 47755925,
"author": "Muhammet Can TONBUL",
"author_id": 6478359,
"author_profile": "https://Stackoverflow.com/users/6478359",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using tools like \"Pop-up\", you can use the \"onFocusOut\" event.</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\ndocument.getElementById(\"inside-div\").focus();\r\n}\r\nfunction loseFocus(){\r\nalert(\"Clicked outside\");\r\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#container{\r\nbackground-color:lightblue;\r\nwidth:200px;\r\nheight:200px;\r\n}\r\n\r\n#inside-div{\r\nbackground-color:lightgray;\r\nwidth:100px;\r\nheight:100px;\r\n\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"container\">\r\n<input type=\"text\" id=\"inside-div\" onfocusout=\"loseFocus()\">\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48161126,
"author": "chea sotheara",
"author_id": 5392288,
"author_profile": "https://Stackoverflow.com/users/5392288",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$('#propertyType').on(\"click\",function(e){\n self.propertyTypeDialog = !self.propertyTypeDialog;\n b = true;\n e.stopPropagation();\n console.log(\"input clicked\");\n });\n\n $(document).on('click','body:not(#propertyType)',function (e) {\n e.stopPropagation();\n if(b == true) {\n if ($(e.target).closest(\"#configuration\").length == 0) {\n b = false;\n self.propertyTypeDialog = false;\n console.log(\"outside clicked\");\n }\n }\n // console.log($(e.target).closest(\"#configuration\").length);\n });\n</code></pre>\n"
},
{
"answer_id": 48247865,
"author": "Rinto George",
"author_id": 510754,
"author_profile": "https://Stackoverflow.com/users/510754",
"pm_score": 3,
"selected": false,
"text": "<p>I have used below script and done with jQuery.</p>\n\n<pre><code>jQuery(document).click(function(e) {\n var target = e.target; //target div recorded\n if (!jQuery(target).is('#tobehide') ) {\n jQuery(this).fadeOut(); //if the click element is not the above id will hide\n }\n})\n</code></pre>\n\n<p>Below find the HTML code</p>\n\n<pre><code><div class=\"main-container\">\n<div> Hello I am the title</div>\n<div class=\"tobehide\">I will hide when you click outside of me</div>\n</div>\n</code></pre>\n\n<p>You can read the tutorial <a href=\"http://tutsplanet.com/trigger-function-clicks-outside-element-jquery-492/\" rel=\"noreferrer\">here</a> </p>\n"
},
{
"answer_id": 48744452,
"author": "Jovanni G",
"author_id": 2090288,
"author_profile": "https://Stackoverflow.com/users/2090288",
"pm_score": 5,
"selected": false,
"text": "<p>I am surprised nobody actually acknowledged <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event\" rel=\"noreferrer\"><code>focusout</code></a> event:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var button = document.getElementById('button');\nbutton.addEventListener('click', function(e){\n e.target.style.backgroundColor = 'green';\n});\nbutton.addEventListener('focusout', function(e){\n e.target.style.backgroundColor = '';\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n</head>\n<body>\n <button id=\"button\">Click</button>\n</body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 49147573,
"author": "DaniG2k",
"author_id": 1741325,
"author_profile": "https://Stackoverflow.com/users/1741325",
"pm_score": 2,
"selected": false,
"text": "<p>I just want to make @Pistos answer more apparent since it's hidden in the comments.</p>\n\n<p>This solution worked perfectly for me. Plain JS:</p>\n\n<pre><code>var elementToToggle = $('.some-element');\n$(document).click( function(event) {\n if( $(event.target).closest(elementToToggle).length === 0 ) {\n elementToToggle.hide();\n }\n});\n</code></pre>\n\n<p>in CoffeeScript:</p>\n\n<pre><code>elementToToggle = $('.some-element')\n$(document).click (event) ->\n if $(event.target).closest(elementToToggle).length == 0\n elementToToggle.hide()\n</code></pre>\n"
},
{
"answer_id": 54633092,
"author": "Yair Cohen",
"author_id": 4424888,
"author_profile": "https://Stackoverflow.com/users/4424888",
"pm_score": 2,
"selected": false,
"text": "<p>Let's say the div you want to detect if the user clicked outside or inside has an id, for example: \"my-special-widget\".</p>\n\n<p>Listen to body click events:</p>\n\n<pre><code>document.body.addEventListener('click', (e) => {\n if (isInsideMySpecialWidget(e.target, \"my-special-widget\")) {\n console.log(\"user clicked INSIDE the widget\");\n }\n console.log(\"user clicked OUTSIDE the widget\");\n});\n\nfunction isInsideMySpecialWidget(elem, mySpecialWidgetId){\n while (elem.parentElement) {\n if (elem.id === mySpecialWidgetId) {\n return true;\n }\n elem = elem.parentElement;\n }\n return false;\n}\n</code></pre>\n\n<p>In this case, you won't break the normal flow of click on some element in your page, since you are not using the \"stopPropagation\" method.</p>\n"
},
{
"answer_id": 56757369,
"author": "Rivenfall",
"author_id": 2234156,
"author_profile": "https://Stackoverflow.com/users/2234156",
"pm_score": -1,
"selected": false,
"text": "<p>First you have to track wether the mouse is inside or outside your element1, using the mouseenter and mouseleave events.\nThen you can create an element2 which covers the whole screen to detect any clicks, and react accordingly depending on wether you are inside or outside element1.</p>\n\n<p>I strongly recommend to handle both initialization and cleanup, and that the element2 is made as temporary as possible, for obvious reasons.</p>\n\n<p>In the example below, the overlay is an element positionned somewhere, which can be selected by clicking inside, and unselected by clicking outside.\nThe _init and _release methods are called as part of an automatic initialisation/cleanup process.\nThe class inherits from a ClickOverlay which has an inner and outerElement, don't worry about it. I used outerElement.parentNode.appendChild to avoid conflicts.</p>\n\n<pre><code>import ClickOverlay from './ClickOverlay.js'\n\n/* CSS */\n// .unselect-helper {\n// position: fixed; left: -100vw; top: -100vh;\n// width: 200vw; height: 200vh;\n// }\n// .selected {outline: 1px solid black}\n\nexport default class ResizeOverlay extends ClickOverlay {\n _init(_opts) {\n this.enterListener = () => this.onEnter()\n this.innerElement.addEventListener('mouseenter', this.enterListener)\n this.leaveListener = () => this.onLeave()\n this.innerElement.addEventListener('mouseleave', this.leaveListener)\n this.selectListener = () => {\n if (this.unselectHelper)\n return\n this.unselectHelper = document.createElement('div')\n this.unselectHelper.classList.add('unselect-helper')\n this.unselectListener = () => {\n if (this.mouseInside)\n return\n this.clearUnselectHelper()\n this.onUnselect()\n }\n this.unselectHelper.addEventListener('pointerdown'\n , this.unselectListener)\n this.outerElement.parentNode.appendChild(this.unselectHelper)\n this.onSelect()\n }\n this.innerElement.addEventListener('pointerup', this.selectListener)\n }\n\n _release() {\n this.innerElement.removeEventListener('mouseenter', this.enterListener)\n this.innerElement.removeEventListener('mouseleave', this.leaveListener)\n this.innerElement.removeEventListener('pointerup', this.selectListener)\n this.clearUnselectHelper()\n }\n\n clearUnselectHelper() {\n if (!this.unselectHelper)\n return\n this.unselectHelper.removeEventListener('pointerdown'\n , this.unselectListener)\n this.unselectHelper.remove()\n delete this.unselectListener\n delete this.unselectHelper\n }\n\n onEnter() {\n this.mouseInside = true\n }\n\n onLeave() {\n delete this.mouseInside\n }\n\n onSelect() {\n this.innerElement.classList.add('selected')\n }\n\n onUnselect() {\n this.innerElement.classList.remove('selected')\n }\n}\n</code></pre>\n"
},
{
"answer_id": 59504665,
"author": "Marcelo Ribeiro",
"author_id": 7043201,
"author_profile": "https://Stackoverflow.com/users/7043201",
"pm_score": 2,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const button = document.querySelector('button')\r\nconst box = document.querySelector('.box');\r\n\r\nconst toggle = event => {\r\n event.stopPropagation();\r\n \r\n if (!event.target.closest('.box')) {\r\n console.log('Click outside');\r\n\r\n box.classList.toggle('active');\r\n\r\n box.classList.contains('active')\r\n ? document.addEventListener('click', toggle)\r\n : document.removeEventListener('click', toggle);\r\n } else {\r\n console.log('Click inside');\r\n }\r\n}\r\n\r\nbutton.addEventListener('click', toggle);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.box {\r\n position: absolute;\r\n display: none;\r\n margin-top: 8px;\r\n padding: 20px;\r\n background: lightgray;\r\n}\r\n\r\n.box.active {\r\n display: block;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button>Toggle box</button>\r\n\r\n<div class=\"box\">\r\n <form action=\"\">\r\n <input type=\"text\">\r\n <button type=\"button\">Search</button>\r\n </form>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 61892470,
"author": "JBarros",
"author_id": 4044566,
"author_profile": "https://Stackoverflow.com/users/4044566",
"pm_score": -1,
"selected": false,
"text": "<p>The easiest way: <code>mouseleave(function())</code></p>\n\n<p>More info: <a href=\"https://www.w3schools.com/jquery/jquery_events.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/jquery/jquery_events.asp</a></p>\n"
},
{
"answer_id": 62657409,
"author": "Илья Зеленько",
"author_id": 5286034,
"author_profile": "https://Stackoverflow.com/users/5286034",
"pm_score": 4,
"selected": false,
"text": "<p>2020 solution using native JS API <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/closest\" rel=\"noreferrer\">closest</a> method.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.addEventListener('click', ({ target }) => {\n if (!target.closest('#menupop')) {\n document.querySelector('#menupop').style.display = 'none'\n }\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#menupop {\n width: 300px;\n height: 300px;\n background-color: red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"menupop\">\nclicking outside will close this\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 63617118,
"author": "Mu-Tsun Tsai",
"author_id": 9953396,
"author_profile": "https://Stackoverflow.com/users/9953396",
"pm_score": 2,
"selected": false,
"text": "<p>Still looking for that perfect solution for detecting clicking outside? Look no further! Introducing <a href=\"https://www.npmjs.com/package/clickout-event\" rel=\"nofollow noreferrer\">Clickout-Event</a>, a package that provides universal support for clickout and other similar events, and it works in <strong>all</strong> scenarios: plain HTML <code>onclickout</code> attributes, <code>.addEventListener('clickout')</code> of vanilla JavaScript, <code>.on('clickout')</code> of jQuery, <code>v-on:clickout</code> directives of Vue.js, you name it. As long as a front-end framework internally uses <code>addEventListener</code> to handle events, Clickout-Event works for it. Just add the script tag anywhere in your page, and it simply works like magic.</p>\n<p>HTML attribute</p>\n<pre class=\"lang-html prettyprint-override\"><code><div onclickout="console.log('clickout detected')">...</div>\n</code></pre>\n<p>Vanilla JavaScript</p>\n<pre class=\"lang-js prettyprint-override\"><code>document.getElementById('myId').addEventListener('clickout', myListener);\n</code></pre>\n<p>jQuery</p>\n<pre class=\"lang-js prettyprint-override\"><code>$('#myId').on('clickout', myListener);\n</code></pre>\n<p>Vue.js</p>\n<pre class=\"lang-html prettyprint-override\"><code><div v-on:clickout="open=false">...</div>\n</code></pre>\n<p>Angular</p>\n<pre class=\"lang-html prettyprint-override\"><code><div (clickout)="close()">...</div>\n</code></pre>\n"
},
{
"answer_id": 64103587,
"author": "online Thomas",
"author_id": 2754599,
"author_profile": "https://Stackoverflow.com/users/2754599",
"pm_score": 2,
"selected": false,
"text": "<p>All of these answers solve the problem, but I would like to contribute with a moders es6 solution that does exactly what is needed. I just hope to make someone happy with this runnable demo.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>window.clickOutSide = (element, clickOutside, clickInside) => {\n document.addEventListener('click', (event) => {\n if (!element.contains(event.target)) {\n if (typeof clickInside === 'function') {\n clickOutside();\n }\n } else {\n if (typeof clickInside === 'function') {\n clickInside();\n }\n }\n });\n};\n\nwindow.clickOutSide(document.querySelector('.block'), () => alert('clicked outside'), () => alert('clicked inside'));</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.block {\n width: 400px;\n height: 400px;\n background-color: red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"block\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 64342309,
"author": "aksl",
"author_id": 9619861,
"author_profile": "https://Stackoverflow.com/users/9619861",
"pm_score": 0,
"selected": false,
"text": "<p>this works fine for me. i am not an expert.</p>\n<pre><code>$(document).click(function(event) {\n var $target = $(event.target);\n if(!$target.closest('#hamburger, a').length &&\n $('#hamburger, a').is(":visible")) {\n $('nav').slideToggle();\n }\n});\n</code></pre>\n"
},
{
"answer_id": 64665817,
"author": "Cezar Augusto",
"author_id": 4902448,
"author_profile": "https://Stackoverflow.com/users/4902448",
"pm_score": 7,
"selected": false,
"text": "<h2>It's 2020 and you can use <code>event.composedPath()</code></h2>\n<p>From: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath</a></p>\n<blockquote>\n<p>The composedPath() method of the Event interface returns the event’s path, which is an array of the objects on which listeners will be invoked.</p>\n</blockquote>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const target = document.querySelector('#myTarget')\n\ndocument.addEventListener('click', (event) => {\n const withinBoundaries = event.composedPath().includes(target)\n\n if (withinBoundaries) {\n target.innerText = 'Click happened inside element'\n } else {\n target.innerText = 'Click happened **OUTSIDE** element'\n } \n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>/* just to make it good looking. you don't need this */\n#myTarget {\n margin: 50px auto;\n width: 500px;\n height: 500px;\n background: gray;\n border: 10px solid black;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"myTarget\">\n click me (or not!)\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 66228309,
"author": "ale",
"author_id": 13005954,
"author_profile": "https://Stackoverflow.com/users/13005954",
"pm_score": 0,
"selected": false,
"text": "<p>I've read all on 2021, but if not wrong, nobody suggested something easy like this, to unbind and remove event. Using two of the above answers and a more little trick so put all in one (could also be added param to the function to pass selectors, for more popups).\nMay it is useful for someone to know that the joke could be done also this way:</p>\n<pre><code><div id="container" style="display:none"><h1>my menu is nice but disappear if i click outside it</h1></div>\n\n<script>\n function printPopup(){\n $("#container").css({ "display":"block" });\n var remListener = $(document).mouseup(function (e) {\n if ($(e.target).closest("#container").length === 0 && (e.target != $('html').get(0))) \n {\n //alert('closest call');\n $("#container").css({ "display":"none" });\n remListener.unbind('mouseup'); // isn't it?\n } \n });\n }\n\n printPopup();\n\n</script>\n</code></pre>\n<p>cheers</p>\n"
},
{
"answer_id": 67036853,
"author": "tim-mccurrach",
"author_id": 7549907,
"author_profile": "https://Stackoverflow.com/users/7549907",
"pm_score": 4,
"selected": false,
"text": "<h3>Use <code>focusout</code> for accessability</h3>\n<p>There is one answer here that says (quite correctly) that focusing on <code>click</code> events is an accessibility problem since we want to cater for keyboard users. The <code>focusout</code> event is the correct thing to use here, but it can be done much more simply than in the other answer (and in pure javascript too):</p>\n<h3>A simpler way of doing it:</h3>\n<p>The 'problem' with using <code>focusout</code> is that if an element inside your dialog/modal/menu loses focus, to something also 'inside' the event will still get fired. We can check that this isn't the case by looking at <code>event.relatedTarget</code> (which tells us what element will have gained focus).</p>\n<pre><code>dialog = document.getElementById("dialogElement")\n\ndialog.addEventListener("focusout", function (event) {\n if (\n // we are still inside the dialog so don't close\n dialog.contains(event.relatedTarget) ||\n // we have switched to another tab so probably don't want to close \n !document.hasFocus() \n ) {\n return;\n }\n dialog.close(); // or whatever logic you want to use to close\n});\n</code></pre>\n<p>There is one slight gotcha to the above, which is that <code>relatedTarget</code> may be <code>null</code>. This is fine if the user is clicking outside the dialog, but will be a problem if unless the user clicks inside the dialog and the dialog happens to not be focusable. To fix this you have to make sure to set <code>tabIndex=0</code> so your dialog is focusable.</p>\n"
},
{
"answer_id": 67482066,
"author": "Normajean",
"author_id": 11930305,
"author_profile": "https://Stackoverflow.com/users/11930305",
"pm_score": 2,
"selected": false,
"text": "<p>This is the simplest answer I have found to this question:</p>\n<pre><code>window.addEventListener('click', close_window = function () {\n if(event.target !== windowEl){\n windowEl.style.display = "none";\n window.removeEventListener('click', close_window, false);\n }\n});\n</code></pre>\n<p>And you will see I named the function "close_window" so that I could remove the event listener when the window closes.</p>\n"
},
{
"answer_id": 68273207,
"author": "Sommelier",
"author_id": 7230858,
"author_profile": "https://Stackoverflow.com/users/7230858",
"pm_score": 2,
"selected": false,
"text": "<p><strong>A way to write in pure JavaScript</strong></p>\n<pre><code>let menu = document.getElementById("menu");\n\ndocument.addEventListener("click", function(){\n // Hide the menus\n menu.style.display = "none";\n}, false);\n\ndocument.getElementById("menuscontainer").addEventListener("click", function(e){\n // Show the menus\n menu.style.display = "block";\n e.stopPropagation();\n}, false);\n</code></pre>\n"
},
{
"answer_id": 69855641,
"author": "jameshfisher",
"author_id": 229792,
"author_profile": "https://Stackoverflow.com/users/229792",
"pm_score": 0,
"selected": false,
"text": "<p>You don't need (much) JavaScript, just the <code>:focus-within</code> selector:</p>\n<ul>\n<li>Use <code>.sidebar:focus-within</code> to display your sidebar.</li>\n<li>Set <code>tabindex=-1</code> on your sidebar and body elements to make them focussable.</li>\n<li>Set the sidebar visibility with <code>sidebarEl.focus()</code> and <code>document.body.focus()</code>.</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const menuButton = document.querySelector('.menu-button');\nconst sidebar = document.querySelector('.sidebar');\n\nmenuButton.onmousedown = ev => {\n ev.preventDefault();\n (sidebar.contains(document.activeElement) ?\n document.body : sidebar).focus();\n};</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* { box-sizing: border-box; }\n\n.sidebar {\n position: fixed;\n width: 15em;\n left: -15em;\n top: 0;\n bottom: 0;\n transition: left 0.3s ease-in-out;\n background-color: #eef;\n padding: 3em 1em;\n}\n\n.sidebar:focus-within {\n left: 0;\n}\n\n.sidebar:focus {\n outline: 0;\n}\n\n.menu-button {\n position: fixed;\n top: 0;\n left: 0;\n padding: 1em;\n background-color: #eef;\n border: 0;\n}\n\nbody {\n max-width: 30em;\n margin: 3em;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body tabindex='-1'>\n <nav class='sidebar' tabindex='-1'>\n Sidebar content\n <input type=\"text\"/>\n </nav>\n <button class=\"menu-button\">☰</button>\n Body content goes here, Lorem ipsum sit amet, etc\n</body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 71228065,
"author": "Felix Furtmayr",
"author_id": 6818578,
"author_profile": "https://Stackoverflow.com/users/6818578",
"pm_score": 0,
"selected": false,
"text": "<p>For those who want a short solution to integrate into their JS code - a small library without JQuery:</p>\n<p>Usage:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// demo code\nvar htmlElem = document.getElementById('my-element')\nfunction doSomething(){ console.log('outside click') }\n\n// use the lib\nvar removeListener = new elemOutsideClickListener(htmlElem, doSomething);\n\n// deregister on your wished event\n$scope.$on('$destroy', removeListener);\n\n</code></pre>\n<p>Here is the lib:</p>\n<pre class=\"lang-js prettyprint-override\"><code>\nfunction elemOutsideClickListener (element, outsideClickFunc, insideClickFunc) {\n function onClickOutside (e) {\n var targetEl = e.target; // clicked element\n do {\n // click inside\n if (targetEl === element) {\n if (insideClickFunc) insideClickFunc();\n return;\n\n // Go up the DOM\n } else {\n targetEl = targetEl.parentNode;\n }\n } while (targetEl);\n\n // click outside\n if (!targetEl && outsideClickFunc) outsideClickFunc();\n }\n\n window.addEventListener('click', onClickOutside);\n\n return function () {\n window.removeEventListener('click', onClickOutside);\n };\n}\n</code></pre>\n<p>I took the code from here and put it in a function:\n<a href=\"https://www.w3docs.com/snippets/javascript/how-to-detect-a-click-outside-an-element.html\" rel=\"nofollow noreferrer\">https://www.w3docs.com/snippets/javascript/how-to-detect-a-click-outside-an-element.html</a></p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.
Is something like this possible with jQuery?
```
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
```
|
>
> Note: Using `stopPropagation` is something that should be avoided as it breaks normal event flow in the DOM. See [this CSS Tricks article](https://css-tricks.com/dangers-stopping-event-propagation/) for more information. Consider using [this method](https://stackoverflow.com/a/3028037/561309) instead.
>
>
>
Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body.
```js
$(window).click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
```
|
152,985 |
<p>And how do you keep them in synch between test and production environments?</p>
<p>When it comes to indexes on database tables, my philosophy is that they are an integral part of writing any code that queries the database. You can't introduce new queries or change a query without analyzing the impact to the indexes.</p>
<p>So I do my best to keep my indexes in synch betweeen all of my environments, but to be honest, I'm not doing very well at automating this. It's a sort of haphazard, manual process.</p>
<p>I periodocally review index stats and delete unnecessary indexes. I usually do this by creating a delete script that I then copy back to the other environments.</p>
<p>But here and there indexes get created and deleted outside of the normal process and it's really tough to see where the differences are.</p>
<p>I've found one thing that really helps is to go with simple, numeric index names, like </p>
<pre><code>idx_t_01
idx_t_02
</code></pre>
<p>where t is a short abbreviation for a table. I find index maintenance impossible when I try to get clever with all the columns involved, like, </p>
<pre><code>idx_c1_c2_c5_c9_c3_c11_5
</code></pre>
<p>It's too hard to differentiate indexes like that.</p>
<p>Does anybody have a really good way to integrate index maintenance into source control and the development lifecycle?</p>
|
[
{
"answer_id": 152999,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, <em>any</em> DML or DDL changes are scripted and checked in to source control, mostly thru activerecord migrations in rails. I hate to continually toot rails' horn, but in many years of building DB-based systems I find the migration route to be so much better than any home-grown system I've used or built.</p>\n\n<p>However, I do name all my indexes (don't let the DBMS come up with whatever crazy name it picks). <strong>Don't prefix them</strong>, that's silly (because you have type metadata in sysobjects, or in whatever db you have), but I do include the table name and columns, e.g. tablename_col1_col2. </p>\n\n<p>That way if I'm browsing sysobjects I can easily see the indexes for a particular table (also it's a force of habit, wayyyy back in the day on some dBMS I used, index names were unique across the whole DB, so the only way to ensure that is to use unique names).</p>\n"
},
{
"answer_id": 153003,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 4,
"selected": false,
"text": "<p>Indexes are a part of the database schema and hence should be source controlled along with everything else. Nobody should go around creating indexes on production without going through the normal QA and release process- particularly performance testing.</p>\n\n<p>There have been numerous other threads on schema versioning.</p>\n"
},
{
"answer_id": 153004,
"author": "Georgi",
"author_id": 13209,
"author_profile": "https://Stackoverflow.com/users/13209",
"pm_score": 0,
"selected": false,
"text": "<p>I do not put my indexes in source control but the creation script of the indexes. ;-)</p>\n\n<p>Index-naming:</p>\n\n<ul>\n<li>IX_CUSTOMER_NAME for the field \"name\" in the table \"customer\"</li>\n<li>PK_CUSTOMER_ID for the primary key,</li>\n<li>UI_CUSTOMER_GUID, for the GUID-field of the customer which is unique (therefore the \"UI\" - unique index).</li>\n</ul>\n"
},
{
"answer_id": 153007,
"author": "Stewart Johnson",
"author_id": 6408,
"author_profile": "https://Stackoverflow.com/users/6408",
"pm_score": 3,
"selected": false,
"text": "<p>The full schema for your database should be in source control right beside your code. When I say \"full schema\" I mean table definitions, queries, stored procedures, indexes, the whole lot.</p>\n\n<p>When doing a fresh installation, then you do:\n- check out version X of the product.\n- from the \"database\" directory of your checkout, run the database script(s) to create your database.\n- use the codebase from your checkout to interact with the database.</p>\n\n<p>When you're developing, every developer should be working against their own private database instance. When they make schema changes they checkin a new set of schema definition files that work against their revised codebase.</p>\n\n<p>With this approach you never have codebase-database sync issues.</p>\n"
},
{
"answer_id": 153008,
"author": "Taptronic",
"author_id": 14728,
"author_profile": "https://Stackoverflow.com/users/14728",
"pm_score": 0,
"selected": false,
"text": "<p>I always source-control SQL (DDL, DML, etc). Its code like any other. Its good practice.</p>\n"
},
{
"answer_id": 153011,
"author": "Tundey",
"author_id": 1453,
"author_profile": "https://Stackoverflow.com/users/1453",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure indexes should be the same across different environments since they have different data sizes. Unless your test and production environments have the same exact data, the indexes would be different. </p>\n\n<p>As to whether they belong in source control, am not really sure.</p>\n"
},
{
"answer_id": 153027,
"author": "joev",
"author_id": 3449,
"author_profile": "https://Stackoverflow.com/users/3449",
"pm_score": 1,
"selected": false,
"text": "<p>I think there are two issues here: the index naming convention, and adding database changes to your source control/lifecycle. I'll tackle the latter issue.</p>\n\n<p>I've been a Java programmer for a long time now, but have recently been introduced to a system that uses Ruby on Rails for database access for part of the system. One thing that I like about RoR is the notion of \"migrations\". Basically, you have a directory full of files that look like 001_add_foo_table.rb, 002_add_bar_table.rb, 003_add_blah_column_to_foo.rb, etc. These Ruby source files extend a parent class, overriding methods called \"up\" and \"down\". The \"up\" method contains the set of database changes that need to be made to bring the previous version of the database schema to the current version. Similarly, the \"down\" method reverts the change back to the previous version. When you want to set the schema for a specific version, the Rails migration scripts check the database to see what the current version is, then finds the .rb files that get you from there up (or down) to the desired revision.</p>\n\n<p>To make this part of your development process, you can check these into source control, and season to taste.</p>\n\n<p>There's nothing specific or special about Rails here, just that it's the first time I've seen this technique widely used. You can probably use pairs of SQL DDL files, too, like 001_UP_add_foo_table.sql and 001_DOWN_remove_foo_table.sql. The rest is a small matter of shell scripting, an exercise left to the reader.</p>\n"
},
{
"answer_id": 153030,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 0,
"selected": false,
"text": "<p>On my current project, I have two things in source control - a full dump of an empty database (using pg_dump -c so it has all the ddl to create tables and indexes) and a script that determines what version of the database you have, and applies alters/drops/adds to bring it up to the current version. The former is run when we're installing on a new site, and also when QA is starting a new round of testing, and the latter is run at every upgrade. When you make database changes, you're required to update both of those files.</p>\n"
},
{
"answer_id": 153031,
"author": "Daniel Honig",
"author_id": 1129162,
"author_profile": "https://Stackoverflow.com/users/1129162",
"pm_score": 0,
"selected": false,
"text": "<p>Using a grails app the indexes are stored in source control by default since you are defining the index definition inside of a file that represents your domain object. Just offering the 'Grails' perspective as an FYI.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] |
And how do you keep them in synch between test and production environments?
When it comes to indexes on database tables, my philosophy is that they are an integral part of writing any code that queries the database. You can't introduce new queries or change a query without analyzing the impact to the indexes.
So I do my best to keep my indexes in synch betweeen all of my environments, but to be honest, I'm not doing very well at automating this. It's a sort of haphazard, manual process.
I periodocally review index stats and delete unnecessary indexes. I usually do this by creating a delete script that I then copy back to the other environments.
But here and there indexes get created and deleted outside of the normal process and it's really tough to see where the differences are.
I've found one thing that really helps is to go with simple, numeric index names, like
```
idx_t_01
idx_t_02
```
where t is a short abbreviation for a table. I find index maintenance impossible when I try to get clever with all the columns involved, like,
```
idx_c1_c2_c5_c9_c3_c11_5
```
It's too hard to differentiate indexes like that.
Does anybody have a really good way to integrate index maintenance into source control and the development lifecycle?
|
Indexes are a part of the database schema and hence should be source controlled along with everything else. Nobody should go around creating indexes on production without going through the normal QA and release process- particularly performance testing.
There have been numerous other threads on schema versioning.
|
153,021 |
<p>I need to generate an XML file in C#.</p>
<p>I want to write the code that generates this in a file that is mostly XML with code inside of it as I can in an ASP.NET MVC page. </p>
<p>So I want a code file that looks like:</p>
<pre><code><lots of angle brackets...>
<% foreach(data in myData)
{ %>
< <%= data.somefield %>
<% } %>
More angle brackets>
</code></pre>
<p>This would generate my XML file. I would not mind using part of <code>System.Web</code> if someone tells me how I can do it without IIS overhead or kludging a generation of a web file.</p>
<p><strong>I want to use templating and I want templating that is similar to ASP.NET</strong></p>
|
[
{
"answer_id": 153172,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": -1,
"selected": false,
"text": "<p>Create a PageView in a standard ASPX file, but don't include a master or anything else. Just start putting in the angle brackets and everything else. The one thing you will need to do is set the content type. But that can be done in your action by calling Response.ContentType = \"text/xml\";</p>\n"
},
{
"answer_id": 153175,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": -1,
"selected": false,
"text": "<p>There is an XSLT View Enging in MvcContrib here:\n<a href=\"http://mvccontrib.googlecode.com/svn/trunk/src/MvcContrib.XsltViewEngine/\" rel=\"nofollow noreferrer\">http://mvccontrib.googlecode.com/svn/trunk/src/MvcContrib.XsltViewEngine/</a></p>\n\n<p>This can probably give you what you need.</p>\n\n<p>(any of the view engines will work, actually... though the WebForms view engine will complain that what you're writing isn't valid HTML.</p>\n"
},
{
"answer_id": 153208,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>First off, its MUCH easier to generate XML using XElements. There are many examples floating around. Just search for \"Linq to XML.\"</p>\n\n<p>Alternatively, if you absolutely need to do templating, I'd suggest using a template engine such as <a href=\"http://sourceforge.net/projects/nvelocity/\" rel=\"nofollow noreferrer\">NVelocity</a> rather than trying to kludge ASP.NET into doing it for you.</p>\n"
},
{
"answer_id": 153232,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": -1,
"selected": false,
"text": "<p>The simplest way of doing this from code would be using the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.aspx\" rel=\"nofollow noreferrer\">XMLWriter</a> class in System.Xml.</p>\n\n<p>Tutorial <a href=\"http://msdn.microsoft.com/en-us/library/4d1k42hb.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code>XmlWriterSettings settings = new XmlWriterSettings();\nsettings.Indent = true;\nsettings.IndentChars = (\" \");\nusing (XmlWriter writer = XmlWriter.Create(\"books.xml\", settings))\n{\n // Write XML data.\n writer.WriteStartElement(\"book\");\n writer.WriteElementString(\"price\", \"19.95\");\n writer.WriteEndElement();\n writer.Flush();\n}\n</code></pre>\n"
},
{
"answer_id": 153393,
"author": "Murph",
"author_id": 1070,
"author_profile": "https://Stackoverflow.com/users/1070",
"pm_score": 0,
"selected": false,
"text": "<p>Further to the above - use the new XML classes delivered with Linq - they make generation of XML in a logical fashion much much easier though you won't get down to something akin to a template in C#.</p>\n\n<p>If you really need something template like then - and I know that this won't necessarily go down well - you should look at doing this part of the system in VB.NET which <em>does</em> have explicit support for template like XML generation as part of its Linq to XML implementation. At the very least you should look at what VB.NET offers before dismissing it.</p>\n\n<p>The nature of .NET means that you don't have to use VB.NET for anything else, you can limit it to the class(es) necessary to do the XML generation and its \"generic\" in the sense that it comes with .NET and the surrounding logic should be comprehensible to any competent .NET programmer.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5189/"
] |
I need to generate an XML file in C#.
I want to write the code that generates this in a file that is mostly XML with code inside of it as I can in an ASP.NET MVC page.
So I want a code file that looks like:
```
<lots of angle brackets...>
<% foreach(data in myData)
{ %>
< <%= data.somefield %>
<% } %>
More angle brackets>
```
This would generate my XML file. I would not mind using part of `System.Web` if someone tells me how I can do it without IIS overhead or kludging a generation of a web file.
**I want to use templating and I want templating that is similar to ASP.NET**
|
First off, its MUCH easier to generate XML using XElements. There are many examples floating around. Just search for "Linq to XML."
Alternatively, if you absolutely need to do templating, I'd suggest using a template engine such as [NVelocity](http://sourceforge.net/projects/nvelocity/) rather than trying to kludge ASP.NET into doing it for you.
|
153,023 |
<p>I'm using C# and Microsoft.Jet.OLEDB.4.0 provider to insert rows into an Access mdb.</p>
<p>Yes, I know Access sucks. It's a huge legacy app, and everything else works OK.</p>
<p>The table has an autonumber column. I insert the rows, but the autonumber column is set to zero.</p>
<p>I Googled the question and read all the articles I could find on this subject. One suggested inserting -1 for the autonumber column, but this didn't work. None of the other suggestions I could find worked.</p>
<p>I am using OleDbParameter's, not concatenating a big SQL text string.</p>
<p>I've tried the insert with and without a transaction. No difference.</p>
<p>How do I get this insert to work (i.e. set the autonumber column contents correctly)?</p>
<p>Thanks very much in advance,</p>
<p>Adam Leffert</p>
|
[
{
"answer_id": 153041,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>When doing the insert, you need to be sure that you are NOT specifying a value for the AutoNumber column. Just like in SQL Server you don't insert a value for an identity column.</p>\n"
},
{
"answer_id": 157815,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 3,
"selected": true,
"text": "<p>In Access it is possible to INSERT an explicit value into an IDENTITY (a.k.a. Automnumber) column. If you (or your middleware) is writing the value zero to the IDENTITY column and there is no unique constraint on the IDENTITY column then that might explain it. </p>\n\n<p>Just to be clear you should be using the syntax </p>\n\n<pre><code>INSERT INTO (<column list>) ... \n</code></pre>\n\n<p>and the column list should omit the IDENTITY column. Jet SQL will allow you to omit the entire column list but then implicitly <em>include</em> the IDENTITY column. Therefore you should use the INSERT INTO () syntax to explicitly omit the IDENTITY column.</p>\n\n<p>In Access/Jet, you can write explicit values to the IDENTITY column, in which case the value will obviously not be auto-generated. Therefore, ensure both you and your middleware (ADO.NET etc) are not explicitly writing a zero value to the IDENTITY column.</p>\n\n<p>BTW just for the IDENTITY column in the below table will auto-generate the value zero every second INSERT:</p>\n\n<pre><code>CREATE Table Test1 \n(\n ID INTEGER IDENTITY(0, -2147483648) NOT NULL, \n data_col INTEGER\n);\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6783/"
] |
I'm using C# and Microsoft.Jet.OLEDB.4.0 provider to insert rows into an Access mdb.
Yes, I know Access sucks. It's a huge legacy app, and everything else works OK.
The table has an autonumber column. I insert the rows, but the autonumber column is set to zero.
I Googled the question and read all the articles I could find on this subject. One suggested inserting -1 for the autonumber column, but this didn't work. None of the other suggestions I could find worked.
I am using OleDbParameter's, not concatenating a big SQL text string.
I've tried the insert with and without a transaction. No difference.
How do I get this insert to work (i.e. set the autonumber column contents correctly)?
Thanks very much in advance,
Adam Leffert
|
In Access it is possible to INSERT an explicit value into an IDENTITY (a.k.a. Automnumber) column. If you (or your middleware) is writing the value zero to the IDENTITY column and there is no unique constraint on the IDENTITY column then that might explain it.
Just to be clear you should be using the syntax
```
INSERT INTO (<column list>) ...
```
and the column list should omit the IDENTITY column. Jet SQL will allow you to omit the entire column list but then implicitly *include* the IDENTITY column. Therefore you should use the INSERT INTO () syntax to explicitly omit the IDENTITY column.
In Access/Jet, you can write explicit values to the IDENTITY column, in which case the value will obviously not be auto-generated. Therefore, ensure both you and your middleware (ADO.NET etc) are not explicitly writing a zero value to the IDENTITY column.
BTW just for the IDENTITY column in the below table will auto-generate the value zero every second INSERT:
```
CREATE Table Test1
(
ID INTEGER IDENTITY(0, -2147483648) NOT NULL,
data_col INTEGER
);
```
|
153,035 |
<p>I've got two tables:</p>
<pre><code>Employees:
uid (number) | first_name (string) | last_name (string) | ...
Projects:
uid | project_title (string) | point_of_contact_id (FK: Employees.uid) | ...
</code></pre>
<p>I'd like to create a form for Projects with a "Point of Contact" combo box (dropdown) field. The display values should be "first_name last_name" but the backing data is the UID. How do I set up the form to show one thing to the user and save another thing to the table?</p>
<p>I'd be fine with only being able to show one field (just "first_name" for example), since I can create a view with a full_name field.</p>
<p><em>Later:</em></p>
<p>If there is a way to do this at the table design level, I would prefer that, since then I would only have to set a setting per UID column (and there are <em>many</em> tables), rather than one setting per UID field (and there are <em>many</em> forms, each with several UID fields).</p>
|
[
{
"answer_id": 153080,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 4,
"selected": true,
"text": "<p>According to <a href=\"http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=124842\" rel=\"noreferrer\">the bug report</a> this is a known issue, still not fixed and there is no workaround.</p>\n"
},
{
"answer_id": 153088,
"author": "Scott Bennett-McLeish",
"author_id": 1915,
"author_profile": "https://Stackoverflow.com/users/1915",
"pm_score": -1,
"selected": false,
"text": "<p>This happens to me also, but it is most notable when I'm connecting to different servers. If you connect to the same server every time then it should remember your password every time.</p>\n\n<p>Maybe one day, SP3 perhaps, Microsoft will release a nice fix for this somewhat continuous annoyance.</p>\n"
},
{
"answer_id": 2676630,
"author": "Travis Laborde",
"author_id": 117460,
"author_profile": "https://Stackoverflow.com/users/117460",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a workaround that I've used. It's lame, but in the absence of a real fix, this works for me!</p>\n\n<p>Add another <strong>hostname</strong> for the server. An example of this would be, if you are trying to get it to remember the name for \"<strong><em>coolserver1</em></strong>\" then create yourself a hostname that resolves to the same server but by a different name, perhaps \"<strong><em>mycoolserver</em></strong>\" or something like that.</p>\n\n<p>You can do that by adding an entry to your hostfile (c:\\windows\\system32\\drivers\\ets\\hosts), or by some DNS or other Windows/AD trickery. The point being that you can now address that server by a new \"name.\"</p>\n\n<p>Then, use that new name in the connect dialog, with your name/password, and hit the \"remember me\" checkbox, and it really will remember you :)</p>\n\n<p>Enjoy!</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
I've got two tables:
```
Employees:
uid (number) | first_name (string) | last_name (string) | ...
Projects:
uid | project_title (string) | point_of_contact_id (FK: Employees.uid) | ...
```
I'd like to create a form for Projects with a "Point of Contact" combo box (dropdown) field. The display values should be "first\_name last\_name" but the backing data is the UID. How do I set up the form to show one thing to the user and save another thing to the table?
I'd be fine with only being able to show one field (just "first\_name" for example), since I can create a view with a full\_name field.
*Later:*
If there is a way to do this at the table design level, I would prefer that, since then I would only have to set a setting per UID column (and there are *many* tables), rather than one setting per UID field (and there are *many* forms, each with several UID fields).
|
According to [the bug report](http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=124842) this is a known issue, still not fixed and there is no workaround.
|
153,046 |
<p>Ok, this probably has a really simple answer, but I've never tried to do it before: How do you launch a web page from within an app? You know, "click here to go to our FAQ", and when they do it launches their default web browser and goes to your page. I'm working in C/C++ in Windows, but if there's a broader, more portable way to do it I'd like to know that, too.</p>
|
[
{
"answer_id": 153050,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 2,
"selected": false,
"text": "<p>I believe you want to use the ShellExecute() function which should respect the users choice of default browser.</p>\n"
},
{
"answer_id": 153058,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 5,
"selected": true,
"text": "<pre><code>#include <windows.h>\n\nvoid main()\n{\n ShellExecute(NULL, \"open\", \"http://yourwebpage.com\",\n NULL, NULL, SW_SHOWNORMAL);\n}\n</code></pre>\n"
},
{
"answer_id": 153059,
"author": "zakker",
"author_id": 23783,
"author_profile": "https://Stackoverflow.com/users/23783",
"pm_score": 2,
"selected": false,
"text": "<p>You can use ShellExecute function.\nSample code:</p>\n\n<pre><code>ShellExecute( NULL, \"open\", \"http://stackoverflow.com\", \"\", \".\", SW_SHOWDEFAULT );\n</code></pre>\n"
},
{
"answer_id": 153398,
"author": "twk",
"author_id": 23524,
"author_profile": "https://Stackoverflow.com/users/23524",
"pm_score": 2,
"selected": false,
"text": "<p>Please read the <a href=\"http://msdn.microsoft.com/en-us/library/bb762153.aspx\" rel=\"nofollow noreferrer\">docs</a> for ShellExecute closely. To really bulletproof your code, they recommend initializing COM. See the docs here, and look for the part that says \"COM should be initialized as shown here\". The short answer is to do this (if you haven't already init'd COM): </p>\n\n<p>CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)</p>\n"
},
{
"answer_id": 6546609,
"author": "nico",
"author_id": 824666,
"author_profile": "https://Stackoverflow.com/users/824666",
"pm_score": 2,
"selected": false,
"text": "<p>For the record (since you asked for a cross-platform option), the following works well in Linux:</p>\n\n<pre><code>#include <unistd.h>\n#include <stdlib.h>\n\nvoid launch(const std::string &url)\n{\n std::string browser = getenv(\"BROWSER\");\n if(browser == \"\") return;\n\n char *args[3];\n args[0] = (char*)browser.c_str();\n args[1] = (char*)url.c_str();\n args[2] = 0;\n\n pid_t pid = fork();\n if(!pid)\n execvp(browser.c_str(), args);\n}\n</code></pre>\n\n<p>Use as:</p>\n\n<pre><code>launch(\"http://example.com\");\n</code></pre>\n"
},
{
"answer_id": 30325779,
"author": "Sig Gam",
"author_id": 4916201,
"author_profile": "https://Stackoverflow.com/users/4916201",
"pm_score": 1,
"selected": false,
"text": "<p>For some reason, ShellExecute do not work sometimes if application is about to terminate right after call it. We've added Sleep(5000) after ShellExecute and it helps.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
] |
Ok, this probably has a really simple answer, but I've never tried to do it before: How do you launch a web page from within an app? You know, "click here to go to our FAQ", and when they do it launches their default web browser and goes to your page. I'm working in C/C++ in Windows, but if there's a broader, more portable way to do it I'd like to know that, too.
|
```
#include <windows.h>
void main()
{
ShellExecute(NULL, "open", "http://yourwebpage.com",
NULL, NULL, SW_SHOWNORMAL);
}
```
|
153,048 |
<p>I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them.</p>
<p>The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface. </p>
<p>What's the best way around this? Should I just use instance methods (which seems wrong) or is there another solution?</p>
|
[
{
"answer_id": 153056,
"author": "Grundlefleck",
"author_id": 4120,
"author_profile": "https://Stackoverflow.com/users/4120",
"pm_score": 6,
"selected": true,
"text": "<p>I would use a method object pattern. Have a static instance of this, and call it in the static method. It should be possible to subclass for testing, depending on your mocking framework.</p>\n\n<p>i.e. in your class with the static method have:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>private static final MethodObject methodObject = new MethodObject();\n\npublic static void doSomething(){\n methodObject.doSomething();\n}\n</code></pre>\n\n<p>and your method object can be a very simple, easily-tested:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class MethodObject {\n public void doSomething() {\n // do your thang\n }\n}\n</code></pre>\n"
},
{
"answer_id": 153067,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "<p>Yes, you use instance methods. Static methods basically say, \"There is one way to accomplish this functionality - it's not polymorphic.\" Mocking relies on polymorphism.</p>\n\n<p>Now, if your static methods logically don't care about what implementation you're using, they might be able to take the interfaces as parameters, or perhaps work without interacting with state at all - but otherwise you should be using instances (and probably dependency injection to wire everything together).</p>\n"
},
{
"answer_id": 153073,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "<p>Use instance methods where possible.</p>\n\n<p>Use public static Func[T, U] (static function references that can be substituted for mock functions) where instance methods are not possible.</p>\n"
},
{
"answer_id": 153119,
"author": "Carlton Jenke",
"author_id": 1215,
"author_profile": "https://Stackoverflow.com/users/1215",
"pm_score": 3,
"selected": false,
"text": "<p>You might be trying to test at too deep a starting point. A test does not need to be created to test each and every method individually; private and static methods should be tested by calling the public methods that then call the private and static ones in turn.</p>\n\n<p>So lets say your code is like this:</p>\n\n<pre><code>public object GetData()\n{\n object obj1 = GetDataFromWherever();\n object obj2 = TransformData(obj1);\n return obj2;\n} \nprivate static object TransformData(object obj)\n{\n//Do whatever\n}\n</code></pre>\n\n<p>You do not need to write a test against the TransformData method (and you can't). Instead write a test for the GetData method that tests the work done in TransformData.</p>\n"
},
{
"answer_id": 153128,
"author": "Rick Minerich",
"author_id": 9251,
"author_profile": "https://Stackoverflow.com/users/9251",
"pm_score": 5,
"selected": false,
"text": "<p>I found a <a href=\"http://www.lnbogen.com/2007/07/04/how-to-mock-static-class-or-static-member-for-testing/\" rel=\"noreferrer\">blog via google</a> with some great examples on how to do this:</p>\n\n<ol>\n<li><p>Refactor class to be an instance class and implement an interface.</p>\n\n<p>You have already stated that you don't want to do this.</p></li>\n<li><p>Use a wrapper instance class with delegates for static classes members</p>\n\n<p>Doing this you can simulate a static interface via delegates.</p></li>\n<li><p>Use a wrapper instance class with protected members which call the static class</p>\n\n<p>This is probably the easiest to mock/manage without refactoring as it can just be inherited from and extended. </p></li>\n</ol>\n"
},
{
"answer_id": 153195,
"author": "asterite",
"author_id": 20459,
"author_profile": "https://Stackoverflow.com/users/20459",
"pm_score": 0,
"selected": false,
"text": "<p>A simple solution is to allow to change the static class's implementation via a setter:</p>\n\n<pre><code>class ClassWithStatics {\n\n private IClassWithStaticsImpl implementation = new DefaultClassWithStaticsImpl();\n\n // Should only be invoked for testing purposes\n public static void overrideImplementation(IClassWithStaticsImpl implementation) {\n ClassWithStatics.implementation = implementation;\n }\n\n public static Foo someMethod() {\n return implementation.someMethod();\n }\n\n}\n</code></pre>\n\n<p>So in the setup of your tests, you call <code>overrideImplementation</code> with some mocked interface. The benefit is that you don't need to change clients of your static class. The downside is that you probably will have a little duplicated code, because you'll have to repeat the methods of the static class and it's implementation. But some times the static methods can use a ligther interface which provide base funcionality.</p>\n"
},
{
"answer_id": 1133040,
"author": "dstarh",
"author_id": 138883,
"author_profile": "https://Stackoverflow.com/users/138883",
"pm_score": 0,
"selected": false,
"text": "<p>The problem you have is when you're using 3rd party code and it's called from one of your methods. What we ended up doing is wrapping it in an object, and calling passing it in with dep inj, and then your unit test can mock 3rd party static method call the setter with it.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4219/"
] |
I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them.
The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface.
What's the best way around this? Should I just use instance methods (which seems wrong) or is there another solution?
|
I would use a method object pattern. Have a static instance of this, and call it in the static method. It should be possible to subclass for testing, depending on your mocking framework.
i.e. in your class with the static method have:
```cs
private static final MethodObject methodObject = new MethodObject();
public static void doSomething(){
methodObject.doSomething();
}
```
and your method object can be a very simple, easily-tested:
```cs
public class MethodObject {
public void doSomething() {
// do your thang
}
}
```
|
153,053 |
<h2>The problem:</h2>
<p>We use a program written by our biggest customer to receive orders, book tranports and do other order-related stuff. We have no other chance but to use the program and the customer is very unsupportive when it comes to problems with their program. We just have to live with the program.</p>
<p>Now this program is most of the time extremely slow when using it with two or more user so I tried to look behind the curtain and find the source of the problem.</p>
<h2>Some points about the program I found out so far:</h2>
<ul>
<li>It's written in VB 6.0</li>
<li>It uses a password-protected Access-DB (Access 2000 MDB) that is located a folder on one user's machine.</li>
<li>That folder is shared over the network and used by all other users.</li>
<li>It uses the msjet40.dll version 4.00.9704 to communicate with access. I guess it's ADO?</li>
</ul>
<p>I also used <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="noreferrer">Process Monitor</a> to monitor file access and found out why the program is so slow: it is doing thousands of read operations on the mdb-file, even when the program is idle. Over the network this is of course tremendously slow:</p>
<p><a href="http://img217.imageshack.us/img217/1456/screenshothw5.png" rel="noreferrer">Process Monitor Trace http://img217.imageshack.us/img217/1456/screenshothw5.png</a></p>
<h2>The real question:</h2>
<p>Is there any way to monitor the queries that are responsible for the read activity? Is there a trace flag I can set? Hooking the JET DLL's? I guess the program is doing some expensive queries that are causing JET to read lots of data in the process.</p>
<p>PS: I already tried to put the mdb on our company's file server with the success that accessing it was even slower than over the local share. I also tried changing the locking mechanisms (opportunistic locking) on the client with no success.</p>
<p>I want to know what's going on and need some hard facts and suggestions for our customer's developer to help him/her make the programm faster.</p>
|
[
{
"answer_id": 167409,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": -1,
"selected": false,
"text": "<p>It is not possible without the help of the developers. Sorry.</p>\n"
},
{
"answer_id": 168993,
"author": "Tim Lara",
"author_id": 3469,
"author_profile": "https://Stackoverflow.com/users/3469",
"pm_score": 0,
"selected": false,
"text": "<p>First question: Do you have a copy of MS Access 2000 or better?</p>\n\n<p>If so:\nWhen you say the MDB is \"password protected\", do you mean that when you try to open it using MS Access you get a prompt for a password only, or does it prompt you for a user name and password? (Or give you an error message that says, \"You do not have the necessary permissions to use the foo.mdb object.\"?)</p>\n\n<p>If it's the latter, (user-level security), look for a corresponding .MDW file that goes along with the MDB. If you find it, this is the \"workgroup information file\" that is used as a \"key\" for opening the MDB. Try making a desktop shortcut with a target like:</p>\n\n<pre><code>\"Path to MSACCESS.EXE\" \"Path To foo.mdb\" /wrkgrp \"Path to foo.mdw\"\n</code></pre>\n\n<p>MS Access should then prompt you for your user name and password which is (hopefully) the same as what the VB6 app asks you for. This would at least allow you to open the MDB file and look at the table structure to see if there are any obvious design flaws.</p>\n\n<p>Beyond that, as far as I know, Eduardo is correct that you pretty much need to be able to run a debugger on the developer's source code to find out exactly what the real-time queries are doing...</p>\n"
},
{
"answer_id": 518279,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 1,
"selected": false,
"text": "<p>Could you not throw a packet sniffer (like Wireshark) on the network and watch the traffic between one user and the host machine?</p>\n"
},
{
"answer_id": 518318,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 1,
"selected": false,
"text": "<p>If it uses an ODBC connection you can enable logging for that.</p>\n\n<ol>\n<li>Start ODBC Data Source Administrator.</li>\n<li>Select the Tracing tab</li>\n<li>Select the Start Tracing Now button.</li>\n<li>Select Apply or OK.</li>\n<li>Run the app for awhile.</li>\n<li>Return to ODBC Administrator.</li>\n<li>Select the Tracing tab.</li>\n<li>Select the Stop Tracing Now button.</li>\n<li>The trace can be viewed in the location that you initially specified in the Log file Path box.</li>\n</ol>\n"
},
{
"answer_id": 781916,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>To get your grubby hands on exactly what Access is doing query-wise behind the scenes there's an undocumented feature called JETSHOWPLAN - when switched on in the registry it creates a <code>showplan.out</code> text file. The details are in \n<a href=\"https://www.techrepublic.com/article/use-microsoft-jets-showplan-to-write-more-efficient-queries/\" rel=\"nofollow noreferrer\">this TechRepublic article</a> <a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-22-5064388.html\" rel=\"nofollow noreferrer\">alternate</a>, summarized here:</p>\n\n<blockquote>\n <p>The ShowPlan option was added to Jet 3.0, and produces a text file\n that contains the query's plan. (ShowPlan doesn't support subqueries.)\n You must enable it by adding a Debug key to the registry like so:</p>\n\n<pre><code>\\\\HKEY_LOCAL_MACHINE\\SOFTWARE\\MICROSOFT\\JET\\4.0\\Engines\\Debug\n</code></pre>\n \n <p>Under the new Debug key, add a string data type named <code>JETSHOWPLAN</code>\n (you must use all uppercase letters). Then, add the key value <code>ON</code> to\n enable the feature. If Access has been running in the background, you\n must close it and relaunch it for the function to work.</p>\n \n <p>When ShowPlan is enabled, Jet creates a text file named <code>SHOWPLAN.OUT</code>\n (which might end up in your <code>My Documents</code> folder or the current\n default folder, depending on the version of Jet you're using) every\n time Jet compiles a query. You can then view this text file for clues\n to how Jet is running your queries. </p>\n \n <p>We recommend that you disable this feature by changing the key's value\n to <code>OFF</code> unless you're specifically using it. Jet appends the plan to\n an existing file and eventually, the process actually slows things\n down. Turn on the feature only when you need to review a specific\n query plan. Open the database, run the query, and then disable the\n feature.</p>\n</blockquote>\n\n<p>For tracking down nightmare problems it's unbeatable - it's the sort of thing you get on your big expensive industrial databases - this feature is cool - it's lovely and fluffy - it's my friend… ;-)</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21038/"
] |
The problem:
------------
We use a program written by our biggest customer to receive orders, book tranports and do other order-related stuff. We have no other chance but to use the program and the customer is very unsupportive when it comes to problems with their program. We just have to live with the program.
Now this program is most of the time extremely slow when using it with two or more user so I tried to look behind the curtain and find the source of the problem.
Some points about the program I found out so far:
-------------------------------------------------
* It's written in VB 6.0
* It uses a password-protected Access-DB (Access 2000 MDB) that is located a folder on one user's machine.
* That folder is shared over the network and used by all other users.
* It uses the msjet40.dll version 4.00.9704 to communicate with access. I guess it's ADO?
I also used [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) to monitor file access and found out why the program is so slow: it is doing thousands of read operations on the mdb-file, even when the program is idle. Over the network this is of course tremendously slow:
[Process Monitor Trace http://img217.imageshack.us/img217/1456/screenshothw5.png](http://img217.imageshack.us/img217/1456/screenshothw5.png)
The real question:
------------------
Is there any way to monitor the queries that are responsible for the read activity? Is there a trace flag I can set? Hooking the JET DLL's? I guess the program is doing some expensive queries that are causing JET to read lots of data in the process.
PS: I already tried to put the mdb on our company's file server with the success that accessing it was even slower than over the local share. I also tried changing the locking mechanisms (opportunistic locking) on the client with no success.
I want to know what's going on and need some hard facts and suggestions for our customer's developer to help him/her make the programm faster.
|
To get your grubby hands on exactly what Access is doing query-wise behind the scenes there's an undocumented feature called JETSHOWPLAN - when switched on in the registry it creates a `showplan.out` text file. The details are in
[this TechRepublic article](https://www.techrepublic.com/article/use-microsoft-jets-showplan-to-write-more-efficient-queries/) [alternate](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-22-5064388.html), summarized here:
>
> The ShowPlan option was added to Jet 3.0, and produces a text file
> that contains the query's plan. (ShowPlan doesn't support subqueries.)
> You must enable it by adding a Debug key to the registry like so:
>
>
>
> ```
> \\HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\JET\4.0\Engines\Debug
>
> ```
>
> Under the new Debug key, add a string data type named `JETSHOWPLAN`
> (you must use all uppercase letters). Then, add the key value `ON` to
> enable the feature. If Access has been running in the background, you
> must close it and relaunch it for the function to work.
>
>
> When ShowPlan is enabled, Jet creates a text file named `SHOWPLAN.OUT`
> (which might end up in your `My Documents` folder or the current
> default folder, depending on the version of Jet you're using) every
> time Jet compiles a query. You can then view this text file for clues
> to how Jet is running your queries.
>
>
> We recommend that you disable this feature by changing the key's value
> to `OFF` unless you're specifically using it. Jet appends the plan to
> an existing file and eventually, the process actually slows things
> down. Turn on the feature only when you need to review a specific
> query plan. Open the database, run the query, and then disable the
> feature.
>
>
>
For tracking down nightmare problems it's unbeatable - it's the sort of thing you get on your big expensive industrial databases - this feature is cool - it's lovely and fluffy - it's my friend… ;-)
|
153,054 |
<p>I need to change the app name based on what configuration I'm using in Visual Studio. For example, if I'm in Debug configuration, I want the app name to show as 'App_Debug' in the Application field in the Elmah_Error table. Does anyone have any experience with this? Or is there another way to do it?</p>
|
[
{
"answer_id": 317442,
"author": "JamesEggers",
"author_id": 28540,
"author_profile": "https://Stackoverflow.com/users/28540",
"pm_score": 4,
"selected": true,
"text": "<p>By default, Elmah uses the AppPool's application GUID as the default application name. It uses this as the key to identify the errors in the Elmah_Error table when you look at the web interface that's created through it's HTTP Module. </p>\n\n<p>I was tasked to explore this option for my company earlier this year. I couldn't find a way to manipulate this by default since Elmah pulls the application name from <code>HttpRuntime.AppDomainAppId</code> in the ErrorLog.cs file. You could manipulate it by whatever key you want; however, that is the AppPool's GUID.</p>\n\n<p>With that said, I was able to manipulate the ErrorLog.cs file to turn Elmah into a callable framework instead of a handler based one and allow for me set the ApplicationName. What I ended up doing was modifying ErrorLog.cs to include a property that allowed me to set the name as below:</p>\n\n<pre><code>public virtual string ApplicationName\n{\n get \n {\n if (_applicationName == null) { _applicationName = HttpRuntime.AppDomainAppId; }\n return _applicationName;\n }\n set { _applicationName = value; }\n}\n</code></pre>\n\n<p>What you will probably need to do is adjust this differently and set the ApplicationName not to <code>HttpRuntime.AppDomainAppId</code> but, instead, a value pulled from the web.config. All in all, it's possible. The way I did it enhanced the <code>ErrorLog.Log(ex)</code> method so I could use Elmah has a callable framework beyond web applications. Looking back I wish I did the app/web.config approach instead. </p>\n\n<p>One thing to keep in mind when changing the application name in Elmah. The http handler that generates the /elmah/default.aspx interface will no longer work. I'm still trying to find time to circle back around to such; however, you may need to look into creating a custom interface when implementing.</p>\n"
},
{
"answer_id": 9329364,
"author": "Stephen Kennedy",
"author_id": 397817,
"author_profile": "https://Stackoverflow.com/users/397817",
"pm_score": 6,
"selected": false,
"text": "<p>This can now be done purely in markup. Just add an <code>applicationName</code> attribute to the <code>errorLog</code> element in the <code><elmah></code> section of the web.config file. Example:</p>\n\n<pre><code><errorLog type=\"Elmah.SqlErrorLog, Elmah\" \n connectionStringName=\"connectionString\" applicationName=\"myApp\" />\n</code></pre>\n\n<p>I've tested this and it works both when logging an exception and when viewing the log via <code>Elmah.axd</code>.</p>\n\n<p>In the case of the OP, one would imagine it can be set programatically too but I didn't test that. For me and I imagine for most scenarios the markup approach is sufficient.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] |
I need to change the app name based on what configuration I'm using in Visual Studio. For example, if I'm in Debug configuration, I want the app name to show as 'App\_Debug' in the Application field in the Elmah\_Error table. Does anyone have any experience with this? Or is there another way to do it?
|
By default, Elmah uses the AppPool's application GUID as the default application name. It uses this as the key to identify the errors in the Elmah\_Error table when you look at the web interface that's created through it's HTTP Module.
I was tasked to explore this option for my company earlier this year. I couldn't find a way to manipulate this by default since Elmah pulls the application name from `HttpRuntime.AppDomainAppId` in the ErrorLog.cs file. You could manipulate it by whatever key you want; however, that is the AppPool's GUID.
With that said, I was able to manipulate the ErrorLog.cs file to turn Elmah into a callable framework instead of a handler based one and allow for me set the ApplicationName. What I ended up doing was modifying ErrorLog.cs to include a property that allowed me to set the name as below:
```
public virtual string ApplicationName
{
get
{
if (_applicationName == null) { _applicationName = HttpRuntime.AppDomainAppId; }
return _applicationName;
}
set { _applicationName = value; }
}
```
What you will probably need to do is adjust this differently and set the ApplicationName not to `HttpRuntime.AppDomainAppId` but, instead, a value pulled from the web.config. All in all, it's possible. The way I did it enhanced the `ErrorLog.Log(ex)` method so I could use Elmah has a callable framework beyond web applications. Looking back I wish I did the app/web.config approach instead.
One thing to keep in mind when changing the application name in Elmah. The http handler that generates the /elmah/default.aspx interface will no longer work. I'm still trying to find time to circle back around to such; however, you may need to look into creating a custom interface when implementing.
|
153,062 |
<p>How do I escape '<' and '>' character in sed.</p>
<p>I have some xml files which needs some text between the tags to be replaced. How do I escape the '>' and '<' characters.</p>
<p>The problem with > and < is it has special meaning in the shell to redirect the output to a file. So backslash doesn't work.</p>
|
[
{
"answer_id": 153068,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 0,
"selected": false,
"text": "<p>Escape them with backslash</p>\n"
},
{
"answer_id": 153070,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 0,
"selected": false,
"text": "<p>Just put a backslash before them or enclose them in single or double quotes. On second thought, your question I think needs to be more clear. Are you trying to use sed to process an XML file and you want to get what's between a tag? Then you want:</p>\n\n<pre><code>sed -re 's@(<TAG.*?>).*?(</TAG>)@\\1hi\\2@' test.xml\n</code></pre>\n"
},
{
"answer_id": 153075,
"author": "cnu",
"author_id": 1448,
"author_profile": "https://Stackoverflow.com/users/1448",
"pm_score": 4,
"selected": true,
"text": "<p>Ok. Found out by myself. Use quotes.</p>\n\n<pre><code>$ sed -i \"s/>foo</>bar</g\" file\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] |
How do I escape '<' and '>' character in sed.
I have some xml files which needs some text between the tags to be replaced. How do I escape the '>' and '<' characters.
The problem with > and < is it has special meaning in the shell to redirect the output to a file. So backslash doesn't work.
|
Ok. Found out by myself. Use quotes.
```
$ sed -i "s/>foo</>bar</g" file
```
|
153,065 |
<p>I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void* argument that is converted into suitable type in the function itself. A short example:</p>
<pre><code>void function(MESSAGE_ID id, void* param)
{
if(id == FOO) {
int real_param = (int)param;
// ...
}
}
</code></pre>
<p>Of course, on a 64 bit machine, I get the error:</p>
<pre><code>error: cast from 'void*' to 'int' loses precision
</code></pre>
<p>I would like to correct this so that it still works on a 32 bit machine and as cleanly as possible. Any idea ?</p>
|
[
{
"answer_id": 153077,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 7,
"selected": true,
"text": "<p>Use <code>intptr_t</code> and <code>uintptr_t</code>.</p>\n\n<p>To ensure it is defined in a portable way, you can use code like this:</p>\n\n<pre><code>#if defined(__BORLANDC__)\n typedef unsigned char uint8_t;\n typedef __int64 int64_t;\n typedef unsigned long uintptr_t;\n#elif defined(_MSC_VER)\n typedef unsigned char uint8_t;\n typedef __int64 int64_t;\n#else\n #include <stdint.h>\n#endif\n</code></pre>\n\n<p>Just place that in some .h file and include wherever you need it.</p>\n\n<p>Alternatively, you can download Microsoft’s version of the <code>stdint.h</code> file from <a href=\"http://msinttypes.googlecode.com/svn/trunk/stdint.h">http://msinttypes.googlecode.com/svn/trunk/stdint.h\" rel=\"noreferrer\">here</a> or use a portable one from <a href=\"http://www.azillionmonkeys.com/qed/pstdint.h">http://www.azillionmonkeys.com/qed/pstdint.h\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 153083,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 4,
"selected": false,
"text": "<p>Use <code>uintptr_t</code> as your integer type.</p>\n"
},
{
"answer_id": 153150,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 2,
"selected": false,
"text": "<p>The best thing to do is to avoid converting from pointer type to non-pointer types.\nHowever, this is clearly not possible in your case.</p>\n\n<p>As everyone said, the uintptr_t is what you should use.</p>\n\n<p>This <a href=\"http://developer.apple.com/documentation/Darwin/Conceptual/64bitPorting/MakingCode64-BitClean/chapter_4_section_4.html\" rel=\"nofollow noreferrer\">link</a> has good info about converting to 64-bit code.</p>\n\n<p>There is also a good discussion of this on <a href=\"http://groups.google.com/group/comp.std.c/browse_thread/thread/6bf9aa8c9e7bc523\" rel=\"nofollow noreferrer\">comp.std.c</a></p>\n"
},
{
"answer_id": 153243,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "<p>Several answers have pointed at <code>uintptr_t</code> and <code>#include <stdint.h></code> as 'the' solution. That is, I suggest, part of the answer, but not the whole answer. You also need to look at where the function is called with the message ID of FOO.</p>\n\n<p>Consider this code and compilation:</p>\n\n<pre><code>$ cat kk.c\n#include <stdio.h>\nstatic void function(int n, void *p)\n{\n unsigned long z = *(unsigned long *)p;\n printf(\"%d - %lu\\n\", n, z);\n}\n\nint main(void)\n{\n function(1, 2);\n return(0);\n}\n$ rmk kk\n gcc -m64 -g -O -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith \\\n -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes \\\n -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE kk.c -o kk \nkk.c: In function 'main':\nkk.c:10: warning: passing argument 2 of 'func' makes pointer from integer without a cast\n$\n</code></pre>\n\n<p>You will observe that there is a problem at the calling location (in <code>main()</code>) — converting an integer to a pointer without a cast. You are going to need to analyze your <code>function()</code> in all its usages to see how values are passed to it. The code inside my <code>function()</code> would work if the calls were written:</p>\n\n<pre><code>unsigned long i = 0x2341;\nfunction(1, &i);\n</code></pre>\n\n<p>Since yours are probably written differently, you need to review the points where the function is called to ensure that it makes sense to use the value as shown. Don't forget, you may be finding a latent bug.</p>\n\n<p>Also, if you are going to format the value of the <code>void *</code> parameter (as converted), look carefully at the <code><inttypes.h></code> header (instead of <code>stdint.h</code> — <code>inttypes.h</code> provides the services of <code>stdint.h</code>, which is unusual, but the C99 standard says <em>[t]he header <code><inttypes.h></code> includes the header <code><stdint.h></code> and extends it with\nadditional facilities provided by hosted implementations</em>) and use the PRIxxx macros in your format strings.</p>\n\n<p>Also, my comments are strictly applicable to C rather than C++, but your code is in the subset of C++ that is portable between C and C++. The chances are fair to good that my comments apply.</p>\n"
},
{
"answer_id": 153466,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 5,
"selected": false,
"text": "<p>'size_t' and 'ptrdiff_t' are required to match your architecture (whatever it is). Therefore, I think rather than using 'int', you should be able to use 'size_t', which on a 64 bit system should be a 64 bit type.</p>\n\n<p>This discussion <a href=\"https://stackoverflow.com/questions/131803/unsigned-int-vs-sizet\">unsigned int vs size_t</a> goes into a bit more detail.</p>\n"
},
{
"answer_id": 4143934,
"author": "Michael S.",
"author_id": 342290,
"author_profile": "https://Stackoverflow.com/users/342290",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li><code>#include <stdint.h></code></li>\n<li>Use <code>uintptr_t</code> standard type defined in the included standard header file.</li>\n</ol>\n"
},
{
"answer_id": 8075684,
"author": "Craig Hicks",
"author_id": 1039128,
"author_profile": "https://Stackoverflow.com/users/1039128",
"pm_score": 1,
"selected": false,
"text": "<p>I think the \"meaning\" of void* in this case is a generic handle.\nIt is not a pointer to a value, it is the value itself.\n(This just happens to be how void* is used by C and C++ programmers.)</p>\n\n<p>If it is holding an integer value, it had better be within integer range!</p>\n\n<p>Here is easy rendering to integer:</p>\n\n<pre><code>int x = (char*)p - (char*)0;\n</code></pre>\n\n<p>It should only give a warning.</p>\n"
},
{
"answer_id": 26586211,
"author": "Alexander Oh",
"author_id": 887836,
"author_profile": "https://Stackoverflow.com/users/887836",
"pm_score": 7,
"selected": false,
"text": "<p>I'd say this is the modern C++ way:</p>\n<pre><code>#include <cstdint>\nvoid *p;\nauto i = reinterpret_cast<std::uintptr_t>(p);\n</code></pre>\n<p><strong>EDIT</strong>:</p>\n<h2>The correct type to the the Integer</h2>\n<p>So the right way to store a pointer as an integer is to use the <code>uintptr_t</code> or <code>intptr_t</code> types. (See also in cppreference <a href=\"http://en.cppreference.com/w/c/types/integer\" rel=\"noreferrer\">integer types for C99</a>).</p>\n<p>These types are defined in <code><stdint.h></code> for C99 and in the namespace <code>std</code> for C++11 in <code><cstdint></code> (see <a href=\"http://en.cppreference.com/w/cpp/types/integer\" rel=\"noreferrer\">integer types for C++</a>).</p>\n<p><strong>C++11 (and onwards) Version</strong></p>\n<pre><code>#include <cstdint>\nstd::uintptr_t i;\n</code></pre>\n<p><strong>C++03 Version</strong></p>\n<pre><code>extern "C" {\n#include <stdint.h>\n}\n\nuintptr_t i;\n</code></pre>\n<p><strong>C99 Version</strong></p>\n<pre><code>#include <stdint.h>\nuintptr_t i;\n</code></pre>\n<h2>The correct casting operator</h2>\n<p>In C there is only one cast and using the C cast in C++ is frowned upon (so don't use it in C++). In C++ there are different types of casts, but <code>reinterpret_cast</code> is the correct cast for this conversion (see also <a href=\"http://en.cppreference.com/w/cpp/language/reinterpret_cast\" rel=\"noreferrer\">here</a>).</p>\n<p><strong>C++11 Version</strong></p>\n<pre><code>auto i = reinterpret_cast<std::uintptr_t>(p);\n</code></pre>\n<p><strong>C++03 Version</strong></p>\n<pre><code>uintptr_t i = reinterpret_cast<uintptr_t>(p);\n</code></pre>\n<p><strong>C Version</strong></p>\n<pre><code>uintptr_t i = (uintptr_t)p; // C Version\n</code></pre>\n<h2>Related Questions</h2>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/1845482/what-is-uintptr-t-data-type\">What is uintptr_t data type</a></li>\n</ul>\n"
},
{
"answer_id": 43019398,
"author": "B.Mr.W.",
"author_id": 1953475,
"author_profile": "https://Stackoverflow.com/users/1953475",
"pm_score": 2,
"selected": false,
"text": "<p>I came across this question while studying the source code of <a href=\"https://www.sqlite.org/\" rel=\"nofollow noreferrer\">SQLite</a>. </p>\n\n<p>In the <a href=\"https://github.com/mackyle/sqlite/blob/master/src/sqliteInt.h#L207\" rel=\"nofollow noreferrer\">sqliteInt.h</a>, there is a paragraph of code defined a macro convert between integer and pointer. The author made a very good statement first pointing out it should be a compiler dependent problem and then implemented the solution to account for most of the popular compilers out there. </p>\n\n<pre><code>#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */\n# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))\n# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))\n#elif !defined(__GNUC__) /* Works for compilers other than LLVM */\n# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])\n# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))\n#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */\n# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))\n# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))\n#else /* Generates a warning - but it always works */\n# define SQLITE_INT_TO_PTR(X) ((void*)(X))\n# define SQLITE_PTR_TO_INT(X) ((int)(X))\n#endif\n</code></pre>\n\n<p>And here is a quote of the comment for more details: </p>\n\n<pre><code>/*\n** The following macros are used to cast pointers to integers and\n** integers to pointers. The way you do this varies from one compiler\n** to the next, so we have developed the following set of #if statements\n** to generate appropriate macros for a wide range of compilers.\n**\n** The correct \"ANSI\" way to do this is to use the intptr_t type.\n** Unfortunately, that typedef is not available on all compilers, or\n** if it is available, it requires an #include of specific headers\n** that vary from one machine to the next.\n**\n** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on\n** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).\n** So we have to define the macros in different ways depending on the\n** compiler.\n*/\n</code></pre>\n\n<p>Credit goes to the committers. </p>\n"
},
{
"answer_id": 49330632,
"author": "Antonio",
"author_id": 2436175,
"author_profile": "https://Stackoverflow.com/users/2436175",
"pm_score": 0,
"selected": false,
"text": "<p>Since <code>uintptr_t</code> is <a href=\"https://stackoverflow.com/a/1846648/2436175\">not guaranteed to be there in C++/C++11</a>, if this is a one way conversion you can consider <code>uintmax_t</code>, always defined in <a href=\"http://en.cppreference.com/w/cpp/header/cstdint\" rel=\"nofollow noreferrer\"><code><cstdint></code></a>.</p>\n\n<pre><code>auto real_param = reinterpret_cast<uintmax_t>(param);\n</code></pre>\n\n<p>To play safe, one could add anywhere in the code an assertion:</p>\n\n<pre><code>static_assert(sizeof (uintmax_t) >= sizeof (void *) ,\n \"No suitable integer type for conversion from pointer type\");\n</code></pre>\n"
},
{
"answer_id": 70092093,
"author": "Tomer Shalev",
"author_id": 2779007,
"author_profile": "https://Stackoverflow.com/users/2779007",
"pm_score": 0,
"selected": false,
"text": "<p>With C++11, For what it's worth, suppose you don't have any headers, then define:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template<bool B, class T, class F> struct cond { typedef T type; };\ntemplate<class T, class F> struct cond<false, T, F> { typedef F type;};\nstatic constexpr unsigned int PS = sizeof (void *);\n\nusing uintptr_type = typename cond<\n PS==sizeof(unsigned short), unsigned short ,\n typename cond<\n PS==sizeof(unsigned int), unsigned int,\n typename cond<\n PS==sizeof(unsigned long), unsigned long, unsigned long long>::type>::type>::type;\n\n</code></pre>\n<p>After that you can do the following:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>static uintptr_type ptr_to_int(const void *pointer) { \n return reinterpret_cast<uintptr_type>(pointer); \n}\nstatic void *int_to_ptr(uintptr_type integer) { \n return reinterpret_cast<void *>(integer); \n}\n\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7136/"
] |
I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void\* argument that is converted into suitable type in the function itself. A short example:
```
void function(MESSAGE_ID id, void* param)
{
if(id == FOO) {
int real_param = (int)param;
// ...
}
}
```
Of course, on a 64 bit machine, I get the error:
```
error: cast from 'void*' to 'int' loses precision
```
I would like to correct this so that it still works on a 32 bit machine and as cleanly as possible. Any idea ?
|
Use `intptr_t` and `uintptr_t`.
To ensure it is defined in a portable way, you can use code like this:
```
#if defined(__BORLANDC__)
typedef unsigned char uint8_t;
typedef __int64 int64_t;
typedef unsigned long uintptr_t;
#elif defined(_MSC_VER)
typedef unsigned char uint8_t;
typedef __int64 int64_t;
#else
#include <stdint.h>
#endif
```
Just place that in some .h file and include wherever you need it.
Alternatively, you can download Microsoft’s version of the `stdint.h` file from [here](http://msinttypes.googlecode.com/svn/trunk/stdint.h">http://msinttypes.googlecode.com/svn/trunk/stdint.h) or use a portable one from [here](http://www.azillionmonkeys.com/qed/pstdint.h">http://www.azillionmonkeys.com/qed/pstdint.h).
|
153,087 |
<p>I have a requirement to read and display the owner of a file (for audit purposes), and potentially changing it as well (this is secondary requirement). Are there any nice C# wrappers?</p>
<p>After a quick google, I found only <a href="http://web.archive.org/web/20061116233324/http://www.softinsight.com/bnoyes/PermaLink.aspx?guid=8edc9d4c-0f2c-4006-8186-a3697ebc7476" rel="noreferrer">the WMI solution</a> and a suggestion to PInvoke GetSecurityInfo</p>
|
[
{
"answer_id": 153146,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 7,
"selected": true,
"text": "<p>No need to P/Invoke. <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.getaccesscontrol.aspx\" rel=\"noreferrer\">System.IO.File.GetAccessControl</a> will return a <a href=\"http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesecurity_members.aspx\" rel=\"noreferrer\">FileSecurity</a> object, which has a <a href=\"http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.objectsecurity.getowner.aspx\" rel=\"noreferrer\">GetOwner</a> method.</p>\n\n<p>Edit: Reading the owner is pretty simple, though it's a bit of a cumbersome API:</p>\n\n<pre><code>const string FILE = @\"C:\\test.txt\";\n\nvar fs = File.GetAccessControl(FILE);\n\nvar sid = fs.GetOwner(typeof(SecurityIdentifier));\nConsole.WriteLine(sid); // SID\n\nvar ntAccount = sid.Translate(typeof(NTAccount));\nConsole.WriteLine(ntAccount); // DOMAIN\\username\n</code></pre>\n\n<p>Setting the owner requires a call to SetAccessControl to save the changes. Also, you're still bound by the Windows rules of ownership - you can't assign ownership to another account. You can give take ownership perms, and they have to take ownership.</p>\n\n<pre><code>var ntAccount = new NTAccount(\"DOMAIN\", \"username\");\nfs.SetOwner(ntAccount);\n\ntry {\n File.SetAccessControl(FILE, fs);\n} catch (InvalidOperationException ex) {\n Console.WriteLine(\"You cannot assign ownership to that user.\" +\n \"Either you don't have TakeOwnership permissions, or it is not your user account.\"\n );\n throw;\n}\n</code></pre>\n"
},
{
"answer_id": 58906456,
"author": "Teemo",
"author_id": 6782249,
"author_profile": "https://Stackoverflow.com/users/6782249",
"pm_score": 0,
"selected": false,
"text": "<pre><code>FileInfo fi = new FileInfo(@\"C:\\test.txt\");\nstring user = fi.GetAccessControl().GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363/"
] |
I have a requirement to read and display the owner of a file (for audit purposes), and potentially changing it as well (this is secondary requirement). Are there any nice C# wrappers?
After a quick google, I found only [the WMI solution](http://web.archive.org/web/20061116233324/http://www.softinsight.com/bnoyes/PermaLink.aspx?guid=8edc9d4c-0f2c-4006-8186-a3697ebc7476) and a suggestion to PInvoke GetSecurityInfo
|
No need to P/Invoke. [System.IO.File.GetAccessControl](http://msdn.microsoft.com/en-us/library/system.io.file.getaccesscontrol.aspx) will return a [FileSecurity](http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesecurity_members.aspx) object, which has a [GetOwner](http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.objectsecurity.getowner.aspx) method.
Edit: Reading the owner is pretty simple, though it's a bit of a cumbersome API:
```
const string FILE = @"C:\test.txt";
var fs = File.GetAccessControl(FILE);
var sid = fs.GetOwner(typeof(SecurityIdentifier));
Console.WriteLine(sid); // SID
var ntAccount = sid.Translate(typeof(NTAccount));
Console.WriteLine(ntAccount); // DOMAIN\username
```
Setting the owner requires a call to SetAccessControl to save the changes. Also, you're still bound by the Windows rules of ownership - you can't assign ownership to another account. You can give take ownership perms, and they have to take ownership.
```
var ntAccount = new NTAccount("DOMAIN", "username");
fs.SetOwner(ntAccount);
try {
File.SetAccessControl(FILE, fs);
} catch (InvalidOperationException ex) {
Console.WriteLine("You cannot assign ownership to that user." +
"Either you don't have TakeOwnership permissions, or it is not your user account."
);
throw;
}
```
|
153,123 |
<p>I am looking for pointers to the solution of the following problem: I have a set of rectangles, whose height is known and x-positions also and I want to pack them in the more compact form. With a little drawing (where all rectangles are of the same width, but the width may vary in real life), i would like, instead of. </p>
<pre><code>-r1-
-r2--
-r3--
-r4-
-r5--
</code></pre>
<p>something like.</p>
<pre><code>-r1- -r3--
-r2-- -r4-
-r5--
</code></pre>
<p>All hints will be appreciated. I am not necessarily looking for "the" best solution.</p>
|
[
{
"answer_id": 153357,
"author": "Jasper",
"author_id": 18702,
"author_profile": "https://Stackoverflow.com/users/18702",
"pm_score": 1,
"selected": false,
"text": "<p>Something like this?</p>\n\n<ul>\n<li>Sort your collection of rectangles by x-position </li>\n<li><p>write a method that checks which rectangles are present on a certain interval of the x-axis</p>\n\n<pre><code>Collection<Rectangle> overlaps (int startx, int endx, Collection<Rectangle> rects){\n...\n}\n</code></pre></li>\n<li><p>loop over the collection of rectangles</p>\n\n<pre><code>Collection<Rectangle> toDraw;\nCollection<Rectangle> drawn;\nforeach (Rectangle r in toDraw){\nCollection<Rectangle> overlapping = overlaps (r.x, r.x+r.width, drawn);\nint y = 0;\nforeach(Rectangle overlapRect in overlapping){\ny += overlapRect.height;\n}\ndrawRectangle(y, Rectangle);\ndrawn.add(r);\n}\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 153373,
"author": "twk",
"author_id": 23524,
"author_profile": "https://Stackoverflow.com/users/23524",
"pm_score": 2,
"selected": false,
"text": "<p>Your problem is a simpler variant, but you might get some tips reading about heuristics developed for the \"binpacking\" problem. There has been a lot written about this, but <a href=\"http://en.wikipedia.org/wiki/Bin_packing_problem\" rel=\"nofollow noreferrer\">this page</a> is a good start. </p>\n"
},
{
"answer_id": 153374,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>Put a tetris-like game into you website. Generate the blocks that fall and the size of the play area based on your paramters. Award points to players based on the compactness (less free space = more points) of their design. Get your website visitors to perform the work for you.</p>\n"
},
{
"answer_id": 153465,
"author": "Chris Johnson",
"author_id": 23732,
"author_profile": "https://Stackoverflow.com/users/23732",
"pm_score": 1,
"selected": false,
"text": "<p>Are the rectangles all of the same height? If they are, and the problem is just which row to put each rectangle in, then the problem boils down to a series of constraints over all pairs of rectangles (X,Y) of the form \"rectangle X cannot be in the same row as rectangle Y\" when rectangle X overlaps in the x-direction with rectangle Y.</p>\n\n<p>A 'greedy' algorithm for this sorts the rectangles from left to right, then assigns each rectangle in turn to the lowest-numbered row in which it fits. Because the rectangles are being processed from left to right, one only needs to worry about whether the left hand edge of the current rectangle will overlap any other rectangles, which simplifies the overlap detection algorithm somewhat.</p>\n\n<p>I can't prove that this is gives the optimal solution, but on the other hand can't think of any counterexamples offhand either. Anyone?</p>\n"
},
{
"answer_id": 153954,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.topcoder.com\" rel=\"nofollow noreferrer\">Topcoder</a> had a competition to solve the 3D version of this problem. The winner discussed his approach <a href=\"http://www.topcoder.com/longcontest/?module=Static&d1=match_editorials&d2=intel_mtcs_6\" rel=\"nofollow noreferrer\">here</a>, it might be an interesting read for you.</p>\n"
},
{
"answer_id": 3089780,
"author": "Eric",
"author_id": 372710,
"author_profile": "https://Stackoverflow.com/users/372710",
"pm_score": 0,
"selected": false,
"text": "<p>I had worked on a problem like this before. The most intuitive picture is probably one where the large rectangles are on the bottom, and the smaller ones are on top, kinda like putting them all in a container and shaking it so the heavy ones fall to the bottom. So to accomplish this, first sort your array in order of decreasing area (or width) -- we will process the large items first and build the picture ground up.</p>\n\n<p>Now the problem is to assign y-coordinates to a set of rectangles whose x-coordinates are given, if I understand you correctly.</p>\n\n<p>Iterate over your array of rectangles. For each rectangle, initialize the rectangle's y-coordinate to 0. Then loop by increasing this rectangle's y-coordinate until it does not intersect with any of the previously placed rectangles (you need to keep track of which rectangles have been previously placed). Commit to the y-coordinate you just found, and continue on to process the next rectangle.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8776/"
] |
I am looking for pointers to the solution of the following problem: I have a set of rectangles, whose height is known and x-positions also and I want to pack them in the more compact form. With a little drawing (where all rectangles are of the same width, but the width may vary in real life), i would like, instead of.
```
-r1-
-r2--
-r3--
-r4-
-r5--
```
something like.
```
-r1- -r3--
-r2-- -r4-
-r5--
```
All hints will be appreciated. I am not necessarily looking for "the" best solution.
|
Your problem is a simpler variant, but you might get some tips reading about heuristics developed for the "binpacking" problem. There has been a lot written about this, but [this page](http://en.wikipedia.org/wiki/Bin_packing_problem) is a good start.
|
153,151 |
<p>I recently upgraded my oracle client to 10g (10.2.0.1.0).</p>
<p>Now when I try to connect to a legacy 8.0 database, I get</p>
<pre><code>ORA-03134: Connections to this server version are no longer supported.
</code></pre>
<p>Is there any workaround for this problem, or do I have to install two clients on my local machine?</p>
|
[
{
"answer_id": 153170,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 1,
"selected": false,
"text": "<p>I had to connect a C# code to an Oracle 7 (I know you it's 8...)... the only way I get it was to get the CD to install the Oracle Server and to go in the \"Optional Configuration Component\" and to use the Oracle73 Ver2.5.</p>\n\n<p>I think you should go check the CD of the Oracle 8 Server and check if an ODBC is still available. </p>\n"
},
{
"answer_id": 153191,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Yes</strong>, you can connect to an Oracle 8i database with the 10g client, but the 8i Database requires the 8.1.7.3 patchset, which you can get from <a href=\"http://metalink.oracle.com/\" rel=\"nofollow noreferrer\">Oracle's Metalink support site</a> (requires login).</p>\n\n<p>Here's an <a href=\"http://forums.oracle.com/forums/thread.jspa?threadID=241380\" rel=\"nofollow noreferrer\">Oracle forum post</a> with the details.</p>\n\n<p><hr>\nIf updating your Oracle Database isn't an option, then you can have 2 different clients installed (in different \"Oracle Homes\" (or directories), and use the <code>selecthome.bat</code> file to switch between your installed clients.</p>\n\n<p>For example, before connecting to 8i, you'd run:</p>\n\n<p><code>C:\\Oracle\\Client1_8i\\bin\\selecthome.bat</code></p>\n\n<p>or this to use your Oracle 10g client:</p>\n\n<p><code>C:\\Oracle\\Client2_10g\\bin\\selecthome.bat</code></p>\n"
},
{
"answer_id": 12518939,
"author": "Niko78",
"author_id": 1686942,
"author_profile": "https://Stackoverflow.com/users/1686942",
"pm_score": 0,
"selected": false,
"text": "<p>The best way to connect an Oracle 8.1.7 and higher is through Instant Client. Download Instant client 10.2 from oracle site, copy all files in the same folder where .NET assemblies resides and use classes located in System.Data.OracleClient. This work for me in .NET 4 project and oracle DB 8.1.7 server.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
I recently upgraded my oracle client to 10g (10.2.0.1.0).
Now when I try to connect to a legacy 8.0 database, I get
```
ORA-03134: Connections to this server version are no longer supported.
```
Is there any workaround for this problem, or do I have to install two clients on my local machine?
|
**Yes**, you can connect to an Oracle 8i database with the 10g client, but the 8i Database requires the 8.1.7.3 patchset, which you can get from [Oracle's Metalink support site](http://metalink.oracle.com/) (requires login).
Here's an [Oracle forum post](http://forums.oracle.com/forums/thread.jspa?threadID=241380) with the details.
---
If updating your Oracle Database isn't an option, then you can have 2 different clients installed (in different "Oracle Homes" (or directories), and use the `selecthome.bat` file to switch between your installed clients.
For example, before connecting to 8i, you'd run:
`C:\Oracle\Client1_8i\bin\selecthome.bat`
or this to use your Oracle 10g client:
`C:\Oracle\Client2_10g\bin\selecthome.bat`
|
153,152 |
<p>I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes. </p>
<p>How do I resize the iframes to fit the height of the iframes' content?</p>
<p>I've tried to decipher the javascript Google uses but it's obfuscated, and searching the web has been fruitless so far.</p>
<p><strong>Update:</strong> Please note that content is loaded from other domains, so the <a href="https://en.wikipedia.org/wiki/Same-origin_policy" rel="noreferrer">same-origin policy</a> applies.</p>
|
[
{
"answer_id": 153187,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": -1,
"selected": false,
"text": "<p>This is slightly tricky as you have to know when the iframe page has loaded, which is difficuly when you're not in control of its content. Its possible to add an onload handler to the iframe, but I've tried this in the past and it has vastly different behaviour across browsers (not guess who's the most annoying...). You'd probably have to add a function to the iframe page that performs the resize and inject some script into the content that either listens to load events or resize events, which then calls the previous function. I'm thinking add a function to the page since you want to make sure its secure, but I have no idea how easy it will be to do.</p>\n"
},
{
"answer_id": 153196,
"author": "Ólafur Waage",
"author_id": 22459,
"author_profile": "https://Stackoverflow.com/users/22459",
"pm_score": -1,
"selected": false,
"text": "<p>Something on the lines of this i belive should work.</p>\n\n<pre><code>parent.document.getElementById(iFrameID).style.height=framedPage.scrollHeight;\n</code></pre>\n\n<p>Load this with your body onload on the iframe content.</p>\n"
},
{
"answer_id": 250275,
"author": "Macho Matt",
"author_id": 1446,
"author_profile": "https://Stackoverflow.com/users/1446",
"pm_score": 3,
"selected": false,
"text": "<p>The solution on <a href=\"http://www.phinesolutions.com/use-jquery-to-adjust-the-iframe-height.html\" rel=\"nofollow noreferrer\">http://www.phinesolutions.com/use-jquery-to-adjust-the-iframe-height.html</a> works great (uses jQuery):</p>\n\n<pre><code><script type=”text/javascript”>\n $(document).ready(function() {\n var theFrame = $(”#iFrameToAdjust”, parent.document.body);\n theFrame.height($(document.body).height() + 30);\n });\n</script>\n</code></pre>\n\n<p>I don't know that you need to add 30 to the length... 1 worked for me.</p>\n\n<p><b>FYI</b>: If you already have a \"height\" attribute on your iFrame, this just adds style=\"height: xxx\". This might not be what you want.</p>\n"
},
{
"answer_id": 250320,
"author": "Joeri Sebrechts",
"author_id": 20980,
"author_profile": "https://Stackoverflow.com/users/20980",
"pm_score": 0,
"selected": false,
"text": "<p>iGoogle gadgets have to actively implement resizing, so my guess is in a cross-domain model you can't do this without the remote content taking part in some way. If your content can send a message with the new size to the container page using typical cross-domain communication techniques, then the rest is simple.</p>\n"
},
{
"answer_id": 362564,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 10,
"selected": true,
"text": "<p>We had this type of problem, but slightly in reverse to your situation - we were providing the iframed content to sites on other domains, so the <a href=\"http://en.wikipedia.org/wiki/Same_origin_policy\" rel=\"noreferrer\">same origin policy</a> was also an issue. After many hours spent trawling google, we eventually found a (somewhat..) workable solution, which you may be able to adapt to your needs.</p>\n\n<p>There is a way around the same origin policy, but it requires changes on both the iframed content and the framing page, so if you haven't the ability to request changes on both sides, this method won't be very useful to you, i'm afraid.</p>\n\n<p>There's a browser quirk which allows us to skirt the same origin policy - javascript can communicate either with pages on its own domain, or with pages it has iframed, but never pages in which it is framed, e.g. if you have:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> www.foo.com/home.html, which iframes\n |-> www.bar.net/framed.html, which iframes\n |-> www.foo.com/helper.html\n</code></pre>\n\n<p>then <code>home.html</code> can communicate with <code>framed.html</code> (iframed) and <code>helper.html</code> (same domain). </p>\n\n<pre class=\"lang-none prettyprint-override\"><code> Communication options for each page:\n +-------------------------+-----------+-------------+-------------+\n | | home.html | framed.html | helper.html |\n +-------------------------+-----------+-------------+-------------+\n | www.foo.com/home.html | N/A | YES | YES |\n | www.bar.net/framed.html | NO | N/A | YES |\n | www.foo.com/helper.html | YES | YES | N/A |\n +-------------------------+-----------+-------------+-------------+\n</code></pre>\n\n<p><code>framed.html</code> can send messages to <code>helper.html</code> (iframed) but <em>not</em> <code>home.html</code> (child can't communicate cross-domain with parent).</p>\n\n<p>The key here is that <code>helper.html</code> can receive messages from <code>framed.html</code>, and <strong>can also communicate</strong> with <code>home.html</code>. </p>\n\n<p>So essentially, when <code>framed.html</code> loads, it works out its own height, tells <code>helper.html</code>, which passes the message on to <code>home.html</code>, which can then resize the iframe in which <code>framed.html</code> sits. </p>\n\n<p>The simplest way we found to pass messages from <code>framed.html</code> to <code>helper.html</code> was through a URL argument. To do this, <code>framed.html</code> has an iframe with <code>src=''</code> specified. When its <code>onload</code> fires, it evaluates its own height, and sets the src of the iframe at this point to <code>helper.html?height=N</code></p>\n\n<p><a href=\"http://www.quora.com/How-does-Facebook-Connect-do-cross-domain-communication\" rel=\"noreferrer\">There's an explanation here</a> of how facebook handle it, which may be slightly clearer than mine above!</p>\n\n<p><hr />\n<strong>Code</strong></p>\n\n<p>In <code>www.foo.com/home.html</code>, the following javascript code is required (this can be loaded from a .js file on any domain, incidentally..):</p>\n\n<pre><code><script>\n // Resize iframe to full height\n function resizeIframe(height)\n {\n // \"+60\" is a general rule of thumb to allow for differences in\n // IE & and FF height reporting, can be adjusted as required..\n document.getElementById('frame_name_here').height = parseInt(height)+60;\n }\n</script>\n<iframe id='frame_name_here' src='http://www.bar.net/framed.html'></iframe>\n</code></pre>\n\n<p>In <code>www.bar.net/framed.html</code>:</p>\n\n<pre><code><body onload=\"iframeResizePipe()\">\n<iframe id=\"helpframe\" src='' height='0' width='0' frameborder='0'></iframe>\n\n<script type=\"text/javascript\">\n function iframeResizePipe()\n {\n // What's the page height?\n var height = document.body.scrollHeight;\n\n // Going to 'pipe' the data to the parent through the helpframe..\n var pipe = document.getElementById('helpframe');\n\n // Cachebuster a precaution here to stop browser caching interfering\n pipe.src = 'http://www.foo.com/helper.html?height='+height+'&cacheb='+Math.random();\n\n }\n</script>\n</code></pre>\n\n<p>Contents of <code>www.foo.com/helper.html</code>:</p>\n\n<pre><code><html> \n<!-- \nThis page is on the same domain as the parent, so can\ncommunicate with it to order the iframe window resizing\nto fit the content \n--> \n <body onload=\"parentIframeResize()\"> \n <script> \n // Tell the parent iframe what height the iframe needs to be\n function parentIframeResize()\n {\n var height = getParam('height');\n // This works as our parent's parent is on our domain..\n parent.parent.resizeIframe(height);\n }\n\n // Helper function, parse param from request string\n function getParam( name )\n {\n name = name.replace(/[\\[]/,\"\\\\\\[\").replace(/[\\]]/,\"\\\\\\]\");\n var regexS = \"[\\\\?&]\"+name+\"=([^&#]*)\";\n var regex = new RegExp( regexS );\n var results = regex.exec( window.location.href );\n if( results == null )\n return \"\";\n else\n return results[1];\n }\n </script> \n </body> \n</html>\n</code></pre>\n"
},
{
"answer_id": 701521,
"author": "Ahmy",
"author_id": 74298,
"author_profile": "https://Stackoverflow.com/users/74298",
"pm_score": 6,
"selected": false,
"text": "<p>If you do not need to handle iframe content from a different domain, try this code, it will solve the problem completely and it's simple:</p>\n\n<pre><code><script language=\"JavaScript\">\n<!--\nfunction autoResize(id){\n var newheight;\n var newwidth;\n\n if(document.getElementById){\n newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;\n newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;\n }\n\n document.getElementById(id).height= (newheight) + \"px\";\n document.getElementById(id).width= (newwidth) + \"px\";\n}\n//-->\n</script>\n\n<iframe src=\"usagelogs/default.aspx\" width=\"100%\" height=\"200px\" id=\"iframe1\" marginheight=\"0\" frameborder=\"0\" onLoad=\"autoResize('iframe1');\"></iframe>\n</code></pre>\n"
},
{
"answer_id": 3002873,
"author": "Vaughan Rowsell",
"author_id": 362007,
"author_profile": "https://Stackoverflow.com/users/362007",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a simple solution using a dynamically generated style sheet served up by the same server as the iframe content. Quite simply the style sheet \"knows\" what is in the iframe, and knows the dimensions to use to style the iframe. This gets around the same origin policy restrictions. </p>\n\n<p><a href=\"http://www.8degrees.co.nz/2010/06/09/dynamically-resize-an-iframe-depending-on-its-content/\" rel=\"nofollow noreferrer\">http://www.8degrees.co.nz/2010/06/09/dynamically-resize-an-iframe-depending-on-its-content/</a></p>\n\n<p>So the supplied iframe code would have an accompanying style sheet like so...</p>\n\n<p><code><link href=\"http://your.site/path/to/css?contents_id=1234&dom_id=iframe_widget\" rel=\"stylesheet\" type=\"text/css\" />
\n<iframe id=\"iframe_widget\" src=\"http://your.site/path/to/content?content_id=1234\" frameborder=\"0\" width=\"100%\" scrolling=\"no\"></iframe></code></p>\n\n<p>This does require the server side logic being able to calculate the dimensions of the rendered content of the iframe.</p>\n"
},
{
"answer_id": 3219970,
"author": "Chris Jacob",
"author_id": 114140,
"author_profile": "https://Stackoverflow.com/users/114140",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://developer.mozilla.org/en/DOM/window.postMessage\" rel=\"noreferrer\">https://developer.mozilla.org/en/DOM/window.postMessage</a></p>\n\n<blockquote>\n <p><em>window.postMessage()</em></p>\n \n <p>window.postMessage is a method for safely enabling cross-origin communication. Normally, scripts on different pages are only allowed to access each other if and only if the pages which executed them are at locations with the same protocol (usually both http), port number (80 being the default for http), and host (modulo document.domain being set by both pages to the same value). window.postMessage provides a controlled mechanism to circumvent this restriction in a way which is secure when properly used.</p>\n \n <p><em>Summary</em></p>\n \n <p>window.postMessage, when called, causes a MessageEvent to be dispatched at the target window when any pending script that must be executed completes (e.g. remaining event handlers if window.postMessage is called from an event handler, previously-set pending timeouts, etc.). The MessageEvent has the type message, a data property which is set to the string value of the first argument provided to window.postMessage, an origin property corresponding to the origin of the main document in the window calling window.postMessage at the time window.postMessage was called, and a source property which is the window from which window.postMessage is called. (Other standard properties of events are present with their expected values.)</p>\n</blockquote>\n\n<p>The <em>iFrame-Resizer</em> library uses postMessage to keep an iFrame sized to it's content, along with <a href=\"https://developer.mozilla.org/en/docs/Web/API/MutationObserver\" rel=\"noreferrer\">MutationObserver</a> to detect changes to the content and doesn't depend on jQuery.</p>\n\n<p><a href=\"https://github.com/davidjbradshaw/iframe-resizer\" rel=\"noreferrer\">https://github.com/davidjbradshaw/iframe-resizer</a></p>\n\n<p>jQuery: Cross-domain scripting goodness</p>\n\n<p><a href=\"http://benalman.com/projects/jquery-postmessage-plugin/\" rel=\"noreferrer\">http://benalman.com/projects/jquery-postmessage-plugin/</a></p>\n\n<p>Has demo of resizing iframe window...</p>\n\n<p><a href=\"http://benalman.com/code/projects/jquery-postmessage/examples/iframe/\" rel=\"noreferrer\">http://benalman.com/code/projects/jquery-postmessage/examples/iframe/</a></p>\n\n<p>This article shows how to remove the dependency on jQuery... Plus has a lot of useful info and links to other solutions. </p>\n\n<p><a href=\"http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/\" rel=\"noreferrer\">http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/</a></p>\n\n<p>Barebones example...</p>\n\n<p><a href=\"http://onlineaspect.com/uploads/postmessage/parent.html\" rel=\"noreferrer\">http://onlineaspect.com/uploads/postmessage/parent.html</a></p>\n\n<p>HTML 5 working draft on window.postMessage</p>\n\n<p><a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\" rel=\"noreferrer\">http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages</a></p>\n\n<p>John Resig on Cross-Window Messaging</p>\n\n<p><a href=\"http://ejohn.org/blog/cross-window-messaging/\" rel=\"noreferrer\">http://ejohn.org/blog/cross-window-messaging/</a></p>\n"
},
{
"answer_id": 6197254,
"author": "kaw",
"author_id": 778860,
"author_profile": "https://Stackoverflow.com/users/778860",
"pm_score": 0,
"selected": false,
"text": "<p>When you want to zoom out a web page to fit it into the iframe size:</p>\n\n<ol>\n<li>You should resize the <strong>iframe</strong> to fit it with the content</li>\n<li>Then you should zoom out the whole iframe with the loaded web page content</li>\n</ol>\n\n<p>Here is an example:</p>\n\n<pre><code><div id=\"wrap\">\n <IFRAME ID=\"frame\" name=\"Main\" src =\"http://www.google.com\" />\n</div>\n</code></pre>\n\n<hr>\n\n<pre><code><style type=\"text/css\">\n #wrap { width: 130px; height: 130px; padding: 0; overflow: hidden; }\n #frame { width: 900px; height: 600px; border: 1px solid black; }\n #frame { zoom:0.15; -moz-transform:scale(0.15);-moz-transform-origin: 0 0; }\n</style>\n</code></pre>\n"
},
{
"answer_id": 9356798,
"author": "فيصل خلبوص",
"author_id": 1220267,
"author_profile": "https://Stackoverflow.com/users/1220267",
"pm_score": -1,
"selected": false,
"text": "<p>I have an easy solution and requires you to determine the width and height in the link, please try (It works with most browsers):</p>\n\n<pre><code><a href='#' onClick=\" document.getElementById('myform').src='t2.htm';document.getElementById('myform').width='500px'; document.getElementById('myform').height='400px'; return false\">500x400</a>\n</code></pre>\n\n\n"
},
{
"answer_id": 9796214,
"author": "Tor Händevik",
"author_id": 774043,
"author_profile": "https://Stackoverflow.com/users/774043",
"pm_score": 1,
"selected": false,
"text": "<p>I'm implementing ConroyP's frame-in-frame solution to replace a solution based on setting document.domain, but found it to be quite hard determining the height of the iframe's content correctly in different browsers (testing with FF11, Ch17 and IE9 right now).</p>\n\n<p>ConroyP uses:</p>\n\n<pre><code>var height = document.body.scrollHeight;\n</code></pre>\n\n<p>But that only works on the initial page load. My iframe has dynamic content and I need to resize the iframe on certain events.</p>\n\n<p>What I ended up doing was using different JS properties for the different browsers.</p>\n\n<pre><code>function getDim () {\n var body = document.body,\n html = document.documentElement;\n\n var bc = body.clientHeight;\n var bo = body.offsetHeight;\n var bs = body.scrollHeight;\n var hc = html.clientHeight;\n var ho = html.offsetHeight;\n var hs = html.scrollHeight;\n\n var h = Math.max(bc, bo, bs, hc, hs, ho);\n\n var bd = getBrowserData();\n\n // Select height property to use depending on browser\n if (bd.isGecko) {\n // FF 11\n h = hc;\n } else if (bd.isChrome) {\n // CH 17\n h = hc;\n } else if (bd.isIE) {\n // IE 9\n h = bs;\n }\n\n return h;\n}\n</code></pre>\n\n<p><em>getBrowserData() is browser detect function \"inspired\" by Ext Core's <a href=\"http://docs.sencha.com/core/source/Ext.html#method-Ext-apply\" rel=\"nofollow\">http://docs.sencha.com/core/source/Ext.html#method-Ext-apply</a></em></p>\n\n<p>That worked well for FF and IE but then there were issues with Chrome. One of the was a timing issue, apparently it takes Chrome a while to set/detect the hight of the iframe. And then Chrome also never returned the height of the content in the iframe correctly if the iframe was higher than the content. This wouldn't work with dynamic content when the height is reduced.</p>\n\n<p>To solve this I always set the iframe to a low height before detecting the content's height and then setting the iframe height to it's correct value.</p>\n\n<pre><code>function resize () {\n // Reset the iframes height to a low value.\n // Otherwise Chrome won't detect the content height of the iframe.\n setIframeHeight(150);\n\n // Delay getting the dimensions because Chrome needs\n // a few moments to get the correct height.\n setTimeout(\"getDimAndResize()\", 100);\n}\n</code></pre>\n\n<p>The code is not optimized, it's from my devel testing :)</p>\n\n<p>Hope someone finds this helpful!</p>\n"
},
{
"answer_id": 12202664,
"author": "Omer Arshad",
"author_id": 1636793,
"author_profile": "https://Stackoverflow.com/users/1636793",
"pm_score": 3,
"selected": false,
"text": "<p>The simplest way using jQuery:</p>\n\n<pre><code>$(\"iframe\")\n.attr({\"scrolling\": \"no\", \"src\":\"http://www.someotherlink.com/\"})\n.load(function() {\n $(this).css(\"height\", $(this).contents().height() + \"px\");\n});\n</code></pre>\n"
},
{
"answer_id": 14486904,
"author": "chad steele",
"author_id": 1669091,
"author_profile": "https://Stackoverflow.com/users/1669091",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a jQuery approach that adds the info in json via the src attribute of the iframe. Here's a demo, resize and scroll this window.. the resulting url with json looks like this... \n<a href=\"http://fiddle.jshell.net/zippyskippy/RJN3G/show/#%7BdocHeight:5124,windowHeight:1019,scrollHeight:571%7D#\" rel=\"nofollow\">http://fiddle.jshell.net/zippyskippy/RJN3G/show/#{docHeight:5124,windowHeight:1019,scrollHeight:571}#</a></p>\n\n<p>Here's the source code fiddle <a href=\"http://jsfiddle.net/zippyskippy/RJN3G/\" rel=\"nofollow\">http://jsfiddle.net/zippyskippy/RJN3G/</a></p>\n\n<pre><code>function updateLocation(){\n\n var loc = window.location.href;\n window.location.href = loc.replace(/#{.*}#/,\"\") \n + \"#{docHeight:\"+$(document).height() \n + \",windowHeight:\"+$(window).height()\n + \",scrollHeight:\"+$(window).scrollTop()\n +\"}#\";\n\n};\n\n//setInterval(updateLocation,500);\n\n$(window).resize(updateLocation);\n$(window).scroll(updateLocation);\n</code></pre>\n"
},
{
"answer_id": 18323772,
"author": "webd3sign",
"author_id": 2697914,
"author_profile": "https://Stackoverflow.com/users/2697914",
"pm_score": 1,
"selected": false,
"text": "<pre><code><html>\n<head>\n<script>\nfunction frameSize(id){\nvar frameHeight;\n\ndocument.getElementById(id).height=0 + \"px\";\nif(document.getElementById){\n newheight=document.getElementById(id).contentWindow.document.body.scrollHeight; \n}\n\ndocument.getElementById(id).height= (frameHeight) + \"px\";\n}\n</script>\n</head>\n\n<body>\n\n<iframe id=\"frame\" src=\"startframe.html\" frameborder=\"0\" marginheight=\"0\" hspace=20 width=\"100%\" \n\nonload=\"javascript:frameSize('frame');\">\n\n<p>This will work, but you need to host it on an http server, you can do it locally. </p>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 20509636,
"author": "YellowGlue",
"author_id": 2585688,
"author_profile": "https://Stackoverflow.com/users/2585688",
"pm_score": 0,
"selected": false,
"text": "<h2>get iframe content height then give it to this iframe</h2>\n\n<pre><code> var iframes = document.getElementsByTagName(\"iframe\");\n for(var i = 0, len = iframes.length; i<len; i++){\n window.frames[i].onload = function(_i){\n return function(){\n iframes[_i].style.height = window.frames[_i].document.body.scrollHeight + \"px\";\n }\n }(i);\n }\n</code></pre>\n"
},
{
"answer_id": 20777751,
"author": "ddlab",
"author_id": 1150871,
"author_profile": "https://Stackoverflow.com/users/1150871",
"pm_score": 2,
"selected": false,
"text": "<p>may be a bit late, as all the other answers are older :-) but... here´s my solution. Tested in actual FF, Chrome and Safari 5.0.</p>\n\n<p>css:</p>\n\n<pre><code>iframe {border:0; overflow:hidden;}\n</code></pre>\n\n<p>javascript:</p>\n\n<pre><code>$(document).ready(function(){\n $(\"iframe\").load( function () {\n var c = (this.contentWindow || this.contentDocument);\n if (c.document) d = c.document;\n var ih = $(d).outerHeight();\n var iw = $(d).outerWidth();\n $(this).css({\n height: ih,\n width: iw\n });\n });\n});\n</code></pre>\n\n<p>Hope this will help anybody.</p>\n"
},
{
"answer_id": 24179165,
"author": "Selvamani",
"author_id": 1514776,
"author_profile": "https://Stackoverflow.com/users/1514776",
"pm_score": 3,
"selected": false,
"text": "<p>Finally I found some other solution for sending data to parent website from iframe using <code>window.postMessage(message, targetOrigin);</code>. Here I explain How I did.</p>\n\n<p>Site A = <a href=\"http://foo.com\" rel=\"noreferrer\">http://foo.com</a> \nSite B = <a href=\"http://bar.com\" rel=\"noreferrer\">http://bar.com</a></p>\n\n<p>SiteB is loading inside the siteA website</p>\n\n<p>SiteB website have this line</p>\n\n<pre><code>window.parent.postMessage(\"Hello From IFrame\", \"*\"); \n</code></pre>\n\n<p>or</p>\n\n<pre><code>window.parent.postMessage(\"Hello From IFrame\", \"http://foo.com\");\n</code></pre>\n\n<p>Then siteA have this following code</p>\n\n<pre><code>// Here \"addEventListener\" is for standards-compliant web browsers and \"attachEvent\" is for IE Browsers.\nvar eventMethod = window.addEventListener ? \"addEventListener\" : \"attachEvent\";\nvar eventer = window[eventMethod];\n\n\nvar messageEvent = eventMethod == \"attachEvent\" ? \"onmessage\" : \"message\";\n\n// Listen to message from child IFrame window\neventer(messageEvent, function (e) {\n alert(e.data);\n // Do whatever you want to do with the data got from IFrame in Parent form.\n}, false); \n</code></pre>\n\n<p>If you want to add security connection you can use this if condition in <code>eventer(messageEvent, function (e) {})</code></p>\n\n<pre><code>if (e.origin == 'http://iframe.example.com') {\n alert(e.data); \n // Do whatever you want to do with the data got from IFrame in Parent form.\n}\n</code></pre>\n\n<p><strong>For IE</strong></p>\n\n<p>Inside IFrame:</p>\n\n<pre><code> window.parent.postMessage('{\"key\":\"value\"}','*');\n</code></pre>\n\n<p>Outside:</p>\n\n<pre><code> eventer(messageEvent, function (e) {\n var data = jQuery.parseJSON(e.data);\n doSomething(data.key);\n }, false);\n</code></pre>\n"
},
{
"answer_id": 24252773,
"author": "Mario Gonzales Flores",
"author_id": 2360106,
"author_profile": "https://Stackoverflow.com/users/2360106",
"pm_score": 0,
"selected": false,
"text": "<p>Work with jquery on load (cross browser):</p>\n\n<pre><code> <iframe src=\"your_url\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"No\" frameborder=\"0\" hspace=\"0\" vspace=\"0\" id=\"containiframe\" onload=\"loaderIframe();\" height=\"100%\" width=\"100%\"></iframe>\n\nfunction loaderIframe(){\nvar heightIframe = $('#containiframe').contents().find('body').height();\n$('#frame').css(\"height\", heightFrame);\n } \n</code></pre>\n\n<p>on resize in responsive page:</p>\n\n<pre><code>$(window).resize(function(){\nif($('#containiframe').length !== 0) {\nvar heightIframe = $('#containiframe').contents().find('body').height();\n $('#frame').css(\"height\", heightFrame);\n}\n});\n</code></pre>\n"
},
{
"answer_id": 28290960,
"author": "Razan Paul",
"author_id": 1037073,
"author_profile": "https://Stackoverflow.com/users/1037073",
"pm_score": 2,
"selected": false,
"text": "<p>This answer is only applicable for websites which uses Bootstrap. The responsive embed feature of the Bootstrap does the job. It is based on the width (not height) of the content.</p>\n\n<pre><code><!-- 16:9 aspect ratio -->\n<div class=\"embed-responsive embed-responsive-16by9\">\n <iframe class=\"embed-responsive-item\" src=\"http://www.youtube.com/embed/WsFWhL4Y84Y\"></iframe>\n</div>\n</code></pre>\n\n<p>jsfiddle: <a href=\"http://jsfiddle.net/00qggsjj/2/\" rel=\"nofollow\">http://jsfiddle.net/00qggsjj/2/</a></p>\n\n<p><a href=\"http://getbootstrap.com/components/#responsive-embed\" rel=\"nofollow\">http://getbootstrap.com/components/#responsive-embed</a></p>\n"
},
{
"answer_id": 32621754,
"author": "The Onin",
"author_id": 1325575,
"author_profile": "https://Stackoverflow.com/users/1325575",
"pm_score": -1,
"selected": false,
"text": "<p>Using jQuery:</p>\n\n<p>parent.html</p>\n\n<pre><code><body>\n<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.4.min.js\"></script>\n<style>\niframe {\n width: 100%;\n border: 1px solid black;\n}\n</style>\n<script>\nfunction foo(w, h) {\n $(\"iframe\").css({width: w, height: h});\n return true; // for debug purposes\n}\n</script>\n<iframe src=\"child.html\"></iframe>\n</body>\n</code></pre>\n\n<p>child.html</p>\n\n<pre><code><body>\n<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.4.min.js\"></script>\n<script>\n$(function() {\n var w = $(\"#container\").css(\"width\");\n var h = $(\"#container\").css(\"height\");\n\n var req = parent.foo(w, h);\n console.log(req); // for debug purposes\n});\n</script>\n<style>\nbody, html {\n margin: 0;\n}\n#container {\n width: 500px;\n height: 500px;\n background-color: red;\n}\n</style>\n<div id=\"container\"></div>\n</body>\n</code></pre>\n"
},
{
"answer_id": 64110306,
"author": "geekhunger",
"author_id": 4383587,
"author_profile": "https://Stackoverflow.com/users/4383587",
"pm_score": 1,
"selected": false,
"text": "<p><em>This is an old thread, but in 2020 it's still a relevant question. I've actually posted this answer in another old thread as well^^ (<a href=\"https://stackoverflow.com/a/64110252/4383587\">https://stackoverflow.com/a/64110252/4383587</a>)</em></p>\n<hr />\n<p>Just wanted to share my solution and excitement. It took me four entire days of intensive research and failure, but I think I've found a neat way of making iframes entirely responsive! Yey!</p>\n<p>I tried a ton of different approaches... I didn't want to use a two-way communication tunnel as with <code>postMessage</code> because it's awkward for same-origin and complicated for cross-origin (as no admin wants to open doors and implement this on your behalf).</p>\n<p>I've tried using MutationObservers and still needed several EventListeners (resize, click,..) to ensure that every change of the layout was handled correctly. - What if a script toggles the visibility of an element? Or what if it dynamically preloads more content on demand? - Another issue was getting an accurate height of the iframe contents from somewhere. Most people suggest using <code>scrollHeight</code> or <code>offsetHeight</code>, or combination of it by using <code>Math.max</code>. The problem is, that these values don't get updated until the iframe element changes its dimensions. To achieve that you could simply reset the <code>iframe.height = 0</code> before grabbing the <code>scrollHeight</code>, but there are even more caveats to this. So, screw this.</p>\n<p>Then, I had another idea to experiment with <code>requestAnimationFrame</code> to get rid of my events and observers hell. Now, I could react to every layout change immediately, but I still had no reliable source to infer the content height of the iframe from. And theeen I discovered <code>getComputedStyle</code>, by accident! This was an enlightenment! Everything just clicked.</p>\n<p>Well, see the code I could eventually distill from my countless attempts.</p>\n<pre><code>function fit() {\n var iframes = document.querySelectorAll("iframe.gh-fit")\n\n for(var id = 0; id < iframes.length; id++) {\n var win = iframes[id].contentWindow\n var doc = win.document\n var html = doc.documentElement\n var body = doc.body\n var ifrm = iframes[id] // or win.frameElement\n\n if(body) {\n body.style.overflowX = "scroll" // scrollbar-jitter fix\n body.style.overflowY = "hidden"\n }\n if(html) {\n html.style.overflowX = "scroll" // scrollbar-jitter fix\n html.style.overflowY = "hidden"\n var style = win.getComputedStyle(html)\n ifrm.width = parseInt(style.getPropertyValue("width")) // round value\n ifrm.height = parseInt(style.getPropertyValue("height"))\n }\n }\n\n requestAnimationFrame(fit)\n}\n\naddEventListener("load", requestAnimationFrame.bind(this, fit))\n</code></pre>\n<p>That is it, yes! - In your HTML code write <code><iframe src="page.html" class="gh-fit gh-fullwidth"></iframe></code>. The <code>gh-fit</code> is a just fake CSS class, used to identify which iframe elements in your DOM should be affect by the script. The <code>gh-fullwidth</code> is a simple CSS class with one rule <code>width: 100%;</code>.</p>\n<p>The above script automatically fetches all iframes from the DOM, that have a <code>.gh-fit</code> class assigned. It then grabs and uses the pre-calculated style values for width and height from <code>document.getComputedStyle(iframe)</code>, which always contain a pixel-perfect size of that element!!! Just perfect!</p>\n<p>Note, this solution doesn't work cross-origin (nor does any other solution, without a two-way communication strategy like IFrameResizer). JS simply can't access the DOM of an iframe, if it doesn't belong to you.</p>\n<p>The only other cross-origin solution I can think of, is to use a proxy like <a href=\"https://github.com/gnuns/allorigins\" rel=\"nofollow noreferrer\">https://github.com/gnuns/allorigins</a>. But this would involve deep-copying every request you make - in other words - you 'steal' the entire page source code (to make it yours and let JS access the DOM) and you patch every link/path in this source, so that it goes through the proxy as well. The re-linking routine is a tough one, but doable.</p>\n<p>I'll probably try myself at this cross-origin problem, but that's for another day. Enjoy the code! :)</p>\n"
},
{
"answer_id": 66190993,
"author": "hanshenrik",
"author_id": 1067003,
"author_profile": "https://Stackoverflow.com/users/1067003",
"pm_score": -1,
"selected": false,
"text": "<p>couldn't find something that perfectly handled large texts + large images, but i ended up with this, seems this gets it right, or nearly right, every single time:</p>\n<pre class=\"lang-js prettyprint-override\"><code> iframe.addEventListener("load",function(){\n // inlineSize, length, perspectiveOrigin, width\n let heightMax = 0;\n // this seems to work best with images...\n heightMax = Math.max(heightMax,iframe.contentWindow.getComputedStyle(iframe.contentWindow.document.body).perspectiveOrigin.split("px")[0]);\n // this seems to work best with text...\n heightMax = Math.max(heightMax,iframe.contentWindow.document.body.scrollHeight);\n // some large 1920x1080 images always gets a little bit off on firefox =/\n const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;\n if(isFirefox && heightMax >= 900){\n // grrr..\n heightMax = heightMax + 100;\n }\n\n iframe.style.height = heightMax+"px";\n //console.log(heightMax);\n });\n\n</code></pre>\n"
},
{
"answer_id": 67044630,
"author": "latitov",
"author_id": 11729048,
"author_profile": "https://Stackoverflow.com/users/11729048",
"pm_score": 0,
"selected": false,
"text": "<p>David Bradshaw and Chris Jacob already suggested using the postMessage approach. And I totally agree, that the proper way of doing things like these.</p>\n<p>I just want to post an example, real code that works, in case it'll be a ready answers for some.</p>\n<p>On the iframed-side:</p>\n<pre><code><body onload="docResizePipe()">\n<script>\nvar v = 0;\nconst docResizeObserver = new ResizeObserver(() => {\n docResizePipe();\n});\ndocResizeObserver.observe(document.querySelector("body"));\nfunction docResizePipe() {\n v += 1;\n if (v > 5) {\n return;\n }\n var w = document.body.scrollWidth;\n var h = document.body.scrollHeight;\n window.parent.postMessage([w,h], "*");\n}\nsetInterval(function() {\n v -= 1;\n if (v < 0) {\n v = 0;\n }\n}, 300);\n</script>\n</code></pre>\n<p>Note the recursion-blocking mechanics - it was necessary because of apparently a bug in Firefox, but anyways let it be there.</p>\n<p>On the parent document side:</p>\n<pre><code><iframe id="rpa-frame" src="3.html" style="border: none;"></iframe>\n<script>\nvar rpaFrame = document.getElementById("rpa-frame");\n\nwindow.addEventListener("message", (event) => {\n var width = event.data[0];\n var height = event.data[1];\n rpaFrame.width = parseInt(width)+60;\n rpaFrame.height = parseInt(height)+60;\n console.log(event);\n}, false);\n</script>\n</code></pre>\n<p>Hope it'll be useful.</p>\n"
},
{
"answer_id": 69226071,
"author": "Ogglas",
"author_id": 3850405,
"author_profile": "https://Stackoverflow.com/users/3850405",
"pm_score": 0,
"selected": false,
"text": "<p>I have been reading a lot of the answers here but nearly everyone gave some sort of cross-origin frame block.</p>\n<p>Example error:</p>\n<blockquote>\n<p>Uncaught DOMException: Blocked a frame with origin "null" from\naccessing a cross-origin frame.</p>\n</blockquote>\n<p>The same for the answers in a related thread:</p>\n<p><a href=\"https://stackoverflow.com/q/9975810/3850405\">Make iframe automatically adjust height according to the contents without using scrollbar?</a></p>\n<p>I do not want to use a third party library like <code>iFrame Resizer</code> or similar library either.</p>\n<p>The answer from @ChrisJacob is close but I'm missing a complete working example and not only links. @Selvamani and @latitov are good complements as well.</p>\n<p><a href=\"https://stackoverflow.com/a/3219970/3850405\">https://stackoverflow.com/a/3219970/3850405</a></p>\n<p>I'm using <code>width="100%"</code> for the <code>iframe</code> but the code can be modified to work with width as well.</p>\n<p>This is how I solved setting a custom height for the <code>iframe</code>:</p>\n<p>Embedded <code>iframe</code>:</p>\n<pre><code><!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="utf-8" />\n <meta name="description"\n content="Web site" />\n <title>Test with embedded iframe</title>\n</head>\n<body>\n <noscript>You need to enable JavaScript to run this app.</noscript>\n <div id="root"></div>\n <iframe id="ifrm" src="https://localhost:44335/package/details?key=123" width="100%"></iframe>\n <script type="text/javascript">\n window.addEventListener('message', receiveMessage, false);\n\n function receiveMessage(evt) {\n console.log("Got message: " + JSON.stringify(evt.data) + " from origin: " + evt.origin);\n // Do we trust the sender of this message?\n if (evt.origin !== "https://localhost:44335") {\n return;\n }\n\n if (evt.data.type === "frame-resized") {\n document.getElementById("ifrm").style.height = evt.data.value + "px";\n }\n }\n </script>\n</body>\n</html>\n</code></pre>\n<p><code>iframe source</code>, example from <code>Create React App</code> but only <code>HTML</code> and <code>JS</code> is used.</p>\n<pre><code><!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="utf-8" />\n <meta name="description"\n content="Web site created using create-react-app" />\n <title>React App</title>\n</head>\n<body>\n <noscript>You need to enable JavaScript to run this app.</noscript>\n <div id="root"></div>\n <script type="text/javascript">\n //Don't run unless in an iframe\n if (self !== top) {\n var rootHeight;\n setInterval(function () {\n var rootElement = document.getElementById("root");\n if (rootElement) {\n var currentRootHeight = rootElement.offsetHeight;\n //Only send values if height has changed since last time\n if (rootHeight !== currentRootHeight) {\n //postMessage to set iframe height\n window.parent.postMessage({ "type": "frame-resized", "value": currentRootHeight }, '*');\n rootHeight = currentRootHeight;\n }\n }\n }\n , 1000);\n }\n </script>\n</body>\n</html>\n</code></pre>\n<p>The code with <code>setInterval</code> can of course be modified but it works really well with dynamic content. <code>setInterval</code> only activates if the content is embedded in a <code>iframe</code> and <code>postMessage</code> only sends a message when height has changed.</p>\n<p>You can read more about <code>Window.postMessage()</code> here but the description fits very good in what we want to achieve:</p>\n<blockquote>\n<p>The window.postMessage() method safely enables cross-origin\ncommunication between Window objects; e.g., between a page and a\npop-up that it spawned, or between a page and an iframe embedded\nwithin it.</p>\n<p>Normally, scripts on different pages are allowed to access each other\nif and only if the pages they originate from share the same protocol,\nport number, and host (also known as the "same-origin policy").\nwindow.postMessage() provides a controlled mechanism to securely\ncircumvent this restriction (if used properly).</p>\n</blockquote>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage</a></p>\n"
},
{
"answer_id": 70334190,
"author": "iMath",
"author_id": 1485853,
"author_profile": "https://Stackoverflow.com/users/1485853",
"pm_score": 2,
"selected": false,
"text": "<p>If you have control over the iframe content , I strongly recommend using</p>\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver\" rel=\"nofollow noreferrer\">ResizeObserver</a></h2>\n<p>Just insert the following at the end of <code>srcdoc</code> attribute of <code>iframe</code> ,\n<a href=\"https://codebeautify.org/html-escape-unescape\" rel=\"nofollow noreferrer\">escape</a> it if needed.</p>\n<pre><code><script type="text/javascript">\nvar ro = new ResizeObserver(entries => {\n for (let entry of entries) {\n const cr = entry.contentRect;\n // console.log(window.frameElement);\n window.frameElement.style.height =cr.height +30+ "px";\n }\n});\n\nro.observe(document.body);\n</script>\n</code></pre>\n"
},
{
"answer_id": 70878965,
"author": "AZ Chad",
"author_id": 2343813,
"author_profile": "https://Stackoverflow.com/users/2343813",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://getbootstrap.com/docs/4.0/utilities/embed/\" rel=\"nofollow noreferrer\">https://getbootstrap.com/docs/4.0/utilities/embed/</a></p>\n<p>After a lot of research, it dawned on me, this is not a unique problem, I bet Bootstrap handles it. Lo and behold…</p>\n\n \n\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842/"
] |
I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes.
How do I resize the iframes to fit the height of the iframes' content?
I've tried to decipher the javascript Google uses but it's obfuscated, and searching the web has been fruitless so far.
**Update:** Please note that content is loaded from other domains, so the [same-origin policy](https://en.wikipedia.org/wiki/Same-origin_policy) applies.
|
We had this type of problem, but slightly in reverse to your situation - we were providing the iframed content to sites on other domains, so the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy) was also an issue. After many hours spent trawling google, we eventually found a (somewhat..) workable solution, which you may be able to adapt to your needs.
There is a way around the same origin policy, but it requires changes on both the iframed content and the framing page, so if you haven't the ability to request changes on both sides, this method won't be very useful to you, i'm afraid.
There's a browser quirk which allows us to skirt the same origin policy - javascript can communicate either with pages on its own domain, or with pages it has iframed, but never pages in which it is framed, e.g. if you have:
```none
www.foo.com/home.html, which iframes
|-> www.bar.net/framed.html, which iframes
|-> www.foo.com/helper.html
```
then `home.html` can communicate with `framed.html` (iframed) and `helper.html` (same domain).
```none
Communication options for each page:
+-------------------------+-----------+-------------+-------------+
| | home.html | framed.html | helper.html |
+-------------------------+-----------+-------------+-------------+
| www.foo.com/home.html | N/A | YES | YES |
| www.bar.net/framed.html | NO | N/A | YES |
| www.foo.com/helper.html | YES | YES | N/A |
+-------------------------+-----------+-------------+-------------+
```
`framed.html` can send messages to `helper.html` (iframed) but *not* `home.html` (child can't communicate cross-domain with parent).
The key here is that `helper.html` can receive messages from `framed.html`, and **can also communicate** with `home.html`.
So essentially, when `framed.html` loads, it works out its own height, tells `helper.html`, which passes the message on to `home.html`, which can then resize the iframe in which `framed.html` sits.
The simplest way we found to pass messages from `framed.html` to `helper.html` was through a URL argument. To do this, `framed.html` has an iframe with `src=''` specified. When its `onload` fires, it evaluates its own height, and sets the src of the iframe at this point to `helper.html?height=N`
[There's an explanation here](http://www.quora.com/How-does-Facebook-Connect-do-cross-domain-communication) of how facebook handle it, which may be slightly clearer than mine above!
---
**Code**
In `www.foo.com/home.html`, the following javascript code is required (this can be loaded from a .js file on any domain, incidentally..):
```
<script>
// Resize iframe to full height
function resizeIframe(height)
{
// "+60" is a general rule of thumb to allow for differences in
// IE & and FF height reporting, can be adjusted as required..
document.getElementById('frame_name_here').height = parseInt(height)+60;
}
</script>
<iframe id='frame_name_here' src='http://www.bar.net/framed.html'></iframe>
```
In `www.bar.net/framed.html`:
```
<body onload="iframeResizePipe()">
<iframe id="helpframe" src='' height='0' width='0' frameborder='0'></iframe>
<script type="text/javascript">
function iframeResizePipe()
{
// What's the page height?
var height = document.body.scrollHeight;
// Going to 'pipe' the data to the parent through the helpframe..
var pipe = document.getElementById('helpframe');
// Cachebuster a precaution here to stop browser caching interfering
pipe.src = 'http://www.foo.com/helper.html?height='+height+'&cacheb='+Math.random();
}
</script>
```
Contents of `www.foo.com/helper.html`:
```
<html>
<!--
This page is on the same domain as the parent, so can
communicate with it to order the iframe window resizing
to fit the content
-->
<body onload="parentIframeResize()">
<script>
// Tell the parent iframe what height the iframe needs to be
function parentIframeResize()
{
var height = getParam('height');
// This works as our parent's parent is on our domain..
parent.parent.resizeIframe(height);
}
// Helper function, parse param from request string
function getParam( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
</script>
</body>
</html>
```
|
153,156 |
<p>How to count distinct values in a node in XSLT?</p>
<p>Example: I want to count the number of existing countries in Country nodes, in this case, it would be 3.</p>
<pre><code><Artists_by_Countries>
<Artist_by_Country>
<Location_ID>62</Location_ID>
<Artist_ID>212</Artist_ID>
<Country>Argentina</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>4</Location_ID>
<Artist_ID>108</Artist_ID>
<Country>Australia</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>4</Location_ID>
<Artist_ID>111</Artist_ID>
<Country>Australia</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>12</Location_ID>
<Artist_ID>78</Artist_ID>
<Country>Germany</Country>
</Artist_by_Country>
</Artists_by_Countries>
</code></pre>
|
[
{
"answer_id": 153204,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "<p>Try something like this:</p>\n\n<pre><code>count(//Country[not(following::Country/text() = text())])\n</code></pre>\n\n<p>\"Give me the count of all Country nodes without a following Country with matching text\"</p>\n\n<p>The interesting bit of that expression, IMO, is the <a href=\"http://www.w3schools.com/xpath/xpath_axes.asp\" rel=\"noreferrer\">following</a> axis.</p>\n\n<p>You could probably also remove the first <code>/text()</code>, and replace the second with <code>.</code></p>\n"
},
{
"answer_id": 153218,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 3,
"selected": false,
"text": "<p>In XSLT 1.0 this isn't obvious, but the following should give you an idea of the requirement:</p>\n\n<pre><code>count(//Artist_by_Country[not(Location_ID=preceding-sibling::Artist_by_Country/Location_ID)]/Location_ID)\n</code></pre>\n\n<p>The more elements in your XML the longer this takes, as it checks every single preceding sibling of every single element.</p>\n"
},
{
"answer_id": 153254,
"author": "Nick Allen",
"author_id": 12918,
"author_profile": "https://Stackoverflow.com/users/12918",
"pm_score": 0,
"selected": false,
"text": "<p>If you have control of the xml generation on the first occurence of a country you could add an attribute to the country node such as distinct='true' flag the country as \"used\" and not subsequently add the distinct attribute if you come across that country again.</p>\n\n<p>You could then do</p>\n\n<pre><code><xsl:for-each select=\"Artists_by_Countries/Artist_by_Country/Country[@distinct='true']\" />\n</code></pre>\n"
},
{
"answer_id": 153969,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 6,
"selected": true,
"text": "<p>If you have a large document, you probably want to use the \"Muenchian Method\", which is usually used for grouping, to identify the distinct nodes. Declare a key that indexes the things you want to count by the values that are distinct:</p>\n\n<pre><code><xsl:key name=\"artists-by-country\" match=\"Artist_by_Country\" use=\"Country\" />\n</code></pre>\n\n<p>Then you can get the <code><Artist_by_Country></code> elements that have distinct countries using:</p>\n\n<pre><code>/Artists_by_Countries\n /Artist_by_Country\n [generate-id(.) =\n generate-id(key('artists-by-country', Country)[1])]\n</code></pre>\n\n<p>and you can count them by wrapping that in a call to the <code>count()</code> function.</p>\n\n<p>Of course in XSLT 2.0, it's as simple as</p>\n\n<pre><code>count(distinct-values(/Artists_by_Countries/Artist_by_Country/Country))\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
How to count distinct values in a node in XSLT?
Example: I want to count the number of existing countries in Country nodes, in this case, it would be 3.
```
<Artists_by_Countries>
<Artist_by_Country>
<Location_ID>62</Location_ID>
<Artist_ID>212</Artist_ID>
<Country>Argentina</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>4</Location_ID>
<Artist_ID>108</Artist_ID>
<Country>Australia</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>4</Location_ID>
<Artist_ID>111</Artist_ID>
<Country>Australia</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>12</Location_ID>
<Artist_ID>78</Artist_ID>
<Country>Germany</Country>
</Artist_by_Country>
</Artists_by_Countries>
```
|
If you have a large document, you probably want to use the "Muenchian Method", which is usually used for grouping, to identify the distinct nodes. Declare a key that indexes the things you want to count by the values that are distinct:
```
<xsl:key name="artists-by-country" match="Artist_by_Country" use="Country" />
```
Then you can get the `<Artist_by_Country>` elements that have distinct countries using:
```
/Artists_by_Countries
/Artist_by_Country
[generate-id(.) =
generate-id(key('artists-by-country', Country)[1])]
```
and you can count them by wrapping that in a call to the `count()` function.
Of course in XSLT 2.0, it's as simple as
```
count(distinct-values(/Artists_by_Countries/Artist_by_Country/Country))
```
|
153,166 |
<p>I'm trying to find out whether there is a way to reliably determine when a managed thread is about to terminate. I'm using a third-party library that includes support for PDF documents and the problem is that in order to use the PDF functionality, I have to explicitly initialize the PDF component, do the work, then explicitly uninitialize the component before the thread terminates. If the uninitialize is not called, exceptions are thrown because unmanaged resources are not being released correctly. Since the thread class is sealed and has no events, I have to wrap the thread instance into a class and only allow instances of this class to do the work. </p>
<p>I should point out that this is part of a shared library used by multiple Windows applications. I may not always have control of threads making calls into this library.</p>
<p>Since a PDF object may be the output of a call to this library, and since the calling thread may do some other work with that object, I don't want to call the cleanup function immediately; I need to try to do it right before the thread terminates. Ideally I'd like to be able to subscribe to something like a Thread.Dispose event, but that's what I'm missing. </p>
|
[
{
"answer_id": 153176,
"author": "Eric",
"author_id": 6367,
"author_profile": "https://Stackoverflow.com/users/6367",
"pm_score": 1,
"selected": false,
"text": "<p>I think you can use an [Auto|Manual]ResetEvent which you will set when the thread terminates</p>\n"
},
{
"answer_id": 153179,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 1,
"selected": false,
"text": "<p>Catch the ThreadAbortExcpetion.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx</a></p>\n"
},
{
"answer_id": 153219,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 2,
"selected": false,
"text": "<p>You don't want to wrap <code>System.Thread</code> per se - just compose it with your <code>PDFWidget</code> class that is doing the work:</p>\n\n<pre><code>class PDFWidget\n{\n private Thread pdfWorker;\n public void DoPDFStuff()\n {\n pdfWorker = new Thread(new ThreadStart(ProcessPDF));\n pdfWorker.Start();\n }\n\n private void ProcessPDF()\n {\n OtherGuysPDFThingie pdfLibrary = new OtherGuysPDFThingie();\n // Use the library to do whatever...\n pdfLibrary.Cleanup();\n }\n}\n</code></pre>\n\n<p>You could also use a <code>ThreadPool</code> thread, if that is more to your taste - the best choice depends on how much control you need over the thread.</p>\n"
},
{
"answer_id": 153288,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>Wouldn't you just wrap your PDF usage with a finally (if it's a single method), or in an IDisposable?</p>\n"
},
{
"answer_id": 153333,
"author": "Drakiula",
"author_id": 2437,
"author_profile": "https://Stackoverflow.com/users/2437",
"pm_score": 0,
"selected": false,
"text": "<p>Check the Powerthreading library at <a href=\"http://wintellect.com\" rel=\"nofollow noreferrer\">http://wintellect.com</a>.</p>\n"
},
{
"answer_id": 153428,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 1,
"selected": false,
"text": "<p>what about calling a standard method in async mode? \ne.g</p>\n\n<pre><code>//declare a delegate with same firmature of your method\npublic delegete string LongMethodDelegate ();\n\n//register a callback func\nAsyncCallback callbackFunc = new AsyncCallback (this.callTermined); \n\n//create delegate for async operations\nLongMethodDelegate th = new LongMethodDelegate (yourObject.metyodWichMakeWork);\n\n//invoke method asnync.\n// pre last parameter is callback delegate.\n//the last parameter is an object wich you re-find in your callback function. to recovery return value, we assign delegate itSelf, see \"callTermined\" method\nlongMethod.beginInvoke(callbackFunc,longMethod); \n\n//follow function is called at the end of thr method\npublic static void callTermined(IAsyincResult result) {\nLongMethodDelegate method = (LongMethodDelegate ) result.AsyncState; \nstring output = method.endInvoke(result);\nConsole.WriteLine(output);\n}\n</code></pre>\n\n<p>See here form more info: <a href=\"http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx</a></p>\n"
},
{
"answer_id": 153462,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 1,
"selected": false,
"text": "<p>There are many ways you can do this, but the most simple one is to do like <a href=\"https://stackoverflow.com/users/3776/mckenzieg1\">McKenzieG1</a> said and just wrap the call to the PDF library. After you've called the PDF-library in the thread you can use an Event or ManualResetEvent depending on how you need to wait for the thread to finish. </p>\n\n<p>Don't forget to marshal event-calls to the UI-thread with a BeginInvoke if you're using the Event approach.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22239/"
] |
I'm trying to find out whether there is a way to reliably determine when a managed thread is about to terminate. I'm using a third-party library that includes support for PDF documents and the problem is that in order to use the PDF functionality, I have to explicitly initialize the PDF component, do the work, then explicitly uninitialize the component before the thread terminates. If the uninitialize is not called, exceptions are thrown because unmanaged resources are not being released correctly. Since the thread class is sealed and has no events, I have to wrap the thread instance into a class and only allow instances of this class to do the work.
I should point out that this is part of a shared library used by multiple Windows applications. I may not always have control of threads making calls into this library.
Since a PDF object may be the output of a call to this library, and since the calling thread may do some other work with that object, I don't want to call the cleanup function immediately; I need to try to do it right before the thread terminates. Ideally I'd like to be able to subscribe to something like a Thread.Dispose event, but that's what I'm missing.
|
You don't want to wrap `System.Thread` per se - just compose it with your `PDFWidget` class that is doing the work:
```
class PDFWidget
{
private Thread pdfWorker;
public void DoPDFStuff()
{
pdfWorker = new Thread(new ThreadStart(ProcessPDF));
pdfWorker.Start();
}
private void ProcessPDF()
{
OtherGuysPDFThingie pdfLibrary = new OtherGuysPDFThingie();
// Use the library to do whatever...
pdfLibrary.Cleanup();
}
}
```
You could also use a `ThreadPool` thread, if that is more to your taste - the best choice depends on how much control you need over the thread.
|
153,183 |
<p>I am working on the admin section of a new rails app and i'm trying to setup some routes to do things "properly". I have the following controller:</p>
<pre><code>class Admin::BlogsController < ApplicationController
def index
@blogs = Blog.find(:all)
end
def show
@blog = Blog.find(params[:id])
end
...
end
</code></pre>
<p>in routes.rb:</p>
<pre><code>map.namespace :admin do |admin|
admin.resources :blogs
end
</code></pre>
<p>in views/admin/blogs/index.html.erb:</p>
<pre><code><% for blog in @blogs %>
<%= link_to 'Delete', admin_blog(blog), :method => :delete
<% end %>
</code></pre>
<p>i have verified that the routes exist:</p>
<pre><code>admin_blogs GET /admin/blogs {:action => "index", :controller=>"admin/blogs"}
admin_blog GET /admin/blogs/:id {:action => "show", :controller => "admin/blogs"}
....
</code></pre>
<p>but when i try to view <a href="http://localhost:3000/admin/blogs" rel="nofollow noreferrer">http://localhost:3000/admin/blogs</a> i get this error:</p>
<pre><code>undefined method 'admin_blog' for #<ActionView::Base:0xb7213da8>
</code></pre>
<p>where am i going wrong and why?</p>
|
[
{
"answer_id": 153228,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": 2,
"selected": false,
"text": "<p>I'm assuming you are using rails 2.0.x so the way you generate a route is\n__path</p>\n\n<pre><code>admin_blog_path(blog) \n</code></pre>\n\n<p>and if you are riding a previous version I think it's just</p>\n\n<pre><code>blog_path(blog)\n</code></pre>\n"
},
{
"answer_id": 153245,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 4,
"selected": true,
"text": "<p>Your Delete link should end in _path:</p>\n\n<pre><code><%= link_to 'Delete', admin_blog_path(blog), :method => :delete %>\n</code></pre>\n"
},
{
"answer_id": 688244,
"author": "Paulo Delgado",
"author_id": 1864,
"author_profile": "https://Stackoverflow.com/users/1864",
"pm_score": 1,
"selected": false,
"text": "<p>Side note:\nI also see that your controller is defined like this:</p>\n\n<pre><code>class Admin::BlogsController < ApplicationController\n</code></pre>\n\n<p>shouldn't it be like this?</p>\n\n<pre><code>class Admin::BlogsController < Admin::ApplicationController\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18811/"
] |
I am working on the admin section of a new rails app and i'm trying to setup some routes to do things "properly". I have the following controller:
```
class Admin::BlogsController < ApplicationController
def index
@blogs = Blog.find(:all)
end
def show
@blog = Blog.find(params[:id])
end
...
end
```
in routes.rb:
```
map.namespace :admin do |admin|
admin.resources :blogs
end
```
in views/admin/blogs/index.html.erb:
```
<% for blog in @blogs %>
<%= link_to 'Delete', admin_blog(blog), :method => :delete
<% end %>
```
i have verified that the routes exist:
```
admin_blogs GET /admin/blogs {:action => "index", :controller=>"admin/blogs"}
admin_blog GET /admin/blogs/:id {:action => "show", :controller => "admin/blogs"}
....
```
but when i try to view <http://localhost:3000/admin/blogs> i get this error:
```
undefined method 'admin_blog' for #<ActionView::Base:0xb7213da8>
```
where am i going wrong and why?
|
Your Delete link should end in \_path:
```
<%= link_to 'Delete', admin_blog_path(blog), :method => :delete %>
```
|
153,227 |
<p>When I call</p>
<pre><code>help(Mod.Cls.f)
</code></pre>
<p>(Mod is a C extension module), I get the output</p>
<pre>Help on method_descriptor:
f(...)
doc_string</pre>
<p>What do I need to do so that the help output is of the form</p>
<pre>Help on method f in module Mod:
f(x, y, z)
doc_string</pre>
<p>like it is for random.Random.shuffle, for example?</p>
<p>My PyMethodDef entry is currently:</p>
<pre><code>{ "f", f, METH_VARARGS, "doc_string" }
</code></pre>
|
[
{
"answer_id": 153284,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 3,
"selected": true,
"text": "<p>You cannot. The inspect module, which is what 'pydoc' and 'help()' use, has no way of figuring out what the exact signature of a C function is. The best you can do is what the builtin functions do: include the signature in the first line of the docstring:</p>\n\n<pre><code>>>> help(range)\nHelp on built-in function range in module __builtin__:\n\nrange(...)\n range([start,] stop[, step]) -> list of integers\n\n...\n</code></pre>\n\n<p>The reason random.shuffle's docstring looks \"correct\" is that it isn't a C function. It's a function written in Python.</p>\n"
},
{
"answer_id": 154131,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 1,
"selected": false,
"text": "<p>Thomas's answer is right on, of course.</p>\n\n<p>I would simply add that many C extension modules have a Python \"wrapper\" around them so that they can support standard function signatures and other dynamic-language features (such as the descriptor protocol).</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11828/"
] |
When I call
```
help(Mod.Cls.f)
```
(Mod is a C extension module), I get the output
```
Help on method_descriptor:
f(...)
doc_string
```
What do I need to do so that the help output is of the form
```
Help on method f in module Mod:
f(x, y, z)
doc_string
```
like it is for random.Random.shuffle, for example?
My PyMethodDef entry is currently:
```
{ "f", f, METH_VARARGS, "doc_string" }
```
|
You cannot. The inspect module, which is what 'pydoc' and 'help()' use, has no way of figuring out what the exact signature of a C function is. The best you can do is what the builtin functions do: include the signature in the first line of the docstring:
```
>>> help(range)
Help on built-in function range in module __builtin__:
range(...)
range([start,] stop[, step]) -> list of integers
...
```
The reason random.shuffle's docstring looks "correct" is that it isn't a C function. It's a function written in Python.
|
153,257 |
<p>I noticed that writing to a file, closing it and moving it to destination place randomly fails on Vista. Specifically, MoveFileEx() would return <code>ERROR_ACCESS_DENIED</code> for no apparent reason. This happens on Vista SP1 at least (32 bit). Does not happen on XP SP3.</p>
<p>Found <a href="http://groups.google.com/group/microsoft.public.windows.file_system/browse_thread/thread/e9774e86e98eb623/3348d92b8ba5858d?lnk=raot&pli=1" rel="nofollow noreferrer">this thread</a> on the internets about exactly the same problem, with no real solutions. So far it looks like the error is caused by Vista's search indexer, see below.</p>
<p>The code example given there is enough to reproduce the problem. I'm pasting it here as well:</p>
<pre><code>#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
bool test() {
unsigned char buf[] = {
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99
};
HANDLE h;
DWORD nbytes;
LPCTSTR fn_tmp = "aaa";
LPCTSTR fn = "bbb";
h = CreateFile(fn_tmp, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_ALWAYS, 0, 0);
if (h == INVALID_HANDLE_VALUE) return 0;
if (!WriteFile(h, buf, sizeof buf, &nbytes, 0)) goto error;
if (!FlushFileBuffers(h)) goto error;
if (!CloseHandle(h)) goto error;
if (!MoveFileEx(fn_tmp, fn, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) {
printf("error=%d\n", GetLastError());
return 0;
}
return 1;
error:
CloseHandle(h);
return 0;
}
int main(int argc, char** argv) {
unsigned int i;
for (i = 0;; ++i) {
printf("*%u\n", i);
if (!test()) return 1;
}
return 0;
}
</code></pre>
<p>Build this as console app with Visual Studio. Correct behaviour would be infinite loop that prints test numbers. On Vista SP1, the program exits after random number of iterations (usually before 100 iterations are made).</p>
<p>This does not happen on Windows XP SP2. There's no antivirus running at all; and no other strange background processes (machine is pretty much vanilla OS install + Visual Studio).</p>
<p><strong>Edit</strong>: Digging further via Process Monitor (thanks @sixlettervariables), I can't see anything particularly bad. Each test iteration results in 176 disk operations, majority of them coming from SearchProtocolHost.exe (search indexer). If search indexing service is stopped, no errors occur, so it looks like it's the culprit.</p>
<p>At the time of failure (when the app gets <code>ERROR_ACCESS_DENIED</code>), SearchProtocolHost.exe has two CreateFile(s) to the detination file (bbb) open with read/write/delete share modes, so it should be ok. One of the opens is followed by opportunistic lock (<code>FSCTL_REQUEST_FILTER_OPLOCK</code>), maybe that's the cause?</p>
<p>Anyway, I found out that I can avoid the problem by setting <code>FILE_ATTRIBUTE_TEMPORARY</code> and <code>FILE_ATTRIBUTE_NOT_CONTENT_INDEXED</code> flags on the file. It looks like <code>FILE_ATTRIBUTE_NOT_CONTENT_INDEXED</code> is enough by itself, but marking file as temporary also dramatically cuts down disk operations caused by search indexer.</p>
<p>But this is <strong>not a real solution</strong>. I mean, if an application can't expect to be able to create a file and rename it because some Vista's search indexer is messing with it, <strong>it's totally crazy</strong>! Should it keep retrying? Yell at the user (which is very undesirable)? Do something else?</p>
|
[
{
"answer_id": 153493,
"author": "Martin Plante",
"author_id": 4898,
"author_profile": "https://Stackoverflow.com/users/4898",
"pm_score": 1,
"selected": false,
"text": "<p>I'd say it's either your anti-virus or Windows Indexing messing with the file at the same moment. Can you run the same test without an anti-virus. Then run it again making sure the temp file is created somewhere not indexed by Windows Search?</p>\n"
},
{
"answer_id": 153511,
"author": "Lee Baldwin",
"author_id": 5200,
"author_profile": "https://Stackoverflow.com/users/5200",
"pm_score": 0,
"selected": false,
"text": "<p>That usually means something else has an open handle on the file in question, maybe an active virus scanner running? Have you tried running something like Process Monitor from the <a href=\"http://technet.microsoft.com/en-us/sysinternals/default.aspx\" rel=\"nofollow noreferrer\">Sysinternals</a> site? You should be to filter all file operations and get a better picture of whats going on underneath the hood.</p>\n"
},
{
"answer_id": 153525,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 3,
"selected": true,
"text": "<p>I suggest you use <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">Process Monitor</a> <em>(edit: the artist formerly known as FileMon)</em> to watch and see which application exactly is getting in the way. It can show you the entire trace of file system calls made on your machine.</p>\n\n<p><em>(edit: thanks to @moocha for the change in application)</em></p>\n"
},
{
"answer_id": 159699,
"author": "Morten Christiansen",
"author_id": 4055,
"author_profile": "https://Stackoverflow.com/users/4055",
"pm_score": 0,
"selected": false,
"text": "<p>Windows has a special location for storing application files and I don't think its indexed (at least not by default). In Vista the path is:</p>\n\n<p>C:\\Users\\<em>user name</em>\\AppData</p>\n\n<p>I suggest you put your files there if it is appropriate for your application.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6799/"
] |
I noticed that writing to a file, closing it and moving it to destination place randomly fails on Vista. Specifically, MoveFileEx() would return `ERROR_ACCESS_DENIED` for no apparent reason. This happens on Vista SP1 at least (32 bit). Does not happen on XP SP3.
Found [this thread](http://groups.google.com/group/microsoft.public.windows.file_system/browse_thread/thread/e9774e86e98eb623/3348d92b8ba5858d?lnk=raot&pli=1) on the internets about exactly the same problem, with no real solutions. So far it looks like the error is caused by Vista's search indexer, see below.
The code example given there is enough to reproduce the problem. I'm pasting it here as well:
```
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
bool test() {
unsigned char buf[] = {
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99
};
HANDLE h;
DWORD nbytes;
LPCTSTR fn_tmp = "aaa";
LPCTSTR fn = "bbb";
h = CreateFile(fn_tmp, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_ALWAYS, 0, 0);
if (h == INVALID_HANDLE_VALUE) return 0;
if (!WriteFile(h, buf, sizeof buf, &nbytes, 0)) goto error;
if (!FlushFileBuffers(h)) goto error;
if (!CloseHandle(h)) goto error;
if (!MoveFileEx(fn_tmp, fn, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) {
printf("error=%d\n", GetLastError());
return 0;
}
return 1;
error:
CloseHandle(h);
return 0;
}
int main(int argc, char** argv) {
unsigned int i;
for (i = 0;; ++i) {
printf("*%u\n", i);
if (!test()) return 1;
}
return 0;
}
```
Build this as console app with Visual Studio. Correct behaviour would be infinite loop that prints test numbers. On Vista SP1, the program exits after random number of iterations (usually before 100 iterations are made).
This does not happen on Windows XP SP2. There's no antivirus running at all; and no other strange background processes (machine is pretty much vanilla OS install + Visual Studio).
**Edit**: Digging further via Process Monitor (thanks @sixlettervariables), I can't see anything particularly bad. Each test iteration results in 176 disk operations, majority of them coming from SearchProtocolHost.exe (search indexer). If search indexing service is stopped, no errors occur, so it looks like it's the culprit.
At the time of failure (when the app gets `ERROR_ACCESS_DENIED`), SearchProtocolHost.exe has two CreateFile(s) to the detination file (bbb) open with read/write/delete share modes, so it should be ok. One of the opens is followed by opportunistic lock (`FSCTL_REQUEST_FILTER_OPLOCK`), maybe that's the cause?
Anyway, I found out that I can avoid the problem by setting `FILE_ATTRIBUTE_TEMPORARY` and `FILE_ATTRIBUTE_NOT_CONTENT_INDEXED` flags on the file. It looks like `FILE_ATTRIBUTE_NOT_CONTENT_INDEXED` is enough by itself, but marking file as temporary also dramatically cuts down disk operations caused by search indexer.
But this is **not a real solution**. I mean, if an application can't expect to be able to create a file and rename it because some Vista's search indexer is messing with it, **it's totally crazy**! Should it keep retrying? Yell at the user (which is very undesirable)? Do something else?
|
I suggest you use [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) *(edit: the artist formerly known as FileMon)* to watch and see which application exactly is getting in the way. It can show you the entire trace of file system calls made on your machine.
*(edit: thanks to @moocha for the change in application)*
|
153,266 |
<p>In C and C++ you can tell the compiler that a number is a 'long' by putting an 'l' at the end of the number.
e.g long x = 0l;</p>
<p>How can I tell the C# compiler that a number is a byte?</p>
|
[
{
"answer_id": 153271,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 3,
"selected": false,
"text": "<pre><code>byte b = (byte) 123; \n</code></pre>\n\n<p>even though</p>\n\n<pre><code>byte b = 123;\n</code></pre>\n\n<p>does the same thing. If you have a variable:</p>\n\n<pre><code>int a = 42;\nbyte b = (byte) a;\n</code></pre>\n"
},
{
"answer_id": 153280,
"author": "casademora",
"author_id": 5619,
"author_profile": "https://Stackoverflow.com/users/5619",
"pm_score": 2,
"selected": false,
"text": "<p>Remember, if you do:</p>\n\n<pre><code>byte b = (byte)300;\n</code></pre>\n\n<p>it's not going to work the way you expect.</p>\n"
},
{
"answer_id": 153305,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 1,
"selected": false,
"text": "<p>MSDN uses <a href=\"http://msdn.microsoft.com/en-us/library/5bdb6693(VS.71).aspx\" rel=\"nofollow noreferrer\">implicit conversion</a>. I don't see a <a href=\"http://msdn.microsoft.com/en-us/library/aa664674(VS.71).aspx\" rel=\"nofollow noreferrer\">byte type suffix</a>, but you might use an explicit cast. I'd just use a 2-digit hexadecimal integer (int) constant.</p>\n"
},
{
"answer_id": 153308,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 1,
"selected": false,
"text": "<p>No need to tell the compiler. You can assign any valid value to the byte variable and the compiler is just fine with it: there's no suffix for byte.</p>\n\n<p>If you want to store a byte in an object you have to cast:</p>\n\n<pre><code>object someValue = (byte) 123;\n</code></pre>\n"
},
{
"answer_id": 153310,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": true,
"text": "<p>According to the <a href=\"http://msdn.microsoft.com/en-us/library/aa664674(VS.71).aspx\" rel=\"noreferrer\">C# language specification</a> there is no way to specify a byte literal. You'll have to cast down to byte in order to get a byte. Your best bet is probably to specify in hex and cast down, like this:</p>\n\n<pre><code>byte b = (byte) 0x10;\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9516/"
] |
In C and C++ you can tell the compiler that a number is a 'long' by putting an 'l' at the end of the number.
e.g long x = 0l;
How can I tell the C# compiler that a number is a byte?
|
According to the [C# language specification](http://msdn.microsoft.com/en-us/library/aa664674(VS.71).aspx) there is no way to specify a byte literal. You'll have to cast down to byte in order to get a byte. Your best bet is probably to specify in hex and cast down, like this:
```
byte b = (byte) 0x10;
```
|
153,287 |
<p>I have implemented a simple file upload-download mechanism. When a user clicks a file name, the file is downloaded with these HTTP headers:</p>
<pre><code>HTTP/1.1 200 OK
Date: Tue, 30 Sep 2008 14:00:39 GMT
Server: Microsoft-IIS/6.0
Content-Disposition: attachment; filename=filename.doc;
Content-Type: application/octet-stream
Content-Length: 10754
</code></pre>
<p>I also support Japanese file names. In order to do that, I encode the file name with this java method:</p>
<pre><code>private String encodeFileName(String name) throws Exception{
String agent = request.getHeader("USER-AGENT");
if(agent != null && agent.indexOf("MSIE") != -1){ // is IE
StringBuffer res = new StringBuffer();
char[] chArr = name.toCharArray();
for(int j = 0; j < chArr.length; j++){
if(chArr[j] < 128){ // plain ASCII char
if (chArr[j] == '.' && j != name.lastIndexOf("."))
res.append("%2E");
else
res.append(chArr[j]);
}
else{ // non-ASCII char
byte[] byteArr = name.substring(j, j + 1).getBytes("UTF8");
for(int i = 0; i < byteArr.length; i++){
// byte must be converted to unsigned int
res.append("%").append(Integer.toHexString((byteArr[i]) & 0xFF));
}
}
}
return res.toString();
}
// Firefox/Mozilla
return MimeUtility.encodeText(name, "UTF8", "B");
}
</code></pre>
<p>It worked well so far, until someone found out that it doesn't work well with long file names. For example: <code>あああああああああああああああ2008.10.1あ.doc</code>. If I change one of the single-byte dots to a single-byte underline , or if I remove the first character, it works OK. i.e., it depends on length and URL-encoding of a dot character.
Following are a few examples. </p>
<p>This is broken (<code>あああああああああああああああ2008.10.1あ.doc</code>):</p>
<pre><code>Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008%2E10%2E1%e3%81%82.doc;
</code></pre>
<p>This is OK (<code>あああああああああああああああ2008_10.1あ.doc</code>):</p>
<pre><code>Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008_10%2E1%e3%81%82.doc;
</code></pre>
<p>This is also fine (<code>あああああああああああああああ2008.10.1あ.doc</code>):</p>
<pre><code>Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008%2E10%2E1%e3%81%82.doc;
</code></pre>
<p>Anybody have a clue?</p>
|
[
{
"answer_id": 153400,
"author": "Ovesh",
"author_id": 3751,
"author_profile": "https://Stackoverflow.com/users/3751",
"pm_score": 4,
"selected": true,
"text": "<p>gmail handles file name escaping somewhat differently: the file name is quoted (double-quotes), and single-byte periods are not URL-escaped. \nThis way, the long file name in the question is OK. </p>\n\n<pre><code>Content-Disposition: attachment; filename=\"%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%822008.10.1%E3%81%82.doc\"\n</code></pre>\n\n<p>However, there is still a limitation (apparently IE-only) on the byte-length of the file name (a bug, I assume). So even if the file name is made of only single-byte characters, the beginning of the file name is truncated.\nThe limitation is around 160 bytes.</p>\n"
},
{
"answer_id": 810818,
"author": "Julian Reschke",
"author_id": 50543,
"author_profile": "https://Stackoverflow.com/users/50543",
"pm_score": 1,
"selected": false,
"text": "<p>The main issue here is that IE does not support the relevant RFC, here: RFC2231. See <a href=\"http://greenbytes.de/tech/tc2231/\" rel=\"nofollow noreferrer\">pointers and test cases</a>. Furthermore, the workaround that you use for IE (just using percent-escaped UTF-8) has several additional problems; it may not work in all locales (as far as I recall, the method fails in Korea unless IE is configured to always use UTF-8 in URLs which is not the default), and, as previously mentioned, there are length limits (I hear that <strong>that</strong> is fixed in IE8, but I did not try yet).</p>\n"
},
{
"answer_id": 1938772,
"author": "Gavin Brock",
"author_id": 235855,
"author_profile": "https://Stackoverflow.com/users/235855",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned above, Content-Disposition and Unicode is impossible to get working all main browsers without browser sniffing and returning different headers for each.</p>\n\n<p>My solution was to avoid the Content-Disposition header entirely, and append the filename to the end of the URL to trick the browser into thinking it was getting a file directly. e.g.</p>\n\n<pre><code>http://www.xyz.com/cgi-bin/dynamic.php/あああああああああああああああ2008.10.1あ.doc\n</code></pre>\n\n<p>This naturally assumes that you know the filename when you create the link, although a quick redirect header could set it on demand.</p>\n"
},
{
"answer_id": 3491141,
"author": "hardik",
"author_id": 421441,
"author_profile": "https://Stackoverflow.com/users/421441",
"pm_score": -1,
"selected": false,
"text": "<p>I think this issue is fixed in IE8, I have seen it working in IE 8.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3751/"
] |
I have implemented a simple file upload-download mechanism. When a user clicks a file name, the file is downloaded with these HTTP headers:
```
HTTP/1.1 200 OK
Date: Tue, 30 Sep 2008 14:00:39 GMT
Server: Microsoft-IIS/6.0
Content-Disposition: attachment; filename=filename.doc;
Content-Type: application/octet-stream
Content-Length: 10754
```
I also support Japanese file names. In order to do that, I encode the file name with this java method:
```
private String encodeFileName(String name) throws Exception{
String agent = request.getHeader("USER-AGENT");
if(agent != null && agent.indexOf("MSIE") != -1){ // is IE
StringBuffer res = new StringBuffer();
char[] chArr = name.toCharArray();
for(int j = 0; j < chArr.length; j++){
if(chArr[j] < 128){ // plain ASCII char
if (chArr[j] == '.' && j != name.lastIndexOf("."))
res.append("%2E");
else
res.append(chArr[j]);
}
else{ // non-ASCII char
byte[] byteArr = name.substring(j, j + 1).getBytes("UTF8");
for(int i = 0; i < byteArr.length; i++){
// byte must be converted to unsigned int
res.append("%").append(Integer.toHexString((byteArr[i]) & 0xFF));
}
}
}
return res.toString();
}
// Firefox/Mozilla
return MimeUtility.encodeText(name, "UTF8", "B");
}
```
It worked well so far, until someone found out that it doesn't work well with long file names. For example: `あああああああああああああああ2008.10.1あ.doc`. If I change one of the single-byte dots to a single-byte underline , or if I remove the first character, it works OK. i.e., it depends on length and URL-encoding of a dot character.
Following are a few examples.
This is broken (`あああああああああああああああ2008.10.1あ.doc`):
```
Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008%2E10%2E1%e3%81%82.doc;
```
This is OK (`あああああああああああああああ2008_10.1あ.doc`):
```
Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008_10%2E1%e3%81%82.doc;
```
This is also fine (`あああああああああああああああ2008.10.1あ.doc`):
```
Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008%2E10%2E1%e3%81%82.doc;
```
Anybody have a clue?
|
gmail handles file name escaping somewhat differently: the file name is quoted (double-quotes), and single-byte periods are not URL-escaped.
This way, the long file name in the question is OK.
```
Content-Disposition: attachment; filename="%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%822008.10.1%E3%81%82.doc"
```
However, there is still a limitation (apparently IE-only) on the byte-length of the file name (a bug, I assume). So even if the file name is made of only single-byte characters, the beginning of the file name is truncated.
The limitation is around 160 bytes.
|
153,298 |
<p>Having recently produced an HTML/CSS/Javascript based report from various word and excel files sent to me I'm trying to work out how to do this better in future, ideally enabling non-technical users in the office to do many of the tasks currently handed to me.</p>
<p>There are a range of HTML editors out there but none of them seem obviously adept at doing this kind of task. For example, most tables in the document are displayed via a thickbox (jquery plugin). In addition to the table, this requires that I enclose them in a div with various id and class attributes and then create a link at the top of the page looking something like this:</p>
<pre><code><a href="#TB_inline?height=300&amp;width=700&amp;inlineId=tbtable2"
class="thickbox tablelink" title="Municipal Operating Expenditure (A$m)">Municipal Operating Expenditure</a>
</code></pre>
<p>I need a solution that will be careful with my templates, have a WYSIWYG interface, but also provide easy input for this kind of thing without frustrating those in the office with no HTML knowledge, ideally keeping them totally away from the code.</p>
|
[
{
"answer_id": 153349,
"author": "nikhil",
"author_id": 7926,
"author_profile": "https://Stackoverflow.com/users/7926",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried <a href=\"http://www.fckeditor.net/\" rel=\"nofollow noreferrer\">FCKEditor</a>. It is very popular and used in a number of blogs, wikis and CMSs. It can produce very clean HTML and is highly customizable.</p>\n"
},
{
"answer_id": 153422,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 1,
"selected": false,
"text": "<p>Get them to use Markdown, just like here, and insert the rendered HTML into your template.</p>\n"
},
{
"answer_id": 370803,
"author": "Laurens",
"author_id": 46572,
"author_profile": "https://Stackoverflow.com/users/46572",
"pm_score": 2,
"selected": false,
"text": "<p>You can't give your non-technial users such a complex HTML template and hope they will not break it. There is no HTML editor that can enforce such rules for structures that are more complex than a class attribute on an element.</p>\n\n<p>This scenario calls for the use of XML: you need to separate your content and presentation. </p>\n\n<p>You should define an XML flavour to describe your report. Then write an XSLT that will transform your <thickbox/> XML element into the HTML structure you describe above.</p>\n\n<p>To allow non-technical users to do some of your tasks, you could use <a href=\"http://xopus.com\" rel=\"nofollow noreferrer\">Xopus</a> to make the XML editable (<a href=\"http://xopus.com/files/demo/xopus/xopus.html#/files/demo/examples/Recipe/start.html\" rel=\"nofollow noreferrer\">demo</a>). You could do the initial conversion from OOXML, or you could use the copy/paste functionality in Xopus to allow them to copy content from Excel and automatically convert it into your <thickbox/> element.</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Having recently produced an HTML/CSS/Javascript based report from various word and excel files sent to me I'm trying to work out how to do this better in future, ideally enabling non-technical users in the office to do many of the tasks currently handed to me.
There are a range of HTML editors out there but none of them seem obviously adept at doing this kind of task. For example, most tables in the document are displayed via a thickbox (jquery plugin). In addition to the table, this requires that I enclose them in a div with various id and class attributes and then create a link at the top of the page looking something like this:
```
<a href="#TB_inline?height=300&width=700&inlineId=tbtable2"
class="thickbox tablelink" title="Municipal Operating Expenditure (A$m)">Municipal Operating Expenditure</a>
```
I need a solution that will be careful with my templates, have a WYSIWYG interface, but also provide easy input for this kind of thing without frustrating those in the office with no HTML knowledge, ideally keeping them totally away from the code.
|
You can't give your non-technial users such a complex HTML template and hope they will not break it. There is no HTML editor that can enforce such rules for structures that are more complex than a class attribute on an element.
This scenario calls for the use of XML: you need to separate your content and presentation.
You should define an XML flavour to describe your report. Then write an XSLT that will transform your <thickbox/> XML element into the HTML structure you describe above.
To allow non-technical users to do some of your tasks, you could use [Xopus](http://xopus.com) to make the XML editable ([demo](http://xopus.com/files/demo/xopus/xopus.html#/files/demo/examples/Recipe/start.html)). You could do the initial conversion from OOXML, or you could use the copy/paste functionality in Xopus to allow them to copy content from Excel and automatically convert it into your <thickbox/> element.
|
153,329 |
<p>We have a service that handles authorization based on a User Name and Password. Instead of making the username and password part of the call, we place it in the SOAP header. </p>
<p>In a typical scenario, a Web Service calls the Authorization service at the start of execution to check that the caller is allowed to call it. The problem is though that some of these Web services call each other, and it would mean that on every sub-call the user's permissions are checked, and that can be very expensive.</p>
<p>What I thought of doing was to have the Authorization service return a Security Token after the first call. Then, instead of having to call the Authorization service each time, the Web Service can validate the Security Header locally.</p>
<p>The Security Header looks something like this (C# code - trimmed to illustrate the essential concept):</p>
<pre><code>public sealed class SecurityHeader : SoapHeader
{
public string UserId; // Encrypted
public string Password; // Encrypted; Just realized this field isn't necessary [thanks CJP]
public DateTime TimeStamp; // Used for calculating header Expiry
public string SecurityToken;
}
</code></pre>
<p>The general idea is that the SecurityHeader gets checked with every call. If it exists, hasn't expired, and the SecurityToken is valid, then the Web Method proceeds as normal. Otherwise it will either return an error, or it will attempt to re-authorize and generate a new SecurityHeader</p>
<p>The SecurityToken is based on a salted hash of the UserId, Password, and TimeStamp. The salt is changed every day to prevent replays.</p>
<p>The one problem I do see is that a user might have permission to access Web Service A, but not Web Service B. If he calls A and receives a security token, as it stands now it means that B will let him through if he uses that same token. I have to change it so that the security token is only valid from Web Service to Web Service, rather than User to Web Service ie. It should be OK if the user calls A which calls B, but not OK if the user calls Service A and then Service D. A way around that is to assign a common key (or a set of keys) to logically related services. (ie. if client can do A then logically he can do B as well).</p>
<p>Alternatively, I'd have to encode the user's entire permission set as part of the security header. I'll have to investigate what the overhead will be.</p>
<p>Edit:</p>
<p>Several people have mentioned looking at other security schemes like WS-Security and SAML etc. I already have. In fact, I got the idea from WS-Security. The problem is that other schemes don't provide the functionality I need (caching authorization information and protecting against replays without an intemediary database). If someone knows of a scheme that does then I will glady use it instead. Also, this is <em>not</em> about authentication. That is handled by another mechanism beyond my control.</p>
<p>If it turns out that there is no way to cache authorization data, then it means that I'll just have to incur the overhead of authorization at each level.</p>
|
[
{
"answer_id": 153378,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>Personally I don't see you having any issues there as long as you have a centralized underlying framework to support the validation of the SecurityToken values.</p>\n"
},
{
"answer_id": 160449,
"author": "ykaganovich",
"author_id": 10026,
"author_profile": "https://Stackoverflow.com/users/10026",
"pm_score": 2,
"selected": false,
"text": "<p>Ok, replacing my older answers with hopefully a better one.</p>\n\n<p>What you describe should work if you have a way to securely share data between your services. For example, if your services share a secret key with the Authorization Service, you can use this key to get the salt.</p>\n\n<p>BTW, I don't know enough cryptography to say whether it's safe enough to add secret salt + hash (although seems fine); I'm pretty sure it's safe to <a href=\"http://en.wikipedia.org/wiki/HMAC\" rel=\"nofollow noreferrer\">HMAC</a> with a secret or private key. Rotating keys is a good idea, so you would still have a master key and propagate a new signing key.</p>\n\n<p>Other issues with your approach are that (a) you're hardcoding the hashing logic in every service, and (b) the services might want to get more detailed data from the Authorization Service than just a yes/no answer. For example, you may want the Authorization Service to insert into the header that this user belongs to roles A and B but not C.</p>\n\n<p>As an alternative, you can let the Authorization Service create a new header with whatever interesting information it has, and sign that block. </p>\n\n<p>At this point, we're discussing a Single Sign-On implementation. You already know about <a href=\"http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=wss\" rel=\"nofollow noreferrer\">WS-Security</a> specs. This header I described sounds a lot like a <a href=\"http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=security\" rel=\"nofollow noreferrer\">SAML</a> assertion. </p>\n\n<p><a href=\"http://www.oracle.com/technology/tech/java/newsletter/articles/wsaudit/ws_audit.html\" rel=\"nofollow noreferrer\">Here's an article</a> about using WS-Security and SAML for Single Sign-On.</p>\n\n<p>Now, I don't know whether you need all this... there are in-between solutions too. For example, the Authorization Service could sign the original Username block; if you worry about public/private crypto performance, and you're ok sharing secret keys, you could also use a secret key to sign instead of public/private keys.</p>\n"
},
{
"answer_id": 160631,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The fundamental problem with your scheme is that you're not using a standard framework, or implementation. This is regardless of any particular merits of your scheme itself.</p>\n\n<p>The reason is simple, security (cryptography in particular) is very, very complicated and pretty much impossible to get right. Use a common tool that is robust, well understood and proven.</p>\n\n<p>See: <strong><a href=\"http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=wss\" rel=\"nofollow noreferrer\">http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=wss</a></strong> for more information on WS-Security.</p>\n\n<p>Most frameworks (.NET/JavaEE etc) will have in-built support (to some degree) for WS-Security.</p>\n\n<p>If you beleive your scheme to be better in some way than the standards, I suggest you write it up as a paper and submit it for peer-review (along with a reference implementation), but DO NOT use it to secure an application.</p>\n\n<p>EDIT to respond to OP Edit: \nI think you're confusing the roles of Authentication and Authorization a little, which is easy to do...</p>\n\n<p>The roll of the Security Token (or similar) in schemes is to Authenticate the sender of the message - basically, is the sender who they should be. As you rightly pointed out, Authentication does not imply anything about which underlying resources the sender is to be granted access to.</p>\n\n<p>Authorization is the process whereby you take an authenticated sender and apply some set of permissions so that you can restrict scope of access. Generally the frameworks won't do authorization by default, you either have to enable it by creating some form of ACL, or by extending some kind of \"Security Manager\" type interface.</p>\n\n<p>In effect, the idea is that the Authentication layer tells you who is trying to access Page A, and leaves it up to you to decide if that person is authorized to access Page A.</p>\n\n<p>You should never store information about the rights and permissions in the message itself - the receiver should verify rights against its ACL (or database or whatever) for each message. This limits your exposure should someone figure out how to modify the message.</p>\n"
},
{
"answer_id": 171336,
"author": "AviD",
"author_id": 10080,
"author_profile": "https://Stackoverflow.com/users/10080",
"pm_score": 0,
"selected": false,
"text": "<p>First of all, read @CJP 's post, he makes an excellent and valid point.<br>\nIf you want to go ahead and roll it yourself anyway (maybe you do have a good reason for it), I would make the following points: </p>\n\n<ul>\n<li>You're talking about an Authentication Service, NOT an authorization service. Just to make sure you know what you're talking about...?</li>\n<li>Second, you need to separate between the salt (which is not secret) and the key (which is). You should have a keyed hash (e.g. HMAC), together with salt (or a keyed salted hash. Sounds like a sandwich.). The salt, as noted, is not secret, but should be changed FOR EACH TOKEN, and can be included in the header; the key MUST be secret and being changed every day is good. Of course, make sure you're using strong hash (e.g. SHA-256), proper key management techniques, etc etc.</li>\n</ul>\n\n<p>Again, I urge you to reconsider rolling your own, but if you have to go out on your own...</p>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9825/"
] |
We have a service that handles authorization based on a User Name and Password. Instead of making the username and password part of the call, we place it in the SOAP header.
In a typical scenario, a Web Service calls the Authorization service at the start of execution to check that the caller is allowed to call it. The problem is though that some of these Web services call each other, and it would mean that on every sub-call the user's permissions are checked, and that can be very expensive.
What I thought of doing was to have the Authorization service return a Security Token after the first call. Then, instead of having to call the Authorization service each time, the Web Service can validate the Security Header locally.
The Security Header looks something like this (C# code - trimmed to illustrate the essential concept):
```
public sealed class SecurityHeader : SoapHeader
{
public string UserId; // Encrypted
public string Password; // Encrypted; Just realized this field isn't necessary [thanks CJP]
public DateTime TimeStamp; // Used for calculating header Expiry
public string SecurityToken;
}
```
The general idea is that the SecurityHeader gets checked with every call. If it exists, hasn't expired, and the SecurityToken is valid, then the Web Method proceeds as normal. Otherwise it will either return an error, or it will attempt to re-authorize and generate a new SecurityHeader
The SecurityToken is based on a salted hash of the UserId, Password, and TimeStamp. The salt is changed every day to prevent replays.
The one problem I do see is that a user might have permission to access Web Service A, but not Web Service B. If he calls A and receives a security token, as it stands now it means that B will let him through if he uses that same token. I have to change it so that the security token is only valid from Web Service to Web Service, rather than User to Web Service ie. It should be OK if the user calls A which calls B, but not OK if the user calls Service A and then Service D. A way around that is to assign a common key (or a set of keys) to logically related services. (ie. if client can do A then logically he can do B as well).
Alternatively, I'd have to encode the user's entire permission set as part of the security header. I'll have to investigate what the overhead will be.
Edit:
Several people have mentioned looking at other security schemes like WS-Security and SAML etc. I already have. In fact, I got the idea from WS-Security. The problem is that other schemes don't provide the functionality I need (caching authorization information and protecting against replays without an intemediary database). If someone knows of a scheme that does then I will glady use it instead. Also, this is *not* about authentication. That is handled by another mechanism beyond my control.
If it turns out that there is no way to cache authorization data, then it means that I'll just have to incur the overhead of authorization at each level.
|
Ok, replacing my older answers with hopefully a better one.
What you describe should work if you have a way to securely share data between your services. For example, if your services share a secret key with the Authorization Service, you can use this key to get the salt.
BTW, I don't know enough cryptography to say whether it's safe enough to add secret salt + hash (although seems fine); I'm pretty sure it's safe to [HMAC](http://en.wikipedia.org/wiki/HMAC) with a secret or private key. Rotating keys is a good idea, so you would still have a master key and propagate a new signing key.
Other issues with your approach are that (a) you're hardcoding the hashing logic in every service, and (b) the services might want to get more detailed data from the Authorization Service than just a yes/no answer. For example, you may want the Authorization Service to insert into the header that this user belongs to roles A and B but not C.
As an alternative, you can let the Authorization Service create a new header with whatever interesting information it has, and sign that block.
At this point, we're discussing a Single Sign-On implementation. You already know about [WS-Security](http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=wss) specs. This header I described sounds a lot like a [SAML](http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=security) assertion.
[Here's an article](http://www.oracle.com/technology/tech/java/newsletter/articles/wsaudit/ws_audit.html) about using WS-Security and SAML for Single Sign-On.
Now, I don't know whether you need all this... there are in-between solutions too. For example, the Authorization Service could sign the original Username block; if you worry about public/private crypto performance, and you're ok sharing secret keys, you could also use a secret key to sign instead of public/private keys.
|
153,344 |
<p>I have a class Animal and an interface it inherits from IAnimal.</p>
<pre><code>@MappedSuperclass
public class Animal implements Serializable, IAnimal{...}.
@Entity
public class Jaguar extends Animal{...}
</code></pre>
<p>My first question is, do I need to annotate the interface?</p>
<p>I asked this because I am getting this error when I run my tests:</p>
<blockquote>
<p>Error compiling the query [SELECT s
FROM animal s WHERE s.atype =
:atype].
Unknown abstract schema type
[animal]</p>
</blockquote>
<p>If I remember correctly, before I added this interface it was working.</p>
|
[
{
"answer_id": 153336,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "<p>Here are a bunch of good textbooks:</p>\n\n<p>Modern Compiler Implementation in Java (Tiger book) \nA.W. Appel \nCambridge University Press, 1998 \nISBN 0-52158-388-8 \nA textbook tutorial on compiler implementation, including techniques for many language features</p>\n\n<p>Compilers: Principles, Techniques and Tools (Dragon book) \nAho, Lam, Sethi and Ullman \nAddison-Wesley, 2006 \nISBN 0321486811 \nThe classic compilers textbook, although its front-end emphasis reflects its age.</p>\n\n<p>Advanced Compiler Design and Implementation (Whale book) \nSteven Muchnick \nMorgan Kaufman Publishers, 1997 \nISBN 1-55860-320-4 \nEssentially a recipe book of optimizations; very complete and suited for industrial practitioners and researchers.</p>\n\n<p>Engineering a Compiler (Ark book) \nKeith D. Cooper, Linda Torczon \nMorgan Kaufman Publishers, 2003 \nISBN 1-55860-698-X \nA modern classroom textbook, with increased emphasis on the back-end and implementation techniques.</p>\n\n<p>Optimizing Compilers for Modern Architectures \nRandy Allen and Ken Kennedy \nMorgan Kaufman Publishers, 2001 \nISBN 1-55860-286-0 \nA modern textbook that focuses on optimizations including parallelization and memory hierarchy optimizations.</p>\n\n<p>Programming Languages Pragmatics \nMichael L. Scott \nMorgan Kaufmann Publishers, 2005 \nISBN 0126339511</p>\n"
},
{
"answer_id": 153338,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": -1,
"selected": false,
"text": "<p>The Purple Dragon Book is the best ever.</p>\n"
},
{
"answer_id": 153353,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://search.barnesandnoble.com/The-Design-and-Evolution-of-C/Bjarne-Stroustrup/e/9780201543308/?itm=1\" rel=\"nofollow noreferrer\">The Design and Evolution of C++</a> by Bjarne Stroustrup, which has fairly little code, but mostly discusses the trade-offs and other concerns in designing the language.</p>\n"
},
{
"answer_id": 153397,
"author": "zvrba",
"author_id": 2583,
"author_profile": "https://Stackoverflow.com/users/2583",
"pm_score": 0,
"selected": false,
"text": "<p>Try to look at the <a href=\"http://llvm.org/\" rel=\"nofollow noreferrer\">LLVM</a> project and their publications and tutorials.</p>\n"
},
{
"answer_id": 153443,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 2,
"selected": false,
"text": "<p>I suggest playing with <a href=\"http://antlr.org/\" rel=\"nofollow noreferrer\">ANTLR</a>. I used it awhile back and found it very easy to use. </p>\n"
},
{
"answer_id": 158298,
"author": "janm",
"author_id": 7256,
"author_profile": "https://Stackoverflow.com/users/7256",
"pm_score": 1,
"selected": false,
"text": "<p>My favourite is \"Building an Optimizing Compiler\" by Robert Morgan. Very practical, covers static single assignment.</p>\n"
},
{
"answer_id": 195855,
"author": "jakobengblom2",
"author_id": 23054,
"author_profile": "https://Stackoverflow.com/users/23054",
"pm_score": 1,
"selected": false,
"text": "<p>Another hint: do not start digging into GCC; it is way too complicated. You want something more researchy and simple to start with, I would suggest looking into something like a Java compiler written in Java or the Erlang compilers written in Erlang. </p>\n"
},
{
"answer_id": 198545,
"author": "Alan",
"author_id": 5878,
"author_profile": "https://Stackoverflow.com/users/5878",
"pm_score": 2,
"selected": false,
"text": "<p>The \"Dragon\" and \"Tiger\" books (see above) are both excellent, though I find the \"Tiger\" (Appel) book a bit dense. I also quite like <em>Modern Compiler Design</em> by David Galles. As for tools and utilities to help you understand, I recommend taking a look at one or more of the following:</p>\n\n<ul>\n<li><a href=\"https://javacc.dev.java.net/\" rel=\"nofollow noreferrer\">JavaaCC</a> for lex and parser generation</li>\n<li><a href=\"http://grammatica.percederberg.net/index.html\" rel=\"nofollow noreferrer\">Grammatica</a> for lex and parser generation</li>\n<li><a href=\"http://jasmin.sourceforge.net/\" rel=\"nofollow noreferrer\">Jasmin</a> and <a href=\"http://www.angelfire.com/tx4/cus/jasper/\" rel=\"nofollow noreferrer\">Jasper</a> for code generation</li>\n</ul>\n"
},
{
"answer_id": 806512,
"author": "user29159",
"author_id": 29159,
"author_profile": "https://Stackoverflow.com/users/29159",
"pm_score": 0,
"selected": false,
"text": "<p>I like Compiler Construction by Nicolas Wirth, but maybe that's because learning (Turbo) Pascal was what made me decide to go into Computer Science.</p>\n\n<p><a href=\"http://www-old.oberon.ethz.ch/WirthPubl/CBEAll.pdf\" rel=\"nofollow noreferrer\">http://www-old.oberon.ethz.ch/WirthPubl/CBEAll.pdf</a></p>\n"
},
{
"answer_id": 1347653,
"author": "Paul Biggar",
"author_id": 104021,
"author_profile": "https://Stackoverflow.com/users/104021",
"pm_score": 2,
"selected": false,
"text": "<p>Supposedly (I read through it, but haven't done it), <a href=\"http://scheme2006.cs.uchicago.edu/11-ghuloum.pdf\" rel=\"nofollow noreferrer\">An Incremental Approach to Compiler Construction</a> is excellent. It describes how the author teaches his compilers course. </p>\n\n<p>From the abstract:</p>\n\n<blockquote>\n <p>Compilers are perceived to be magical artifacts, carefully crafted by the wizards, and unfathomable by the mere mortals. Books on compilers are better described as wizard-talk: written by and for a clique of all-knowing practitioners. Real-life compilers are too complex to serve as an educational tool. And the gap between real-life compilers and the educational toy compilers is too wide. The novice compiler writer stands puzzled facing an impenetrable barrier, “better write an interpreter instead.”</p>\n \n <p>The goal of this paper is to break that barrier. We show that building a compiler can be as easy as building an interpreter. The compiler we construct accepts a large subset of the Scheme programming language and produces assembly code for the Intel-x86 architecture, the dominant architecture of personal computing. The development of the compiler is broken into many small incremental steps. Every step yields a fully working compiler for a progressively expanding subset of Scheme. Every compiler step produces real assembly code that can be assembled then executed directly by the hardware. We assume that the reader is familiar with the basic computer architecture: its components and execution model. Detailed knowledge of the Intel-x86 architecture is not required.</p>\n \n <p>The development of the compiler is described in detail in an extended tutorial. Supporting material for the tutorial such as an automated testing facility coupled with a comprehensive test suite are provided with the tutorial. It is our hope that current and future implementors of Scheme find in this paper the motivation for developing high-performance compilers and the means for achieving that goal.</p>\n</blockquote>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22763/"
] |
I have a class Animal and an interface it inherits from IAnimal.
```
@MappedSuperclass
public class Animal implements Serializable, IAnimal{...}.
@Entity
public class Jaguar extends Animal{...}
```
My first question is, do I need to annotate the interface?
I asked this because I am getting this error when I run my tests:
>
> Error compiling the query [SELECT s
> FROM animal s WHERE s.atype =
> :atype].
> Unknown abstract schema type
> [animal]
>
>
>
If I remember correctly, before I added this interface it was working.
|
Here are a bunch of good textbooks:
Modern Compiler Implementation in Java (Tiger book)
A.W. Appel
Cambridge University Press, 1998
ISBN 0-52158-388-8
A textbook tutorial on compiler implementation, including techniques for many language features
Compilers: Principles, Techniques and Tools (Dragon book)
Aho, Lam, Sethi and Ullman
Addison-Wesley, 2006
ISBN 0321486811
The classic compilers textbook, although its front-end emphasis reflects its age.
Advanced Compiler Design and Implementation (Whale book)
Steven Muchnick
Morgan Kaufman Publishers, 1997
ISBN 1-55860-320-4
Essentially a recipe book of optimizations; very complete and suited for industrial practitioners and researchers.
Engineering a Compiler (Ark book)
Keith D. Cooper, Linda Torczon
Morgan Kaufman Publishers, 2003
ISBN 1-55860-698-X
A modern classroom textbook, with increased emphasis on the back-end and implementation techniques.
Optimizing Compilers for Modern Architectures
Randy Allen and Ken Kennedy
Morgan Kaufman Publishers, 2001
ISBN 1-55860-286-0
A modern textbook that focuses on optimizations including parallelization and memory hierarchy optimizations.
Programming Languages Pragmatics
Michael L. Scott
Morgan Kaufmann Publishers, 2005
ISBN 0126339511
|
153,354 |
<p>I have the following code that I wrote but it the SQLBindCol does not seem to work correctly (of course I could have screwed up the whole program too!.) The connection works, it creates the table in the DB, addes the record fine and they all look good in SQL Enterprise Manager. So what I need help with is after the comment "Part 3 & 4: Searchs based on criteria." Perhaps I should have done this assignment completely different or is this an acceptable method?</p>
<pre><code>#include <iostream>
#include <cstdio>
#include <string>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
using namespace std; // to save us having to type std::
const int MAX_CHAR = 1024;
int main ( )
{
SQLCHAR SQLStmt[MAX_CHAR];
char strSQL[MAX_CHAR];
char chrTemp;
SQLVARCHAR rtnFirstName[50];
SQLVARCHAR rtnLastName[50];
SQLVARCHAR rtnAddress[30];
SQLVARCHAR rtnCity[30];
SQLVARCHAR rtnState[3];
SQLDOUBLE rtnSalary;
SQLVARCHAR rtnGender[1];
SQLINTEGER rtnAge;
// Get a handle to the database
SQLHENV EnvironmentHandle;
RETCODE retcode = SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvironmentHandle );
// Set the SQL environment flags
retcode = SQLSetEnvAttr( EnvironmentHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER );
// create handle to the SQL database
SQLHDBC ConnHandle;
retcode = SQLAllocHandle( SQL_HANDLE_DBC, EnvironmentHandle, &ConnHandle );
// Open the database using a System DSN
retcode = SQLDriverConnect(ConnHandle,
NULL,
(SQLCHAR*)"DSN=PRG411;UID=myUser;PWD=myPass;",
SQL_NTS,
NULL,
SQL_NTS,
NULL,
SQL_DRIVER_NOPROMPT);
if (!retcode)
{
cout << "SQLConnect() Failed";
}
else
{
// create a SQL Statement variable
SQLHSTMT StatementHandle;
retcode = SQLAllocHandle(SQL_HANDLE_STMT, ConnHandle, &StatementHandle);
// Part 1: Create the Employee table (Database)
do
{
cout << "Create the new table? ";
cin >> chrTemp;
} while (cin.fail());
if (chrTemp == 'y' || chrTemp == 'Y')
{
strcpy((char *) SQLStmt, "CREATE TABLE [dbo].[Employee]([pkEmployeeID] [int] IDENTITY(1,1) NOT NULL,[FirstName] [varchar](50) NOT NULL,[LastName] [varchar](50) NOT NULL,[Address] [varchar](30) NOT NULL,[City] [varchar](30) NOT NULL,[State] [varchar](3) NOT NULL, [Salary] [double] NOT NULL,[Gender] [varchar](1) NOT NULL, [Age] [int] NOT NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([pkEmployeeID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
}
// Part 2: Hardcode records into the table
do
{
cout << "Add records to the table? ";
cin >> chrTemp;
} while (cin.fail());
if (chrTemp == 'y' || chrTemp == 'Y')
{
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Mike','Slentz','123 Torrey Dr.','North Clairmont','CA', 48000.00 ,'M',34)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sue','Vander Hayden','46 East West St.','San Diego','CA', 36000.00 ,'F',28)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sharon','Stonewall','756 West Olive Garden Way','Plymouth','MA', 56000.00 ,'F',58)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('James','Bartholemew','777 Praying Way','Falls Church','VA', 51000.00 ,'M',45)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Joe','Smith','111 North 43rd Ave','Peoria','AZ', 44000.00 ,'M', 40)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Michael','Smith','20344 North Swan Park','Phoenix','AZ', 24000.00 ,'M', 40)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Jennifer','Jones','123 West North Ave','Flagstaff','AZ', 40000.00 ,'F', 40)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Cora','York','33rd Park Way Drive','Mayville','MI', 30000.00 ,'F', 61)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Tom','Jefferson','234 Friendship Way','Battle Creek','MI', 41000.00 ,'M', 31)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
}
// Part 3 & 4: Searchs based on criteria
do
{
cout << "1. Display all records in the database" << endl;
cout << "2. Display all records with age greater than 40" << endl;
cout << "3. Display all records with salary over $30K" << endl;
cout << "4. Exit" << endl << endl;
do
{
cout << "Please enter a selection: ";
cin >> chrTemp;
} while (cin.fail());
if (chrTemp == '1')
{
strcpy((char *) SQLStmt, "SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE");
}
else if (chrTemp == '2')
{
strcpy((char *) SQLStmt, "SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [AGE] > 40");
}
else if (chrTemp == '3')
{
strcpy((char *) SQLStmt, "SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [Salary] > 30000");
}
if (chrTemp == '1' || chrTemp == '2' || chrTemp == '3')
{
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
SQLBindCol(StatementHandle, 1, SQL_C_CHAR, &rtnFirstName, sizeof(rtnFirstName), NULL );
SQLBindCol(StatementHandle, 2, SQL_C_CHAR, &rtnLastName, sizeof(rtnLastName), NULL );
SQLBindCol(StatementHandle, 3, SQL_C_CHAR, &rtnAddress, sizeof(rtnAddress), NULL );
SQLBindCol(StatementHandle, 4, SQL_C_CHAR, &rtnCity, sizeof(rtnCity), NULL );
SQLBindCol(StatementHandle, 5, SQL_C_CHAR, &rtnState, sizeof(rtnState), NULL );
SQLBindCol(StatementHandle, 6, SQL_C_DOUBLE, &rtnSalary, sizeof(rtnSalary), NULL );
SQLBindCol(StatementHandle, 7, SQL_C_CHAR, &rtnGender, sizeof(rtnGender), NULL );
SQLBindCol(StatementHandle, 8, SQL_C_NUMERIC, &rtnAge, sizeof(rtnAge), NULL );
for(;;)
{
retcode = SQLFetch(StatementHandle);
if (retcode == SQL_NO_DATA_FOUND) break;
cout << rtnFirstName << " " << rtnLastName << " " << rtnAddress << " " << rtnCity << " " << rtnState << " " << rtnSalary << " " << rtnGender << "" << rtnAge << endl;
}
}
} while (chrTemp != '4');
SQLFreeStmt(StatementHandle, SQL_CLOSE );
SQLFreeConnect(ConnHandle);
SQLFreeEnv(EnvironmentHandle);
printf( "Done.\n" );
}
return 0;
}
</code></pre>
|
[
{
"answer_id": 153386,
"author": "antik",
"author_id": 1625,
"author_profile": "https://Stackoverflow.com/users/1625",
"pm_score": 2,
"selected": false,
"text": "<p>You can get enough diagnostic out of SQL that you may be able to isolate and resolve the issue.</p>\n\n<p>You can get the statement handle to tell you what has gone wrong with it by calling when SQLExecDirect returns something other than <code>SQL_SUCCESS</code> or <code>SQL_SUCCESS_WITH_INFO</code></p>\n\n<p><code>SQLGetDiagRec( SQL_HANDLE_STMT, StatementHandle, req, state, &error, (SQLCHAR*) buffer, (SQLINTEGER) MAX_CHAR, (SQLSMALLINT*) &output_length );</code></p>\n\n<p>You'll have to allocate the variables you see here of course... I suggest you put a throw away line after the <code>SQLGetDiagRec</code> call and assign a breakpoint to it. When it breaks there, you can look at <code>state</code>'s value: that will align with the \"Diagnostics\" section here:\n<a href=\"http://msdn.microsoft.com/en-us/library/ms713611(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms713611(VS.85).aspx</a></p>\n"
},
{
"answer_id": 155047,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>OK, here is the code now working...</p>\n\n<pre><code>using namespace std; // to save us having to type std::\n\nconst int MAX_CHAR = 1024;\n\nint main ( )\n{\n SQLSMALLINT RecNumber;\n SQLCHAR * SQLState;\n SQLINTEGER * NativeErrorPtr;\n SQLCHAR * MessageText;\n SQLSMALLINT BufferLength;\n SQLSMALLINT * TextLengthPtr;\n\n SQLCHAR SQLStmt[MAX_CHAR];\n char strSQL[MAX_CHAR];\n char chrTemp;\n\n SQLVARCHAR rtnFirstName[50];\n SQLVARCHAR rtnLastName[50];\n SQLVARCHAR rtnAddress[30];\n SQLVARCHAR rtnCity[30];\n SQLVARCHAR rtnState[3];\n SQLDOUBLE rtnSalary;\n SQLVARCHAR rtnGender[2];\n SQLINTEGER rtnAge;\n\n // Get a handle to the database\n\n SQLHENV EnvironmentHandle;\n RETCODE retcode = SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvironmentHandle );\n\n // Set the SQL environment flags\n\n retcode = SQLSetEnvAttr( EnvironmentHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER );\n\n // create handle to the SQL database\n\n SQLHDBC ConnHandle;\n retcode = SQLAllocHandle( SQL_HANDLE_DBC, EnvironmentHandle, &ConnHandle );\n\n // Open the database using a System DSN\n\n retcode = SQLDriverConnect(ConnHandle, \n NULL, \n (SQLCHAR*)\"DSN=PRG411;UID=myUser;PWD=myPass;\", \n SQL_NTS,\n NULL, \n SQL_NTS, \n NULL, \n SQL_DRIVER_NOPROMPT);\n if (!retcode) \n {\n cout << \"SQLConnect() Failed\";\n }\n else\n {\n // create a SQL Statement variable\n\n SQLHSTMT StatementHandle;\n retcode = SQLAllocHandle(SQL_HANDLE_STMT, ConnHandle, &StatementHandle);\n\n // Part 1: Create the Employee table (Database)\n\n do\n {\n cout << \"Create the new table? \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == 'y' || chrTemp == 'Y')\n {\n strcpy((char *) SQLStmt, \"CREATE TABLE [dbo].[Employee]([pkEmployeeID] [int] IDENTITY(1,1) NOT NULL,[FirstName] [varchar](50) NOT NULL,[LastName] [varchar](50) NOT NULL,[Address] [varchar](30) NOT NULL,[City] [varchar](30) NOT NULL,[State] [varchar](3) NOT NULL, [Salary] [decimal] NOT NULL,[Gender] [varchar](1) NOT NULL, [Age] [int] NOT NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([pkEmployeeID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n }\n\n // Part 2: Hardcode records into the table\n\n do\n {\n cout << \"Add records to the table? \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == 'y' || chrTemp == 'Y')\n {\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Mike','Slentz','123 Torrey Dr.','North Clairmont','CA', 48000.00 ,'M',34)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sue','Vander Hayden','46 East West St.','San Diego','CA', 36000.00 ,'F',28)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sharon','Stonewall','756 West Olive Garden Way','Plymouth','MA', 56000.00 ,'F',58)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('James','Bartholemew','777 Praying Way','Falls Church','VA', 51000.00 ,'M',45)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Joe','Smith','111 North 43rd Ave','Peoria','AZ', 44000.00 ,'M', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Michael','Smith','20344 North Swan Park','Phoenix','AZ', 24000.00 ,'M', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Jennifer','Jones','123 West North Ave','Flagstaff','AZ', 40000.00 ,'F', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Cora','York','33rd Park Way Drive','Mayville','MI', 30000.00 ,'F', 61)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Tom','Jefferson','234 Friendship Way','Battle Creek','MI', 41000.00 ,'M', 31)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n }\n\n // Part 3 & 4: Searchs based on criteria\n\n do\n {\n cout << \"1. Display all records in the database\" << endl;\n cout << \"2. Display all records with age 40 or over\" << endl;\n cout << \"3. Display all records with salary $30K or over\" << endl;\n cout << \"4. Exit\" << endl << endl;\n\n do\n {\n cout << \"Please enter a selection: \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == '1')\n {\n strcpy((char *) SQLStmt, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE\");\n }\n else if (chrTemp == '2')\n {\n strcpy((char *) SQLStmt, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [AGE] >= 40\");\n }\n else if (chrTemp == '3')\n {\n strcpy((char *) SQLStmt, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [Salary] >= 30000\");\n }\n\n if (chrTemp == '1' || chrTemp == '2' || chrTemp == '3')\n {\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n //SQLGetDiagRec(SQL_HANDLE_STMT, StatementHandle, RecNumber, SQLState, NativeErrorPtr, (SQLCHAR*) MessageText, (SQLINTEGER) BufferLength, (SQLSMALLINT*) &TextLengthPtr);\n\n SQLBindCol(StatementHandle, 1, SQL_C_CHAR, &rtnFirstName, sizeof(rtnFirstName), NULL );\n SQLBindCol(StatementHandle, 2, SQL_C_CHAR, &rtnLastName, sizeof(rtnLastName), NULL );\n SQLBindCol(StatementHandle, 3, SQL_C_CHAR, &rtnAddress, sizeof(rtnAddress), NULL );\n SQLBindCol(StatementHandle, 4, SQL_C_CHAR, &rtnCity, sizeof(rtnCity), NULL );\n SQLBindCol(StatementHandle, 5, SQL_C_CHAR, &rtnState, sizeof(rtnState), NULL );\n SQLBindCol(StatementHandle, 6, SQL_C_DOUBLE, &rtnSalary, sizeof(rtnSalary), NULL );\n SQLBindCol(StatementHandle, 7, SQL_C_CHAR, &rtnGender, sizeof(rtnGender), NULL );\n SQLBindCol(StatementHandle, 8, SQL_C_LONG, &rtnAge, sizeof(rtnAge), NULL );\n\n for(;;) \n {\n retcode = SQLFetch(StatementHandle);\n if (retcode == SQL_NO_DATA_FOUND) break;\n\n cout << rtnFirstName << \" \" << rtnLastName << \" \" << rtnAddress << \" \" << rtnCity << \" \" << rtnState << \" \" << rtnSalary << \" \" << rtnGender << \" \" << rtnAge << endl;\n }\n\n SQLFreeStmt(StatementHandle, SQL_CLOSE);\n\n }\n } while (chrTemp != '4');\n\n SQLFreeStmt(StatementHandle, SQL_CLOSE );\n SQLFreeHandle(SQL_HANDLE_STMT, StatementHandle);\n\n SQLDisconnect(ConnHandle);\n\n SQLFreeHandle(SQL_HANDLE_DBC, ConnHandle);\n SQLFreeHandle(SQL_HANDLE_ENV, EnvironmentHandle);\n\n printf( \"Done.\\n\" );\n }\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 1353009,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You said you were getting errors with:</p>\n\n<p>string sqlString = \"Select * From Customers Where Customers.Employee = '\" +id+ \"'\";</p>\n\n<p>It should be obvious, sorry, lol. The id is integer, sure. But when you evaluate the string, it comes up like so:</p>\n\n<p>string sqlString = \"Select * From Customers Where Customers.Employee = '100'\";</p>\n\n<p>Notice what's wrong? You have single quotes around it. So no matter what data type you are using, the single quotes makes the SQL treat it as a string. So just take them out like so:</p>\n\n<p>string sqlString = \"Select * From Customers Where Customers.Employee = \" + id + \"\";\n . . . . . . . Or,\nstring sqlString = \"Select * From Customers Where Customers.Employee = \" + id;</p>\n\n<hr>\n\n<p>My question is this... Can you explain how looping through records in C++ works? For example, the user inputs a user name to strUName, and you wanna see if that user name is in the database table Users. The SQL is easy enough (select * from Users where [UName] = '\" + strUName + \"'; But How do you actually execute it in C++ and figure it out?</p>\n\n<p>I see the SQLStmt, I see it being executed using Direct. I then see some SQLBindCol junk and then an infinite loop until break evals. But I don't quite get what's happening (This is easy for any other language for me, but I'm new to C++.</p>\n"
},
{
"answer_id": 28044976,
"author": "Satheesh",
"author_id": 4473897,
"author_profile": "https://Stackoverflow.com/users/4473897",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the corrected code.</p>\n\n<pre><code> #include <iostream>\n #include <cstdio>\n #include <string>\n\n #include <windows.h>\n #include <sql.h>\n #include <sqlext.h>\n #include <sqltypes.h> \n\n using namespace std; // to save us having to type std::\n\n const int MAX_CHAR = 1024;\n\n int main()\n {\n SQLSMALLINT RecNumber;\n SQLCHAR * SQLState;\n SQLINTEGER * NativeErrorPtr;\n SQLCHAR * MessageText;\n SQLSMALLINT BufferLength;\n SQLSMALLINT * TextLengthPtr;\n\n SQLCHAR SQLStmt[MAX_CHAR];\n char strSQL[MAX_CHAR];\n char chrTemp;\n\n SQLVARCHAR rtnFirstName[50];\n SQLVARCHAR rtnLastName[50];\n SQLVARCHAR rtnAddress[30];\n SQLVARCHAR rtnCity[30];\n SQLVARCHAR rtnState[3];\n SQLDOUBLE rtnSalary;\n SQLVARCHAR rtnGender[2];\n SQLINTEGER rtnAge;\n\n // Get a handle to the database\n\n SQLHENV EnvironmentHandle;\n RETCODE retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvironmentHandle);\n\n // Set the SQL environment flags\n HWND desktopHandle = GetDesktopWindow();\n retcode = SQLSetEnvAttr(EnvironmentHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER);\n\n // create handle to the SQL database\n\n SQLHDBC ConnHandle;\n retcode = SQLAllocHandle(SQL_HANDLE_DBC, EnvironmentHandle, &ConnHandle);\n SQLSetConnectAttr(ConnHandle, SQL_LOGIN_TIMEOUT, (SQLPOINTER)5, 0);\n // Open the database using a System DSN\n\n retcode = SQLDriverConnect(ConnHandle,\n desktopHandle,\n (SQLCHAR*)\"DSN=PRG411;UID=myUser;PWD=myPass;\",\n SQL_NTS,\n NULL,\n SQL_NTS,\n NULL,\n SQL_DRIVER_NOPROMPT);\n if (retcode != SQL_SUCCESS || retcode != SQL_SUCCESS_WITH_INFO)\n {\n cout << \"SQLConnect() Failed\";\n } \n else\n {\n // create a SQL Statement variable\n\n SQLHSTMT StatementHandle;\n retcode = SQLAllocHandle(SQL_HANDLE_STMT, ConnHandle, &StatementHandle);\n\n // Part 1: Create the Employee table (Database)\n\n do\n {\n cout << \"Create the new table? \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == 'y' || chrTemp == 'Y')\n {\n strcpy_s((char *)SQLStmt,1024, \"CREATE TABLE [dbo].[Employee]([pkEmployeeID] [int] IDENTITY(1,1) NOT NULL,[FirstName] [varchar](50) NOT NULL,[LastName] [varchar](50) NOT NULL,[Address] [varchar](30) NOT NULL,[City] [varchar](30) NOT NULL,[State] [varchar](3) NOT NULL, [Salary] [decimal] NOT NULL,[Gender] [varchar](1) NOT NULL, [Age] [int] NOT NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([pkEmployeeID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n }\n\n // Part 2: Hardcode records into the table\n\n do\n {\n cout << \"Add records to the table? \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == 'y' || chrTemp == 'Y')\n {\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Mike','Slentz','123 Torrey Dr.','North Clairmont','CA', 48000.00 ,'M',34)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sue','Vander Hayden','46 East West St.','San Diego','CA', 36000.00 ,'F',28)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sharon','Stonewall','756 West Olive Garden Way','Plymouth','MA', 56000.00 ,'F',58)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('James','Bartholemew','777 Praying Way','Falls Church','VA', 51000.00 ,'M',45)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Joe','Smith','111 North 43rd Ave','Peoria','AZ', 44000.00 ,'M', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Michael','Smith','20344 North Swan Park','Phoenix','AZ', 24000.00 ,'M', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Jennifer','Jones','123 West North Ave','Flagstaff','AZ', 40000.00 ,'F', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Cora','York','33rd Park Way Drive','Mayville','MI', 30000.00 ,'F', 61)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Tom','Jefferson','234 Friendship Way','Battle Creek','MI', 41000.00 ,'M', 31)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n }\n\n // Part 3 & 4: Searchs based on criteria\n\n do\n {\n cout << \"1. Display all records in the database\" << endl;\n cout << \"2. Display all records with age 40 or over\" << endl;\n cout << \"3. Display all records with salary $30K or over\" << endl;\n cout << \"4. Exit\" << endl << endl;\n\n do\n {\n cout << \"Please enter a selection: \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == '1')\n {\n strcpy_s((char *)SQLStmt,1024, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE\");\n }\n else if (chrTemp == '2')\n {\n strcpy_s((char *)SQLStmt,1024, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [AGE] >= 40\");\n }\n else if (chrTemp == '3')\n {\n strcpy_s((char *)SQLStmt,1024, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [Salary] >= 30000\");\n }\n\n if (chrTemp == '1' || chrTemp == '2' || chrTemp == '3')\n {\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n //SQLGetDiagRec(SQL_HANDLE_STMT, StatementHandle, RecNumber, SQLState, NativeErrorPtr, (SQLCHAR*) MessageText, (SQLINTEGER) BufferLength, (SQLSMALLINT*) &TextLengthPtr);\n\n SQLBindCol(StatementHandle, 1, SQL_C_CHAR, &rtnFirstName, sizeof(rtnFirstName), NULL);\n SQLBindCol(StatementHandle, 2, SQL_C_CHAR, &rtnLastName, sizeof(rtnLastName), NULL);\n SQLBindCol(StatementHandle, 3, SQL_C_CHAR, &rtnAddress, sizeof(rtnAddress), NULL);\n SQLBindCol(StatementHandle, 4, SQL_C_CHAR, &rtnCity, sizeof(rtnCity), NULL);\n SQLBindCol(StatementHandle, 5, SQL_C_CHAR, &rtnState, sizeof(rtnState), NULL);\n SQLBindCol(StatementHandle, 6, SQL_C_DOUBLE, &rtnSalary, sizeof(rtnSalary), NULL);\n SQLBindCol(StatementHandle, 7, SQL_C_CHAR, &rtnGender, sizeof(rtnGender), NULL);\n SQLBindCol(StatementHandle, 8, SQL_C_LONG, &rtnAge, sizeof(rtnAge), NULL);\n\n for (;;)\n {\n retcode = SQLFetch(StatementHandle);\n if (retcode == SQL_NO_DATA_FOUND) break;\n\n cout << rtnFirstName << \" \" << rtnLastName << \" \" << rtnAddress << \" \" << rtnCity << \" \" << rtnState << \" \" << rtnSalary << \" \" << rtnGender << \" \" << rtnAge << endl;\n }\n\n SQLFreeStmt(StatementHandle, SQL_CLOSE);\n\n }\n } while (chrTemp != '4');\n\n SQLFreeStmt(StatementHandle, SQL_CLOSE);\n SQLFreeHandle(SQL_HANDLE_STMT, StatementHandle);\n\n SQLDisconnect(ConnHandle);\n\n SQLFreeHandle(SQL_HANDLE_DBC, ConnHandle);\n SQLFreeHandle(SQL_HANDLE_ENV, EnvironmentHandle);\n\n printf(\"Done.\\n\");\n }\n\n return 0;\n }\n</code></pre>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have the following code that I wrote but it the SQLBindCol does not seem to work correctly (of course I could have screwed up the whole program too!.) The connection works, it creates the table in the DB, addes the record fine and they all look good in SQL Enterprise Manager. So what I need help with is after the comment "Part 3 & 4: Searchs based on criteria." Perhaps I should have done this assignment completely different or is this an acceptable method?
```
#include <iostream>
#include <cstdio>
#include <string>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
using namespace std; // to save us having to type std::
const int MAX_CHAR = 1024;
int main ( )
{
SQLCHAR SQLStmt[MAX_CHAR];
char strSQL[MAX_CHAR];
char chrTemp;
SQLVARCHAR rtnFirstName[50];
SQLVARCHAR rtnLastName[50];
SQLVARCHAR rtnAddress[30];
SQLVARCHAR rtnCity[30];
SQLVARCHAR rtnState[3];
SQLDOUBLE rtnSalary;
SQLVARCHAR rtnGender[1];
SQLINTEGER rtnAge;
// Get a handle to the database
SQLHENV EnvironmentHandle;
RETCODE retcode = SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvironmentHandle );
// Set the SQL environment flags
retcode = SQLSetEnvAttr( EnvironmentHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER );
// create handle to the SQL database
SQLHDBC ConnHandle;
retcode = SQLAllocHandle( SQL_HANDLE_DBC, EnvironmentHandle, &ConnHandle );
// Open the database using a System DSN
retcode = SQLDriverConnect(ConnHandle,
NULL,
(SQLCHAR*)"DSN=PRG411;UID=myUser;PWD=myPass;",
SQL_NTS,
NULL,
SQL_NTS,
NULL,
SQL_DRIVER_NOPROMPT);
if (!retcode)
{
cout << "SQLConnect() Failed";
}
else
{
// create a SQL Statement variable
SQLHSTMT StatementHandle;
retcode = SQLAllocHandle(SQL_HANDLE_STMT, ConnHandle, &StatementHandle);
// Part 1: Create the Employee table (Database)
do
{
cout << "Create the new table? ";
cin >> chrTemp;
} while (cin.fail());
if (chrTemp == 'y' || chrTemp == 'Y')
{
strcpy((char *) SQLStmt, "CREATE TABLE [dbo].[Employee]([pkEmployeeID] [int] IDENTITY(1,1) NOT NULL,[FirstName] [varchar](50) NOT NULL,[LastName] [varchar](50) NOT NULL,[Address] [varchar](30) NOT NULL,[City] [varchar](30) NOT NULL,[State] [varchar](3) NOT NULL, [Salary] [double] NOT NULL,[Gender] [varchar](1) NOT NULL, [Age] [int] NOT NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([pkEmployeeID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
}
// Part 2: Hardcode records into the table
do
{
cout << "Add records to the table? ";
cin >> chrTemp;
} while (cin.fail());
if (chrTemp == 'y' || chrTemp == 'Y')
{
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Mike','Slentz','123 Torrey Dr.','North Clairmont','CA', 48000.00 ,'M',34)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sue','Vander Hayden','46 East West St.','San Diego','CA', 36000.00 ,'F',28)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sharon','Stonewall','756 West Olive Garden Way','Plymouth','MA', 56000.00 ,'F',58)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('James','Bartholemew','777 Praying Way','Falls Church','VA', 51000.00 ,'M',45)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Joe','Smith','111 North 43rd Ave','Peoria','AZ', 44000.00 ,'M', 40)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Michael','Smith','20344 North Swan Park','Phoenix','AZ', 24000.00 ,'M', 40)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Jennifer','Jones','123 West North Ave','Flagstaff','AZ', 40000.00 ,'F', 40)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Cora','York','33rd Park Way Drive','Mayville','MI', 30000.00 ,'F', 61)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Tom','Jefferson','234 Friendship Way','Battle Creek','MI', 41000.00 ,'M', 31)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
}
// Part 3 & 4: Searchs based on criteria
do
{
cout << "1. Display all records in the database" << endl;
cout << "2. Display all records with age greater than 40" << endl;
cout << "3. Display all records with salary over $30K" << endl;
cout << "4. Exit" << endl << endl;
do
{
cout << "Please enter a selection: ";
cin >> chrTemp;
} while (cin.fail());
if (chrTemp == '1')
{
strcpy((char *) SQLStmt, "SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE");
}
else if (chrTemp == '2')
{
strcpy((char *) SQLStmt, "SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [AGE] > 40");
}
else if (chrTemp == '3')
{
strcpy((char *) SQLStmt, "SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [Salary] > 30000");
}
if (chrTemp == '1' || chrTemp == '2' || chrTemp == '3')
{
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
SQLBindCol(StatementHandle, 1, SQL_C_CHAR, &rtnFirstName, sizeof(rtnFirstName), NULL );
SQLBindCol(StatementHandle, 2, SQL_C_CHAR, &rtnLastName, sizeof(rtnLastName), NULL );
SQLBindCol(StatementHandle, 3, SQL_C_CHAR, &rtnAddress, sizeof(rtnAddress), NULL );
SQLBindCol(StatementHandle, 4, SQL_C_CHAR, &rtnCity, sizeof(rtnCity), NULL );
SQLBindCol(StatementHandle, 5, SQL_C_CHAR, &rtnState, sizeof(rtnState), NULL );
SQLBindCol(StatementHandle, 6, SQL_C_DOUBLE, &rtnSalary, sizeof(rtnSalary), NULL );
SQLBindCol(StatementHandle, 7, SQL_C_CHAR, &rtnGender, sizeof(rtnGender), NULL );
SQLBindCol(StatementHandle, 8, SQL_C_NUMERIC, &rtnAge, sizeof(rtnAge), NULL );
for(;;)
{
retcode = SQLFetch(StatementHandle);
if (retcode == SQL_NO_DATA_FOUND) break;
cout << rtnFirstName << " " << rtnLastName << " " << rtnAddress << " " << rtnCity << " " << rtnState << " " << rtnSalary << " " << rtnGender << "" << rtnAge << endl;
}
}
} while (chrTemp != '4');
SQLFreeStmt(StatementHandle, SQL_CLOSE );
SQLFreeConnect(ConnHandle);
SQLFreeEnv(EnvironmentHandle);
printf( "Done.\n" );
}
return 0;
}
```
|
You can get enough diagnostic out of SQL that you may be able to isolate and resolve the issue.
You can get the statement handle to tell you what has gone wrong with it by calling when SQLExecDirect returns something other than `SQL_SUCCESS` or `SQL_SUCCESS_WITH_INFO`
`SQLGetDiagRec( SQL_HANDLE_STMT, StatementHandle, req, state, &error, (SQLCHAR*) buffer, (SQLINTEGER) MAX_CHAR, (SQLSMALLINT*) &output_length );`
You'll have to allocate the variables you see here of course... I suggest you put a throw away line after the `SQLGetDiagRec` call and assign a breakpoint to it. When it breaks there, you can look at `state`'s value: that will align with the "Diagnostics" section here:
<http://msdn.microsoft.com/en-us/library/ms713611(VS.85).aspx>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.