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
|
---|---|---|---|---|---|---|
121,722 |
<pre><code>string percentage = e.Row.Cells[7].Text;
</code></pre>
<p>I am trying to do some dynamic stuff with my GridView, so I have wired up some code to the RowDataBound event. I am trying to get the value from a particular cell, which is a TemplateField. But the code above always seems to be returning an empty string. </p>
<p>Any ideas?</p>
<p>To clarify, here is a bit the offending cell:</p>
<pre><code><asp:TemplateField HeaderText="# Percentage click throughs">
<ItemTemplate>
<%# AddPercentClickThroughs((int)Eval("EmailSummary.pLinksClicked"), (int)Eval("NumberOfSends")) %>
</ItemTemplate>
</asp:TemplateField>
</code></pre>
<p>On a related note, does anyone know if there is a better way of selecting the cell in the row. It sucks putting in <code>cell[1]</code>. Couldn't I do <code>cell["mycellname"]</code>, so if I decide to change the order of my cells, bugs wont appear?</p>
|
[
{
"answer_id": 121740,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 5,
"selected": true,
"text": "<p>First you need to wrap your code in a <code>Label</code> or <code>Literal</code> control so that you can reference it properly. What's happening is that there's no way for the system to keep track of it, because there's no control associated with the text. It's the control's responsibility to add its contents to viewstate.</p>\n\n<p>You need to use gridView.FindControl(\"controlName\"); to get the control in the row. From there you can get at its properties including <code>Text</code>.</p>\n\n<p>You can also get at the DataItem property of the Row in question and cast it to the appropriate type and extract the information directly.</p>\n"
},
{
"answer_id": 121751,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 6,
"selected": false,
"text": "<p>why not pull the data directly out of the data source.</p>\n\n<pre><code>DataBinder.Eval(e.Row.DataItem, \"ColumnName\")\n</code></pre>\n"
},
{
"answer_id": 179832,
"author": "Chris",
"author_id": 13700,
"author_profile": "https://Stackoverflow.com/users/13700",
"pm_score": 5,
"selected": false,
"text": "<p>When you use a TemplateField and bind literal text to it like you are doing, asp.net will actually insert a control FOR YOU! It gets put into a DataBoundLiteralControl. You can see this if you look in the debugger near your line of code that is getting the empty text.</p>\n\n<p>So, to access the information without changing your template to use a control, you would cast like this:</p>\n\n<pre><code>string percentage = ((DataBoundLiteralControl)e.Row.Cells[7].Controls[0]).Text;\n</code></pre>\n\n<p>That will get you your text!</p>\n"
},
{
"answer_id": 738051,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>The above are good suggestions, but you can get at the text value of a cell in a grid view without wrapping it in a literal or label control. You just have to know what event to wire up. In this case, use the DataBound event instead, like so:</p>\n\n<pre><code>protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n if (e.Row.Cells[0].Text.Contains(\"sometext\"))\n {\n e.Row.Cells[0].Font.Bold = true;\n }\n }\n}\n</code></pre>\n\n<p>When running a debugger, you will see the text appear in this method.</p>\n"
},
{
"answer_id": 5491397,
"author": "Ahmad",
"author_id": 684598,
"author_profile": "https://Stackoverflow.com/users/684598",
"pm_score": 3,
"selected": false,
"text": "<p>Just use a loop to check your cell in a gridview for example:</p>\n\n<pre><code>for (int i = 0; i < GridView2.Rows.Count; i++)\n{\n string vr;\n vr = GridView2.Rows[i].Cells[4].Text; // here you go vr = the value of the cel\n if (vr == \"0\") // you can check for anything\n {\n GridView2.Rows[i].Cells[4].Text = \"Done\";\n // you can format this cell \n }\n}\n</code></pre>\n"
},
{
"answer_id": 5570440,
"author": "SEO Service",
"author_id": 695317,
"author_profile": "https://Stackoverflow.com/users/695317",
"pm_score": 2,
"selected": false,
"text": "<p>use <code>RowDataBound</code> function to bind data with a perticular cell, and to get control use \n(ASP Control Name like DropDownList) <code>GridView.FindControl(\"Name of Control\")</code></p>\n"
},
{
"answer_id": 12091252,
"author": "Vaibhav Saran",
"author_id": 362310,
"author_profile": "https://Stackoverflow.com/users/362310",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Label lblSecret = ((Label)e.Row.FindControl(\"lblSecret\"));\n</code></pre>\n"
},
{
"answer_id": 12626043,
"author": "Mark Meuer",
"author_id": 9117,
"author_profile": "https://Stackoverflow.com/users/9117",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar question, but found the solution through a slightly different approach. Instead of looking up the control as Chris suggested, I first changed the way the field was specified in the .aspx page. Instead of using a <code><asp:TemplateField ...></code> tag, I changed the field in question to use <code><asp:BoundField ...></code>. Then, when I got to the RowDataBound event, the data could be accessed in the cell directly. </p>\n\n<p>The relevant fragments: First, the aspx page:</p>\n\n<pre><code><asp:GridView ID=\"gvVarianceReport\" runat=\"server\" ... >\n...Other fields...\n <asp:BoundField DataField=\"TotalExpected\" \n HeaderText=\"Total Expected <br />Filtration Events\" \n HtmlEncode=\"False\" ItemStyle-HorizontalAlign=\"Left\" \n SortExpression=\"TotalExpected\" />\n...\n</asp:Gridview>\n</code></pre>\n\n<p>Then in the RowDataBound event I can access the values directly:</p>\n\n<pre><code>protected void gvVarianceReport_Sorting(object sender, GridViewSortEventArgs e)\n{\n if (e.Row.Cells[2].Text == \"0\")\n {\n e.Row.Cells[2].Text = \"N/A\";\n e.Row.Cells[3].Text = \"N/A\";\n e.Row.Cells[4].Text = \"N/A\";\n }\n}\n</code></pre>\n\n<p>If someone could comment on <em>why</em> this works, I'd appreciate it. I don't fully understand why without the BoundField the value is not in the cell after the bind, but you have to look it up via the control.</p>\n"
},
{
"answer_id": 26269264,
"author": "user3679550",
"author_id": 3679550,
"author_profile": "https://Stackoverflow.com/users/3679550",
"pm_score": 0,
"selected": false,
"text": "<pre><code><asp:TemplateField HeaderText=\"# Percentage click throughs\">\n <ItemTemplate>\n <%# AddPercentClickThroughs(Convert.ToDecimal(DataBinder.Eval(Container.DataItem, \"EmailSummary.pLinksClicked\")), Convert.ToDecimal(DataBinder.Eval(Container.DataItem, \"NumberOfSends\")))%>\n </ItemTemplate>\n</asp:TemplateField>\n\n\npublic string AddPercentClickThroughs(decimal NumberOfSends, decimal EmailSummary.pLinksClicked)\n{\n decimal OccupancyPercentage = 0;\n if (TotalNoOfRooms != 0 && RoomsOccupied != 0)\n {\n OccupancyPercentage = (Convert.ToDecimal(NumberOfSends) / Convert.ToDecimal(EmailSummary.pLinksClicked) * 100);\n }\n return OccupancyPercentage.ToString(\"F\");\n}\n</code></pre>\n"
},
{
"answer_id": 29454155,
"author": "ashiq",
"author_id": 4750795,
"author_profile": "https://Stackoverflow.com/users/4750795",
"pm_score": -1,
"selected": false,
"text": "<pre><code>protected void gvbind_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n e.Row.Attributes[\"onmouseover\"] = \"this.style.cursor='hand';\";\n e.Row.Attributes[\"onmouseout\"] = \"this.style.textDecoration='none';\";\n e.Row.Attributes[\"onclick\"] = ClientScript.GetPostBackClientHyperlink(this.gvbind, \"Select$\" + e.Row.RowIndex);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 41738662,
"author": "vemund",
"author_id": 5200895,
"author_profile": "https://Stackoverflow.com/users/5200895",
"pm_score": 0,
"selected": false,
"text": "<p>If you set the attribute <strong>Visible</strong> on the asp:BoundField to <strong>False</strong>. Like this</p>\n\n<pre><code><asp:BoundField DataField=\"F1\" HeaderText=\"F1\" Visible=\"False\"/>\n</code></pre>\n\n<p>You will <strong>not</strong> get any Text in the Cells[i].Text property when you loop the rows. So</p>\n\n<pre><code>foreach (GridViewRow row in myGrid.Rows)\n{\n userList.Add(row.Cells[0].Text); //this will be empty \"\"\n}\n</code></pre>\n\n<p>But you can set a column not visible by connecting the grid to the event OnRowDataBound then from here do this</p>\n\n<pre><code>e.Row.Cells[0].Visible = false //now the cell has Text but it's hidden\n</code></pre>\n"
},
{
"answer_id": 62479479,
"author": "Niklas",
"author_id": 3956100,
"author_profile": "https://Stackoverflow.com/users/3956100",
"pm_score": 0,
"selected": false,
"text": "<p>Regarding the index selection style of the columns i suggest you do the following. i ran into this problem but i was going to set values dynamically using an <code>API</code> so what i did was this : \nkeep in mind <code>.CastTo<T></code> is simply <code>((T)e.Row.DataItem)</code><br><br>\nand you have to call <code>DataBind()</code> in order to see the changes in the grid. this way you wont run into issues if you decide to add a column to the grid.</p>\n\n<pre><code> protected void gvdata_RowDataBound(object sender, GridViewRowEventArgs e)\n {\n if(e.Row.RowType == DataControlRowType.DataRow)\n {\n var number = e.Row.DataItem.CastTo<DataRowView>().Row[\"number\"];\n e.Row.DataItem.CastTo<DataRowView>().Row[\"ActivationDate\"] = DateTime.Parse(userData.basic_info.creation_date).ToShortDateString();\n e.Row.DataItem.CastTo<DataRowView>().Row[\"ExpirationDate\"] = DateTime.Parse(userData.basic_info.nearest_exp_date).ToShortDateString();\n e.Row.DataItem.CastTo<DataRowView>().Row[\"Remainder\"] = Convert.ToDecimal(userData.basic_info.credit).ToStringWithSeparator();\n\n e.Row.DataBind();\n }\n }\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/121722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3193/"
] |
```
string percentage = e.Row.Cells[7].Text;
```
I am trying to do some dynamic stuff with my GridView, so I have wired up some code to the RowDataBound event. I am trying to get the value from a particular cell, which is a TemplateField. But the code above always seems to be returning an empty string.
Any ideas?
To clarify, here is a bit the offending cell:
```
<asp:TemplateField HeaderText="# Percentage click throughs">
<ItemTemplate>
<%# AddPercentClickThroughs((int)Eval("EmailSummary.pLinksClicked"), (int)Eval("NumberOfSends")) %>
</ItemTemplate>
</asp:TemplateField>
```
On a related note, does anyone know if there is a better way of selecting the cell in the row. It sucks putting in `cell[1]`. Couldn't I do `cell["mycellname"]`, so if I decide to change the order of my cells, bugs wont appear?
|
First you need to wrap your code in a `Label` or `Literal` control so that you can reference it properly. What's happening is that there's no way for the system to keep track of it, because there's no control associated with the text. It's the control's responsibility to add its contents to viewstate.
You need to use gridView.FindControl("controlName"); to get the control in the row. From there you can get at its properties including `Text`.
You can also get at the DataItem property of the Row in question and cast it to the appropriate type and extract the information directly.
|
121,762 |
<p>I have two threads in an Android application, one is the view thread, and the other is the worker thread. What I want to do is, sleep the worker thread until the view thread terminates the handling of the onDraw method.</p>
<p>How i can do this? is there any wait for the signal or something?</p>
|
[
{
"answer_id": 121853,
"author": "Paul Brinkley",
"author_id": 18160,
"author_profile": "https://Stackoverflow.com/users/18160",
"pm_score": 6,
"selected": true,
"text": "<p>Share a java.lang.Object between the two threads, whose sole purpose is to tell the worker thread when it can continue its work. Whenever the worker thread reaches a point where it should sleep, it does this:</p>\n\n<pre><code>stick.wait();\n</code></pre>\n\n<p>When the view thread finishes its onDraw work, it calls this:</p>\n\n<pre><code>stick.notify();\n</code></pre>\n\n<p>Note the requirement that the view thread owns the monitor on the object. In your case, this should be fairly simple to enforce with a small sync block:</p>\n\n<pre><code>void onDraw() {\n ...\n synchronized (stick) {\n stick.notify();\n }\n} // end onDraw()\n</code></pre>\n\n<p>Consult the javadoc for java.lang.Object on these methods (and notifyAll, just in case); they're very well written. </p>\n"
},
{
"answer_id": 122272,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 2,
"selected": false,
"text": "<p>If you want a higher-level concurreny API (with things like Barriers), you could try the backport of the java 5 concurrency API, which works on java 1.3 and above, and may work on Android. The likes of Object.wait/notify will work, but they can be a bit terse.</p>\n\n<p><a href=\"http://backport-jsr166.sourceforge.net/\" rel=\"nofollow noreferrer\">Backport-util-concurrent</a></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/121762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7363/"
] |
I have two threads in an Android application, one is the view thread, and the other is the worker thread. What I want to do is, sleep the worker thread until the view thread terminates the handling of the onDraw method.
How i can do this? is there any wait for the signal or something?
|
Share a java.lang.Object between the two threads, whose sole purpose is to tell the worker thread when it can continue its work. Whenever the worker thread reaches a point where it should sleep, it does this:
```
stick.wait();
```
When the view thread finishes its onDraw work, it calls this:
```
stick.notify();
```
Note the requirement that the view thread owns the monitor on the object. In your case, this should be fairly simple to enforce with a small sync block:
```
void onDraw() {
...
synchronized (stick) {
stick.notify();
}
} // end onDraw()
```
Consult the javadoc for java.lang.Object on these methods (and notifyAll, just in case); they're very well written.
|
121,810 |
<p><strong>Is there any way that I can remove the Print item from the context menu when you right-click on an email with VBA?</strong></p>
<p>I am forever right-clicking to reply to an email, only to accidentally click <code>Print</code> and have Outlook send it directly to the printer quicker than I can stop it.</p>
<p><img src="https://farm4.static.flickr.com/3221/2882658372_496d6e7a11_o.jpg" alt="alt text"></p>
<p><strong>NB:</strong> I am using Outlook 2007.</p>
|
[
{
"answer_id": 121899,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 3,
"selected": false,
"text": "<p>Thera is sample how to programaticly working with Outlook:\n<a href=\"http://msdn.microsoft.com/en-us/library/bb176426.aspx\" rel=\"noreferrer\">How to: Customize an Item Context Menu</a></p>\n"
},
{
"answer_id": 582063,
"author": "Will Rickards",
"author_id": 290835,
"author_profile": "https://Stackoverflow.com/users/290835",
"pm_score": 4,
"selected": true,
"text": "<p>Based on the link TcKs provide, that was pretty simple.\nIn the example below I check the type of the item so that it only affects e-mails and not calendar items.\nTo enter the code in outlook, Type Alt + F11, then expand the Microsoft Office Outlook Objects in the Project pane. Then double click the ThisOutlookSession. Then paste this code into the code window. I don't like to check captions like this as you can run into issues with internationalization. But I didn't see an ActionID or anything on the Command. There was a FaceID but that is just the id of the printer icon.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub Application_ItemContextMenuDisplay(ByVal CommandBar As Office.CommandBar, ByVal Selection As Selection)\n\n Dim cmdTemp As Office.CommandBarControl\n\n If Selection.Count > 0 Then\n\n Select Case TypeName(Selection.Item(1))\n\n Case \"MailItem\"\n\n For Each cmdTemp In CommandBar.Controls\n\n If cmdTemp.Caption = \"&Print\" Then\n\n cmdTemp.Delete\n Exit For\n\n End If\n\n Next cmdTemp\n\n Case Else\n\n 'Debug.Print TypeName(Selection.Item(1))\n\n End Select\n\n End If\n\nEnd Sub\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/121810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
**Is there any way that I can remove the Print item from the context menu when you right-click on an email with VBA?**
I am forever right-clicking to reply to an email, only to accidentally click `Print` and have Outlook send it directly to the printer quicker than I can stop it.

**NB:** I am using Outlook 2007.
|
Based on the link TcKs provide, that was pretty simple.
In the example below I check the type of the item so that it only affects e-mails and not calendar items.
To enter the code in outlook, Type Alt + F11, then expand the Microsoft Office Outlook Objects in the Project pane. Then double click the ThisOutlookSession. Then paste this code into the code window. I don't like to check captions like this as you can run into issues with internationalization. But I didn't see an ActionID or anything on the Command. There was a FaceID but that is just the id of the printer icon.
```vb
Private Sub Application_ItemContextMenuDisplay(ByVal CommandBar As Office.CommandBar, ByVal Selection As Selection)
Dim cmdTemp As Office.CommandBarControl
If Selection.Count > 0 Then
Select Case TypeName(Selection.Item(1))
Case "MailItem"
For Each cmdTemp In CommandBar.Controls
If cmdTemp.Caption = "&Print" Then
cmdTemp.Delete
Exit For
End If
Next cmdTemp
Case Else
'Debug.Print TypeName(Selection.Item(1))
End Select
End If
End Sub
```
|
121,813 |
<p>We have redesigned the structure to a website which has several business units. Now I want to redirect (301) to the new page.</p>
<p>IE: <br />
was www.example.com/abc <br />
now www.example.com/default.aspx?article=abc <br /></p>
<p>I have tried to use Global.asax to do this, and it works properly when I debug through it.</p>
<pre><code> if (Request.RawUrl.Contains("abc"))
{
Response.RedirectLocation = "/default.aspx?article=abc";
Response.StatusCode = 301;
Response.StatusDescription = "Moved";
Response.End();
}
</code></pre>
<p>So <a href="http://localhost:1234/example/abc" rel="nofollow noreferrer">http://localhost:1234/example/abc</a> redirects properly, but (where 1234 is the port for the debugging server)<br/>
<a href="http://localhost/example/abc" rel="nofollow noreferrer">http://localhost/example/abc</a> does not redirect, it gives me a 404.</p>
<p>Any ideas?</p>
<hr>
<p>Additional info:
If I go to <a href="http://localhost/example/abc/default.aspx" rel="nofollow noreferrer">http://localhost/example/abc/default.aspx</a> then it redirects properly.</p>
|
[
{
"answer_id": 121834,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>Have you made sure the web.config files are the same for each website (assuming :1234 is different to :80)</p>\n\n<p>Also, have you tried localhost:80?</p>\n"
},
{
"answer_id": 121838,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 1,
"selected": false,
"text": "<p>Are you currently testing the site in the Visual Studio web server? That usually runs the site on \"localhost:nnnnn\" where \"nnnnn\" is a port number (as above is 1234), it doesn't set it to run without one.</p>\n\n<p>If you've got IIS installed on the machine concerned, publish your project to it and you should be able to verify that it works without the \"nnnnn\" as there doesn't look to be anything in your code that would cause it to not do so.</p>\n"
},
{
"answer_id": 121861,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps you want to take a look at <strong>Routing</strong>.</p>\n\n<p>See:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/cc668201.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/cc668201.aspx</a></li>\n<li><a href=\"http://blogs.msdn.com/mikeormond/archive/2008/05/14/using-asp-net-routing-independent-of-mvc.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/mikeormond/archive/2008/05/14/using-asp-net-routing-independent-of-mvc.aspx</a></li>\n</ul>\n"
},
{
"answer_id": 121862,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 4,
"selected": true,
"text": "<p>Well, if the port indicates you are using the built-in web server (the one that comes with VS), this probably works because that <em>always</em> routes requests through the ASP.NET framework.</p>\n\n<p>Requests ending with /abc will not automatically route through the ASP.NET framework because IIS may not \"know\" you want them to. You need to check your IIS settings to make sure such requests are routed to the aspnet_isapi.dll</p>\n\n<hr>\n\n<p><strong>EDIT:</strong> To accomplish this, you need to add a <a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx\" rel=\"nofollow noreferrer\"><strong>wildcard mapping</strong></a>:</p>\n\n<ol>\n<li>In IIS Manager, expand the local computer, expand the Web Sites folder, right-click the Web site or virtual directory that you want, and then click Properties.</li>\n<li>Click the appropriate tab: Home Directory, Virtual Directory, or Directory.</li>\n<li>In the Application settings area, click Configuration, and then click the Mappings tab.</li>\n<li>To install a wildcard application map, do the following:\n\n<ul>\n<li>On the Mappings tab, click Add or Insert.</li>\n<li>Type the path to the DLL in the Executable text box or click Browse to navigate to it (for example, the ASP.NET 2.0 dll is at c:\\windows\\microsoft.net\\framework\\v2.0.50727\\aspnet_isapi.dll on my machine)</li>\n<li>For extension, use \".*\" without quotes, of course</li>\n<li>Select which verbs you want to look for (GET,HEAD,POST,DEBUG are the usual for ASP.NET, you decide)</li>\n<li>Make sure \"Script engine\" or \"Application engine\" is selected</li>\n<li>Uncheck \"Check that file exists\"</li>\n<li>Click okay.</li>\n</ul></li>\n</ol>\n\n<p>I may be off on this, but if I am, hopefully someone will correct me. :)</p>\n"
},
{
"answer_id": 121865,
"author": "SaaS Developer",
"author_id": 7215,
"author_profile": "https://Stackoverflow.com/users/7215",
"pm_score": 0,
"selected": false,
"text": "<p>Your <a href=\"http://localhost/example/abc\" rel=\"nofollow noreferrer\">http://localhost/example/abc</a> is not invoking the Global.asax like you expect. Typically <a href=\"http://localhost\" rel=\"nofollow noreferrer\">http://localhost</a> is running on port 80 (:80). If you want to run your site on port 80 you will need to deploy your site in IIS to run here.</p>\n"
},
{
"answer_id": 121882,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>You need to set up a Handler mapping in IIS to forward all unknown extensions to asp.net. The first one works because cassini is handling all requests, the second one doesn't work because IIS is looking for that directory, and it doesn't exist, instead of the .net framework running the code you have.</p>\n\n<p>Here's information on how to do <a href=\"http://msdn.microsoft.com/en-us/library/ms972974.aspx\" rel=\"nofollow noreferrer\">Url Rewriting in asp.net</a>.</p>\n\n<p>If possible though, i would suggest using the new <a href=\"http://www.hanselman.com/blog/NewModulesForIIS7ApplicationRequestRoutingProxyAndLoadBalancingModule.aspx\" rel=\"nofollow noreferrer\">Application Request Routing</a> or <a href=\"http://www.urlrewriting.net/149/en/home.html\" rel=\"nofollow noreferrer\">UrlRewrite.net</a></p>\n"
},
{
"answer_id": 121893,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 2,
"selected": false,
"text": "<p>You should use the IIS wild card redirection, you will need something like this;</p>\n<pre><code> *; www.example.com/*; www.example.com/default.aspx?article=$0\n</code></pre>\n<p>There is a reasonable reference at <a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/41c238b2-1188-488f-bf2d-464383b1bb08.mspx?mfr=true\" rel=\"nofollow noreferrer\">Microsoft</a></p>\n<p>If you're using Apache I think you'll need to modify the htaccess file.</p>\n"
},
{
"answer_id": 123165,
"author": "Jason",
"author_id": 17573,
"author_profile": "https://Stackoverflow.com/users/17573",
"pm_score": 0,
"selected": false,
"text": "<p>IIS, by default, doesn't hand all requests over to ASP.NET for handling. Only some resource extensions, among them \"aspx\" will be passed over to asp.net for handling. What's happening when you request <a href=\"http://localhost/example/abc\" rel=\"nofollow noreferrer\">http://localhost/example/abc</a> is that IIS tries to locate the directory to see if you have a default file (i.e. default.aspx, index.html) to load from that directory. Since it can't find the directory with the junk \"abc\" tag in it, it never finds the default.aspx file to load.</p>\n\n<p>When you try to load <a href=\"http://localhost/example/abc/default.aspx\" rel=\"nofollow noreferrer\">http://localhost/example/abc/default.aspx</a>, IIS sees the \"aspx\" extension and immediately hands it over to the ASP.NET runtime for handling. The reason that the <a href=\"http://localhost/example/abc\" rel=\"nofollow noreferrer\">http://localhost/example/abc</a> request doesn't load is that it never gets handed to ASP.NET, so of course the global.asax never sees it.</p>\n\n<p>The Cassini hosted site handles all requests, thus that call does get handled by ASP.NET and the global.asax file.</p>\n\n<p>I agree with Darren Kopp, who suggested that you need to set up Handler mapping in IIS to forward unknown extensions to ASP.NET.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/121813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18821/"
] |
We have redesigned the structure to a website which has several business units. Now I want to redirect (301) to the new page.
IE:
was www.example.com/abc
now www.example.com/default.aspx?article=abc
I have tried to use Global.asax to do this, and it works properly when I debug through it.
```
if (Request.RawUrl.Contains("abc"))
{
Response.RedirectLocation = "/default.aspx?article=abc";
Response.StatusCode = 301;
Response.StatusDescription = "Moved";
Response.End();
}
```
So <http://localhost:1234/example/abc> redirects properly, but (where 1234 is the port for the debugging server)
<http://localhost/example/abc> does not redirect, it gives me a 404.
Any ideas?
---
Additional info:
If I go to <http://localhost/example/abc/default.aspx> then it redirects properly.
|
Well, if the port indicates you are using the built-in web server (the one that comes with VS), this probably works because that *always* routes requests through the ASP.NET framework.
Requests ending with /abc will not automatically route through the ASP.NET framework because IIS may not "know" you want them to. You need to check your IIS settings to make sure such requests are routed to the aspnet\_isapi.dll
---
**EDIT:** To accomplish this, you need to add a [**wildcard mapping**](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx):
1. In IIS Manager, expand the local computer, expand the Web Sites folder, right-click the Web site or virtual directory that you want, and then click Properties.
2. Click the appropriate tab: Home Directory, Virtual Directory, or Directory.
3. In the Application settings area, click Configuration, and then click the Mappings tab.
4. To install a wildcard application map, do the following:
* On the Mappings tab, click Add or Insert.
* Type the path to the DLL in the Executable text box or click Browse to navigate to it (for example, the ASP.NET 2.0 dll is at c:\windows\microsoft.net\framework\v2.0.50727\aspnet\_isapi.dll on my machine)
* For extension, use ".\*" without quotes, of course
* Select which verbs you want to look for (GET,HEAD,POST,DEBUG are the usual for ASP.NET, you decide)
* Make sure "Script engine" or "Application engine" is selected
* Uncheck "Check that file exists"
* Click okay.
I may be off on this, but if I am, hopefully someone will correct me. :)
|
121,817 |
<p>I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.</p>
<pre><code><div id="panel">
<div id="field_name">TEXT GOES HERE</div>
</div>
</code></pre>
<p>Here's what the function will look like:</p>
<pre><code>function showPanel(fieldName) {
var fieldNameElement = document.getElementById('field_name');
//Make replacement here
}
</code></pre>
|
[
{
"answer_id": 121822,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$('field_name').innerHTML = 'Your text.';\n</code></pre>\n\n<p>One of the nifty features of Prototype is that <code>$('field_name')</code> does the same thing as <code>document.getElementById('field_name')</code>. Use it! :-)</p>\n\n<p>John Topley's answer using Prototype's <code>update</code> function is another good solution.</p>\n"
},
{
"answer_id": 121824,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 8,
"selected": false,
"text": "<p>You can simply use:</p>\n\n<pre><code>fieldNameElement.innerHTML = \"My new text!\";\n</code></pre>\n"
},
{
"answer_id": 121825,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 3,
"selected": false,
"text": "<p>If you really want us to just continue where you left off, you could do:</p>\n\n<pre><code>if (fieldNameElement)\n fieldNameElement.innerHTML = 'some HTML';\n</code></pre>\n"
},
{
"answer_id": 121859,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 7,
"selected": true,
"text": "<p>I would use Prototype's <code>update</code> method which supports plain text, an HTML snippet or any JavaScript object that defines a <code>toString</code> method.</p>\n\n<pre><code>$(\"field_name\").update(\"New text\");\n</code></pre>\n\n<ul>\n<li><a href=\"http://www.prototypejs.org/api/element/update\" rel=\"noreferrer\">Element.update documentation</a></li>\n</ul>\n"
},
{
"answer_id": 121874,
"author": "hollystyles",
"author_id": 2083160,
"author_profile": "https://Stackoverflow.com/users/2083160",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function showPanel(fieldName) {\n var fieldNameElement = document.getElementById(field_name);\n\n fieldNameElement.removeChild(fieldNameElement.firstChild);\n var newText = document.createTextNode(\"New Text\");\n fieldNameElement.appendChild(newText);\n}\n</code></pre>\n"
},
{
"answer_id": 121877,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 4,
"selected": false,
"text": "<p>The quick answer is to use innerHTML (or prototype's update method which pretty much the same thing). The problem with innerHTML is you need to escape the content being assigned. Depending on your targets you will need to do that with other code OR</p>\n\n<p>in IE:-</p>\n\n<pre><code>document.getElementById(\"field_name\").innerText = newText;\n</code></pre>\n\n<p>in FF:-</p>\n\n<pre><code>document.getElementById(\"field_name\").textContent = newText;\n</code></pre>\n\n<p>(Actually of FF have the following present in by code)</p>\n\n<pre><code>HTMLElement.prototype.__defineGetter__(\"innerText\", function () { return this.textContent; })\n\nHTMLElement.prototype.__defineSetter__(\"innerText\", function (inputText) { this.textContent = inputText; })\n</code></pre>\n\n<p>Now I can just use innerText if you need widest possible browser support then this is not a complete solution but neither is using innerHTML in the raw.</p>\n"
},
{
"answer_id": 121898,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 6,
"selected": false,
"text": "<pre><code>\nfunction showPanel(fieldName) {\n var fieldNameElement = document.getElementById(\"field_name\");\n while(fieldNameElement.childNodes.length >= 1) {\n fieldNameElement.removeChild(fieldNameElement.firstChild);\n }\n fieldNameElement.appendChild(fieldNameElement.ownerDocument.createTextNode(fieldName));\n}\n</code></pre>\n\n<p>The advantages of doing it this way:</p>\n\n<ol>\n<li>It only uses the DOM, so the technique is portable to other languages, and doesn't rely on the non-standard innerHTML</li>\n<li>fieldName might contain HTML, which could be an attempted XSS attack. If we know it's just text, we should be creating a text node, instead of having the browser parse it for HTML</li>\n</ol>\n\n<p>If I were going to use a javascript library, I'd use jQuery, and do this:</p>\n\n<pre><code>\n $(\"div#field_name\").text(fieldName);\n</code></pre>\n\n<p>Note that <a href=\"https://stackoverflow.com/questions/121817/replace-text-inside-a-div-element#comment27322_121898\">@AnthonyWJones' comment</a> is correct: \"field_name\" isn't a particularly descriptive id or variable name.</p>\n"
},
{
"answer_id": 121914,
"author": "Steve Perks",
"author_id": 16124,
"author_profile": "https://Stackoverflow.com/users/16124",
"pm_score": 2,
"selected": false,
"text": "<p>If you're inclined to start using a lot of JavaScript on your site, jQuery makes playing with the DOM extremely simple.</p>\n\n<p><a href=\"http://docs.jquery.com/Manipulation\" rel=\"nofollow noreferrer\"><a href=\"http://docs.jquery.com/Manipulation\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Manipulation</a></a></p>\n\n<p>Makes it as simple as:\n$(\"#field-name\").text(\"Some new text.\");</p>\n"
},
{
"answer_id": 2326249,
"author": "Cosmin",
"author_id": 280352,
"author_profile": "https://Stackoverflow.com/users/280352",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an easy <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> way:</p>\n\n<pre><code>var el = $('#yourid .yourclass');\n\nel.html(el.html().replace(/Old Text/ig, \"New Text\"));\n</code></pre>\n"
},
{
"answer_id": 3339069,
"author": "palswim",
"author_id": 393280,
"author_profile": "https://Stackoverflow.com/users/393280",
"pm_score": 3,
"selected": false,
"text": "<p>nodeValue is also a standard DOM property you can use:</p>\n\n<pre><code>function showPanel(fieldName) {\n var fieldNameElement = document.getElementById(field_name);\n if(fieldNameElement.firstChild)\n fieldNameElement.firstChild.nodeValue = \"New Text\";\n}\n</code></pre>\n"
},
{
"answer_id": 8260506,
"author": "Adrian Adkison",
"author_id": 158095,
"author_profile": "https://Stackoverflow.com/users/158095",
"pm_score": 2,
"selected": false,
"text": "<pre><code>el.innerHTML='';\nel.appendChild(document.createTextNode(\"yo\"));\n</code></pre>\n"
},
{
"answer_id": 18723036,
"author": "mikemaccana",
"author_id": 123671,
"author_profile": "https://Stackoverflow.com/users/123671",
"pm_score": 8,
"selected": false,
"text": "<p><strong>Updated for everyone reading this in 2013 and later:</strong></p>\n\n<p>This answer has a lot of SEO, but all the answers are severely out of date and depend on libraries to do things that all current browsers do out of the box.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent#Browser_compatibility\" rel=\"noreferrer\">To replace text inside a div element, use Node.textContent, which is provided in all current browsers.</a></p>\n\n<pre><code>fieldNameElement.textContent = \"New text\";\n</code></pre>\n"
},
{
"answer_id": 50548849,
"author": "Youth overturn",
"author_id": 2630686,
"author_profile": "https://Stackoverflow.com/users/2630686",
"pm_score": 2,
"selected": false,
"text": "<p>Use innerText if you can't assume structure\n- Use Text#data to update existing text\n<a href=\"https://twitter.com/_developit/status/997132016612270081\" rel=\"nofollow noreferrer\">Performance Test</a></p>\n"
},
{
"answer_id": 61691911,
"author": "Trees",
"author_id": 10350895,
"author_profile": "https://Stackoverflow.com/users/10350895",
"pm_score": 0,
"selected": false,
"text": "<p>In HTML put this</p>\n\n<pre><code><div id=\"field_name\">TEXT GOES HERE</div>\n</code></pre>\n\n<p>In Javascript put this</p>\n\n<pre><code>var fieldNameElement = document.getElementById('field_name');\n if (fieldNameElement)\n {fieldNameElement.innerHTML = 'some HTML';}\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/121817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.
```
<div id="panel">
<div id="field_name">TEXT GOES HERE</div>
</div>
```
Here's what the function will look like:
```
function showPanel(fieldName) {
var fieldNameElement = document.getElementById('field_name');
//Make replacement here
}
```
|
I would use Prototype's `update` method which supports plain text, an HTML snippet or any JavaScript object that defines a `toString` method.
```
$("field_name").update("New text");
```
* [Element.update documentation](http://www.prototypejs.org/api/element/update)
|
121,864 |
<p>As compared to say:</p>
<pre><code>REPLICATE(@padchar, @len - LEN(@str)) + @str
</code></pre>
|
[
{
"answer_id": 121890,
"author": "AlexCuse",
"author_id": 794,
"author_profile": "https://Stackoverflow.com/users/794",
"pm_score": 9,
"selected": true,
"text": "<p>This is simply an inefficient use of SQL, no matter how you do it. </p>\n\n<p>perhaps something like </p>\n\n<pre><code>right('XXXXXXXXXXXX'+ rtrim(@str), @n)\n</code></pre>\n\n<p>where X is your padding character and @n is the number of characters in the resulting string (assuming you need the padding because you are dealing with a fixed length). </p>\n\n<p>But as I said you should really avoid doing this in your database.</p>\n"
},
{
"answer_id": 121896,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure that the method that you give is really inefficient, but an alternate way, as long as it doesn't have to be flexible in the length or padding character, would be (assuming that you want to pad it with \"0\" to 10 characters:</p>\n\n<pre><code>DECLARE\n @pad_characters VARCHAR(10)\n\nSET @pad_characters = '0000000000'\n\nSELECT RIGHT(@pad_characters + @str, 10)\n</code></pre>\n"
},
{
"answer_id": 121901,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 4,
"selected": false,
"text": "<pre><code>@padstr = REPLICATE(@padchar, @len) -- this can be cached, done only once\n\nSELECT RIGHT(@padstr + @str, @len)\n</code></pre>\n"
},
{
"answer_id": 121917,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select right(replicate(@padchar, @len) + @str, @len)\n</code></pre>\n"
},
{
"answer_id": 121920,
"author": "Kramii",
"author_id": 11514,
"author_profile": "https://Stackoverflow.com/users/11514",
"pm_score": 1,
"selected": false,
"text": "<p>In SQL Server 2005 and later you could create a CLR function to do this.</p>\n"
},
{
"answer_id": 121968,
"author": "ila",
"author_id": 1178,
"author_profile": "https://Stackoverflow.com/users/1178",
"pm_score": 2,
"selected": false,
"text": "<p>probably overkill, I often use this UDF:</p>\n\n<pre><code>CREATE FUNCTION [dbo].[f_pad_before](@string VARCHAR(255), @desired_length INTEGER, @pad_character CHAR(1))\nRETURNS VARCHAR(255) AS \nBEGIN\n\n-- Prefix the required number of spaces to bulk up the string and then replace the spaces with the desired character\n RETURN ltrim(rtrim(\n CASE\n WHEN LEN(@string) < @desired_length\n THEN REPLACE(SPACE(@desired_length - LEN(@string)), ' ', @pad_character) + @string\n ELSE @string\n END\n ))\nEND\n</code></pre>\n\n<p>So that you can do things like:</p>\n\n<pre><code>select dbo.f_pad_before('aaa', 10, '_')\n</code></pre>\n"
},
{
"answer_id": 140089,
"author": "Kevin",
"author_id": 19038,
"author_profile": "https://Stackoverflow.com/users/19038",
"pm_score": 5,
"selected": false,
"text": "<p>Several people gave versions of this:</p>\n\n<pre><code>right('XXXXXXXXXXXX'+ @str, @n)\n</code></pre>\n\n<p>be careful with that because it will truncate your actual data if it is longer than n.</p>\n"
},
{
"answer_id": 678126,
"author": "joshblair",
"author_id": 79122,
"author_profile": "https://Stackoverflow.com/users/79122",
"pm_score": 1,
"selected": false,
"text": "<p>How about this:</p>\n\n<pre><code>replace((space(3 - len(MyField))\n</code></pre>\n\n<p>3 is the number of <code>zeros</code> to pad</p>\n"
},
{
"answer_id": 2982326,
"author": "TonyP",
"author_id": 225394,
"author_profile": "https://Stackoverflow.com/users/225394",
"pm_score": 3,
"selected": false,
"text": "<p>Perhaps an over kill I have these UDFs to pad left and right</p>\n\n<pre><code>ALTER Function [dbo].[fsPadLeft](@var varchar(200),@padChar char(1)='0',@len int)\nreturns varchar(300)\nas\nBegin\n\nreturn replicate(@PadChar,@len-Len(@var))+@var\n\nend\n</code></pre>\n\n<p>and to right</p>\n\n<pre><code>ALTER function [dbo].[fsPadRight](@var varchar(200),@padchar char(1)='0', @len int) returns varchar(201) as\nBegin\n\n--select @padChar=' ',@len=200,@var='hello'\n\n\nreturn @var+replicate(@PadChar,@len-Len(@var))\nend\n</code></pre>\n"
},
{
"answer_id": 4389352,
"author": "Ahmad",
"author_id": 535212,
"author_profile": "https://Stackoverflow.com/users/535212",
"pm_score": 2,
"selected": false,
"text": "<p>this is a simple way to pad left:</p>\n\n<pre><code>REPLACE(STR(FACT_HEAD.FACT_NO, x, 0), ' ', y)\n</code></pre>\n\n<p>Where <code>x</code> is the pad number and <code>y</code> is the pad character.</p>\n\n<p>sample:</p>\n\n<pre><code>REPLACE(STR(FACT_HEAD.FACT_NO, 3, 0), ' ', 0)\n</code></pre>\n"
},
{
"answer_id": 6372730,
"author": "vnRock",
"author_id": 512327,
"author_profile": "https://Stackoverflow.com/users/512327",
"pm_score": 2,
"selected": false,
"text": "<p>I hope this helps someone. </p>\n\n<pre><code>STUFF ( character_expression , start , length ,character_expression )\n\nselect stuff(@str, 1, 0, replicate('0', @n - len(@str)))\n</code></pre>\n"
},
{
"answer_id": 7499464,
"author": "Deanos",
"author_id": 685717,
"author_profile": "https://Stackoverflow.com/users/685717",
"pm_score": -1,
"selected": false,
"text": "<p>Here is how I would normally pad a varchar</p>\n\n<pre><code>WHILE Len(@String) < 8\nBEGIN\n SELECT @String = '0' + @String\nEND\n</code></pre>\n"
},
{
"answer_id": 7931179,
"author": "Kevin",
"author_id": 1018604,
"author_profile": "https://Stackoverflow.com/users/1018604",
"pm_score": 2,
"selected": false,
"text": "<p>I liked vnRocks solution, here it is in the form of a udf</p>\n\n<pre><code>create function PadLeft(\n @String varchar(8000)\n ,@NumChars int\n ,@PadChar char(1) = ' ')\nreturns varchar(8000)\nas\nbegin\n return stuff(@String, 1, 0, replicate(@PadChar, @NumChars - len(@String)))\nend\n</code></pre>\n"
},
{
"answer_id": 9763742,
"author": "mattpm",
"author_id": 590021,
"author_profile": "https://Stackoverflow.com/users/590021",
"pm_score": -1,
"selected": false,
"text": "<p>To provide numerical values rounded to two decimal places but right-padded with zeros if required I have:</p>\n\n<pre><code>DECLARE @value = 20.1\nSET @value = ROUND(@value,2) * 100\nPRINT LEFT(CAST(@value AS VARCHAR(20)), LEN(@value)-2) + '.' + RIGHT(CAST(@value AS VARCHAR(20)),2)\n</code></pre>\n\n<p>If anyone can think of a neater way, that would be appreciated - the above seems <em>clumsy</em>.</p>\n\n<p><strong>Note</strong>: in this instance, I'm using SQL Server to email reports in HTML format and so wish to format the information without involving an additional tool to parse the data. </p>\n"
},
{
"answer_id": 16678606,
"author": "Joseph Morgan",
"author_id": 1440294,
"author_profile": "https://Stackoverflow.com/users/1440294",
"pm_score": 0,
"selected": false,
"text": "<p>I use this one. It allows you to determine the length you want the result to be as well as a default padding character if one is not provided. Of course you can customize the length of the input and output for whatever maximums you are running into.</p>\n\n<pre><code>/*===============================================================\n Author : Joey Morgan\n Create date : November 1, 2012\n Description : Pads the string @MyStr with the character in \n : @PadChar so all results have the same length\n ================================================================*/\n CREATE FUNCTION [dbo].[svfn_AMS_PAD_STRING]\n (\n @MyStr VARCHAR(25),\n @LENGTH INT,\n @PadChar CHAR(1) = NULL\n )\nRETURNS VARCHAR(25)\n AS \n BEGIN\n SET @PadChar = ISNULL(@PadChar, '0');\n DECLARE @Result VARCHAR(25);\n SELECT\n @Result = RIGHT(SUBSTRING(REPLICATE('0', @LENGTH), 1,\n (@LENGTH + 1) - LEN(RTRIM(@MyStr)))\n + RTRIM(@MyStr), @LENGTH)\n\n RETURN @Result\n\n END\n</code></pre>\n\n<p>Your mileage may vary. :-)<br /><br />\nJoey Morgan<br />\nProgrammer/Analyst Principal I<br />\nWellPoint Medicaid Business Unit</p>\n"
},
{
"answer_id": 26107021,
"author": "jediCouncilor",
"author_id": 900953,
"author_profile": "https://Stackoverflow.com/users/900953",
"pm_score": 6,
"selected": false,
"text": "<p>I know this was originally asked back in 2008, but there are some new functions that were introduced with SQL Server 2012. The <a href=\"https://msdn.microsoft.com/en-us/library/hh213505(v=sql.110).aspx\" rel=\"noreferrer\">FORMAT function</a> simplifies padding left with zeros nicely. It will also perform the conversion for you:</p>\n\n<pre><code>declare @n as int = 2\nselect FORMAT(@n, 'd10') as padWithZeros\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>I wanted to test the actual efficiency of the FORMAT function myself. I was quite surprised to find the efficiency was not very good compared to the original answer from <a href=\"https://stackoverflow.com/users/794/alexcuse\">AlexCuse</a>. Although I find the FORMAT function cleaner, it is not very efficient in terms of execution time. The Tally table I used has 64,000 records. Kudos to <a href=\"https://stackoverflow.com/users/73226/martin-smith\">Martin Smith</a> for pointing out execution time efficiency.</p>\n\n<pre><code>SET STATISTICS TIME ON\nselect FORMAT(N, 'd10') as padWithZeros from Tally\nSET STATISTICS TIME OFF\n</code></pre>\n\n<p>SQL Server Execution Times:\n CPU time = 2157 ms, elapsed time = 2696 ms.</p>\n\n<pre><code>SET STATISTICS TIME ON\nselect right('0000000000'+ rtrim(cast(N as varchar(5))), 10) from Tally\nSET STATISTICS TIME OFF\n</code></pre>\n\n<p>SQL Server Execution Times:</p>\n\n<blockquote>\n <p>CPU time = 31 ms, elapsed time = 235 ms.</p>\n</blockquote>\n"
},
{
"answer_id": 44188657,
"author": "Mass Dot Net",
"author_id": 165494,
"author_profile": "https://Stackoverflow.com/users/165494",
"pm_score": 0,
"selected": false,
"text": "<p>Here's my solution, which avoids truncated strings and uses plain ol' SQL. Thanks to <em>@AlexCuse</em>, <em>@Kevin</em> and <em>@Sklivvz</em>, whose solutions are the foundation of this code.</p>\n\n<pre><code> --[@charToPadStringWith] is the character you want to pad the string with.\ndeclare @charToPadStringWith char(1) = 'X';\n\n-- Generate a table of values to test with.\ndeclare @stringValues table (RowId int IDENTITY(1,1) NOT NULL PRIMARY KEY, StringValue varchar(max) NULL);\ninsert into @stringValues (StringValue) values (null), (''), ('_'), ('A'), ('ABCDE'), ('1234567890');\n\n-- Generate a table to store testing results in.\ndeclare @testingResults table (RowId int IDENTITY(1,1) NOT NULL PRIMARY KEY, StringValue varchar(max) NULL, PaddedStringValue varchar(max) NULL);\n\n-- Get the length of the longest string, then pad all strings based on that length.\ndeclare @maxLengthOfPaddedString int = (select MAX(LEN(StringValue)) from @stringValues);\ndeclare @longestStringValue varchar(max) = (select top(1) StringValue from @stringValues where LEN(StringValue) = @maxLengthOfPaddedString);\nselect [@longestStringValue]=@longestStringValue, [@maxLengthOfPaddedString]=@maxLengthOfPaddedString;\n\n-- Loop through each of the test string values, apply padding to it, and store the results in [@testingResults].\nwhile (1=1)\nbegin\n declare\n @stringValueRowId int,\n @stringValue varchar(max);\n\n -- Get the next row in the [@stringLengths] table.\n select top(1) @stringValueRowId = RowId, @stringValue = StringValue\n from @stringValues \n where RowId > isnull(@stringValueRowId, 0) \n order by RowId;\n\n if (@@ROWCOUNT = 0) \n break;\n\n -- Here is where the padding magic happens.\n declare @paddedStringValue varchar(max) = RIGHT(REPLICATE(@charToPadStringWith, @maxLengthOfPaddedString) + @stringValue, @maxLengthOfPaddedString);\n\n -- Added to the list of results.\n insert into @testingResults (StringValue, PaddedStringValue) values (@stringValue, @paddedStringValue);\nend\n\n-- Get all of the testing results.\nselect * from @testingResults;\n</code></pre>\n"
},
{
"answer_id": 55034858,
"author": "blind Skwirl",
"author_id": 5271220,
"author_profile": "https://Stackoverflow.com/users/5271220",
"pm_score": 0,
"selected": false,
"text": "<p>I know this isn't adding much to the conversation at this point but I'm running a file generation procedure and its going incredibly slow. I've been using replicate and saw this trim method and figured I'd give it a shot. </p>\n\n<p>You can see in my code where the switch between the two is in addition to the new @padding variable (and the limitation that now exists). I ran my procedure with the function in both states with the same results in execution time. So at least in SQLServer2016, I'm not seeing any difference in efficiency that other found.</p>\n\n<p>Anyways, here's my UDF that I wrote years ago plus the changes today which is much the same as other's other than it has a LEFT/RIGHT param option and some error checking.</p>\n\n<pre><code>CREATE FUNCTION PadStringTrim \n(\n @inputStr varchar(500), \n @finalLength int, \n @padChar varchar (1),\n @padSide varchar(1)\n)\nRETURNS VARCHAR(500)\n\nAS BEGIN\n -- the point of this function is to avoid using replicate which is extremely slow in SQL Server\n -- to get away from this though we now have a limitation of how much padding we can add, so I've settled on a hundred character pad \n DECLARE @padding VARCHAR (100) = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'\n SET @padding = REPLACE(@padding, 'X', @padChar)\n\n\n SET @inputStr = RTRIM(LTRIM(@inputStr))\n\n IF LEN(@inputStr) > @finalLength \n RETURN '!ERROR!' -- can search for ! in the returned text \n\n ELSE IF(@finalLength > LEN(@inputStr))\n IF @padSide = 'L'\n SET @inputStr = RIGHT(@padding + @inputStr, @finalLength)\n --SET @inputStr = REPLICATE(@padChar, @finalLength - LEN(@inputStr)) + @inputStr\n ELSE IF @padSide = 'R'\n SET @inputStr = LEFT(@inputStr + @padding, @finalLength)\n --SET @inputStr = @inputStr + REPLICATE(@padChar, @finalLength - LEN(@inputStr)) \n\n\n\n -- if LEN(@inputStr) = @finalLength we just return it \n RETURN @inputStr;\nEND\n\n-- SELECT dbo.PadStringTrim( tblAccounts.account, 20, '~' , 'R' ) from tblAccounts\n-- SELECT dbo.PadStringTrim( tblAccounts.account, 20, '~' , 'L' ) from tblAccounts\n</code></pre>\n"
},
{
"answer_id": 57532237,
"author": "Pancho R",
"author_id": 11938268,
"author_profile": "https://Stackoverflow.com/users/11938268",
"pm_score": 0,
"selected": false,
"text": "<p>I have one function that lpad with x decimals:\nCREATE FUNCTION [dbo].[LPAD_DEC]\n(\n -- Add the parameters for the function here\n @pad nvarchar(MAX),\n @string nvarchar(MAX),\n @length int,\n @dec int\n)\nRETURNS nvarchar(max)\nAS\nBEGIN\n -- Declare the return variable here\n DECLARE @resp nvarchar(max)</p>\n\n<pre><code>IF LEN(@string)=@length\nBEGIN\n IF CHARINDEX('.',@string)>0\n BEGIN\n SELECT @resp = CASE SIGN(@string)\n WHEN -1 THEN\n -- Nros negativos grandes con decimales\n concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))\n ELSE\n -- Nros positivos grandes con decimales\n concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec))) \n END\n END\n ELSE\n BEGIN\n SELECT @resp = CASE SIGN(@string)\n WHEN -1 THEN\n --Nros negativo grande sin decimales\n concat('-',SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))\n ELSE\n -- Nros positivos grandes con decimales\n concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec))) \n END \n END\nEND\nELSE\n IF CHARINDEX('.',@string)>0\n BEGIN\n SELECT @resp =CASE SIGN(@string)\n WHEN -1 THEN\n -- Nros negativos con decimales\n concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))\n ELSE\n --Ntos positivos con decimales\n concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec))) \n END\n END\n ELSE\n BEGIN\n SELECT @resp = CASE SIGN(@string)\n WHEN -1 THEN\n -- Nros Negativos sin decimales\n concat('-',SUBSTRING(replicate(@pad,@length-3),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))\n ELSE\n -- Nros Positivos sin decimales\n concat(SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))\n END\n END\nRETURN @resp\n</code></pre>\n\n<p>END</p>\n"
},
{
"answer_id": 64320371,
"author": "DGM0522",
"author_id": 14436698,
"author_profile": "https://Stackoverflow.com/users/14436698",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my solution. I can pad any character and it is fast. Went with simplicity. You can change variable size to meet your needs.</p>\n<p>Updated with a parameter to handle what to return if null: null will return a null if null</p>\n<pre><code>CREATE OR ALTER FUNCTION code.fnConvert_PadLeft(\n @in_str nvarchar(1024),\n @pad_length int, \n @pad_char nchar(1) = ' ', \n @rtn_null NVARCHAR(1024) = '')\nRETURNS NVARCHAR(1024)\nAS\nBEGIN\n DECLARE @rtn NCHAR(1024) = ' '\n RETURN RIGHT(REPLACE(@rtn,' ',@pad_char)+ISNULL(@in_str,@rtn_null), @pad_length)\nEND\nGO\n\nCREATE OR ALTER FUNCTION code.fnConvert_PadRight(\n @in_str nvarchar(1024), \n @pad_length int, \n @pad_char nchar(1) = ' ', \n @rtn_null NVARCHAR(1024) = '')\nRETURNS NVARCHAR(1024)\nAS\nBEGIN\n DECLARE @rtn NCHAR(1024) = ' '\n RETURN LEFT(ISNULL(@in_str,@rtn_null)+REPLACE(@rtn,' ',@pad_char), @pad_length)\nEND\nGO \n\n-- Example\nSET STATISTICS time ON \nSELECT code.fnConvert_PadLeft('88',10,'0',''), \n code.fnConvert_PadLeft(null,10,'0',''), \n code.fnConvert_PadLeft(null,10,'0',null), \n code.fnConvert_PadRight('88',10,'0',''), \n code.fnConvert_PadRight(null,10,'0',''),\n code.fnConvert_PadRight(null,10,'0',NULL)\n\n\n0000000088 0000000000 NULL 8800000000 0000000000 NULL\n\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/121864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18255/"
] |
As compared to say:
```
REPLICATE(@padchar, @len - LEN(@str)) + @str
```
|
This is simply an inefficient use of SQL, no matter how you do it.
perhaps something like
```
right('XXXXXXXXXXXX'+ rtrim(@str), @n)
```
where X is your padding character and @n is the number of characters in the resulting string (assuming you need the padding because you are dealing with a fixed length).
But as I said you should really avoid doing this in your database.
|
121,866 |
<p>I'm preparing to deploy my Django app and I noticed that when I change the "DEBUG" setting to False, all references to static files (i.e., JavaScript, CSS, etc..) result in <code>HTTP 500</code> errors.</p>
<p>Any idea what's causing that issue (and how to fix it)?</p>
|
[
{
"answer_id": 122052,
"author": "Peter Shinners",
"author_id": 17209,
"author_profile": "https://Stackoverflow.com/users/17209",
"pm_score": 5,
"selected": true,
"text": "<p>I would highly recommend letting your web server handle the static requests, without getting to Django. In my <code>urls.py</code>, I only add the static request handler when debug is set to True.</p>\n\n<p>Technically, Django serving the static works fine though. Definitely read the short docs page, <a href=\"http://docs.djangoproject.com/en/dev/howto/static-files/\" rel=\"noreferrer\">http://docs.djangoproject.com/en/dev/howto/static-files/</a>. You'll want to use an entry like this in <code>urls.py</code></p>\n\n<pre><code>(r'^static/(?P<path>.*)$', 'django.views.static.serve',\n {'document_root': '/path/to/media'})\n</code></pre>\n"
},
{
"answer_id": 122068,
"author": "Kevin",
"author_id": 2678,
"author_profile": "https://Stackoverflow.com/users/2678",
"pm_score": 3,
"selected": false,
"text": "<p>It sounds like you might be trying to serve your static media using the Django development server. Take a look at <a href=\"http://docs.djangoproject.com/en/dev/howto/deployment/\" rel=\"noreferrer\">http://docs.djangoproject.com/en/dev/howto/deployment/</a> for some deployment scenarios/howtos and <a href=\"http://docs.djangoproject.com/en/dev/howto/static-files/\" rel=\"noreferrer\">http://docs.djangoproject.com/en/dev/howto/static-files/</a> for how to serve static files (but note the disclaimer about NOT using those methods in production).</p>\n\n<p>In general, I'd look at your server logs and see where it's trying to fetch the files from. I suspect the 500 errors are really 404 errors, but they become 500 errors because Django can't find or render the 404.html template. If that's not the case, it would be helpful if you could post the specific 500 error you're getting.</p>\n"
},
{
"answer_id": 17164006,
"author": "webzy",
"author_id": 1309235,
"author_profile": "https://Stackoverflow.com/users/1309235",
"pm_score": 0,
"selected": false,
"text": "<p>You must also check your URLs all over the place. When the DEBUG is set to False, all URLs without trailing \"/\" are treated as a bug, unlike when you have DEBUG = True, in which case Django will append \"/\" everywhere it is missing. So, in short, make sure all links end with a slash EVERYWHERE.</p>\n"
},
{
"answer_id": 38675118,
"author": "wcyn",
"author_id": 2878244,
"author_profile": "https://Stackoverflow.com/users/2878244",
"pm_score": 0,
"selected": false,
"text": "<p>Turns out I'd commented out the <code>SECRET_KEY</code> variable. There was no way for me to know though. Just had to try things out.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/121866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
] |
I'm preparing to deploy my Django app and I noticed that when I change the "DEBUG" setting to False, all references to static files (i.e., JavaScript, CSS, etc..) result in `HTTP 500` errors.
Any idea what's causing that issue (and how to fix it)?
|
I would highly recommend letting your web server handle the static requests, without getting to Django. In my `urls.py`, I only add the static request handler when debug is set to True.
Technically, Django serving the static works fine though. Definitely read the short docs page, <http://docs.djangoproject.com/en/dev/howto/static-files/>. You'll want to use an entry like this in `urls.py`
```
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/path/to/media'})
```
|
121,922 |
<p>I am currently suffering a brain fart. I've done this before but I can't remember the exact syntax and I can't look at the code I wrote because I was working at another company at the time. I have this arrangement:</p>
<pre><code>class P
{
// stuff
};
class PW : public P
{
// more stuff
};
class PR : public P
{
// more stuff
};
class C
{
public:
P GetP() const { return p; }
private:
P p;
};
// ...
P p = c.GetP( ); // valid
PW p = c.GetP( ); // invalid
PR p = c.GetP( ); // invalid
// ...
</code></pre>
<p>Now I would like to make P interchangeable with PW and PR (and thus PW and PR can be interchanged). I could probably get away with casts but this code change has occurred quite a few times in this module alone. I am pretty sure it is a operator but for the life of me I can't remember what.</p>
<p><strong>How do I make P interchangeable with PW and PR with minimal amount of code?</strong></p>
<p><strong>Update:</strong> To give a bit more clarification. P stands for Project and the R and W stands for Reader and Writer respectively. All the Reader has is the code for loading - no variables, and the writer has code for simply Writing. It needs to be separate because the Reading and Writing sections has various manager classes and dialogs which is none of Projects real concern which is the manipulation of project files.</p>
<p><strong>Update:</strong> I also need to be able to call the methods of P and PW. So if P has a method a() and PW as a method call b() then I could :</p>
<pre><code>PW p = c.GetP();
p.a();
p.b();
</code></pre>
<p>It's basically to make the conversion transparent.</p>
|
[
{
"answer_id": 121944,
"author": "Carl Seleborg",
"author_id": 2095,
"author_profile": "https://Stackoverflow.com/users/2095",
"pm_score": 2,
"selected": false,
"text": "<p>In the code above, you have the opposite of the <strong>slicing</strong> problem.</p>\n\n<p>What you're trying to do is assign from a P to a PW or PR that contain more information than the source object. How do you do this? Say P only has 3 member variables, but PW has 12 additional members - where do the values for these come when you write <code>PW p = c.GetP()</code>?</p>\n\n<p>If this assignment actually <em>is</em> valid, which should really indicate some kind of design weirdness, then I would implement <code>PW::operator=(const P&)</code> and <code>PR::operator=(const P&)</code>, <code>PW::PW(const P&)</code> and <code>PR::PR(const P&)</code>. But I wouldn't sleep too well that night.</p>\n"
},
{
"answer_id": 121964,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": -1,
"selected": false,
"text": "<p>Use a reference or pointer to P rather than an object:</p>\n\n<pre><code>class C\n{\n public:\n P* GetP() const { return p; }\n private:\n P* p;\n};\n</code></pre>\n\n<p>This will allow a PW* or a PR* to be bound to C.p. However, if you need to go from a P to a PW or PR, you need to use dynamic_cast<PW*>(p), which will return the PW* version of p, or NULL of p is not a PW* (for instance, because it's a PR*). Dynamic_cast has some overhead, though, and it's best avoided if possible (use virtuals).</p>\n\n<p>You can also use the typeid() operator to determine the run-time type of an object, but it has several issues, including that you must include and that it can't detect extra derivation.</p>\n"
},
{
"answer_id": 121966,
"author": "Jon Grant",
"author_id": 18774,
"author_profile": "https://Stackoverflow.com/users/18774",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps you mean the <a href=\"http://msdn.microsoft.com/en-us/library/cby9kycs(VS.80).aspx\" rel=\"nofollow noreferrer\">dynamic_cast</a> operator?</p>\n"
},
{
"answer_id": 121980,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 0,
"selected": false,
"text": "<p>They are not fully interchangeable. PW is a P. PR is a P. But P is not necessarily a PW, and it is not necessarily a PR. You can use static_cast to cast pointers from PW * to P *, or from PR * to P *. You should not use static_cast to cast actual objects to their super-class because of \"slicing\". E. g. if you cast an object of PW to P the extra stuff in PW will be \"sliced\" off. You also cannot use static_cast to cast from P * to PW *. If you really have to do it, use dynamic_cast, which will check at run-time whether the object is actually of the right sub-class, and give you a run-time error if it is not.</p>\n"
},
{
"answer_id": 121983,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure what you mean exactly, but bear with me.</p>\n\n<p>They kind of already are. Just call everything P and you can pretend PR and PW are P's.\nPR and PW are still different though.</p>\n\n<p>Making all three equivalent would result in trouble with the <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov principle</a>. But then why would you give them different names if they are truly equivalent?</p>\n"
},
{
"answer_id": 122004,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 2,
"selected": false,
"text": "<p>You're trying to coerce actual variables, rather than pointers. To do that would require a cast. However, if your class definition looked like this:</p>\n\n<pre><code>class C\n\n {\n public: \n P* GetP() const { return p; }\n private:\n P* p;\n }\n</code></pre>\n\n<p>Then, whether p was a pointer to a P, a PW, or a PR, your function wouldn't change, and any (virtual) functions called on the P* returned by the function would use the implementation from P, PW or PR depending on what the member p was..</p>\n\n<p>I guess the key thing to remember is the <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov Substitution Principle</a>. Since PW and PR are subclasses of P, they can be treated as if they were Ps. However, PWs cannot be treated as PRs, and vice versa.</p>\n"
},
{
"answer_id": 122023,
"author": "nymacro",
"author_id": 10499,
"author_profile": "https://Stackoverflow.com/users/10499",
"pm_score": 0,
"selected": false,
"text": "<p>The second and third would be invalid because it is an implicit upcast -- which is a dangerous thing in C++. This is because the class which you're casting to has more functionality than the class it is being assigned, so unless you explicitly cast it yourself, the C++ compiler will throw an error (at least it should). Of course, this is simplifying things slightly (you can use RTTI for certain things which may relate to what you want to do safely without invoking the wrath of bad object'ness) -- but simplicity is always a good way to approach problems.</p>\n\n<p>Of course, as stated in a few other solutions, you can get around this problem -- but I think before you try to get around the problem, you may want to rethink the design.</p>\n"
},
{
"answer_id": 122075,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "<p>To make PW and PR usable via a P you need to use references (or pointers).\nSo you really need t change the interface of C so it returns a reference.</p>\n\n<p>The main problem in the old code was that you were copying a P into a PW or a PR. This is not going to work as the PW and PR potentially have more information than a P and from a type perspective an object of type P is not a PW or a PR. Though PW and PR are both P.</p>\n\n<p>Change the code to this and it will compile:\nIf you want to return different objects derived from a P class at runtime then the class C must potentially be able to store all the different types you expect and be specialized at runtime. So in the class below I allow you to specialize by passing in a pointer to an object that will be returned by reference. To make sure the object is exception safe I have wrapped the pointer in a smart pointer.</p>\n\n<pre><code>class C\n{\n public:\n C(std::auto_ptr<P> x):\n p(x)\n {\n if (p.get() == NULL) {throw BadInit;}\n }\n // Return a reference.\n P& GetP() const { return *p; } \n private:\n // I use auto_ptr just as an example\n // there are many different valid ways to do this.\n // Once the object is correctly initialized p is always valid.\n std::auto_ptr<P> p;\n};\n\n// ...\nP& p = c.GetP( ); // valid\nPW& p = dynamic_cast<PW>(c.GetP( )); // valid Throws exception if not PW\nPR& p = dynamic_cast<PR>(c.GetP( )); // valid Thorws exception if not PR\n// ...\n</code></pre>\n"
},
{
"answer_id": 122265,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 1,
"selected": false,
"text": "<p>This kind of does something sensible, given that everything is being passed by value. Not sure if it's what you were thinking of.</p>\n\n<pre><code>class P\n{\npublic:\n template <typename T>\n operator T() const\n {\n T t;\n static_cast<T&>(t) = *this;\n return t;\n }\n};\n</code></pre>\n"
},
{
"answer_id": 122443,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 3,
"selected": true,
"text": "<p>If you want to get this part to compile:</p>\n\n<pre><code>\n\n// ...\n P p = c.GetP( ); // valid\n PW p = c.GetP( ); // invalid\n PR p = c.GetP( ); // invalid\n// ...\n</code></pre>\n\n<p>You need to be able to construct/convert a P into a PW or a PR.\nYou need to do something like this:</p>\n\n<pre><code>\n\nclass PW : public P\n{\n PW(const P &);\n// more stuff\n};\n\nclass PR : public P\n{\n PR(const P &);\n// more stuff\n};\n\n</code></pre>\n\n<p>Or did you mean something more like:</p>\n\n<pre><code>\nclass P\n{\n operator PW() const;\n operator PR() const;\n// stuff\n};\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/121922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342/"
] |
I am currently suffering a brain fart. I've done this before but I can't remember the exact syntax and I can't look at the code I wrote because I was working at another company at the time. I have this arrangement:
```
class P
{
// stuff
};
class PW : public P
{
// more stuff
};
class PR : public P
{
// more stuff
};
class C
{
public:
P GetP() const { return p; }
private:
P p;
};
// ...
P p = c.GetP( ); // valid
PW p = c.GetP( ); // invalid
PR p = c.GetP( ); // invalid
// ...
```
Now I would like to make P interchangeable with PW and PR (and thus PW and PR can be interchanged). I could probably get away with casts but this code change has occurred quite a few times in this module alone. I am pretty sure it is a operator but for the life of me I can't remember what.
**How do I make P interchangeable with PW and PR with minimal amount of code?**
**Update:** To give a bit more clarification. P stands for Project and the R and W stands for Reader and Writer respectively. All the Reader has is the code for loading - no variables, and the writer has code for simply Writing. It needs to be separate because the Reading and Writing sections has various manager classes and dialogs which is none of Projects real concern which is the manipulation of project files.
**Update:** I also need to be able to call the methods of P and PW. So if P has a method a() and PW as a method call b() then I could :
```
PW p = c.GetP();
p.a();
p.b();
```
It's basically to make the conversion transparent.
|
If you want to get this part to compile:
```
// ...
P p = c.GetP( ); // valid
PW p = c.GetP( ); // invalid
PR p = c.GetP( ); // invalid
// ...
```
You need to be able to construct/convert a P into a PW or a PR.
You need to do something like this:
```
class PW : public P
{
PW(const P &);
// more stuff
};
class PR : public P
{
PR(const P &);
// more stuff
};
```
Or did you mean something more like:
```
class P
{
operator PW() const;
operator PR() const;
// stuff
};
```
|
121,946 |
<p>Ok, so I just ran into the following problem that raised an eyebrow.</p>
<p>For various reasons I have a testing setup where Testing classes in a TestingAssembly.dll depend on the TestingBase class in a BaseTestingAssembly.dll.
One of the things the TestBase does in the meantime is look for a certain embedded resource in its own and the calling assembly</p>
<p>So my BaseTestingAssembly contained the following lines...</p>
<pre><code>public class TestBase {
private static Assembly _assembly;
private static Assembly _calling_assembly;
static TestBase() {
_assembly = Assembly.GetExecutingAssembly();
_calling_assembly = Assembly.GetCallingAssembly();
}
}
</code></pre>
<p>Static since I figured, these assemblies would be the same over the application's lifetime so why bother recalculating them on every single test.</p>
<p>When running this however I noticed that both _assembly and _calling_assembly were being set to BaseTestingAssembly rather than BaseTestingAssembly and TestingAssembly respectively.</p>
<p>Setting the variables to non-static and having them initialized in a regular constructor fixed this but I am confused why this happened to begin this. I thought static constructors run the first time a static member gets referenced. This could only have been from my TestingAssembly which should then have been the caller. Does anyone know what might have happened?</p>
|
[
{
"answer_id": 122049,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 1,
"selected": false,
"text": "<p>I think the answer is here in the discussion of <a href=\"http://msdn.microsoft.com/en-us/library/k9x6w0hc(VS.80).aspx\" rel=\"nofollow noreferrer\">C# static constructors</a>. My best guess is that the static constructor is getting called from an unexpected context because:</p>\n\n<blockquote>\n <p>The user has no control on when the\n static constructor is executed in the\n program</p>\n</blockquote>\n"
},
{
"answer_id": 122060,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 4,
"selected": true,
"text": "<p>The static constructor is called by the runtime and not directly by user code. You can see this by setting a breakpoint in the constructor and then running in the debugger. The function immediately above it in the call chain is native code.</p>\n\n<p><strong>Edit:</strong> There are a lot of ways in which static initializers run in a different environment than other user code. Some other ways are</p>\n\n<ol>\n<li>They're implicitly protected against race conditions resulting from multithreading</li>\n<li>You can't catch exceptions from outside the initializer</li>\n</ol>\n\n<p>In general, it's probably best not to use them for anything too sophisticated. You can implement single-init with the following pattern:</p>\n\n<pre><code>private static Assembly _assembly;\nprivate static Assembly Assembly {\n get {\n if (_assembly == null) _assembly = Assembly.GetExecutingAssembly();\n return _assembly;\n }\n}\n\nprivate static Assembly _calling_assembly;\nprivate static Assembly CallingAssembly {\n get {\n if (_calling_assembly == null) _calling_assembly = Assembly.GetCallingAssembly();\n return _calling_assembly;\n }\n}\n</code></pre>\n\n<p>Add locking if you expect multithreaded access.</p>\n"
},
{
"answer_id": 341142,
"author": "chilltemp",
"author_id": 28736,
"author_profile": "https://Stackoverflow.com/users/28736",
"pm_score": 1,
"selected": false,
"text": "<p>Assembly.GetCallingAssembly() simply returns the assembly of the second entry in the call stack. That can very depending upon where how your method/getter/constructor is called. Here is what I did in a library to get the assembly of the first method that is not in my library. (This even works in static constructors.)</p>\n\n<pre><code>private static Assembly GetMyCallingAssembly()\n{\n Assembly me = Assembly.GetExecutingAssembly();\n\n StackTrace st = new StackTrace(false);\n foreach (StackFrame frame in st.GetFrames())\n {\n MethodBase m = frame.GetMethod();\n if (m != null && m.DeclaringType != null && m.DeclaringType.Assembly != me)\n return m.DeclaringType.Assembly;\n }\n\n return null;\n}\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/121946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
Ok, so I just ran into the following problem that raised an eyebrow.
For various reasons I have a testing setup where Testing classes in a TestingAssembly.dll depend on the TestingBase class in a BaseTestingAssembly.dll.
One of the things the TestBase does in the meantime is look for a certain embedded resource in its own and the calling assembly
So my BaseTestingAssembly contained the following lines...
```
public class TestBase {
private static Assembly _assembly;
private static Assembly _calling_assembly;
static TestBase() {
_assembly = Assembly.GetExecutingAssembly();
_calling_assembly = Assembly.GetCallingAssembly();
}
}
```
Static since I figured, these assemblies would be the same over the application's lifetime so why bother recalculating them on every single test.
When running this however I noticed that both \_assembly and \_calling\_assembly were being set to BaseTestingAssembly rather than BaseTestingAssembly and TestingAssembly respectively.
Setting the variables to non-static and having them initialized in a regular constructor fixed this but I am confused why this happened to begin this. I thought static constructors run the first time a static member gets referenced. This could only have been from my TestingAssembly which should then have been the caller. Does anyone know what might have happened?
|
The static constructor is called by the runtime and not directly by user code. You can see this by setting a breakpoint in the constructor and then running in the debugger. The function immediately above it in the call chain is native code.
**Edit:** There are a lot of ways in which static initializers run in a different environment than other user code. Some other ways are
1. They're implicitly protected against race conditions resulting from multithreading
2. You can't catch exceptions from outside the initializer
In general, it's probably best not to use them for anything too sophisticated. You can implement single-init with the following pattern:
```
private static Assembly _assembly;
private static Assembly Assembly {
get {
if (_assembly == null) _assembly = Assembly.GetExecutingAssembly();
return _assembly;
}
}
private static Assembly _calling_assembly;
private static Assembly CallingAssembly {
get {
if (_calling_assembly == null) _calling_assembly = Assembly.GetCallingAssembly();
return _calling_assembly;
}
}
```
Add locking if you expect multithreaded access.
|
121,962 |
<p>How can I consistently get the absolute, fully-qualified root or base url of the site regardless of whether the site is in a virtual directory and regardless of where my code is in the directory structure? I've tried every variable and function I can think of and haven't found a good way.</p>
<p>I want to be able to get the url of the current site, i.e. <a href="http://www.example.com" rel="nofollow noreferrer">http://www.example.com</a> or if it's a virtual directory, <a href="http://www.example.com/DNN/" rel="nofollow noreferrer">http://www.example.com/DNN/</a></p>
<hr>
<p>Here's some of the things I've tried and the result. The only one that includes the whole piece that I want (<a href="http://localhost:4471/DNN441" rel="nofollow noreferrer">http://localhost:4471/DNN441</a>) is Request.URI.AbsoluteURI:</p>
<ul>
<li>Request.PhysicalPath: C:\WebSites\DNN441\Default.aspx</li>
<li>Request.ApplicationPath: /DNN441</li>
<li>Request.PhysicalApplicationPath: C:\WebSites\DNN441\</li>
<li>MapPath:
C:\WebSites\DNN441\DesktopModules\Articles\Templates\Default.aspx</li>
<li>RawURL:
/DNN441/ModuleTesting/Articles/tabid/56/ctl/Details/mid/374/ItemID/1/Default.aspx</li>
<li>Request.Url.AbsoluteUri: <a href="http://localhost:4471/DNN441/Default.aspx" rel="nofollow noreferrer">http://localhost:4471/DNN441/Default.aspx</a></li>
<li>Request.Url.AbsolutePath: /DNN441/Default.aspx</li>
<li>Request.Url.LocalPath: /DNN441/Default.aspx Request.Url.Host: localhost</li>
<li>Request.Url.PathAndQuery:
/DNN441/Default.aspx?TabId=56&ctl=Details&mid=374&ItemID=1</li>
</ul>
|
[
{
"answer_id": 121970,
"author": "Dave Neeley",
"author_id": 9660,
"author_profile": "https://Stackoverflow.com/users/9660",
"pm_score": 3,
"selected": false,
"text": "<p>There is some excellent discussion and ideas on <a href=\"http://www.west-wind.com/Weblog/posts/154812.aspx\" rel=\"nofollow noreferrer\">Rick Strahl's blog</a></p>\n\n<p>EDIT: I should add that the ideas work with or without a valid HttpContext.</p>\n\n<p>EDIT2: Here's the <a href=\"http://www.west-wind.com/Weblog/posts/154812.aspx#466571\" rel=\"nofollow noreferrer\">specific comment / code</a> on that post that answers the question</p>\n"
},
{
"answer_id": 121978,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried AppSettings.RootUrl which is usually configured in the web.config file?</p>\n"
},
{
"answer_id": 121997,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "<p>Are you talking about for use as links?</p>\n\n<p>if so, then doing this <code><a href='/'>goes to root</a></code> will take you to the default file of the web root.</p>\n\n<p>Now, for client side, doing, passing \"~/\" to the Control::ResolveUrl method will provide you what you're looking for. (<a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveurl.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveurl.aspx</a>)</p>\n"
},
{
"answer_id": 122227,
"author": "Omar Kooheji",
"author_id": 20400,
"author_profile": "https://Stackoverflow.com/users/20400",
"pm_score": 0,
"selected": false,
"text": "<p>I have no way to validate this at the moment but have you tried \"Request.Url.AbsoluteUri\" from another machine?</p>\n\n<p>It occurs to me that as far as your machine is concerned it's browser is requesting from localhost.</p>\n\n<p>I could be wrong though but I think request is relative to the browser and not the webserver.</p>\n"
},
{
"answer_id": 231475,
"author": "EfficionDave",
"author_id": 4318,
"author_profile": "https://Stackoverflow.com/users/4318",
"pm_score": 5,
"selected": true,
"text": "<p>In reading through the answer provided in Rick Strahl's Blog I found what I really needed was quite simple. First you need to determine the relative path (which for me was the easy part), and pass that into the function defined below:</p>\n\n<p>VB.NET</p>\n\n<pre><code>Public Shared Function GetFullyQualifiedURL(ByVal s as string) As String\n Dim Result as URI = New URI(HttpContext.Current.Request.Url, s)\n Return Result.ToString\nEnd Function\n</code></pre>\n\n<p>C#</p>\n\n<pre><code>public static string GetFullyQualifiedURL(string s) {\n Uri Result = new Uri(HttpContext.Current.Request.Url, s);\n return Result.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 1588605,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 2,
"selected": false,
"text": "<p>Found <a href=\"http://www.geekpedia.com/KB44_Get-the-path-of-the-ASP.NET-web-application-that-is-currently-running.html\" rel=\"nofollow noreferrer\">this code here</a>:</p>\n\n<pre><code>string appPath = null;\n\nappPath = string.Format(\"{0}://{1}{2}{3}\",\n Request.Url.Scheme,\n Request.Url.Host,\n Request.Url.Port == 80 ? string.Empty : \":\" + Request.Url.Port,\n Request.ApplicationPath);\n</code></pre>\n"
},
{
"answer_id": 7112493,
"author": "Scott Stafford",
"author_id": 237091,
"author_profile": "https://Stackoverflow.com/users/237091",
"pm_score": 3,
"selected": false,
"text": "<p>The accepted answer assumes that the current request is already at the server/virtual root. Try this:</p>\n\n<pre><code>Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/121962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4318/"
] |
How can I consistently get the absolute, fully-qualified root or base url of the site regardless of whether the site is in a virtual directory and regardless of where my code is in the directory structure? I've tried every variable and function I can think of and haven't found a good way.
I want to be able to get the url of the current site, i.e. <http://www.example.com> or if it's a virtual directory, <http://www.example.com/DNN/>
---
Here's some of the things I've tried and the result. The only one that includes the whole piece that I want (<http://localhost:4471/DNN441>) is Request.URI.AbsoluteURI:
* Request.PhysicalPath: C:\WebSites\DNN441\Default.aspx
* Request.ApplicationPath: /DNN441
* Request.PhysicalApplicationPath: C:\WebSites\DNN441\
* MapPath:
C:\WebSites\DNN441\DesktopModules\Articles\Templates\Default.aspx
* RawURL:
/DNN441/ModuleTesting/Articles/tabid/56/ctl/Details/mid/374/ItemID/1/Default.aspx
* Request.Url.AbsoluteUri: <http://localhost:4471/DNN441/Default.aspx>
* Request.Url.AbsolutePath: /DNN441/Default.aspx
* Request.Url.LocalPath: /DNN441/Default.aspx Request.Url.Host: localhost
* Request.Url.PathAndQuery:
/DNN441/Default.aspx?TabId=56&ctl=Details&mid=374&ItemID=1
|
In reading through the answer provided in Rick Strahl's Blog I found what I really needed was quite simple. First you need to determine the relative path (which for me was the easy part), and pass that into the function defined below:
VB.NET
```
Public Shared Function GetFullyQualifiedURL(ByVal s as string) As String
Dim Result as URI = New URI(HttpContext.Current.Request.Url, s)
Return Result.ToString
End Function
```
C#
```
public static string GetFullyQualifiedURL(string s) {
Uri Result = new Uri(HttpContext.Current.Request.Url, s);
return Result.ToString();
}
```
|
122,033 |
<p>Yesterday, I asked <a href="https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby">this</a> question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.</p>
<p>Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ:</p>
<pre><code>
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
</code></pre>
<p>Can you translate my LINQ to Ruby? Python? Any other functional programming language?</p>
<p><strong>Note:</strong> Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.</p>
<p>I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!</p>
<p><strong>Edit:</strong><br />
Why all the downvotes?</p>
<p>Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.</p>
<p><strong>Apology:</strong><br />
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.</p>
|
[
{
"answer_id": 122047,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 0,
"selected": false,
"text": "<p>Python with Numeric Python:</p>\n\n<pre><code>from numpy import *\na = random.random_integers(0, 100, 5)\nb = unique(a)\n</code></pre>\n\n<p>Voilà! Sure you could do something similar in a functional programming style but... why?</p>\n"
},
{
"answer_id": 122062,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 2,
"selected": false,
"text": "<p>I will forgo the simplest solutions using the 'random' module since I take it that's not really what you are after. Here's what I think you are looking for in Python:</p>\n\n<pre><code>>>> import random\n>>> \n>>> def getUniqueRandomNumbers(num, highest):\n... seen = set()\n... while len(seen) < num:\n... i = random.randrange(0, highest)\n... if i not in seen:\n... seen.add(i) \n... yield i\n... \n>>>\n</code></pre>\n\n<p>To show you how it works:</p>\n\n<pre><code>>>> list(getUniqueRandomNumbers(10, 100))\n[81, 57, 98, 47, 93, 31, 29, 24, 97, 10]\n</code></pre>\n"
},
{
"answer_id": 122064,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 4,
"selected": false,
"text": "<pre><code>>>> import random\n>>> print random.sample(xrange(100), 5)\n[61, 54, 91, 72, 85]\n</code></pre>\n\n<p>This should yield 5 unique values in the range <code>0 — 99</code>. The <code>xrange</code> object generates values as requested so no memory is used for values that aren't sampled.</p>\n"
},
{
"answer_id": 122085,
"author": "hjdivad",
"author_id": 7538,
"author_profile": "https://Stackoverflow.com/users/7538",
"pm_score": -1,
"selected": false,
"text": "<p>I can't really read your LINQ, but I think you're trying to get 5 random numbers up to 100 and then remove duplicates.</p>\n\n<p>Here's a solution for that:</p>\n\n<pre><code>def random(max)\n (rand * max).to_i\nend\n\n# Get 5 random numbers between 0 and 100\na = (1..5).inject([]){|acc,i| acc << random( 100)}\n# Remove Duplicates\na = a & a\n</code></pre>\n\n<p>But perhaps you're actually looking for 5 distinct random numbers between 0 and 100. In which case:</p>\n\n<pre><code>def random(max)\n (rand * max).to_i\nend\n\na = []\nwhile( a.size < 5)\n a << random( 100)\n a = a & a\nend\n</code></pre>\n\n<p>Now, this one might violate your sense of \"not too many loops,\" but presumably Take and Distinct are just hiding the looping from you. It would be easy enough to just add methods to Enumerable to hide the while loop.</p>\n"
},
{
"answer_id": 122093,
"author": "Will Boyce",
"author_id": 5757,
"author_profile": "https://Stackoverflow.com/users/5757",
"pm_score": 2,
"selected": false,
"text": "<p>Hmm... How about (Python):</p>\n\n<pre><code>s = set()\nwhile len(s) <= N: s.update((random.random(),))\n</code></pre>\n"
},
{
"answer_id": 122116,
"author": "Michael Deardeuff",
"author_id": 4931,
"author_profile": "https://Stackoverflow.com/users/4931",
"pm_score": 4,
"selected": true,
"text": "<p>In Ruby:</p>\n\n<pre><code>a = (0..100).entries.sort_by {rand}.slice! 0, 5\n</code></pre>\n\n<p><strong>Update</strong>: Here is a slightly different way:\n a = (0...100).entries.sort_by{rand}[0...5]</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>and In Ruby 1.9 you can do this:</p>\n\n<pre><code>Array(0..100).sample(5) \n</code></pre>\n"
},
{
"answer_id": 122121,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 2,
"selected": false,
"text": "<p>Here's another Ruby solution:</p>\n\n<pre><code>a = (1..5).collect { rand(100) }\na & a\n</code></pre>\n\n<p>I think, with your LINQ statement, the Distinct will remove duplicates after 5 have already been taken, so you aren't guaranteed to get 5 back. Someone can correct me if I'm wrong, though.</p>\n"
},
{
"answer_id": 122146,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import random\n\ndef makeRand(n):\n rand = random.Random()\n while 1:\n yield rand.randint(0,n)\n yield rand.randint(0,n) \n\ngen = makeRand(100) \nterms = [ gen.next() for n in range(5) ]\n\nprint \"raw list\"\nprint terms\nprint \"de-duped list\"\nprint list(set(terms))\n\n# produces output similar to this\n#\n# raw list\n# [22, 11, 35, 55, 1]\n# de-duped list\n# [35, 11, 1, 22, 55]\n</code></pre>\n"
},
{
"answer_id": 122159,
"author": "apenwarr",
"author_id": 42219,
"author_profile": "https://Stackoverflow.com/users/42219",
"pm_score": 0,
"selected": false,
"text": "<p>Well, first you rewrite LINQ in Python. Then your solution is a one-liner :)</p>\n\n<pre><code>from random import randrange\n\ndef Distinct(items):\n set = {}\n for i in items:\n if not set.has_key(i):\n yield i\n set[i] = 1\n\ndef Take(num, items):\n for i in items:\n if num > 0:\n yield i\n num = num - 1\n else:\n break\n\ndef ToArray(items):\n return [i for i in items]\n\ndef GetRandomNumbers(max):\n while 1:\n yield randrange(max)\n\nprint ToArray(Take(5, Distinct(GetRandomNumbers(100))))\n</code></pre>\n\n<p>If you put all the simple methods above into a module called LINQ.py, you can impress your friends.</p>\n\n<p>(Disclaimer: of course, this is not <em>actually</em> rewriting LINQ in Python. People have the misconception that LINQ is just a bunch of trivial extension methods and some new syntax. The really advanced part of LINQ, however, is automatic SQL generation so that when you're querying a database, it's the database that implements Distinct() rather than the client side.)</p>\n"
},
{
"answer_id": 122188,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 2,
"selected": false,
"text": "<p>EDIT : Ok, just for fun, a shorter and faster one (and still using iterators).</p>\n\n<pre><code>def getRandomNumbers(max, size) :\n pool = set()\n return ((lambda x : pool.add(x) or x)(random.randrange(max)) for x in xrange(size) if len(a) < size)\n\nprint [x for x in gen(100, 5)]\n[0, 10, 19, 51, 18]\n</code></pre>\n\n<p>Yeah, I know, one-liners should be left to perl lovers, but I think this one is quite powerful isn't it ?</p>\n\n<p>Old message here :</p>\n\n<p>My god, how complicated is all that ! Let's be pythonic :</p>\n\n<pre><code>import random\ndef getRandomNumber(max, size, min=0) :\n # using () and xrange = using iterators\n return (random.randrange(min, max) for x in xrange(size))\n\nprint set(getRandomNumber(100, 5)) # set() removes duplicates\nset([88, 99, 29, 70, 23])\n</code></pre>\n\n<p>Enjoy</p>\n\n<p>EDIT : As commentators noticed, this is an exact translation of the question's code.</p>\n\n<p>To avoid the problem we got by removing duplicates after generating the list, resulting in too little data, you can choose another way :</p>\n\n<pre><code>def getRandomNumbers(max, size) :\n pool = []\n while len(pool) < size :\n tmp = random.randrange(max)\n if tmp not in pool :\n yield pool.append(tmp) or tmp\n\nprint [x for x in getRandomNumbers(5, 5)]\n[2, 1, 0, 3, 4]\n</code></pre>\n"
},
{
"answer_id": 122212,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a transliteration from your solution to Python.</p>\n\n<p>First, a generator that creates Random numbers. This isn't very Pythonic, but it's a good match with your sample code. </p>\n\n<pre><code>>>> import random\n>>> def getRandomNumbers( max ):\n... while True:\n... yield random.randrange(0,max)\n</code></pre>\n\n<p>Here's a client loop that collects a set of 5 distinct values. This is -- again -- not the most Pythonic implementation.</p>\n\n<pre><code>>>> distinctSet= set()\n>>> for r in getRandomNumbers( 100 ):\n... distinctSet.add( r )\n... if len(distinctSet) == 5: \n... break\n... \n>>> distinctSet\nset([81, 66, 28, 53, 46])\n</code></pre>\n\n<p>It's not clear why you want to use a generator for random numbers -- that's one of the few things that's so simple that a generator doesn't simplify it. </p>\n\n<p>A more Pythonic version might be something like:</p>\n\n<pre><code>distinctSet= set()\nwhile len(distinctSet) != 5:\n distinctSet.add( random.randrange(0,100) )\n</code></pre>\n\n<p>If the requirements are to generate 5 values and find distinct among those 5, then something like</p>\n\n<pre><code>distinctSet= set( [random.randrange(0,100) for i in range(5) ] )\n</code></pre>\n"
},
{
"answer_id": 122285,
"author": "user19087",
"author_id": 19087,
"author_profile": "https://Stackoverflow.com/users/19087",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe this will suit your needs and look a bit more linqish:</p>\n\n<pre><code>from numpy import random,unique\n\ndef GetRandomNumbers(total=5):\n while True:\n yield unique(random.random(total*2))[:total]\n\nrandomGenerator = GetRandomNumbers()\n\nmyRandomNumbers = randomGenerator.next()\n</code></pre>\n"
},
{
"answer_id": 123258,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 0,
"selected": false,
"text": "<p>Here's another python version, more closely matching the structure of your C# code. There isn't a builtin for giving distinct results, so I've added a function to do this.</p>\n\n<pre><code>import itertools, random\n\ndef distinct(seq):\n seen=set()\n for item in seq:\n if item not in seen:\n seen.add(item)\n yield item\n\ndef getRandomNumbers(max):\n while 1:\n yield random.randint(0,max)\n\nfor item in itertools.islice(distinct(getRandomNumbers(100)), 5):\n print item\n</code></pre>\n"
},
{
"answer_id": 3793197,
"author": "horseyguy",
"author_id": 66725,
"author_profile": "https://Stackoverflow.com/users/66725",
"pm_score": 1,
"selected": false,
"text": "<p>In Ruby 1.9:</p>\n\n<pre><code>Array(0..100).sample(5)\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
] |
Yesterday, I asked [this](https://stackoverflow.com/questions/119107/how-do-i-generate-a-list-of-n-unique-random-numbers-in-ruby) question and never really got an answer I was really happy with. I really would like to know how to generate a list of N unique random numbers using a functional language such as Ruby without having to be extremely imperative in style.
Since I didn't see anything I really liked, I've written the solution I was looking for in LINQ:
```
static void Main(string[] args)
{
var temp = from q in GetRandomNumbers(100).Distinct().Take(5) select q;
}
private static IEnumerable GetRandomNumbers(int max)
{
Random r = new Random();
while (true)
{
yield return r.Next(max);
}
}
```
Can you translate my LINQ to Ruby? Python? Any other functional programming language?
**Note:** Please try not to use too many loops and conditionals - otherwise the solution is trivial. Also, I'd rather see a solution where you don't have to generate an array much bigger than N so you can then just remove the duplicates and trim it down to N.
I know I'm being picky, but I'd really like to see some elegant solutions to this problem.
Thanks!
**Edit:**
Why all the downvotes?
Originally my code sample had the Distinct() after the Take() which, as many pointed out, could leave me with an empty list. I've changed the order in which those methods are called to reflect what I meant in the first place.
**Apology:**
I've been told this post came across as rather snobbish. I wasn't trying to imply that LINQ is better than Ruby/Python; or that my solution is much better than everyone else's. My intent is just to learn how to do this (with certain constraints) in Ruby. I'm sorry if I came across as a jerk.
|
In Ruby:
```
a = (0..100).entries.sort_by {rand}.slice! 0, 5
```
**Update**: Here is a slightly different way:
a = (0...100).entries.sort\_by{rand}[0...5]
**EDIT:**
and In Ruby 1.9 you can do this:
```
Array(0..100).sample(5)
```
|
122,067 |
<p>I have a site using a custom favicon.ico. The favicon displays as expected in all browsers except IE. When trying to display the favicon in IE, I get the big red x; when displaying the favicon in another browser, it displays just fine. The page source includes
and it does work in other browsers. Thanks for your thoughts.</p>
<p><strong>EDIT: SOLVED: The source of the issue was the file was a jpg renamed to ico. I created the file as an ico and it is working as expected. Thanks for your input.</strong></p>
|
[
{
"answer_id": 122111,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 7,
"selected": true,
"text": "<p>Right you've not been that helpful (providing source would be have been really useful!) but here you go... Some things to check:</p>\n\n<p>Is the code like this:</p>\n\n<pre><code><link rel=\"icon\" href=\"http://www.example.com/favicon.ico\" type=\"image/x-icon\" />\n<link rel=\"shortcut icon\" href=\"http://www.example.com/favicon.ico\" type=\"image/x-icon\" />\n</code></pre>\n\n<p>Is it in the <code><head></code>?</p>\n\n<p>Is the image a <em>real</em> ico file? (renaming a bitmap is not a real .ico! Mildly different format)</p>\n\n<p>Does it work when you add the page as a bookmark?</p>\n"
},
{
"answer_id": 122114,
"author": "Sec",
"author_id": 20555,
"author_profile": "https://Stackoverflow.com/users/20555",
"pm_score": 0,
"selected": false,
"text": "<p>Care to share the URL? Many browsers cope with favicons in (e.g.) png format while IE had often troubles. - Also older versions of IE did not check the html source for the location of the favicon but just single-mindedly tried to get \"/favicon.ico\" from the webserver.</p>\n"
},
{
"answer_id": 122125,
"author": "Jonathan Tran",
"author_id": 12887,
"author_profile": "https://Stackoverflow.com/users/12887",
"pm_score": 2,
"selected": false,
"text": "<p>Did you try putting the icon at the URI \"<code>/favicon.ico</code>\" ? IE might not know about the link tag way of referring to it.</p>\n\n<p>More info <a href=\"http://www.w3.org/2005/10/howto-favicon\" rel=\"nofollow noreferrer\">from W3</a>.</p>\n"
},
{
"answer_id": 122143,
"author": "Mihai Lazar",
"author_id": 4204,
"author_profile": "https://Stackoverflow.com/users/4204",
"pm_score": 0,
"selected": false,
"text": "<p>I once used a PNG as a favicon.ico and it displayed in all browsers except IE. Maybe something in the file causes it to not be recognized by IE. Also make sure it's 32x32. Don't know if it matters though. But it's something I had to make sure in order to see it in IE.</p>\n\n<p>Hope it helps. Try to use an ico file from some place else just to see if that works.</p>\n"
},
{
"answer_id": 7109811,
"author": "Jammin Jamy",
"author_id": 900878,
"author_profile": "https://Stackoverflow.com/users/900878",
"pm_score": 2,
"selected": false,
"text": "<p>If you tried everything above and it still doesn’t work in IE, check your IIS settings if you are using a Windows Server.\nMake sure that the HTTP Headers > “Enable content expiration” setting, IS NOT SET to “Expire immediately” </p>\n"
},
{
"answer_id": 11423240,
"author": "germankiwi",
"author_id": 1397352,
"author_profile": "https://Stackoverflow.com/users/1397352",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is a really old topic now, but as it's the first one that came up on my google search I just wanted to add my solution to it:</p>\n\n<p>I had this problem as well with an icon that was supplied by a client. It displayed in all browsers apart from IE. Adding the <code>link</code> or <code>meta</code> tags didn't work, so I started to look at the format of the icon file.<br>\nIt appeared to be a valid icon file (not just a renamed image), but what fixed it in the end was to <strong>convert it to an image, save it as a GIF, and then converting it back to an icon</strong>.<br>\nAlso make sure to clear the IE cache while you're testing.</p>\n"
},
{
"answer_id": 12067017,
"author": "Nivedita",
"author_id": 1615999,
"author_profile": "https://Stackoverflow.com/users/1615999",
"pm_score": 4,
"selected": false,
"text": "<pre><code> <link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"FolderName/favicon.ico\" />\n</code></pre>\n\n<ol>\n<li>Your favicon.ico must be placed between <strong>head</strong> tag</li>\n<li>size : 16 X 16</li>\n<li><strong>and for Internet Explorer it must be transparent (the outer white part should not visible)</strong></li>\n</ol>\n"
},
{
"answer_id": 12373835,
"author": "yoel halb",
"author_id": 640195,
"author_profile": "https://Stackoverflow.com/users/640195",
"pm_score": 4,
"selected": false,
"text": "<p>In IE and FireFox the favicon.ico is only being requested at the first page visited on the site, which means that if the favicon.ico requires log-in (for example your site is a closed site and requires log in) then the icon will not be displayed.</p>\n\n<p>The solution is to add an exception for the favicon.ico, for example in ASP.Net you add in the web.config:</p>\n\n<pre><code><location path=\"favicon.ico\">\n <system.web>\n <authorization>\n <allow users=\"*\" />\n </authorization>\n </system.web>\n</location> \n</code></pre>\n"
},
{
"answer_id": 13296643,
"author": "Ferdinand Ta",
"author_id": 1810381,
"author_profile": "https://Stackoverflow.com/users/1810381",
"pm_score": 0,
"selected": false,
"text": "<p>this seems to be an ASPX pages problem, I have never been able to show a favicon in any page for IE (all others yes Chrome, FF and safari) the only sites that I've seen that are the exception to that rule are bing.com, msdn.com and others that belong to MS and run on asp.net, there is something that they are not telling us! even world-known sites cant show in IE eg: manu.com (most browsed sports team in the world) aspx site and fails to dislplay the favicon on IE. <a href=\"http://www.manutd.com/favicon.ico\" rel=\"nofollow\">http://www.manutd.com/favicon.ico</a> does show the icon. </p>\n\n<p>Please prove me wrong.</p>\n"
},
{
"answer_id": 15634862,
"author": "Rob Durden",
"author_id": 2211170,
"author_profile": "https://Stackoverflow.com/users/2211170",
"pm_score": 0,
"selected": false,
"text": "<p>THE SOLUTION : </p>\n\n<ul>\n<li><p>I created an icon from existing png file by simply changing the extension of the image from png to ico. I use drupal 7 bartik theme, so I uploaded the shortcut icon to the server and it WORKED for Chrome and Firefox but not IE. Also, the image icon was white-blank on the desktop.</p></li>\n<li><p>Then I took the advice of some guys here and reduced the size of the image to 32x32 pixels using an image editor (gimp 2<<</li>\n<li><p>I uploaded the icon in the same way as earlier, and it worked fine for all browsers.</p></li>\n</ul>\n\n<p>I love you guys on stackoverflow, you helped me solve LOTS of problems. THANK YOU!</p>\n"
},
{
"answer_id": 16420318,
"author": "RaghuRam Kattreddi",
"author_id": 2358530,
"author_profile": "https://Stackoverflow.com/users/2358530",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for all your help.I tried different options but the below one worked for me.</p>\n\n<pre><code><link rel=\"shortcut icon\" href=\"/favicon.ico\" >\n<link rel=\"icon\" type=\"/image/ico\" href=\"/favicon.ico\" >\n</code></pre>\n\n<p>I have added the above two lines in the header of my page and it worked in all browsers.</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 17611352,
"author": "Rajeev",
"author_id": 676300,
"author_profile": "https://Stackoverflow.com/users/676300",
"pm_score": 0,
"selected": false,
"text": "<p>May be this help others.</p>\n\n<p>For me ICON was not getting displayed in IE, even after following all steps.</p>\n\n<p>Finally I found a note in MSDN <a href=\"http://msdn.microsoft.com/en-us/library/ms537656%28v=vs.85%29.aspx#Troubleshooting_Shortcut_Icons\" rel=\"nofollow\">Troubleshooting Shortcut Icons</a>.</p>\n\n<blockquote>\n <p>Verify that Internet Explorer can store the shortcut icon in the\n Temporary Internet Files folder. If you have set Internet Explorer to\n not keep a cache, then it will not be able to store the icon and will\n display the default Internet Explorer shortcut icon instead.</p>\n</blockquote>\n\n<p>I was using IE in \"In Private\" mode, once I verified in normal mode.... Fav Icon displayed properly.</p>\n"
},
{
"answer_id": 17719461,
"author": "user984003",
"author_id": 984003,
"author_profile": "https://Stackoverflow.com/users/984003",
"pm_score": 3,
"selected": false,
"text": "<p>Should anyone make it down to this answer:</p>\n\n<p>Same issue: didn't work in IE (including IE 10), worked everywhere else.</p>\n\n<p>Turns out that the file was not a \"real\" .ico file. I fixed this by uploading it to <a href=\"http://www.favicon.cc/\">http://www.favicon.cc/</a> and then downloading it again. </p>\n\n<p>First I tested it by generating a random .ico file on this site and using that instead of my original file. Saw that it worked.</p>\n"
},
{
"answer_id": 21023868,
"author": "RustyIngles",
"author_id": 650220,
"author_profile": "https://Stackoverflow.com/users/650220",
"pm_score": 2,
"selected": false,
"text": "<p>I had this exact problem and nothing seemed to work. After clearing the browser cache countless times and even updating IE to v9 I found this: <a href=\"http://favicon.htmlkit.com/favicon/\" rel=\"nofollow\">http://favicon.htmlkit.com/favicon/</a></p>\n\n<p>The above link solved the problem perfectly for me!</p>\n"
},
{
"answer_id": 21214989,
"author": "orschiro",
"author_id": 1159747,
"author_profile": "https://Stackoverflow.com/users/1159747",
"pm_score": 0,
"selected": false,
"text": "<p>Regarding incompatibilities with IE9 I came across <a href=\"http://www.adam-bertrand.com/blog/2011/04/hello-world/\" rel=\"nofollow\">this</a> blog post which gives tips for creating a favicon that is recognised by IE9.</p>\n\n<p>In an essence, try creating a favicon with the following site: <a href=\"http://www.xiconeditor.com/\" rel=\"nofollow\">http://www.xiconeditor.com/</a></p>\n"
},
{
"answer_id": 31747474,
"author": "Lachlan Hunt",
"author_id": 132537,
"author_profile": "https://Stackoverflow.com/users/132537",
"pm_score": 0,
"selected": false,
"text": "<p>Check the response headers for your favicon. They must not include \"Cache-Control: no-cache\".</p>\n\n<p>You can check this from the command line using:</p>\n\n<pre><code>curl -I http://example.com/favicon.ico\n</code></pre>\n\n<p>or</p>\n\n<pre><code>wget --server-response --spider http://example.com/favicon.ico\n</code></pre>\n\n<p>(or use some other tool that will show you response headers)</p>\n\n<p>If you see \"Cache-Control: no-cache\" in there, adjust your server configuration to either remove that header from the favicon response or set a max-age.</p>\n"
},
{
"answer_id": 35764828,
"author": "Durgaprasad MV",
"author_id": 6011648,
"author_profile": "https://Stackoverflow.com/users/6011648",
"pm_score": -1,
"selected": false,
"text": "<p>Run Internet Explorer as Administrator. If you open IE in normal mode then favicon will not display on IE 11 (Win 7). I am not sure about the behavior on other version of browsers.</p>\n"
},
{
"answer_id": 36644995,
"author": "Kappacake",
"author_id": 4220401,
"author_profile": "https://Stackoverflow.com/users/4220401",
"pm_score": 1,
"selected": false,
"text": "<p>None of the above solutions worked for me.</p>\n\n<p>First of all I made sure the icon is in the right format using the website to create favicons suggested above.</p>\n\n<p>Then I renamed the icon from 'favicon.ico' to 'myicon.ico' and added the following code to my page (within the <code><head></code> tags):</p>\n\n<pre><code><link rel=\"shortcut icon\" href=\"myicon.ico\" type=\"image/x-icon\" />\n</code></pre>\n\n<p>The icon is on the same folder as the page.</p>\n\n<p>This solved the problem for me. The issue behind the scenes had probably something to do with the caching of IE, but I'm not sure.</p>\n"
},
{
"answer_id": 42260475,
"author": "An Bo",
"author_id": 7571474,
"author_profile": "https://Stackoverflow.com/users/7571474",
"pm_score": 0,
"selected": false,
"text": "<p>Also - certificate errors (https) can prevent the favicon from appearing. The security team changed our server settings and I started getting \"There is a problem with this website’s security certificate.\" Clicking on \"Continue to this website (not recommended).\" took me to the website but would NOT show the favicon.</p>\n"
},
{
"answer_id": 49784270,
"author": "BillVo",
"author_id": 237913,
"author_profile": "https://Stackoverflow.com/users/237913",
"pm_score": 0,
"selected": false,
"text": "<p>I'm seeing different behaviors between Windows 10 and Windows Server 2016 and between IE and Edge. I tested using www.microsoft.com.</p>\n\n<p>Windows Server 2016 IE 11:<br>\nFavorites: site icon<br> \nAddress bar: site icon<br> \nBrowser tab: site icon<br> </p>\n\n<p>Windows 10 IE 11:<br>\nFavorites: site icon <br>\nAddress bar: generic blue-E icon <br>\nBrowser tab: generic blue-E icon <br></p>\n\n<p>Windows 10 Edge:<br>\nFavorites: site icon <br>\nAddress bar: no icon<br>\nBrowser tab: site icon <br></p>\n\n<p>What's the deal with Windows 10 IE showing the generic icon?</p>\n"
},
{
"answer_id": 55024503,
"author": "Wilson Delgado",
"author_id": 11160065,
"author_profile": "https://Stackoverflow.com/users/11160065",
"pm_score": 0,
"selected": false,
"text": "<p>This work crossbrowser for me (IE11, EDGE, CHROME, FIREFOX, OPERA), use <a href=\"https://www.icoconverter.com/\" rel=\"nofollow noreferrer\">https://www.icoconverter.com/</a> to create .ico file</p>\n\n<pre><code><link data-senna-track=\"temporary\" href=\"${favicon_url}\" rel=\"Shortcut Icon\" />\n<link rel=\"icon\" href=\"${favicon_url}\" type=\"image/x-icon\" />\n<link rel=\"shortcut icon\" href=\"${favicon_url}\" type=\"image/x-icon\" />\n</code></pre>\n"
},
{
"answer_id": 57505325,
"author": "AllmanTool",
"author_id": 5188689,
"author_profile": "https://Stackoverflow.com/users/5188689",
"pm_score": 0,
"selected": false,
"text": "<p>Try something like:</p>\n\n<p>Add to html:</p>\n\n<pre><code> <link id=\"shortcutIcon\" rel=\"shortcut icon\" type=\"image/x-icon\">\n <link id=\"icon\" rel=\"icon\" type=\"image/x-icon\">\n</code></pre>\n\n<p>Add minified script after tag:</p>\n\n<pre><code><script type=\"text/javascript\">\n(function(b,c,d,a){a=c+d+b,document.getElementById('shortcutIcon').href=a,document.getElementById('icon').href=a;}(Math.random()*100,(document.querySelector('base')||{}).href,'/assets/images/favicon.ico?v='));\n</script>\n</code></pre>\n\n<p>where </p>\n\n<ul>\n<li>'/assets/images/favicon.ico' related path to .ico</li>\n<li>?v='Math.random()*100' - to force browser update favicon.ico</li>\n</ul>\n\n<p>Before test clear history: (ctr + shfit + del)</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13465/"
] |
I have a site using a custom favicon.ico. The favicon displays as expected in all browsers except IE. When trying to display the favicon in IE, I get the big red x; when displaying the favicon in another browser, it displays just fine. The page source includes
and it does work in other browsers. Thanks for your thoughts.
**EDIT: SOLVED: The source of the issue was the file was a jpg renamed to ico. I created the file as an ico and it is working as expected. Thanks for your input.**
|
Right you've not been that helpful (providing source would be have been really useful!) but here you go... Some things to check:
Is the code like this:
```
<link rel="icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.example.com/favicon.ico" type="image/x-icon" />
```
Is it in the `<head>`?
Is the image a *real* ico file? (renaming a bitmap is not a real .ico! Mildly different format)
Does it work when you add the page as a bookmark?
|
122,088 |
<p>I have a table in a MSSQL database that looks like this:</p>
<pre><code>Timestamp (datetime)
Message (varchar(20))
</code></pre>
<p>Once a day, a particular process inserts the current time and the message 'Started' when it starts. When it is finished it inserts the current time and the message 'Finished'.</p>
<p>What is a good query or set of statements that, given a particular date, returns:</p>
<ul>
<li>0 if the process never started</li>
<li>1 if the process started but did not finish</li>
<li>2 if the process started and finished</li>
</ul>
<p>There are other messages in the table, but 'Started' and 'Finished' are unique to this one process.</p>
<p>EDIT: For bonus karma, raise an error if the data is invalid, for example there are two 'Started' messages, or there is a 'Finished' without a 'Started'.</p>
|
[
{
"answer_id": 122129,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 3,
"selected": true,
"text": "<pre><code>Select Count(Message) As Status\nFrom Process_monitor\nWhere TimeStamp >= '20080923'\n And TimeStamp < '20080924'\n And (Message = 'Started' or Message = 'Finished')\n</code></pre>\n\n<p>You could modify this slightly to detect invalid conditions, like multiple starts, finishes, starts without a finish, etc...</p>\n\n<pre><code>Select Case When SumStarted = 0 And SumFinished = 0 Then 'Not Started'\n When SumStarted = 1 And SumFinished = 0 Then 'Started'\n When SumStarted = 1 And SumFinished = 1 Then 'Finished'\n When SumStarted > 1 Then 'Multiple Starts' \n When SumFinished > 1 Then 'Multiple Finish'\n When SumFinished > 0 And SumStarted = 0 Then 'Finish Without Start'\n End As StatusMessage\nFrom (\n Select Sum(Case When Message = 'Started' Then 1 Else 0 End) As SumStarted,\n Sum(Case When Message = 'Finished' Then 1 Else 0 End) As SumFinished\n From Process_monitor\n Where TimeStamp >= '20080923'\n And TimeStamp < '20080924'\n And (Message = 'Started' or Message = 'Finished')\n ) As AliasName\n</code></pre>\n"
},
{
"answer_id": 122150,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<pre><code>DECLARE @TargetDate datetime\nSET @TargetDate = '2008-01-01'\n\nDECLARE @Messages varchar(max)\n\nSET @Messages = ''\n\nSELECT @Messages = @Messages + '|' + Message\nFROM process_monitor\nWHERE @TargetDate <= Timestamp and Timestamp < DateAdd(dd, 1, @TargetDate)\n and Message in ('Finished', 'Started')\nORDER BY Timestamp desc\n\nSELECT CASE\n WHEN @Messages = '|Finished|Started' THEN 2\n WHEN @Messages = '|Started' THEN 1\n WHEN @Messages = '' THEN 0\n ELSE -1\nEND\n</code></pre>\n"
},
{
"answer_id": 122151,
"author": "Grant Johnson",
"author_id": 12518,
"author_profile": "https://Stackoverflow.com/users/12518",
"pm_score": -1,
"selected": false,
"text": "<pre><code>select count(*) from process_monitor \nwhere timestamp > yesterday and timestamp < tomorrow.\n</code></pre>\n\n<p>Alternately, you could use a self join with a max to show the newest message for a particular day:</p>\n\n<pre><code>select * from process_monitor where \ntimestamp=(select max(timestamp) where timestamp<next_day);\n</code></pre>\n"
},
{
"answer_id": 122249,
"author": "Aheho",
"author_id": 21155,
"author_profile": "https://Stackoverflow.com/users/21155",
"pm_score": 0,
"selected": false,
"text": "<p>You are missing a column that uniquely identifies the process. Lets add a int column called ProcessID. You would also need another table to identify processes. If you were relying on your original table, you'd never know about processes that never started because there wouldn't be any row for that process.</p>\n\n<pre><code>select\n ProcessID,\n ProcessName,\n\n CASE\n WHEN \n (Select \n COUNT(*) \n from \n ProcessActivity \n where \n ProcessActivity.processid = Processes.processid \n and Message = 'STARTED') = 1 \n\n And\n (Select \n COUNT(*) \n from \n ProcessActivity \n where \n ProcessActivity.processid = Processes.processid \n and Message = 'FINISHED') = 0\n THEN 1\n\n WHEN\n (Select \n COUNT(*) \n from \n ProcessActivity \n where \n ProcessActivity.processid = Processes.processid \n and Message = 'STARTED') = 1 \n And\n (Select \n COUNT(*) \n from \n ProcessActivity \n where \n ProcessActivity.processid = Processes.processid \n and Message = 'FINISHED') = 1 \nTHEN 2\n ELSE 0\n\nEND as Status\n\nFrom\n Processes\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16881/"
] |
I have a table in a MSSQL database that looks like this:
```
Timestamp (datetime)
Message (varchar(20))
```
Once a day, a particular process inserts the current time and the message 'Started' when it starts. When it is finished it inserts the current time and the message 'Finished'.
What is a good query or set of statements that, given a particular date, returns:
* 0 if the process never started
* 1 if the process started but did not finish
* 2 if the process started and finished
There are other messages in the table, but 'Started' and 'Finished' are unique to this one process.
EDIT: For bonus karma, raise an error if the data is invalid, for example there are two 'Started' messages, or there is a 'Finished' without a 'Started'.
|
```
Select Count(Message) As Status
From Process_monitor
Where TimeStamp >= '20080923'
And TimeStamp < '20080924'
And (Message = 'Started' or Message = 'Finished')
```
You could modify this slightly to detect invalid conditions, like multiple starts, finishes, starts without a finish, etc...
```
Select Case When SumStarted = 0 And SumFinished = 0 Then 'Not Started'
When SumStarted = 1 And SumFinished = 0 Then 'Started'
When SumStarted = 1 And SumFinished = 1 Then 'Finished'
When SumStarted > 1 Then 'Multiple Starts'
When SumFinished > 1 Then 'Multiple Finish'
When SumFinished > 0 And SumStarted = 0 Then 'Finish Without Start'
End As StatusMessage
From (
Select Sum(Case When Message = 'Started' Then 1 Else 0 End) As SumStarted,
Sum(Case When Message = 'Finished' Then 1 Else 0 End) As SumFinished
From Process_monitor
Where TimeStamp >= '20080923'
And TimeStamp < '20080924'
And (Message = 'Started' or Message = 'Finished')
) As AliasName
```
|
122,089 |
<p>A brief search shows that all available (uUnix command line) tools that convert from xsd (XML Schema) to rng (RelaxNG) or rnc (compact RelaxNG) have problems of some sort.</p>
<p>First, if I use rngconv:</p>
<pre><code>$ wget https://msv.dev.java.net/files/documents/61/31333/rngconv.20060319.zip
$ unzip rngconv.20060319.zip
$ cd rngconv-20060319/
$ java -jar rngconv.jar my.xsd > my.rng
</code></pre>
<p>It does not have a way to de-normalize elements so all end up being alternative start elements (it also seems to be a bit buggy).</p>
<p>Trang is an alternative, but it doesn't support xsd files on the input only on the output (why?). It supports DTD, however. Converting to DTD first comes to mind, but a solid xsd2dtd is hard to find as well. The one below:</p>
<pre><code> $ xsltproc http://crism.maden.org/consulting/pub/xsl/xsd2dtd.xsl in.xsd > out.dtd
</code></pre>
<p>Seems to be buggy.</p>
<p>All this is very surprising. For all these years of XML (ab)use, there no decent command line tools for these trivial basic tasks? Are people using only editors? Do those work? I much prefer command line, especially because I'd like to automate these tasks.</p>
<p>Any enlightening comments on this?</p>
|
[
{
"answer_id": 122434,
"author": "Adrian Mouat",
"author_id": 4332,
"author_profile": "https://Stackoverflow.com/users/4332",
"pm_score": 2,
"selected": false,
"text": "<p>Converting XSD is a very hard task; the XSD specification is a bit of a nightmare and extremely complex. From some quick <a href=\"http://www.tbray.org/ongoing/When/200x/2006/11/27/Choose-Relax\" rel=\"nofollow noreferrer\">research,</a> it seems that it is easy to go from RelaxNG to XSD, but that the reverse may not be true or even possible (which explains your question about Trang).</p>\n\n<p>I don't understand your question about editors - if you are asking if most people end up converting between XSD and RNG by hand, then yes, I expect so.</p>\n\n<p>The best advice may be to avoid XSD if possible, or at least use RNG as the definitive document and generate the XSD from that. You might also want to take a look at <a href=\"http://www.schematron.com/\" rel=\"nofollow noreferrer\">schematron</a>.</p>\n"
},
{
"answer_id": 122788,
"author": "kmt",
"author_id": 21205,
"author_profile": "https://Stackoverflow.com/users/21205",
"pm_score": 0,
"selected": false,
"text": "<p>Again, regarding editors: I see that there's no way to do this with Oxygen which seems to be a popular tool.</p>\n"
},
{
"answer_id": 323601,
"author": "cmarqu",
"author_id": 41347,
"author_profile": "https://Stackoverflow.com/users/41347",
"pm_score": 0,
"selected": false,
"text": "<p>Another possibility might be <a href=\"http://www.brics.dk/schematools/\" rel=\"nofollow noreferrer\">http://www.brics.dk/schematools/</a>, but I didn't try it yet.</p>\n"
},
{
"answer_id": 1095094,
"author": "neozen",
"author_id": 59412,
"author_profile": "https://Stackoverflow.com/users/59412",
"pm_score": 2,
"selected": false,
"text": "<p>True, trang does not accept xsd on the input side. Trang <strong>can</strong> however take a set of xml files which should meet the spec and generate a rnc or rng schema which they would all be valid against.</p>\n\n<p>Downsides:</p>\n\n<ul>\n<li>It requires many compliant xml files (I'd imagine the more the better)</li>\n<li>Resulting schema could probably still use some tweaking.</li>\n</ul>\n\n<p><strong>Sample Case:</strong></p>\n\n<p>If my compliant xml files are stashed in <code>1.xml 2.xml 3.xml 4.xml 5.xml</code></p>\n\n<p>the following command would tell trang to output a rnc schema that would be valid for all of them:</p>\n\n<pre><code>java -jar trang.jar -I xml -O rnc 1.xml 2.xml 3.xml 4.xml 5.xml foo.rnc\n</code></pre>\n\n<p><strong>Conclusion</strong></p>\n\n<p>If you have a nice test set of xml files which meet your schema (or you can easily create them) this may be the best option available.</p>\n\n<p>I wish you the best of luck.</p>\n"
},
{
"answer_id": 2302117,
"author": "antonj",
"author_id": 183994,
"author_profile": "https://Stackoverflow.com/users/183994",
"pm_score": 2,
"selected": false,
"text": "<p>There is an online converter (<a href=\"http://debeissat.nicolas.free.fr/XSDtoRNG.php\" rel=\"nofollow noreferrer\">XSD -> RNG</a>) added to the list at <code>http://relaxng.org/#conversion</code>. I have tried to convert maven-v4_0_0.xsd for validation of pom.xml files in emacs, without any luck though. The site also contains the XSL stylesheet that you could use with <code>xsltproc</code>, can't vouch for the quality of the outcome...</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21205/"
] |
A brief search shows that all available (uUnix command line) tools that convert from xsd (XML Schema) to rng (RelaxNG) or rnc (compact RelaxNG) have problems of some sort.
First, if I use rngconv:
```
$ wget https://msv.dev.java.net/files/documents/61/31333/rngconv.20060319.zip
$ unzip rngconv.20060319.zip
$ cd rngconv-20060319/
$ java -jar rngconv.jar my.xsd > my.rng
```
It does not have a way to de-normalize elements so all end up being alternative start elements (it also seems to be a bit buggy).
Trang is an alternative, but it doesn't support xsd files on the input only on the output (why?). It supports DTD, however. Converting to DTD first comes to mind, but a solid xsd2dtd is hard to find as well. The one below:
```
$ xsltproc http://crism.maden.org/consulting/pub/xsl/xsd2dtd.xsl in.xsd > out.dtd
```
Seems to be buggy.
All this is very surprising. For all these years of XML (ab)use, there no decent command line tools for these trivial basic tasks? Are people using only editors? Do those work? I much prefer command line, especially because I'd like to automate these tasks.
Any enlightening comments on this?
|
Converting XSD is a very hard task; the XSD specification is a bit of a nightmare and extremely complex. From some quick [research,](http://www.tbray.org/ongoing/When/200x/2006/11/27/Choose-Relax) it seems that it is easy to go from RelaxNG to XSD, but that the reverse may not be true or even possible (which explains your question about Trang).
I don't understand your question about editors - if you are asking if most people end up converting between XSD and RNG by hand, then yes, I expect so.
The best advice may be to avoid XSD if possible, or at least use RNG as the definitive document and generate the XSD from that. You might also want to take a look at [schematron](http://www.schematron.com/).
|
122,098 |
<p>I have a Google Web Toolkit (GWT) application and when I link to it, I want to pass some arguments/parameters that it can use to dynamically retrieve data. E.g. if it were a stock chart application, I would want my link to contain the symbol and then have the GWT app read that and make a request to some stock service. E.g. <a href="http://myapp/gwt/StockChart?symbol=GOOG" rel="noreferrer">http://myapp/gwt/StockChart?symbol=GOOG</a> would be the link to my StockChart GWT app and it would make a request to my stock info web service for the GOOG stock. </p>
<p>So far, I've been using the server-side code to add Javascript variables to the page and then I've read those variables using JSNI (JavaScript Native Interface). </p>
<p>For example:</p>
<p>In the host HTML:</p>
<pre><code><script type="text/javascript">
var stockSymbol = '<%= request.getParameter("symbol") %>';
</script>
</code></pre>
<p>In the GWT code:</p>
<pre><code>public static native String getSymbol() /*-{
return $wnd.stockSymbol;
}-*/;
</code></pre>
<p>(Although this code is based on real code that works, I've modified it for this question so I might have goofed somewhere)</p>
<p>However, this doesn't always work well in hosted mode (especially with arrays) and since JSNI wasn't around in version 1.4 and previous, I'm guessing there's another/better way. </p>
|
[
{
"answer_id": 122833,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to read query string parameters from the request you can use the <strong>com.google.gwt.user.client.Window</strong> class:</p>\n\n<pre><code>// returns whole query string \npublic static String getQueryString() \n{\n return Window.Location.getQueryString();\n}\n\n// returns specific parameter\npublic static String getQueryString(String name)\n{ \n return Window.Location.getParameter(name);\n} \n</code></pre>\n"
},
{
"answer_id": 12100219,
"author": "mxro",
"author_id": 270662,
"author_profile": "https://Stackoverflow.com/users/270662",
"pm_score": 1,
"selected": false,
"text": "<p>It is also a nice option to 'parameterize' a GWT application using hash values. </p>\n\n<p>So, instead of</p>\n\n<pre><code> http://myapp/gwt/StockChart?symbol=GOOG\n</code></pre>\n\n<p>use</p>\n\n<pre><code> http://myapp/gwt/StockChart#symbol=GOOG\n</code></pre>\n\n<p>There is some nice tooling support for such 'parameters' through <a href=\"https://developers.google.com/web-toolkit/doc/latest/DevGuideCodingBasicsHistory\" rel=\"nofollow\">GWT's History Mechanism</a>.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9910/"
] |
I have a Google Web Toolkit (GWT) application and when I link to it, I want to pass some arguments/parameters that it can use to dynamically retrieve data. E.g. if it were a stock chart application, I would want my link to contain the symbol and then have the GWT app read that and make a request to some stock service. E.g. <http://myapp/gwt/StockChart?symbol=GOOG> would be the link to my StockChart GWT app and it would make a request to my stock info web service for the GOOG stock.
So far, I've been using the server-side code to add Javascript variables to the page and then I've read those variables using JSNI (JavaScript Native Interface).
For example:
In the host HTML:
```
<script type="text/javascript">
var stockSymbol = '<%= request.getParameter("symbol") %>';
</script>
```
In the GWT code:
```
public static native String getSymbol() /*-{
return $wnd.stockSymbol;
}-*/;
```
(Although this code is based on real code that works, I've modified it for this question so I might have goofed somewhere)
However, this doesn't always work well in hosted mode (especially with arrays) and since JSNI wasn't around in version 1.4 and previous, I'm guessing there's another/better way.
|
If you want to read query string parameters from the request you can use the **com.google.gwt.user.client.Window** class:
```
// returns whole query string
public static String getQueryString()
{
return Window.Location.getQueryString();
}
// returns specific parameter
public static String getQueryString(String name)
{
return Window.Location.getParameter(name);
}
```
|
122,102 |
<p>What is the most efficient way to clone a JavaScript object? I've seen <code>obj = eval(uneval(o));</code> being used, but <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval" rel="noreferrer">that's non-standard and only supported by Firefox</a>.<br/><br/> I've done things like <code>obj = JSON.parse(JSON.stringify(o));</code> but question the efficiency. <br/><br/> I've also seen recursive copying functions with various flaws.
<br />
I'm surprised no canonical solution exists.</p>
|
[
{
"answer_id": 122190,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 9,
"selected": false,
"text": "<p>If there wasn't any builtin one, you could try:</p>\n\n<pre><code>function clone(obj) {\n if (obj === null || typeof (obj) !== 'object' || 'isActiveClone' in obj)\n return obj;\n\n if (obj instanceof Date)\n var temp = new obj.constructor(); //or new Date(obj);\n else\n var temp = obj.constructor();\n\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n obj['isActiveClone'] = null;\n temp[key] = clone(obj[key]);\n delete obj['isActiveClone'];\n }\n }\n return temp;\n}\n</code></pre>\n"
},
{
"answer_id": 122232,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": false,
"text": "<pre><code>function clone(obj)\n { var clone = {};\n clone.prototype = obj.prototype;\n for (property in obj) clone[property] = obj[property];\n return clone;\n }\n</code></pre>\n"
},
{
"answer_id": 122704,
"author": "John Resig",
"author_id": 6524,
"author_profile": "https://Stackoverflow.com/users/6524",
"pm_score": 13,
"selected": true,
"text": "<h1>Native deep cloning</h1>\n<p>There's now a JS standard called <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/structuredClone\" rel=\"noreferrer\">"structured cloning"</a>, that works experimentally in Node 11 and later, will land in browsers, and which has <a href=\"https://www.npmjs.com/package/@ungap/structured-clone\" rel=\"noreferrer\">polyfills for existing systems</a>.</p>\n<pre><code>structuredClone(value)\n</code></pre>\n<p>If needed, loading the polyfill first:</p>\n<pre><code>import structuredClone from '@ungap/structured-clone';\n</code></pre>\n<p>See <a href=\"https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/10916838#10916838\">this answer</a> for more details.</p>\n<h1>Older answers</h1>\n<h2>Fast cloning with data loss - JSON.parse/stringify</h2>\n<p>If you do not use <code>Date</code>s, functions, <code>undefined</code>, <code>Infinity</code>, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, a very simple one liner to deep clone an object is:</p>\n<p><code>JSON.parse(JSON.stringify(object))</code></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const a = {\n string: 'string',\n number: 123,\n bool: false,\n nul: null,\n date: new Date(), // stringified\n undef: undefined, // lost\n inf: Infinity, // forced to 'null'\n re: /.*/, // lost\n}\nconsole.log(a);\nconsole.log(typeof a.date); // Date object\nconst clone = JSON.parse(JSON.stringify(a));\nconsole.log(clone);\nconsole.log(typeof clone.date); // result of .toISOString()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>See <a href=\"https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/5344074#5344074\">Corban's answer</a> for benchmarks.</p>\n<h2>Reliable cloning using a library</h2>\n<p>Since cloning objects is not trivial (complex types, circular references, function etc.), most major libraries provide function to clone objects. <strong>Don't reinvent the wheel</strong> - if you're already using a library, check if it has an object cloning function. For example,</p>\n<ul>\n<li>lodash - <a href=\"https://lodash.com/docs#cloneDeep\" rel=\"noreferrer\"><code>cloneDeep</code></a>; can be imported separately via the <a href=\"https://www.npmjs.com/package/lodash.clonedeep\" rel=\"noreferrer\">lodash.clonedeep</a> module and is probably your best choice if you're not already using a library that provides a deep cloning function</li>\n<li>AngularJS - <a href=\"https://docs.angularjs.org/api/ng/function/angular.copy\" rel=\"noreferrer\"><code>angular.copy</code></a></li>\n<li>jQuery - <a href=\"https://api.jquery.com/jquery.extend/#jQuery-extend-deep-target-object1-objectN\" rel=\"noreferrer\"><code>jQuery.extend(true, { }, oldObject)</code></a>; <code>.clone()</code> only clones DOM elements</li>\n<li>just library - <a href=\"https://www.npmjs.com/package/just-clone\" rel=\"noreferrer\"><code>just-clone</code></a>; Part of a library of zero-dependency npm modules that do just do one thing.\nGuilt-free utilities for every occasion.</li>\n</ul>\n"
},
{
"answer_id": 1042676,
"author": "Kamarey",
"author_id": 86296,
"author_profile": "https://Stackoverflow.com/users/86296",
"pm_score": 7,
"selected": false,
"text": "<p>Code:</p>\n\n<pre><code>// extends 'from' object with members from 'to'. If 'to' is null, a deep clone of 'from' is returned\nfunction extend(from, to)\n{\n if (from == null || typeof from != \"object\") return from;\n if (from.constructor != Object && from.constructor != Array) return from;\n if (from.constructor == Date || from.constructor == RegExp || from.constructor == Function ||\n from.constructor == String || from.constructor == Number || from.constructor == Boolean)\n return new from.constructor(from);\n\n to = to || new from.constructor();\n\n for (var name in from)\n {\n to[name] = typeof to[name] == \"undefined\" ? extend(from[name], null) : to[name];\n }\n\n return to;\n}\n</code></pre>\n\n<p>Test:</p>\n\n<pre><code>var obj =\n{\n date: new Date(),\n func: function(q) { return 1 + q; },\n num: 123,\n text: \"asdasd\",\n array: [1, \"asd\"],\n regex: new RegExp(/aaa/i),\n subobj:\n {\n num: 234,\n text: \"asdsaD\"\n }\n}\n\nvar clone = extend(obj);\n</code></pre>\n"
},
{
"answer_id": 1891377,
"author": "Alan",
"author_id": 229955,
"author_profile": "https://Stackoverflow.com/users/229955",
"pm_score": 7,
"selected": false,
"text": "<p>This is what I'm using:</p>\n\n<pre><code>function cloneObject(obj) {\n var clone = {};\n for(var i in obj) {\n if(typeof(obj[i])==\"object\" && obj[i] != null)\n clone[i] = cloneObject(obj[i]);\n else\n clone[i] = obj[i];\n }\n return clone;\n}\n</code></pre>\n"
},
{
"answer_id": 1963559,
"author": "Zibri",
"author_id": 236062,
"author_profile": "https://Stackoverflow.com/users/236062",
"pm_score": 6,
"selected": false,
"text": "<pre><code>var clone = function() {\n var newObj = (this instanceof Array) ? [] : {};\n for (var i in this) {\n if (this[i] && typeof this[i] == \"object\") {\n newObj[i] = this[i].clone();\n }\n else\n {\n newObj[i] = this[i];\n }\n }\n return newObj;\n}; \n\nObject.defineProperty( Object.prototype, \"clone\", {value: clone, enumerable: false});\n</code></pre>\n"
},
{
"answer_id": 2728898,
"author": "Dima",
"author_id": 327790,
"author_profile": "https://Stackoverflow.com/users/327790",
"pm_score": 4,
"selected": false,
"text": "<pre><code>// obj target object, vals source object\nvar setVals = function (obj, vals) {\n if (obj && vals) {\n for (var x in vals) {\n if (vals.hasOwnProperty(x)) {\n if (obj[x] && typeof vals[x] === 'object') {\n obj[x] = setVals(obj[x], vals[x]);\n } else {\n obj[x] = vals[x];\n }\n }\n }\n }\n return obj;\n};\n</code></pre>\n"
},
{
"answer_id": 3873968,
"author": "Chris Broski",
"author_id": 468111,
"author_profile": "https://Stackoverflow.com/users/468111",
"pm_score": 5,
"selected": false,
"text": "<p>Crockford suggests (and I prefer) using this function:</p>\n\n<pre><code>function object(o) {\n function F() {}\n F.prototype = o;\n return new F();\n}\n\nvar newObject = object(oldObject);\n</code></pre>\n\n<p>It's terse, works as expected and you don't need a library.</p>\n\n<hr>\n\n<p><strong>EDIT:</strong></p>\n\n<p>This is a polyfill for <code>Object.create</code>, so you also can use this.</p>\n\n<pre><code>var newObject = Object.create(oldObject);\n</code></pre>\n\n<p><strong>NOTE:</strong> If you use some of this, you may have problems with some iteration who use <code>hasOwnProperty</code>. Because, <code>create</code> create new empty object who inherits <code>oldObject</code>. But it is still useful and practical for cloning objects.</p>\n\n<p>For exemple if <code>oldObject.a = 5;</code></p>\n\n<pre><code>newObject.a; // is 5\n</code></pre>\n\n<p>but:</p>\n\n<pre><code>oldObject.hasOwnProperty(a); // is true\nnewObject.hasOwnProperty(a); // is false\n</code></pre>\n"
},
{
"answer_id": 3951975,
"author": "Page Notes",
"author_id": 478323,
"author_profile": "https://Stackoverflow.com/users/478323",
"pm_score": 4,
"selected": false,
"text": "<p>There seems to be no ideal deep clone operator yet for array-like objects. As the code below illustrates, John Resig's jQuery cloner turns arrays with non-numeric properties into objects that are not arrays, and RegDwight's JSON cloner drops the non-numeric properties. The following tests illustrate these points on multiple browsers:</p>\n\n<pre><code>function jQueryClone(obj) {\n return jQuery.extend(true, {}, obj)\n}\n\nfunction JSONClone(obj) {\n return JSON.parse(JSON.stringify(obj))\n}\n\nvar arrayLikeObj = [[1, \"a\", \"b\"], [2, \"b\", \"a\"]];\narrayLikeObj.names = [\"m\", \"n\", \"o\"];\nvar JSONCopy = JSONClone(arrayLikeObj);\nvar jQueryCopy = jQueryClone(arrayLikeObj);\n\nalert(\"Is arrayLikeObj an array instance?\" + (arrayLikeObj instanceof Array) +\n \"\\nIs the jQueryClone an array instance? \" + (jQueryCopy instanceof Array) +\n \"\\nWhat are the arrayLikeObj names? \" + arrayLikeObj.names +\n \"\\nAnd what are the JSONClone names? \" + JSONCopy.names)\n</code></pre>\n"
},
{
"answer_id": 4591639,
"author": "Sultan Shakir",
"author_id": 505062,
"author_profile": "https://Stackoverflow.com/users/505062",
"pm_score": 9,
"selected": false,
"text": "<p>Assuming that you have only properties and not any functions in your object, you can just use:</p>\n<pre><code>var newObject = JSON.parse(JSON.stringify(oldObject));\n</code></pre>\n"
},
{
"answer_id": 5344074,
"author": "Corban Brook",
"author_id": 69959,
"author_profile": "https://Stackoverflow.com/users/69959",
"pm_score": 11,
"selected": false,
"text": "<p>Checkout this benchmark: <a href=\"http://jsben.ch/#/bWfk9\" rel=\"noreferrer\">http://jsben.ch/#/bWfk9</a></p>\n\n<p>In my previous tests where speed was a main concern I found </p>\n\n<pre><code>JSON.parse(JSON.stringify(obj))\n</code></pre>\n\n<p>to be the slowest way to deep clone an object (it is slower than <a href=\"https://api.jquery.com/jQuery.extend/\" rel=\"noreferrer\">jQuery.extend</a> with <code>deep</code> flag set true by 10-20%).</p>\n\n<p>jQuery.extend is pretty fast when the <code>deep</code> flag is set to <code>false</code> (shallow clone). It is a good option, because it includes some extra logic for type validation and doesn't copy over undefined properties, etc., but this will also slow you down a little.</p>\n\n<p>If you know the structure of the objects you are trying to clone or can avoid deep nested arrays you can write a simple <code>for (var i in obj)</code> loop to clone your object while checking hasOwnProperty and it will be much much faster than jQuery.</p>\n\n<p>Lastly if you are attempting to clone a known object structure in a hot loop you can get MUCH MUCH MORE PERFORMANCE by simply in-lining the clone procedure and manually constructing the object.</p>\n\n<p>JavaScript trace engines suck at optimizing <code>for..in</code> loops and checking hasOwnProperty will slow you down as well. Manual clone when speed is an absolute must.</p>\n\n<pre><code>var clonedObject = {\n knownProp: obj.knownProp,\n ..\n}\n</code></pre>\n\n<p>Beware using the <code>JSON.parse(JSON.stringify(obj))</code> method on <code>Date</code> objects - <code>JSON.stringify(new Date())</code> returns a string representation of the date in ISO format, which <code>JSON.parse()</code> <strong>doesn't</strong> convert back to a <code>Date</code> object. <a href=\"https://stackoverflow.com/questions/11491938/issues-with-date-when-using-json-stringify-and-json-parse/11491993#11491993\">See this answer for more details</a>.</p>\n\n<p>Additionally, please note that, in Chrome 65 at least, native cloning is not the way to go. According to JSPerf, performing native cloning by creating a new function is nearly <strong>800x</strong> slower than using JSON.stringify which is incredibly fast all the way across the board.</p>\n\n<p><strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"noreferrer\">Update for ES6</a></strong></p>\n\n<p>If you are using Javascript ES6 try this native method for cloning or shallow copy.</p>\n\n<pre><code>Object.assign({}, obj);\n</code></pre>\n"
},
{
"answer_id": 5452191,
"author": "gion_13",
"author_id": 491075,
"author_profile": "https://Stackoverflow.com/users/491075",
"pm_score": 2,
"selected": false,
"text": "<p>I think that this is the best solution if you want to generalize your object cloning algorithm.<br>\nIt can be used with or without jQuery, although I recommend leaving jQuery's extend method out if you want you the cloned object to have the same \"class\" as the original one.</p>\n\n<pre><code>function clone(obj){\n if(typeof(obj) == 'function')//it's a simple function\n return obj;\n //of it's not an object (but could be an array...even if in javascript arrays are objects)\n if(typeof(obj) != 'object' || obj.constructor.toString().indexOf('Array')!=-1)\n if(JSON != undefined)//if we have the JSON obj\n try{\n return JSON.parse(JSON.stringify(obj));\n }catch(err){\n return JSON.parse('\"'+JSON.stringify(obj)+'\"');\n }\n else\n try{\n return eval(uneval(obj));\n }catch(err){\n return eval('\"'+uneval(obj)+'\"');\n }\n // I used to rely on jQuery for this, but the \"extend\" function returns\n //an object similar to the one cloned,\n //but that was not an instance (instanceof) of the cloned class\n /*\n if(jQuery != undefined)//if we use the jQuery plugin\n return jQuery.extend(true,{},obj);\n else//we recursivley clone the object\n */\n return (function _clone(obj){\n if(obj == null || typeof(obj) != 'object')\n return obj;\n function temp () {};\n temp.prototype = obj;\n var F = new temp;\n for(var key in obj)\n F[key] = clone(obj[key]);\n return F;\n })(obj); \n}\n</code></pre>\n"
},
{
"answer_id": 5527124,
"author": "neatonk",
"author_id": 682672,
"author_profile": "https://Stackoverflow.com/users/682672",
"pm_score": 4,
"selected": false,
"text": "<p>This isn't generally the most efficient solution, but it does what I need. Simple test cases below...</p>\n\n<pre><code>function clone(obj, clones) {\n // Makes a deep copy of 'obj'. Handles cyclic structures by\n // tracking cloned obj's in the 'clones' parameter. Functions \n // are included, but not cloned. Functions members are cloned.\n var new_obj,\n already_cloned,\n t = typeof obj,\n i = 0,\n l,\n pair; \n\n clones = clones || [];\n\n if (obj === null) {\n return obj;\n }\n\n if (t === \"object\" || t === \"function\") {\n\n // check to see if we've already cloned obj\n for (i = 0, l = clones.length; i < l; i++) {\n pair = clones[i];\n if (pair[0] === obj) {\n already_cloned = pair[1];\n break;\n }\n }\n\n if (already_cloned) {\n return already_cloned; \n } else {\n if (t === \"object\") { // create new object\n new_obj = new obj.constructor();\n } else { // Just use functions as is\n new_obj = obj;\n }\n\n clones.push([obj, new_obj]); // keep track of objects we've cloned\n\n for (key in obj) { // clone object members\n if (obj.hasOwnProperty(key)) {\n new_obj[key] = clone(obj[key], clones);\n }\n }\n }\n }\n return new_obj || obj;\n}\n</code></pre>\n\n<p>Cyclic array test...</p>\n\n<pre><code>a = []\na.push(\"b\", \"c\", a)\naa = clone(a)\naa === a //=> false\naa[2] === a //=> false\naa[2] === a[2] //=> false\naa[2] === aa //=> true\n</code></pre>\n\n<p>Function test...</p>\n\n<pre><code>f = new Function\nf.a = a\nff = clone(f)\nff === f //=> true\nff.a === a //=> false\n</code></pre>\n"
},
{
"answer_id": 6466050,
"author": "Steve Tomlin",
"author_id": 813831,
"author_profile": "https://Stackoverflow.com/users/813831",
"pm_score": 3,
"selected": false,
"text": "<p>This is the fastest method I have created that doesn't use the prototype, so it will maintain hasOwnProperty in the new object.</p>\n\n<p>The solution is to iterate the top level properties of the original object, make two copies, delete each property from the original and then reset the original object and return the new copy. It only has to iterate as many times as top level properties. This saves all the <code>if</code> conditions to check if each property is a function, object, string, etc., and doesn't have to iterate each descendant property.</p>\n\n<p>The only drawback is that the original object must be supplied with its original created namespace, in order to reset it.</p>\n\n<pre><code>copyDeleteAndReset:function(namespace,strObjName){\n var obj = namespace[strObjName],\n objNew = {},objOrig = {};\n for(i in obj){\n if(obj.hasOwnProperty(i)){\n objNew[i] = objOrig[i] = obj[i];\n delete obj[i];\n }\n }\n namespace[strObjName] = objOrig;\n return objNew;\n}\n\nvar namespace = {};\nnamespace.objOrig = {\n '0':{\n innerObj:{a:0,b:1,c:2}\n }\n}\n\nvar objNew = copyDeleteAndReset(namespace,'objOrig');\nobjNew['0'] = 'NEW VALUE';\n\nconsole.log(objNew['0']) === 'NEW VALUE';\nconsole.log(namespace.objOrig['0']) === innerObj:{a:0,b:1,c:2};\n</code></pre>\n"
},
{
"answer_id": 7541349,
"author": "Joe",
"author_id": 962942,
"author_profile": "https://Stackoverflow.com/users/962942",
"pm_score": 6,
"selected": false,
"text": "<p>I know this is an old post, but I thought this may be of some help to the next person who stumbles along.</p>\n\n<p>As long as you don't assign an object to anything it maintains no reference in memory. So to make an object that you want to share among other objects, you'll have to create a factory like so:</p>\n\n<pre><code>var a = function(){\n return {\n father:'zacharias'\n };\n},\nb = a(),\nc = a();\nc.father = 'johndoe';\nalert(b.father);\n</code></pre>\n"
},
{
"answer_id": 8522874,
"author": "itsadok",
"author_id": 7581,
"author_profile": "https://Stackoverflow.com/users/7581",
"pm_score": 6,
"selected": false,
"text": "<p>If you're using it, the <a href=\"https://underscorejs.org/\" rel=\"nofollow noreferrer\">Underscore.js</a> library has a <a href=\"https://underscorejs.org/#clone\" rel=\"nofollow noreferrer\">clone</a> method.</p>\n<pre><code>var newObject = _.clone(oldObject);\n</code></pre>\n"
},
{
"answer_id": 10916838,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 9,
"selected": false,
"text": "<h1>Structured Cloning</h1>\n<p><strong>2022 update:</strong> The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/structuredClone\" rel=\"noreferrer\"><code>structuredClone</code> global function</a> is already available in Firefox 94, Node 17 and Deno 1.14</p>\n<p>The HTML standard includes <a href=\"https://html.spec.whatwg.org/multipage/structured-data.html#safe-passing-of-structured-data\" rel=\"noreferrer\"><strong>an internal structured cloning/serialization algorithm</strong></a> that can create deep clones of objects. It is still limited to certain built-in types, but in addition to the few types supported by JSON it also supports Dates, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays, and probably more in the future. It also preserves references within the cloned data, allowing it to support cyclical and recursive structures that would cause errors for JSON.</p>\n<h2>Support in Node.js:</h2>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/structuredClone\" rel=\"noreferrer\"><code>structuredClone</code> global function</a> is provided by Node 17.0:</p>\n<pre><code>const clone = structuredClone(original);\n</code></pre>\n<p>Previous versions: The <code>v8</code> module in Node.js (as of Node 11) <a href=\"https://nodejs.org/api/all.html#v8_serialization_api\" rel=\"noreferrer\">exposes the structured serialization API directly</a>, but this functionality is still marked as "experimental", and subject to change or removal in future versions. If you're using a compatible version, cloning an object is as simple as:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const v8 = require('v8');\n\nconst structuredClone = obj => {\n return v8.deserialize(v8.serialize(obj));\n};\n</code></pre>\n<h2>Direct Support in Browsers: Available in Firefox 94</h2>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/structuredClone\" rel=\"noreferrer\"><code>structuredClone</code> global function</a> will soon be provided by all major browsers (having previously been discussed in <a href=\"https://github.com/whatwg/html/issues/793\" rel=\"noreferrer\">whatwg/html#793 on GitHub</a>). It looks / will look like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const clone = structuredClone(original);\n</code></pre>\n<p>Until this is shipped, browsers' structured clone implementations are only exposed indirectly.</p>\n<h2>Asynchronous Workaround: Usable. </h2>\n<p>The lower-overhead way to create a structured clone with existing APIs is to post the data through one port of a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel\" rel=\"noreferrer\">MessageChannels</a>. The other port will emit a <code>message</code> event with a structured clone of the attached <code>.data</code>. Unfortunately, listening for these events is necessarily asynchronous, and the synchronous alternatives are less practical.</p>\n<pre class=\"lang-js prettyprint-override\"><code>class StructuredCloner {\n constructor() {\n this.pendingClones_ = new Map();\n this.nextKey_ = 0;\n \n const channel = new MessageChannel();\n this.inPort_ = channel.port1;\n this.outPort_ = channel.port2;\n \n this.outPort_.onmessage = ({data: {key, value}}) => {\n const resolve = this.pendingClones_.get(key);\n resolve(value);\n this.pendingClones_.delete(key);\n };\n this.outPort_.start();\n }\n\n cloneAsync(value) {\n return new Promise(resolve => {\n const key = this.nextKey_++;\n this.pendingClones_.set(key, resolve);\n this.inPort_.postMessage({key, value});\n });\n }\n}\n\nconst structuredCloneAsync = window.structuredCloneAsync =\n StructuredCloner.prototype.cloneAsync.bind(new StructuredCloner);\n</code></pre>\n<h3>Example Use:</h3>\n<pre class=\"lang-js prettyprint-override\"><code>const main = async () => {\n const original = { date: new Date(), number: Math.random() };\n original.self = original;\n\n const clone = await structuredCloneAsync(original);\n\n // They're different objects:\n console.assert(original !== clone);\n console.assert(original.date !== clone.date);\n\n // They're cyclical:\n console.assert(original.self === original);\n console.assert(clone.self === clone);\n\n // They contain equivalent values:\n console.assert(original.number === clone.number);\n console.assert(Number(original.date) === Number(clone.date));\n \n console.log("Assertions complete.");\n};\n\nmain();\n</code></pre>\n<h2>Synchronous Workarounds: Awful! </h2>\n<p>There are no good options for creating structured clones synchronously. Here are a couple of impractical hacks instead.</p>\n<p><code>history.pushState()</code> and <code>history.replaceState()</code> both create a structured clone of their first argument, and assign that value to <code>history.state</code>. You can use this to create a structured clone of any object like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const structuredClone = obj => {\n const oldState = history.state;\n history.replaceState(obj, null);\n const clonedObj = history.state;\n history.replaceState(oldState, null);\n return clonedObj;\n};\n</code></pre>\n<h3>Example Use:</h3>\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>'use strict';\n\nconst main = () => {\n const original = { date: new Date(), number: Math.random() };\n original.self = original;\n\n const clone = structuredClone(original);\n \n // They're different objects:\n console.assert(original !== clone);\n console.assert(original.date !== clone.date);\n\n // They're cyclical:\n console.assert(original.self === original);\n console.assert(clone.self === clone);\n\n // They contain equivalent values:\n console.assert(original.number === clone.number);\n console.assert(Number(original.date) === Number(clone.date));\n \n console.log(\"Assertions complete.\");\n};\n\nconst structuredClone = obj => {\n const oldState = history.state;\n history.replaceState(obj, null);\n const clonedObj = history.state;\n history.replaceState(oldState, null);\n return clonedObj;\n};\n\nmain();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Though synchronous, this can be extremely slow. It incurs all of the overhead associated with manipulating the browser history. Calling this method repeatedly can cause Chrome to become temporarily unresponsive.</p>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Notification/Notification\" rel=\"noreferrer\"><code>Notification</code> constructor</a> creates a structured clone of its associated data. It also attempts to display a browser notification to the user, but this will silently fail unless you have requested notification permission. In case you have the permission for other purposes, we'll immediately close the notification we've created.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const structuredClone = obj => {\n const n = new Notification('', {data: obj, silent: true});\n n.onshow = n.close.bind(n);\n return n.data;\n};\n</code></pre>\n<h3>Example Use:</h3>\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>'use strict';\n\nconst main = () => {\n const original = { date: new Date(), number: Math.random() };\n original.self = original;\n\n const clone = structuredClone(original);\n \n // They're different objects:\n console.assert(original !== clone);\n console.assert(original.date !== clone.date);\n\n // They're cyclical:\n console.assert(original.self === original);\n console.assert(clone.self === clone);\n\n // They contain equivalent values:\n console.assert(original.number === clone.number);\n console.assert(Number(original.date) === Number(clone.date));\n \n console.log(\"Assertions complete.\");\n};\n\nconst structuredClone = obj => {\n const n = new Notification('', {data: obj, silent: true});\n n.close();\n return n.data;\n};\n\nmain();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 11335725,
"author": "Maël Nison",
"author_id": 880703,
"author_profile": "https://Stackoverflow.com/users/880703",
"pm_score": 4,
"selected": false,
"text": "<p>Shallow copy one-liner (<a href=\"https://en.wikipedia.org/wiki/ECMAScript#5th_Edition\" rel=\"nofollow noreferrer\">ECMAScript 5th edition</a>):</p>\n<pre><code>var origin = { foo : {} };\nvar copy = Object.keys(origin).reduce(function(c,k){c[k]=origin[k];return c;},{});\n\nconsole.log(origin, copy);\nconsole.log(origin == copy); // false\nconsole.log(origin.foo == copy.foo); // true\n</code></pre>\n<p>And shallow copy one-liner (<a href=\"https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_%E2%80%93_ECMAScript_2015\" rel=\"nofollow noreferrer\">ECMAScript 6th edition</a>, 2015):</p>\n<pre><code>var origin = { foo : {} };\nvar copy = Object.assign({}, origin);\n\nconsole.log(origin, copy);\nconsole.log(origin == copy); // false\nconsole.log(origin.foo == copy.foo); // true\n</code></pre>\n"
},
{
"answer_id": 11620938,
"author": "user1547016",
"author_id": 1547016,
"author_profile": "https://Stackoverflow.com/users/1547016",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a comprehensive clone() method that can clone any JavaScript object. It handles almost all the cases:</p>\n\n<pre><code>function clone(src, deep) {\n\n var toString = Object.prototype.toString;\n if (!src && typeof src != \"object\") {\n // Any non-object (Boolean, String, Number), null, undefined, NaN\n return src;\n }\n\n // Honor native/custom clone methods\n if (src.clone && toString.call(src.clone) == \"[object Function]\") {\n return src.clone(deep);\n }\n\n // DOM elements\n if (src.nodeType && toString.call(src.cloneNode) == \"[object Function]\") {\n return src.cloneNode(deep);\n }\n\n // Date\n if (toString.call(src) == \"[object Date]\") {\n return new Date(src.getTime());\n }\n\n // RegExp\n if (toString.call(src) == \"[object RegExp]\") {\n return new RegExp(src);\n }\n\n // Function\n if (toString.call(src) == \"[object Function]\") {\n\n //Wrap in another method to make sure == is not true;\n //Note: Huge performance issue due to closures, comment this :)\n return (function(){\n src.apply(this, arguments);\n });\n }\n\n var ret, index;\n //Array\n if (toString.call(src) == \"[object Array]\") {\n //[].slice(0) would soft clone\n ret = src.slice();\n if (deep) {\n index = ret.length;\n while (index--) {\n ret[index] = clone(ret[index], true);\n }\n }\n }\n //Object\n else {\n ret = src.constructor ? new src.constructor() : {};\n for (var prop in src) {\n ret[prop] = deep\n ? clone(src[prop], true)\n : src[prop];\n }\n }\n return ret;\n};\n</code></pre>\n"
},
{
"answer_id": 12941013,
"author": "pvorb",
"author_id": 432354,
"author_profile": "https://Stackoverflow.com/users/432354",
"pm_score": 6,
"selected": false,
"text": "<p>There’s a <a href=\"https://github.com/pvorb/node-clone\" rel=\"noreferrer\">library (called “clone”)</a>, that does this quite well. It provides the most complete recursive cloning/copying of arbitrary objects that I know of. It also supports circular references, which is not covered by the other answers, yet.</p>\n\n<p>You can <a href=\"https://npmjs.org/package/clone\" rel=\"noreferrer\">find it on npm</a>, too. It can be used for the browser as well as Node.js.</p>\n\n<p>Here is an example on how to use it:</p>\n\n<p>Install it with</p>\n\n<pre><code>npm install clone\n</code></pre>\n\n<p>or package it with <a href=\"https://github.com/ender-js/Ender\" rel=\"noreferrer\">Ender</a>.</p>\n\n<pre><code>ender build clone [...]\n</code></pre>\n\n<p>You can also download the source code manually.</p>\n\n<p>Then you can use it in your source code.</p>\n\n<pre><code>var clone = require('clone');\n\nvar a = { foo: { bar: 'baz' } }; // inital value of a\nvar b = clone(a); // clone a -> b\na.foo.bar = 'foo'; // change a\n\nconsole.log(a); // { foo: { bar: 'foo' } }\nconsole.log(b); // { foo: { bar: 'baz' } }\n</code></pre>\n\n<p>(Disclaimer: I’m the author of the library.)</p>\n"
},
{
"answer_id": 13333781,
"author": "Matt Browne",
"author_id": 560114,
"author_profile": "https://Stackoverflow.com/users/560114",
"pm_score": 6,
"selected": false,
"text": "<p>Here's a version of ConroyP's answer above that works even if the constructor has required parameters:</p>\n\n<pre><code>//If Object.create isn't already defined, we just do the simple shim,\n//without the second argument, since that's all we need here\nvar object_create = Object.create;\nif (typeof object_create !== 'function') {\n object_create = function(o) {\n function F() {}\n F.prototype = o;\n return new F();\n };\n}\n\nfunction deepCopy(obj) {\n if(obj == null || typeof(obj) !== 'object'){\n return obj;\n }\n //make sure the returned object has the same prototype as the original\n var ret = object_create(obj.constructor.prototype);\n for(var key in obj){\n ret[key] = deepCopy(obj[key]);\n }\n return ret;\n}\n</code></pre>\n\n<p>This function is also available in my <a href=\"https://github.com/mbrowne/simpleoo.js\" rel=\"noreferrer\">simpleoo</a> library.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Here's a more robust version (thanks to Justin McCandless this now supports cyclic references as well):</p>\n\n<pre><code>/**\n * Deep copy an object (make copies of all its object properties, sub-properties, etc.)\n * An improved version of http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone\n * that doesn't break if the constructor has required parameters\n * \n * It also borrows some code from http://stackoverflow.com/a/11621004/560114\n */ \nfunction deepCopy(src, /* INTERNAL */ _visited, _copiesVisited) {\n if(src === null || typeof(src) !== 'object'){\n return src;\n }\n\n //Honor native/custom clone methods\n if(typeof src.clone == 'function'){\n return src.clone(true);\n }\n\n //Special cases:\n //Date\n if(src instanceof Date){\n return new Date(src.getTime());\n }\n //RegExp\n if(src instanceof RegExp){\n return new RegExp(src);\n }\n //DOM Element\n if(src.nodeType && typeof src.cloneNode == 'function'){\n return src.cloneNode(true);\n }\n\n // Initialize the visited objects arrays if needed.\n // This is used to detect cyclic references.\n if (_visited === undefined){\n _visited = [];\n _copiesVisited = [];\n }\n\n // Check if this object has already been visited\n var i, len = _visited.length;\n for (i = 0; i < len; i++) {\n // If so, get the copy we already made\n if (src === _visited[i]) {\n return _copiesVisited[i];\n }\n }\n\n //Array\n if (Object.prototype.toString.call(src) == '[object Array]') {\n //[].slice() by itself would soft clone\n var ret = src.slice();\n\n //add it to the visited array\n _visited.push(src);\n _copiesVisited.push(ret);\n\n var i = ret.length;\n while (i--) {\n ret[i] = deepCopy(ret[i], _visited, _copiesVisited);\n }\n return ret;\n }\n\n //If we've reached here, we have a regular object\n\n //make sure the returned object has the same prototype as the original\n var proto = (Object.getPrototypeOf ? Object.getPrototypeOf(src): src.__proto__);\n if (!proto) {\n proto = src.constructor.prototype; //this line would probably only be reached by very old browsers \n }\n var dest = object_create(proto);\n\n //add this object to the visited array\n _visited.push(src);\n _copiesVisited.push(dest);\n\n for (var key in src) {\n //Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc.\n //For an example of how this could be modified to do so, see the singleMixin() function\n dest[key] = deepCopy(src[key], _visited, _copiesVisited);\n }\n return dest;\n}\n\n//If Object.create isn't already defined, we just do the simple shim,\n//without the second argument, since that's all we need here\nvar object_create = Object.create;\nif (typeof object_create !== 'function') {\n object_create = function(o) {\n function F() {}\n F.prototype = o;\n return new F();\n };\n}\n</code></pre>\n"
},
{
"answer_id": 16406986,
"author": "Michael Uzquiano",
"author_id": 1489973,
"author_profile": "https://Stackoverflow.com/users/1489973",
"pm_score": 4,
"selected": false,
"text": "<p>I have two good answers depending on whether your objective is to clone a \"plain old JavaScript object\" or not.</p>\n\n<p>Let's also assume that your intention is to create a complete clone with no prototype references back to the source object. If you're not interested in a complete clone, then you can use many of the Object.clone() routines provided in some of the other answers (Crockford's pattern).</p>\n\n<p>For plain old JavaScript objects, a tried and true good way to clone an object in modern runtimes is quite simply:</p>\n\n<pre><code>var clone = JSON.parse(JSON.stringify(obj));\n</code></pre>\n\n<p>Note that the source object must be a pure JSON object. This is to say, all of its nested properties must be scalars (like boolean, string, array, object, etc). Any functions or special objects like RegExp or Date will not be cloned.</p>\n\n<p>Is it efficient? Heck yes. We've tried all kinds of cloning methods and this works best. I'm sure some ninja could conjure up a faster method. But I suspect we're talking about marginal gains.</p>\n\n<p>This approach is just simple and easy to implement. Wrap it into a convenience function and if you really need to squeeze out some gain, go for at a later time.</p>\n\n<p>Now, for non-plain JavaScript objects, there isn't a really simple answer. In fact, there can't be because of the dynamic nature of JavaScript functions and inner object state. Deep cloning a JSON structure with functions inside requires you recreate those functions and their inner context. And JavaScript simply doesn't have a standardized way of doing that.</p>\n\n<p>The correct way to do this, once again, is via a convenience method that you declare and reuse within your code. The convenience method can be endowed with some understanding of your own objects so you can make sure to properly recreate the graph within the new object.</p>\n\n<p>We're written our own, but the best general approach I've seen is covered here:</p>\n\n<p><a href=\"http://davidwalsh.name/javascript-clone\" rel=\"noreferrer\">http://davidwalsh.name/javascript-clone</a></p>\n\n<p>This is the right idea. The author (David Walsh) has commented out the cloning of generalized functions. This is something you might choose to do, depending on your use case.</p>\n\n<p>The main idea is that you need to special handle the instantiation of your functions (or prototypal classes, so to speak) on a per-type basis. Here, he's provided a few examples for RegExp and Date.</p>\n\n<p>Not only is this code brief, but it's also very readable. It's pretty easy to extend.</p>\n\n<p>Is this efficient? Heck yes. Given that the goal is to produce a true deep-copy clone, then you're going to have to walk the members of the source object graph. With this approach, you can tweak exactly which child members to treat and how to manually handle custom types.</p>\n\n<p>So there you go. Two approaches. Both are efficient in my view.</p>\n"
},
{
"answer_id": 17252104,
"author": "opensas",
"author_id": 47633,
"author_profile": "https://Stackoverflow.com/users/47633",
"pm_score": 5,
"selected": false,
"text": "<p>Lodash has a nice <a href=\"http://lodash.com/docs#cloneDeep\" rel=\"noreferrer\">_.cloneDeep(value)</a> method:</p>\n\n<pre><code>var objects = [{ 'a': 1 }, { 'b': 2 }];\n\nvar deep = _.cloneDeep(objects);\nconsole.log(deep[0] === objects[0]);\n// => false\n</code></pre>\n"
},
{
"answer_id": 17915351,
"author": "Daniel Lorenz",
"author_id": 1245940,
"author_profile": "https://Stackoverflow.com/users/1245940",
"pm_score": 3,
"selected": false,
"text": "<p>There are a lot of answers, but none of them gave the desired effect I needed. I wanted to utilize the power of jQuery's deep copy... However, when it runs into an array, it simply copies the reference to the array and deep copies the items in it. To get around this, I made a nice little recursive function that will create a new array automatically. </p>\n\n<p>(It even checks for kendo.data.ObservableArray if you want it to! Though, make sure you make sure you call kendo.observable(newItem) if you want the Arrays to be observable again.) </p>\n\n<p>So, to fully copy an existing item, you just do this:</p>\n\n<pre><code>var newItem = jQuery.extend(true, {}, oldItem);\ncreateNewArrays(newItem);\n\n\nfunction createNewArrays(obj) {\n for (var prop in obj) {\n if ((kendo != null && obj[prop] instanceof kendo.data.ObservableArray) || obj[prop] instanceof Array) {\n var copy = [];\n $.each(obj[prop], function (i, item) {\n var newChild = $.extend(true, {}, item);\n createNewArrays(newChild);\n copy.push(newChild);\n });\n obj[prop] = copy;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 23277075,
"author": "Cody",
"author_id": 1153121,
"author_profile": "https://Stackoverflow.com/users/1153121",
"pm_score": 3,
"selected": false,
"text": "<p>I usually use <code>var newObj = JSON.parse( JSON.stringify(oldObje) );</code> but, here's a more proper way:</p>\n\n<pre><code>var o = {};\n\nvar oo = Object.create(o);\n\n(o === oo); // => false\n</code></pre>\n\n<p>Watch legacy browsers!</p>\n"
},
{
"answer_id": 24248152,
"author": "weeger",
"author_id": 2057976,
"author_profile": "https://Stackoverflow.com/users/2057976",
"pm_score": 2,
"selected": false,
"text": "<p>This is my version of object cloner. This is a stand-alone version of the jQuery method, with only few tweaks and adjustments. Check out the <a href=\"http://jsfiddle.net/eyYJB/\" rel=\"nofollow\">fiddle</a>. I've used a lot of jQuery until the day I realized that I'd use only this function most of the time x_x.</p>\n\n<p>The usage is the same as described into the jQuery API:</p>\n\n<ul>\n<li>Non-deep clone: <code>extend(object_dest, object_source);</code></li>\n<li>Deep clone: <code>extend(true, object_dest, object_source);</code></li>\n</ul>\n\n<p>One extra function is used to define if object is proper to be cloned.</p>\n\n<pre><code>/**\n * This is a quasi clone of jQuery's extend() function.\n * by Romain WEEGER for wJs library - www.wexample.com\n * @returns {*|{}}\n */\nfunction extend() {\n // Make a copy of arguments to avoid JavaScript inspector hints.\n var to_add, name, copy_is_array, clone,\n\n // The target object who receive parameters\n // form other objects.\n target = arguments[0] || {},\n\n // Index of first argument to mix to target.\n i = 1,\n\n // Mix target with all function arguments.\n length = arguments.length,\n\n // Define if we merge object recursively.\n deep = false;\n\n // Handle a deep copy situation.\n if (typeof target === 'boolean') {\n deep = target;\n\n // Skip the boolean and the target.\n target = arguments[ i ] || {};\n\n // Use next object as first added.\n i++;\n }\n\n // Handle case when target is a string or something (possible in deep copy)\n if (typeof target !== 'object' && typeof target !== 'function') {\n target = {};\n }\n\n // Loop trough arguments.\n for (false; i < length; i += 1) {\n\n // Only deal with non-null/undefined values\n if ((to_add = arguments[ i ]) !== null) {\n\n // Extend the base object.\n for (name in to_add) {\n\n // We do not wrap for loop into hasOwnProperty,\n // to access to all values of object.\n // Prevent never-ending loop.\n if (target === to_add[name]) {\n continue;\n }\n\n // Recurse if we're merging plain objects or arrays.\n if (deep && to_add[name] && (is_plain_object(to_add[name]) || (copy_is_array = Array.isArray(to_add[name])))) {\n if (copy_is_array) {\n copy_is_array = false;\n clone = target[name] && Array.isArray(target[name]) ? target[name] : [];\n }\n else {\n clone = target[name] && is_plain_object(target[name]) ? target[name] : {};\n }\n\n // Never move original objects, clone them.\n target[name] = extend(deep, clone, to_add[name]);\n }\n\n // Don't bring in undefined values.\n else if (to_add[name] !== undefined) {\n target[name] = to_add[name];\n }\n }\n }\n }\n return target;\n}\n\n/**\n * Check to see if an object is a plain object\n * (created using \"{}\" or \"new Object\").\n * Forked from jQuery.\n * @param obj\n * @returns {boolean}\n */\nfunction is_plain_object(obj) {\n // Not plain objects:\n // - Any object or value whose internal [[Class]] property is not \"[object Object]\"\n // - DOM nodes\n // - window\n if (obj === null || typeof obj !== \"object\" || obj.nodeType || (obj !== null && obj === obj.window)) {\n return false;\n }\n // Support: Firefox <20\n // The try/catch suppresses exceptions thrown when attempting to access\n // the \"constructor\" property of certain host objects, i.e. |window.location|\n // https://bugzilla.mozilla.org/show_bug.cgi?id=814622\n try {\n if (obj.constructor && !this.hasOwnProperty.call(obj.constructor.prototype, \"isPrototypeOf\")) {\n return false;\n }\n }\n catch (e) {\n return false;\n }\n\n // If the function hasn't returned already, we're confident that\n // |obj| is a plain object, created by {} or constructed with new Object\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 25476365,
"author": "Robin Whittleton",
"author_id": 453783,
"author_profile": "https://Stackoverflow.com/users/453783",
"pm_score": 3,
"selected": false,
"text": "<p>For future reference, the current draft of <a href=\"https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_-_ECMAScript_2015\" rel=\"nofollow\">ECMAScript 6</a> introduces <a href=\"http://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign\" rel=\"nofollow\">Object.assign</a> as a way of cloning objects. Example code would be:</p>\n\n<pre><code>var obj1 = { a: true, b: 1 };\nvar obj2 = Object.assign(obj1);\nconsole.log(obj2); // { a: true, b: 1 }\n</code></pre>\n\n<p>At the time of writing <a href=\"http://kangax.github.io/compat-table/es6/#Object.assign\" rel=\"nofollow\">support is limited to Firefox 34 in browsers</a> so it’s not usable in production code just yet (unless you’re writing a Firefox extension of course).</p>\n"
},
{
"answer_id": 25921504,
"author": "tim-montague",
"author_id": 1404726,
"author_profile": "https://Stackoverflow.com/users/1404726",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Deep copy by performance:</strong>\nRanked from best to worst</p>\n<ul>\n<li>spread operator <code>...</code> (primitive arrays - only)</li>\n<li><code>splice(0)</code> (primitive arrays - only)</li>\n<li><code>slice()</code> (primitive arrays - only)</li>\n<li><code>concat()</code> (primitive arrays - only)</li>\n<li>custom function, as seen below (any array)</li>\n<li>jQuery's <code>$.extend()</code> (any array)</li>\n<li><code>JSON.parse(JSON.stringify())</code> (primitive and literal arrays - only)</li>\n<li>Underscore's <code>_.clone()</code> (primitive and literal arrays - only)</li>\n<li>Lodash's <code>_.cloneDeep()</code> (any array)</li>\n</ul>\n<p>Where:</p>\n<ul>\n<li>primitives = strings, numbers, and booleans</li>\n<li>literals = object literals <code>{}</code>, array literals <code>[]</code></li>\n<li>any = primitives, literals, and prototypes</li>\n</ul>\n<p><strong>Deep copy an array of primitives:</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>let arr1a = [1, 'a', true];\n</code></pre>\n<p>To deep copy arrays with primitives only (i.e. numbers, strings, and booleans), reassignment, <code>slice()</code>, <code>concat()</code>, and Underscore's <code>clone()</code> can be used.</p>\n<p>Where spread has the fastest performance:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let arr1b = [...arr1a];\n</code></pre>\n<p>And where <code>slice()</code> has better performance than <code>concat()</code>: <a href=\"https://jsbench.me/x5ktn7o94d/\" rel=\"noreferrer\">https://jsbench.me/x5ktn7o94d/</a></p>\n<pre class=\"lang-js prettyprint-override\"><code>let arr1c = arr1a.splice(0);\nlet arr1d = arr1a.slice();\nlet arr1e = arr1a.concat();\n</code></pre>\n<p><strong>Deep copy an array of primitive and object literals:</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>let arr2a = [1, 'a', true, {}, []];\nlet arr2b = JSON.parse(JSON.stringify(arr2a));\n</code></pre>\n<p><strong>Deep copy an array of primitive, object literals, and prototypes:</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>let arr3a = [1, 'a', true, {}, [], new Object()];\n</code></pre>\n<p>Write a custom function (has faster performance than <code>$.extend()</code> or <code>JSON.parse</code>):</p>\n<pre class=\"lang-js prettyprint-override\"><code>function copy(aObject) {\n // Prevent undefined objects\n // if (!aObject) return aObject;\n\n let bObject = Array.isArray(aObject) ? [] : {};\n\n let value;\n for (const key in aObject) {\n\n // Prevent self-references to parent object\n // if (Object.is(aObject[key], aObject)) continue;\n \n value = aObject[key];\n\n bObject[key] = (typeof value === "object") ? copy(value) : value;\n }\n\n return bObject;\n}\n\nlet arr3b = copy(arr3a);\n</code></pre>\n<p>Or use third-party utility functions:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let arr3c = $.extend(true, [], arr3a); // jQuery Extend\nlet arr3d = _.cloneDeep(arr3a); // Lodash\n</code></pre>\n<p>Note: jQuery's <code>$.extend</code> also has better performance than <code>JSON.parse(JSON.stringify())</code>:</p>\n<ul>\n<li><a href=\"https://jsbench.me/5kktn8f3ss\" rel=\"noreferrer\">js-deep-copy</a></li>\n<li><a href=\"https://jsbench.me/imktn8ppco\" rel=\"noreferrer\">jquery-extend-vs-json-parse</a></li>\n</ul>\n"
},
{
"answer_id": 30929199,
"author": "Steven Vachon",
"author_id": 923745,
"author_profile": "https://Stackoverflow.com/users/923745",
"pm_score": 2,
"selected": false,
"text": "<p>Use <code>Object.create()</code> to get the <code>prototype</code> and support for <code>instanceof</code>, and use a <code>for()</code> loop to get enumerable keys:</p>\n\n<pre><code>function cloneObject(source) {\n var key,value;\n var clone = Object.create(source);\n\n for (key in source) {\n if (source.hasOwnProperty(key) === true) {\n value = source[key];\n\n if (value!==null && typeof value===\"object\") {\n clone[key] = cloneObject(value);\n } else {\n clone[key] = value;\n }\n }\n }\n\n return clone;\n}\n</code></pre>\n"
},
{
"answer_id": 31817825,
"author": "Tristian",
"author_id": 3629804,
"author_profile": "https://Stackoverflow.com/users/3629804",
"pm_score": 2,
"selected": false,
"text": "<p>Requires new-ish browsers, but...</p>\n\n<p>Let's extend the native Object and get a <strong>real</strong> <code>.extend()</code>;</p>\n\n<pre><code>Object.defineProperty(Object.prototype, 'extend', {\n enumerable: false,\n value: function(){\n var that = this;\n\n Array.prototype.slice.call(arguments).map(function(source){\n var props = Object.getOwnPropertyNames(source),\n i = 0, l = props.length,\n prop;\n\n for(; i < l; ++i){\n prop = props[i];\n\n if(that.hasOwnProperty(prop) && typeof(that[prop]) === 'object'){\n that[prop] = that[prop].extend(source[prop]);\n }else{\n Object.defineProperty(that, prop, Object.getOwnPropertyDescriptor(source, prop));\n }\n }\n });\n\n return this;\n }\n});\n</code></pre>\n\n<p>Just pop that in prior to any code that uses .extend() on an object.</p>\n\n<p>Example:</p>\n\n<pre><code>var obj1 = {\n node1: '1',\n node2: '2',\n node3: 3\n};\n\nvar obj2 = {\n node1: '4',\n node2: 5,\n node3: '6'\n};\n\nvar obj3 = ({}).extend(obj1, obj2);\n\nconsole.log(obj3);\n// Object {node1: \"4\", node2: 5, node3: \"6\"}\n</code></pre>\n"
},
{
"answer_id": 32144541,
"author": "nathan rogers",
"author_id": 4761444,
"author_profile": "https://Stackoverflow.com/users/4761444",
"pm_score": 5,
"selected": false,
"text": "<p>The following creates two instances of the same object. I found it and am using it currently. It's simple and easy to use.</p>\n\n<pre><code>var objToCreate = JSON.parse(JSON.stringify(cloneThis));\n</code></pre>\n"
},
{
"answer_id": 33273256,
"author": "andrew",
"author_id": 797230,
"author_profile": "https://Stackoverflow.com/users/797230",
"pm_score": 4,
"selected": false,
"text": "<p>Only when you can use <a href=\"https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_%E2%80%93_ECMAScript_2015\" rel=\"nofollow noreferrer\">ECMAScript 6</a> or <a href=\"https://en.wikipedia.org/wiki/Source-to-source_compiler\" rel=\"nofollow noreferrer\">transpilers</a>.</p>\n<p>Features:</p>\n<ul>\n<li>Won't trigger getter/setter while copying.</li>\n<li>Preserves getter/setter.</li>\n<li>Preserves prototype informations.</li>\n<li>Works with both <strong>object-literal</strong> and <strong>functional</strong> <a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">OO</a> writing styles.</li>\n</ul>\n<p>Code:</p>\n<pre><code>function clone(target, source){\n\n for(let key in source){\n\n // Use getOwnPropertyDescriptor instead of source[key] to prevent from trigering setter/getter.\n let descriptor = Object.getOwnPropertyDescriptor(source, key);\n if(descriptor.value instanceof String){\n target[key] = new String(descriptor.value);\n }\n else if(descriptor.value instanceof Array){\n target[key] = clone([], descriptor.value);\n }\n else if(descriptor.value instanceof Object){\n let prototype = Reflect.getPrototypeOf(descriptor.value);\n let cloneObject = clone({}, descriptor.value);\n Reflect.setPrototypeOf(cloneObject, prototype);\n target[key] = cloneObject;\n }\n else {\n Object.defineProperty(target, key, descriptor);\n }\n }\n let prototype = Reflect.getPrototypeOf(source);\n Reflect.setPrototypeOf(target, prototype);\n return target;\n}\n</code></pre>\n"
},
{
"answer_id": 33419329,
"author": "Buzinas",
"author_id": 3358027,
"author_profile": "https://Stackoverflow.com/users/3358027",
"pm_score": 4,
"selected": false,
"text": "<p>For the people who want to use the <code>JSON.parse(JSON.stringify(obj))</code> version, but without losing the Date objects, you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter\" rel=\"noreferrer\">second argument of <code>parse</code> method</a> to convert the strings back to Date:</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>function clone(obj) {\n var regExp = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$/;\n return JSON.parse(JSON.stringify(obj), function(k, v) {\n if (typeof v === 'string' && regExp.test(v))\n return new Date(v)\n return v;\n })\n}\n\n// usage:\nvar original = {\n a: [1, null, undefined, 0, {a:null}, new Date()],\n b: {\n c(){ return 0 }\n }\n}\n\nvar cloned = clone(original)\n\nconsole.log(cloned)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 34283281,
"author": "Eugene Tiurin",
"author_id": 2676500,
"author_profile": "https://Stackoverflow.com/users/2676500",
"pm_score": 7,
"selected": false,
"text": "<h1>The efficient way to clone(not deep-clone) an object in one line of code</h1>\n<p>An <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"noreferrer\"><code>Object.assign</code></a> method is part of the ECMAScript 2015 (ES6) standard and does exactly what you need.</p>\n<pre><code>var clone = Object.assign({}, obj);\n</code></pre>\n<blockquote>\n<p>The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.</p>\n</blockquote>\n<p><a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"noreferrer\">Read more...</a></p>\n<p>The <strong>polyfill</strong> to support older browsers:</p>\n<pre><code>if (!Object.assign) {\n Object.defineProperty(Object, 'assign', {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function(target) {\n 'use strict';\n if (target === undefined || target === null) {\n throw new TypeError('Cannot convert first argument to object');\n }\n\n var to = Object(target);\n for (var i = 1; i < arguments.length; i++) {\n var nextSource = arguments[i];\n if (nextSource === undefined || nextSource === null) {\n continue;\n }\n nextSource = Object(nextSource);\n\n var keysArray = Object.keys(nextSource);\n for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {\n var nextKey = keysArray[nextIndex];\n var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);\n if (desc !== undefined && desc.enumerable) {\n to[nextKey] = nextSource[nextKey];\n }\n }\n }\n return to;\n }\n });\n}\n</code></pre>\n"
},
{
"answer_id": 34555013,
"author": "Bodhi Hu",
"author_id": 2176133,
"author_profile": "https://Stackoverflow.com/users/2176133",
"pm_score": 3,
"selected": false,
"text": "<p>As recursion is just too expensive for JavaScript, and most answers I have found are using recursion, while JSON approach will skip the non-JSON-convertible parts (Function, etc.). So I did a little research and found this trampoline technique to avoid it. Here's the code:</p>\n<pre><code>/*\n * Trampoline to avoid recursion in JavaScript, see:\n * https://www.integralist.co.uk/posts/functional-recursive-javascript-programming/\n */\nfunction trampoline() {\n var func = arguments[0];\n var args = [];\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n\n var currentBatch = func.apply(this, args);\n var nextBatch = [];\n\n while (currentBatch && currentBatch.length > 0) {\n currentBatch.forEach(function(eachFunc) {\n var ret = eachFunc();\n if (ret && ret.length > 0) {\n nextBatch = nextBatch.concat(ret);\n }\n });\n\n currentBatch = nextBatch;\n nextBatch = [];\n }\n};\n\n/*\n * Deep clone an object using the trampoline technique.\n *\n * @param target {Object} Object to clone\n * @return {Object} Cloned object.\n */\nfunction clone(target) {\n if (typeof target !== 'object') {\n return target;\n }\n if (target == null || Object.keys(target).length == 0) {\n return target;\n }\n\n function _clone(b, a) {\n var nextBatch = [];\n for (var key in b) {\n if (typeof b[key] === 'object' && b[key] !== null) {\n if (b[key] instanceof Array) {\n a[key] = [];\n }\n else {\n a[key] = {};\n }\n nextBatch.push(_clone.bind(null, b[key], a[key]));\n }\n else {\n a[key] = b[key];\n }\n }\n return nextBatch;\n };\n\n var ret = target instanceof Array ? [] : {};\n (trampoline.bind(null, _clone))(target, ret);\n return ret;\n};\n</code></pre>\n"
},
{
"answer_id": 36177142,
"author": "Barry Staes",
"author_id": 2096041,
"author_profile": "https://Stackoverflow.com/users/2096041",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Cloning an object using today's JavaScript: <a href=\"https://en.wikipedia.org/wiki/ECMAScript#6th_Edition_%E2%80%93_ECMAScript_2015\" rel=\"nofollow noreferrer\">ECMAScript 2015</a></strong> (formerly known as ECMAScript 6)</p>\n<pre><code>var original = {a: 1};\n\n// Method 1: New object with original assigned.\nvar copy1 = Object.assign({}, original);\n\n// Method 2: New object with spread operator assignment.\nvar copy2 = {...original};\n</code></pre>\n<p>Old browsers may not support ECMAScript 2015. A common solution is to use a JavaScript-to-JavaScript compiler like Babel to output an <a href=\"https://en.wikipedia.org/wiki/ECMAScript#5th_Edition\" rel=\"nofollow noreferrer\">ECMAScript 5</a> version of your JavaScript code.</p>\n<p>As <a href=\"https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object-in-javascript?page=2&tab=oldest#comment60081951_36177142\">pointed out by @jim-hall</a>, <strong>this is only a shallow copy</strong>. Properties of properties are copied as a reference: changing one would change the value in the other object/instance.</p>\n"
},
{
"answer_id": 37220122,
"author": "Dan Atkinson",
"author_id": 31532,
"author_profile": "https://Stackoverflow.com/users/31532",
"pm_score": 4,
"selected": false,
"text": "<p>Just because I didn't see <a href=\"http://en.wikipedia.org/wiki/AngularJS\" rel=\"noreferrer\">AngularJS</a> mentioned and thought that people might want to know...</p>\n\n<p><a href=\"https://docs.angularjs.org/api/ng/function/angular.copy\" rel=\"noreferrer\"><code>angular.copy</code></a> also provides a method of deep copying objects and arrays.</p>\n"
},
{
"answer_id": 38423812,
"author": "Shishir Arora",
"author_id": 3221274,
"author_profile": "https://Stackoverflow.com/users/3221274",
"pm_score": 3,
"selected": false,
"text": "<p>Single-line ECMAScript 6 solution (special object types like Date/Regex not handled):</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>const clone = (o) =>\r\n typeof o === 'object' && o !== null ? // only clone objects\r\n (Array.isArray(o) ? // if cloning an array\r\n o.map(e => clone(e)) : // clone each of its elements\r\n Object.keys(o).reduce( // otherwise reduce every key in the object\r\n (r, k) => (r[k] = clone(o[k]), r), {} // and save its cloned value into a new object\r\n )\r\n ) :\r\n o; // return non-objects as is\r\n\r\nvar x = {\r\n nested: {\r\n name: 'test'\r\n }\r\n};\r\n\r\nvar y = clone(x);\r\n\r\nconsole.log(x.nested !== y.nested);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 38796058,
"author": "user3071643",
"author_id": 3071643,
"author_profile": "https://Stackoverflow.com/users/3071643",
"pm_score": 3,
"selected": false,
"text": "<p>I use the npm clone library. Apparently it also works in the browser.</p>\n\n<p><a href=\"https://www.npmjs.com/package/clone\" rel=\"noreferrer\">https://www.npmjs.com/package/clone</a></p>\n\n<pre><code>let a = clone(b)\n</code></pre>\n"
},
{
"answer_id": 39491721,
"author": "azerafati",
"author_id": 3160597,
"author_profile": "https://Stackoverflow.com/users/3160597",
"pm_score": 4,
"selected": false,
"text": "<h2>AngularJS</h2>\n\n<p>Well if you're using angular you could do this too</p>\n\n<pre><code>var newObject = angular.copy(oldObject);\n</code></pre>\n"
},
{
"answer_id": 40326630,
"author": "SAlidadi",
"author_id": 6249763,
"author_profile": "https://Stackoverflow.com/users/6249763",
"pm_score": 2,
"selected": false,
"text": "<p>This is a solution with recursion:</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>obj = {\r\n a: { b: { c: { d: ['1', '2'] } } },\r\n e: 'Saeid'\r\n}\r\nconst Clone = function (obj) {\r\n \r\n const container = Array.isArray(obj) ? [] : {}\r\n const keys = Object.keys(obj)\r\n \r\n for (let i = 0; i < keys.length; i++) {\r\n const key = keys[i]\r\n if(typeof obj[key] == 'object') {\r\n container[key] = Clone(obj[key])\r\n }\r\n else\r\n container[key] = obj[key].slice()\r\n }\r\n \r\n return container\r\n}\r\n console.log(Clone(obj))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 40722084,
"author": "Ashutosh Jha",
"author_id": 3387029,
"author_profile": "https://Stackoverflow.com/users/3387029",
"pm_score": 2,
"selected": false,
"text": "<p>For future reference, one can use this code</p>\n\n<p>ES6:</p>\n\n<pre><code>_clone: function(obj){\n let newObj = {};\n for(let i in obj){\n if(typeof(obj[i]) === 'object' && Object.keys(obj[i]).length){\n newObj[i] = clone(obj[i]);\n } else{\n newObj[i] = obj[i];\n }\n }\n return Object.assign({},newObj);\n}\n</code></pre>\n\n<p>ES5:</p>\n\n<pre><code>function clone(obj){\nlet newObj = {};\nfor(let i in obj){\n if(typeof(obj[i]) === 'object' && Object.keys(obj[i]).length){\n newObj[i] = clone(obj[i]);\n } else{\n newObj[i] = obj[i];\n }\n}\nreturn Object.assign({},newObj);\n</code></pre>\n\n<p>}</p>\n\n<p>E.g </p>\n\n<pre><code>var obj ={a:{b:1,c:3},d:4,e:{f:6}}\nvar xc = clone(obj);\nconsole.log(obj); //{a:{b:1,c:3},d:4,e:{f:6}}\nconsole.log(xc); //{a:{b:1,c:3},d:4,e:{f:6}}\n\nxc.a.b = 90;\nconsole.log(obj); //{a:{b:1,c:3},d:4,e:{f:6}}\nconsole.log(xc); //{a:{b:90,c:3},d:4,e:{f:6}}\n</code></pre>\n"
},
{
"answer_id": 40784968,
"author": "Ihor Pavlyk",
"author_id": 3552556,
"author_profile": "https://Stackoverflow.com/users/3552556",
"pm_score": 2,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class Handler {\r\n static deepCopy (obj) {\r\n if (Object.prototype.toString.call(obj) === '[object Array]') {\r\n const result = [];\r\n \r\n for (let i = 0, len = obj.length; i < len; i++) {\r\n result[i] = Handler.deepCopy(obj[i]);\r\n }\r\n return result;\r\n } else if (Object.prototype.toString.call(obj) === '[object Object]') {\r\n const result = {};\r\n for (let prop in obj) {\r\n result[prop] = Handler.deepCopy(obj[prop]);\r\n }\r\n return result;\r\n }\r\n return obj;\r\n }\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 43188775,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 6,
"selected": false,
"text": "<p>Cloning an object was always a concern in JS, but it was all about before ES6, I list different ways of copying an object in JavaScript below, imagine you have the Object below and would like to have a deep copy of that:</p>\n<pre><code>var obj = {a:1, b:2, c:3, d:4};\n</code></pre>\n<p>There are few ways to copy this object, without changing the origin:</p>\n<ol>\n<li><p>ES5+, Using a simple function to do the copy for you:</p>\n<pre><code>function deepCopyObj(obj) {\n if (null == obj || "object" != typeof obj) return obj;\n if (obj instanceof Date) {\n var copy = new Date();\n copy.setTime(obj.getTime());\n return copy;\n }\n if (obj instanceof Array) {\n var copy = [];\n for (var i = 0, len = obj.length; i < len; i++) {\n copy[i] = deepCopyObj(obj[i]);\n }\n return copy;\n }\n if (obj instanceof Object) {\n var copy = {};\n for (var attr in obj) {\n if (obj.hasOwnProperty(attr)) copy[attr] = deepCopyObj(obj[attr]);\n }\n return copy;\n }\n throw new Error("Unable to copy obj this object.");\n}\n</code></pre>\n</li>\n<li><p>ES5+, using <code>JSON.parse</code> and <code>JSON.stringify</code>.</p>\n<pre><code>var deepCopyObj = JSON.parse(JSON.stringify(obj));\n</code></pre>\n</li>\n<li><p>Angular:</p>\n<pre><code>var deepCopyObj = angular.copy(obj);\n</code></pre>\n</li>\n<li><p>jQuery:</p>\n<pre><code>var deepCopyObj = jQuery.extend(true, {}, obj);\n</code></pre>\n</li>\n<li><p>Underscore.js & Lodash:</p>\n<pre><code>var deepCopyObj = _.cloneDeep(obj); //latest version of Underscore.js makes shallow copy\n</code></pre>\n</li>\n</ol>\n<p>Hope these help…</p>\n"
},
{
"answer_id": 43235072,
"author": "Redu",
"author_id": 4543207,
"author_profile": "https://Stackoverflow.com/users/4543207",
"pm_score": 2,
"selected": false,
"text": "<p>Without touching the prototypical inheritance you may deep lone objects and arrays 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>function objectClone(o){\r\n var ot = Array.isArray(o);\r\n return o !== null && typeof o === \"object\" ? Object.keys(o)\r\n .reduce((r,k) => o[k] !== null && typeof o[k] === \"object\" ? (r[k] = objectClone(o[k]),r)\r\n : (r[k] = o[k],r), ot ? [] : {})\r\n : o;\r\n}\r\nvar obj = {a: 1, b: {c: 2, d: {e: 3, f: {g: 4, h: null}}}},\r\n arr = [1,2,[3,4,[5,6,[7]]]],\r\n nil = null,\r\n clobj = objectClone(obj),\r\n clarr = objectClone(arr),\r\n clnil = objectClone(nil);\r\nconsole.log(clobj, obj === clobj);\r\nconsole.log(clarr, arr === clarr);\r\nconsole.log(clnil, nil === clnil);\r\nclarr[2][2][2] = \"seven\";\r\nconsole.log(arr, clarr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 44358642,
"author": "Daniel Barde",
"author_id": 1134317,
"author_profile": "https://Stackoverflow.com/users/1134317",
"pm_score": 3,
"selected": false,
"text": "<p>Lodash has a function that handles that for you like so.</p>\n\n<pre><code>var foo = {a: 'a', b: {c:'d', e: {f: 'g'}}};\n\nvar bar = _.cloneDeep(foo);\n// bar = {a: 'a', b: {c:'d', e: {f: 'g'}}} \n</code></pre>\n\n<p>Read the docs <a href=\"https://lodash.com/docs/#cloneDeep\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 44612374,
"author": "prograhammer",
"author_id": 1110941,
"author_profile": "https://Stackoverflow.com/users/1110941",
"pm_score": 4,
"selected": false,
"text": "<p>I disagree with the answer with the greatest votes <a href=\"https://stackoverflow.com/a/5344074/1110941\">here</a>. A <strong>Recursive Deep Clone</strong> is <strong>much faster</strong> than the <em>JSON.parse(JSON.stringify(obj))</em> approach mentioned. </p>\n\n<ul>\n<li><strong>Jsperf</strong> ranks it number one here: <a href=\"https://jsperf.com/deep-copy-vs-json-stringify-json-parse/5\" rel=\"noreferrer\">https://jsperf.com/deep-copy-vs-json-stringify-json-parse/5</a></li>\n<li><strong>Jsben</strong> from the answer above updated to show that a recursive deep clone beats all the others mentioned: <a href=\"http://jsben.ch/13YKQ\" rel=\"noreferrer\">http://jsben.ch/13YKQ</a></li>\n</ul>\n\n<p>And here's the function for quick reference:</p>\n\n<pre><code>function cloneDeep (o) {\n let newO\n let i\n\n if (typeof o !== 'object') return o\n\n if (!o) return o\n\n if (Object.prototype.toString.apply(o) === '[object Array]') {\n newO = []\n for (i = 0; i < o.length; i += 1) {\n newO[i] = cloneDeep(o[i])\n }\n return newO\n }\n\n newO = {}\n for (i in o) {\n if (o.hasOwnProperty(i)) {\n newO[i] = cloneDeep(o[i])\n }\n }\n return newO\n}\n</code></pre>\n"
},
{
"answer_id": 45706299,
"author": "JTeam",
"author_id": 3714376,
"author_profile": "https://Stackoverflow.com/users/3714376",
"pm_score": 1,
"selected": false,
"text": "<p>As this question is having lot of attention and answers with reference to inbuilt features such as Object.assign or custom code to deep clone, i would like to share some libraries to deep clone, </p>\n\n<p><strong>1. esclone</strong></p>\n\n<p>npm install --savedev esclone <a href=\"https://www.npmjs.com/package/esclone\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/esclone</a></p>\n\n<p>Example use in ES6:</p>\n\n<pre><code>import esclone from \"esclone\";\n\nconst rockysGrandFather = {\n name: \"Rockys grand father\",\n father: \"Don't know :(\"\n};\nconst rockysFather = {\n name: \"Rockys Father\",\n father: rockysGrandFather\n};\n\nconst rocky = {\n name: \"Rocky\",\n father: rockysFather\n};\n\nconst rockyClone = esclone(rocky);\n</code></pre>\n\n<p>Example use in ES5:</p>\n\n<pre><code>var esclone = require(\"esclone\")\nvar foo = new String(\"abcd\")\nvar fooClone = esclone.default(foo)\nconsole.log(fooClone)\nconsole.log(foo === fooClone)\n</code></pre>\n\n<p><strong>2. deep copy</strong></p>\n\n<p>npm install deep-copy\n<a href=\"https://www.npmjs.com/package/deep-copy\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/deep-copy</a></p>\n\n<p>Example:</p>\n\n<pre><code>var dcopy = require('deep-copy')\n\n// deep copy object \nvar copy = dcopy({a: {b: [{c: 5}]}})\n\n// deep copy array \nvar copy = dcopy([1, 2, {a: {b: 5}}])\n</code></pre>\n\n<p><strong>3. clone-deep</strong></p>\n\n<p>$ npm install --save clone-deep\n<a href=\"https://www.npmjs.com/package/clone-deep\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/clone-deep</a></p>\n\n<p>Example:</p>\n\n<pre><code>var cloneDeep = require('clone-deep');\n\nvar obj = {a: 'b'};\nvar arr = [obj];\n\nvar copy = cloneDeep(arr);\nobj.c = 'd';\n\nconsole.log(copy);\n//=> [{a: 'b'}] \n\nconsole.log(arr);\n</code></pre>\n"
},
{
"answer_id": 46132039,
"author": "shobhit1",
"author_id": 3711475,
"author_profile": "https://Stackoverflow.com/users/3711475",
"pm_score": 3,
"selected": false,
"text": "<p>There are so many ways to achieve this, but if you want to do this without any library, you can use the following:</p>\n\n<pre><code>const cloneObject = (oldObject) => {\n let newObject = oldObject;\n if (oldObject && typeof oldObject === 'object') {\n if(Array.isArray(oldObject)) {\n newObject = [];\n } else if (Object.prototype.toString.call(oldObject) === '[object Date]' && !isNaN(oldObject)) {\n newObject = new Date(oldObject.getTime());\n } else {\n newObject = {};\n for (let i in oldObject) {\n newObject[i] = cloneObject(oldObject[i]);\n }\n }\n\n }\n return newObject;\n}\n</code></pre>\n\n<p>Let me know what you think.</p>\n"
},
{
"answer_id": 46692810,
"author": "Mayur Agarwal",
"author_id": 5838627,
"author_profile": "https://Stackoverflow.com/users/5838627",
"pm_score": 4,
"selected": false,
"text": "<p>I am late to answer this question, but I have an another way of cloning the object:</p>\n<pre><code>function cloneObject(obj) {\n if (obj === null || typeof(obj) !== 'object')\n return obj;\n var temp = obj.constructor(); // changed\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n obj['isActiveClone'] = null;\n temp[key] = cloneObject(obj[key]);\n delete obj['isActiveClone'];\n }\n }\n return temp;\n}\n\nvar b = cloneObject({"a":1,"b":2}); // calling\n</code></pre>\n<p>which is much better and faster then:</p>\n<pre><code>var a = {"a":1,"b":2};\nvar b = JSON.parse(JSON.stringify(a)); \n</code></pre>\n<p>and</p>\n<pre><code>var a = {"a":1,"b":2};\n\n// Deep copy\nvar newObject = jQuery.extend(true, {}, a);\n</code></pre>\n<p>I have bench-marked the code and you can test the results <a href=\"http://jsben.ch/vyEky\" rel=\"noreferrer\">here</a>:</p>\n<p>and sharing the results:\n<a href=\"https://i.stack.imgur.com/K8ztO.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/K8ztO.png\" alt=\"enter image description here\" /></a>\nReferences: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty</a></p>\n"
},
{
"answer_id": 46759423,
"author": "Julez",
"author_id": 1502014,
"author_profile": "https://Stackoverflow.com/users/1502014",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my way of deep cloning a object with <code>ES2015</code> default value and spread operator</p>\n\n<pre><code> const makeDeepCopy = (obj, copy = {}) => {\n for (let item in obj) {\n if (typeof obj[item] === 'object') {\n makeDeepCopy(obj[item], copy)\n }\n if (obj.hasOwnProperty(item)) {\n copy = {\n ...obj\n }\n }\n }\n return copy\n}\n</code></pre>\n\n<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 testObj = {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"userId\": {\r\n \"type\": \"string\",\r\n \"chance\": \"guid\"\r\n },\r\n \"emailAddr\": {\r\n \"type\": \"string\",\r\n \"chance\": {\r\n \"email\": {\r\n \"domain\": \"fake.com\"\r\n }\r\n },\r\n \"pattern\": \".+@fake.com\"\r\n }\r\n },\r\n \"required\": [\r\n \"userId\",\r\n \"emailAddr\"\r\n ]\r\n}\r\n\r\nconst makeDeepCopy = (obj, copy = {}) => {\r\n for (let item in obj) {\r\n if (typeof obj[item] === 'object') {\r\n makeDeepCopy(obj[item], copy)\r\n }\r\n if (obj.hasOwnProperty(item)) {\r\n copy = {\r\n ...obj\r\n }\r\n }\r\n }\r\n return copy\r\n}\r\n\r\nconsole.log(makeDeepCopy(testObj))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48360733,
"author": "Константин Ван",
"author_id": 4510033,
"author_profile": "https://Stackoverflow.com/users/4510033",
"pm_score": 2,
"selected": false,
"text": "<p>What about asynchronous object cloning done by a <code>Promise</code>?</p>\n\n<pre><code>async function clone(thingy /**/)\n{\n if(thingy instanceof Promise)\n {\n throw Error(\"This function cannot clone Promises.\");\n }\n return thingy;\n}\n</code></pre>\n"
},
{
"answer_id": 48981290,
"author": "Steve Griffith",
"author_id": 1195361,
"author_profile": "https://Stackoverflow.com/users/1195361",
"pm_score": 2,
"selected": false,
"text": "<p>Looking through this long list of answers nearly all the solutions have been covered except one that I am aware of. This is the list of VANILLA JS ways of deep cloning an object.</p>\n\n<ol>\n<li><p>JSON.parse(JSON.stringify( obj ) );</p></li>\n<li><p>Through history.state with pushState or replaceState</p></li>\n<li><p>Web Notifications API but this has the downside of asking the user for permissions.</p></li>\n<li><p>Doing your own recursive loop through the object to copy each level.</p></li>\n<li><p>The answer I didn't see -> Using ServiceWorkers. The messages (objects) passed back and forth between the page and the ServiceWorker script will be deep clones of any object.</p></li>\n</ol>\n"
},
{
"answer_id": 49497485,
"author": "codeMonkey",
"author_id": 4009972,
"author_profile": "https://Stackoverflow.com/users/4009972",
"pm_score": 3,
"selected": false,
"text": "<p>ES 2017 example:</p>\n\n<pre><code>let objectToCopy = someObj;\nlet copyOfObject = {};\nObject.defineProperties(copyOfObject, Object.getOwnPropertyDescriptors(objectToCopy));\n// copyOfObject will now be the same as objectToCopy\n</code></pre>\n"
},
{
"answer_id": 50937561,
"author": "Parabolord",
"author_id": 9154756,
"author_profile": "https://Stackoverflow.com/users/9154756",
"pm_score": 3,
"selected": false,
"text": "<p>In my experience, a recursive version vastly outperforms <code>JSON.parse(JSON.stringify(obj))</code>. Here is a modernized recursive deep object copy function which can fit on a single line:</p>\n\n<pre><code>function deepCopy(obj) {\n return Object.keys(obj).reduce((v, d) => Object.assign(v, {\n [d]: (obj[d].constructor === Object) ? deepCopy(obj[d]) : obj[d]\n }), {});\n}\n</code></pre>\n\n<p>This is performing around <a href=\"https://www.measurethat.net/Benchmarks/ShowResult/25487\" rel=\"noreferrer\">40 times faster</a> than the <code>JSON.parse...</code> method.</p>\n"
},
{
"answer_id": 51013125,
"author": "Vikram K",
"author_id": 4960055,
"author_profile": "https://Stackoverflow.com/users/4960055",
"pm_score": 2,
"selected": false,
"text": "<p>For a shallow copy there is a great, simple method introduced in ECMAScript2018 standard. It involves the use of <em>Spread Operator</em> :</p>\n\n<pre><code>let obj = {a : \"foo\", b:\"bar\" , c:10 , d:true , e:[1,2,3] };\n\nlet objClone = { ...obj };\n</code></pre>\n\n<p>I have tested it in Chrome browser, both objects are stored in different locations, so changing immediate child values in either will not change the other. Though (in the example) changing a value in <code>e</code> will effect both copies.</p>\n\n<p>This technique is very simple and straight forward. I consider this a true Best Practice for this question once and for all. </p>\n"
},
{
"answer_id": 51357086,
"author": "Jinu Joseph Daniel",
"author_id": 822982,
"author_profile": "https://Stackoverflow.com/users/822982",
"pm_score": 2,
"selected": false,
"text": "<p>Hope this helps.</p>\n\n<pre><code>function deepClone(obj) {\n /*\n * Duplicates an object \n */\n\n var ret = null;\n if (obj !== Object(obj)) { // primitive types\n return obj;\n }\n if (obj instanceof String || obj instanceof Number || obj instanceof Boolean) { // string objecs\n ret = obj; // for ex: obj = new String(\"Spidergap\")\n } else if (obj instanceof Date) { // date\n ret = new obj.constructor();\n } else\n ret = Object.create(obj.constructor.prototype);\n\n var prop = null;\n var allProps = Object.getOwnPropertyNames(obj); //gets non enumerables also\n\n\n var props = {};\n for (var i in allProps) {\n prop = allProps[i];\n props[prop] = false;\n }\n\n for (i in obj) {\n props[i] = i;\n }\n\n //now props contain both enums and non enums \n var propDescriptor = null;\n var newPropVal = null; // value of the property in new object\n for (i in props) {\n prop = obj[i];\n propDescriptor = Object.getOwnPropertyDescriptor(obj, i);\n\n if (Array.isArray(prop)) { //not backward compatible\n prop = prop.slice(); // to copy the array\n } else\n if (prop instanceof Date == true) {\n prop = new prop.constructor();\n } else\n if (prop instanceof Object == true) {\n if (prop instanceof Function == true) { // function\n if (!Function.prototype.clone) {\n Function.prototype.clone = function() {\n var that = this;\n var temp = function tmp() {\n return that.apply(this, arguments);\n };\n for (var ky in this) {\n temp[ky] = this[ky];\n }\n return temp;\n }\n }\n prop = prop.clone();\n\n } else // normal object \n {\n prop = deepClone(prop);\n }\n\n }\n\n newPropVal = {\n value: prop\n };\n if (propDescriptor) {\n /*\n * If property descriptors are there, they must be copied\n */\n newPropVal.enumerable = propDescriptor.enumerable;\n newPropVal.writable = propDescriptor.writable;\n\n }\n if (!ret.hasOwnProperty(i)) // when String or other predefined objects\n Object.defineProperty(ret, i, newPropVal); // non enumerable\n\n }\n return ret;\n}\n</code></pre>\n\n<p><a href=\"https://github.com/jinujd/Javascript-Deep-Clone\" rel=\"nofollow noreferrer\">https://github.com/jinujd/Javascript-Deep-Clone</a></p>\n"
},
{
"answer_id": 51741812,
"author": "Tính Ngô Quang",
"author_id": 2949104,
"author_profile": "https://Stackoverflow.com/users/2949104",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Deep copying objects in JavaScript (I think the best and the simplest)</strong></p>\n\n<p><strong>1. Using JSON.parse(JSON.stringify(object));</strong></p>\n\n<pre><code>var obj = { \n a: 1,\n b: { \n c: 2\n }\n}\nvar newObj = JSON.parse(JSON.stringify(obj));\nobj.b.c = 20;\nconsole.log(obj); // { a: 1, b: { c: 20 } }\nconsole.log(newObj); // { a: 1, b: { c: 2 } } \n</code></pre>\n\n<p><strong>2.Using created method</strong></p>\n\n<pre><code>function cloneObject(obj) {\n var clone = {};\n for(var i in obj) {\n if(obj[i] != null && typeof(obj[i])==\"object\")\n clone[i] = cloneObject(obj[i]);\n else\n clone[i] = obj[i];\n }\n return clone;\n}\n\nvar obj = { \n a: 1,\n b: { \n c: 2\n }\n}\nvar newObj = cloneObject(obj);\nobj.b.c = 20;\n\nconsole.log(obj); // { a: 1, b: { c: 20 } }\nconsole.log(newObj); // { a: 1, b: { c: 2 } } \n</code></pre>\n\n<p><strong>3. Using Lo-Dash's _.cloneDeep</strong> link <a href=\"https://lodash.com/docs/4.17.10#cloneDeep\" rel=\"noreferrer\">lodash</a></p>\n\n<pre><code>var obj = { \n a: 1,\n b: { \n c: 2\n }\n}\n\nvar newObj = _.cloneDeep(obj);\nobj.b.c = 20;\nconsole.log(obj); // { a: 1, b: { c: 20 } }\nconsole.log(newObj); // { a: 1, b: { c: 2 } } \n</code></pre>\n\n<p><strong>4. Using Object.assign() method</strong></p>\n\n<pre><code>var obj = { \n a: 1,\n b: 2\n}\n\nvar newObj = _.clone(obj);\nobj.b = 20;\nconsole.log(obj); // { a: 1, b: 20 }\nconsole.log(newObj); // { a: 1, b: 2 } \n</code></pre>\n\n<p><strong>BUT WRONG WHEN</strong></p>\n\n<pre><code>var obj = { \n a: 1,\n b: { \n c: 2\n }\n}\n\nvar newObj = Object.assign({}, obj);\nobj.b.c = 20;\nconsole.log(obj); // { a: 1, b: { c: 20 } }\nconsole.log(newObj); // { a: 1, b: { c: 20 } } --> WRONG\n// Note: Properties on the prototype chain and non-enumerable properties cannot be copied.\n</code></pre>\n\n<p><strong>5.Using Underscore.js _.clone</strong> link <a href=\"https://underscorejs.org/#clone\" rel=\"noreferrer\">Underscore.js</a></p>\n\n<pre><code>var obj = { \n a: 1,\n b: 2\n}\n\nvar newObj = _.clone(obj);\nobj.b = 20;\nconsole.log(obj); // { a: 1, b: 20 }\nconsole.log(newObj); // { a: 1, b: 2 } \n</code></pre>\n\n<p><strong>BUT WRONG WHEN</strong></p>\n\n<pre><code>var obj = { \n a: 1,\n b: { \n c: 2\n }\n}\n\nvar newObj = _.cloneDeep(obj);\nobj.b.c = 20;\nconsole.log(obj); // { a: 1, b: { c: 20 } }\nconsole.log(newObj); // { a: 1, b: { c: 20 } } --> WRONG\n// (Create a shallow-copied clone of the provided plain object. Any nested objects or arrays will be copied by reference, not duplicated.)\n</code></pre>\n\n<p><strong>JSBEN.CH Performance Benchmarking Playground 1~3 <a href=\"http://jsben.ch/KVQLd\" rel=\"noreferrer\">http://jsben.ch/KVQLd</a></strong>\n<a href=\"https://i.stack.imgur.com/Assgk.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Assgk.png\" alt=\"Performance Deep copying objects in JavaScript\"></a></p>\n"
},
{
"answer_id": 51982744,
"author": "Prasanth Jaya",
"author_id": 2148827,
"author_profile": "https://Stackoverflow.com/users/2148827",
"pm_score": 2,
"selected": false,
"text": "<p>When your object is nested and it contains data object, other structured object or some property object, etc then using <code>JSON.parse(JSON.stringify(object))</code> or <code>Object.assign({}, obj)</code> or <code>$.extend(true, {}, obj)</code> will not work. In that case use lodash. It is simple and easy..</p>\n\n<pre><code>var obj = {a: 25, b: {a: 1, b: 2}, c: new Date(), d: anotherNestedObject };\nvar A = _.cloneDeep(obj);\n</code></pre>\n\n<p>Now A will be your new cloned of obj without any references.. </p>\n"
},
{
"answer_id": 52736806,
"author": "shunryu111",
"author_id": 2630316,
"author_profile": "https://Stackoverflow.com/users/2630316",
"pm_score": 2,
"selected": false,
"text": "<p>if you find yourself doing this type of thing regular ( eg- creating undo redo functionality ) it might be worth looking into <a href=\"https://facebook.github.io/immutable-js/\" rel=\"nofollow noreferrer\">Immutable.js</a></p>\n\n<pre><code>const map1 = Immutable.fromJS( { a: 1, b: 2, c: { d: 3 } } );\nconst map2 = map1.setIn( [ 'c', 'd' ], 50 );\n\nconsole.log( `${ map1.getIn( [ 'c', 'd' ] ) } vs ${ map2.getIn( [ 'c', 'd' ] ) }` ); // \"3 vs 50\"\n</code></pre>\n\n<p><a href=\"https://codepen.io/anon/pen/OBpqNE?editors=1111\" rel=\"nofollow noreferrer\">https://codepen.io/anon/pen/OBpqNE?editors=1111</a></p>\n"
},
{
"answer_id": 53151804,
"author": "chandan gupta",
"author_id": 8869104,
"author_profile": "https://Stackoverflow.com/users/8869104",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>In JavaScript, you can write your <code>deepCopy</code> method like </p>\n</blockquote>\n\n<pre><code>function deepCopy(src) {\n let target = Array.isArray(src) ? [] : {};\n for (let prop in src) {\n let value = src[prop];\n if(value && typeof value === 'object') {\n target[prop] = deepCopy(value);\n } else {\n target[prop] = value;\n }\n }\n return target;\n}\n</code></pre>\n"
},
{
"answer_id": 54526566,
"author": "Mystical",
"author_id": 6368005,
"author_profile": "https://Stackoverflow.com/users/6368005",
"pm_score": 0,
"selected": false,
"text": "<p>How about merging the <i>keys</i> of the object with its <i>values</i>?</p>\n\n<pre><code>function deepClone(o) {\n var keys = Object.keys(o);\n var values = Object.values(o);\n\n var clone = {};\n\n keys.forEach(function(key, i) {\n clone[key] = typeof values[i] == 'object' ? Object.create(values[i]) : values[i];\n });\n\n return clone;\n}\n</code></pre>\n\n<p><strong>Note:</strong> <em>This method doesn't necessarily make shallow copies</em>, but it only copies with the depth of one inner-object, meaning that when you are given something like <code>{a: {b: {c: null}}}</code>, it will only clone the objects that are directly inside of them, so <code>deepClone(a.b).c</code> is technically a reference to <code>a.b.c</code>, while <code>deepClone(a).b</code> is a clone, <em>not a reference</em>.</p>\n"
},
{
"answer_id": 54535859,
"author": "shakthi nagaraj",
"author_id": 7241090,
"author_profile": "https://Stackoverflow.com/users/7241090",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function clone(obj) {\n var copy;\n\n // Handle the 3 simple types, and null or undefined\n if (null == obj || \"object\" != typeof obj) return obj;\n\n // Handle Date\n if (obj instanceof Date) {\n copy = new Date();\n copy.setTime(obj.getTime());\n return copy;\n }\n\n // Handle Array\n if (obj instanceof Array) {\n copy = [];\n for (var i = 0, len = obj.length; i < len; i++) {\n copy[i] = clone(obj[i]);\n }\n return copy;\n }\n\n // Handle Object\n if (obj instanceof Object) {\n copy = {};\n for (var attr in obj) {\n if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);\n }\n return copy;\n }\n\n throw new Error(\"Unable to copy obj! Its type isn't supported.\");\n}\n</code></pre>\n\n<p>use the following method instead of <code>JSON.parse(JSON.stringify(obj))</code> because \nit is slower than the following method </p>\n\n<p><a href=\"https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object\">How do I correctly clone a JavaScript object?</a></p>\n"
},
{
"answer_id": 55701165,
"author": "Shidersz",
"author_id": 10366495,
"author_profile": "https://Stackoverflow.com/users/10366495",
"pm_score": 2,
"selected": false,
"text": "<p>With the proposal of the new method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries\" rel=\"nofollow noreferrer\">Object.fromEntries()</a> that is supported on newer versions of some browsers (<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries#Browser_compatibility\" rel=\"nofollow noreferrer\">reference</a>). I want to contribute with the next recursive approach:</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>const obj = {\r\n key1: {key11: \"key11\", key12: \"key12\", key13: {key131: 22}},\r\n key2: {key21: \"key21\", key22: \"key22\"},\r\n key3: \"key3\",\r\n key4: [1,2,3, {key: \"value\"}]\r\n}\r\n\r\nconst cloneObj = (obj) =>\r\n{\r\n if (Object(obj) !== obj)\r\n return obj;\r\n else if (Array.isArray(obj))\r\n return obj.map(cloneObj);\r\n\r\n return Object.fromEntries(Object.entries(obj).map(\r\n ([k,v]) => ([k, cloneObj(v)])\r\n ));\r\n}\r\n\r\n// Clone the original object.\r\nlet newObj = cloneObj(obj);\r\n\r\n// Make changes on the original object.\r\nobj.key1.key11 = \"TEST\";\r\nobj.key3 = \"TEST\";\r\nobj.key1.key13.key131 = \"TEST\";\r\nobj.key4[1] = \"TEST\";\r\nobj.key4[3].key = \"TEST\";\r\n\r\n// Display both objects on the console.\r\nconsole.log(\"Original object: \", obj);\r\nconsole.log(\"Cloned object: \", newObj);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console {background-color:black !important; color:lime;}\r\n.as-console-wrapper {max-height:100% !important; top:0;}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 56207766,
"author": "Kamyar",
"author_id": 3281955,
"author_profile": "https://Stackoverflow.com/users/3281955",
"pm_score": 2,
"selected": false,
"text": "<p>My scenario was a bit different. I had an object with nested objects as well as functions. Therefore, <code>Object.assign()</code> and <code>JSON.stringify()</code> were not solutions to my problem. Using third-party libraries was not an option for me neither.</p>\n\n<p>Hence, I decided to make a simple function to use built-in methods to copy an object with its literal properties, its nested objects, and functions.</p>\n\n<pre><code>let deepCopy = (target, source) => {\n Object.assign(target, source);\n // check if there's any nested objects\n Object.keys(source).forEach((prop) => {\n /**\n * assign function copies functions and\n * literals (int, strings, etc...)\n * except for objects and arrays, so:\n */\n if (typeof(source[prop]) === 'object') {\n // check if the item is, in fact, an array\n if (Array.isArray(source[prop])) {\n // clear the copied referenece of nested array\n target[prop] = Array();\n // iterate array's item and copy over\n source[prop].forEach((item, index) => {\n // array's items could be objects too!\n if (typeof(item) === 'object') {\n // clear the copied referenece of nested objects\n target[prop][index] = Object();\n // and re do the process for nested objects\n deepCopy(target[prop][index], item);\n } else {\n target[prop].push(item);\n }\n });\n // otherwise, treat it as an object\n } else {\n // clear the copied referenece of nested objects\n target[prop] = Object();\n // and re do the process for nested objects\n deepCopy(target[prop], source[prop]);\n }\n }\n });\n};\n</code></pre>\n\n<p>Here's a test code:</p>\n\n<pre><code>let a = {\n name: 'Human', \n func: () => {\n console.log('Hi!');\n }, \n prop: {\n age: 21, \n info: {\n hasShirt: true, \n hasHat: false\n }\n },\n mark: [89, 92, { exam: [1, 2, 3] }]\n};\n\nlet b = Object();\n\ndeepCopy(b, a);\n\na.name = 'Alien';\na.func = () => { console.log('Wassup!'); };\na.prop.age = 1024;\na.prop.info.hasShirt = false;\na.mark[0] = 87;\na.mark[1] = 91;\na.mark[2].exam = [4, 5, 6];\n\nconsole.log(a); // updated props\nconsole.log(b);\n</code></pre>\n\n<p>For efficiency-related concerns, I believe this is the simplest and most efficient solution to the problem I had. I would appreciate any comments on this algorithm that could make it more efficient.</p>\n"
},
{
"answer_id": 56336059,
"author": "KRIPA SHANKAR JHA",
"author_id": 9249953,
"author_profile": "https://Stackoverflow.com/users/9249953",
"pm_score": 3,
"selected": false,
"text": "<p><code>Object.assign({},sourceObj)</code> only clones the object if their property is not having reference type key.\nex </p>\n\n<pre><code>obj={a:\"lol\",b:[\"yes\",\"no\",\"maybe\"]}\nclonedObj = Object.assign({},obj);\n\nclonedObj.b.push(\"skip\")// changes will reflected to the actual obj as well because of its reference type.\nobj.b //will also console => yes,no,maybe,skip\n</code></pre>\n\n<p>So for the deep cloning is not possible to achieve in this way.</p>\n\n<p>The best solution that works is</p>\n\n<pre><code>var obj = Json.stringify(yourSourceObj)\nvar cloned = Json.parse(obj);\n</code></pre>\n"
},
{
"answer_id": 57340254,
"author": "Ankur Kedia",
"author_id": 6419016,
"author_profile": "https://Stackoverflow.com/users/6419016",
"pm_score": 2,
"selected": false,
"text": "<p>This is my solution without using any library or native javascript function.</p>\n\n<pre><code>function deepClone(obj) {\n if (typeof obj !== \"object\") {\n return obj;\n } else {\n let newObj =\n typeof obj === \"object\" && obj.length !== undefined ? [] : {};\n for (let key in obj) {\n if (key) {\n newObj[key] = deepClone(obj[key]);\n }\n }\n return newObj;\n }\n}\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12694/"
] |
What is the most efficient way to clone a JavaScript object? I've seen `obj = eval(uneval(o));` being used, but [that's non-standard and only supported by Firefox](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval).
I've done things like `obj = JSON.parse(JSON.stringify(o));` but question the efficiency.
I've also seen recursive copying functions with various flaws.
I'm surprised no canonical solution exists.
|
Native deep cloning
===================
There's now a JS standard called ["structured cloning"](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone), that works experimentally in Node 11 and later, will land in browsers, and which has [polyfills for existing systems](https://www.npmjs.com/package/@ungap/structured-clone).
```
structuredClone(value)
```
If needed, loading the polyfill first:
```
import structuredClone from '@ungap/structured-clone';
```
See [this answer](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/10916838#10916838) for more details.
Older answers
=============
Fast cloning with data loss - JSON.parse/stringify
--------------------------------------------------
If you do not use `Date`s, functions, `undefined`, `Infinity`, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, a very simple one liner to deep clone an object is:
`JSON.parse(JSON.stringify(object))`
```js
const a = {
string: 'string',
number: 123,
bool: false,
nul: null,
date: new Date(), // stringified
undef: undefined, // lost
inf: Infinity, // forced to 'null'
re: /.*/, // lost
}
console.log(a);
console.log(typeof a.date); // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);
console.log(typeof clone.date); // result of .toISOString()
```
See [Corban's answer](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/5344074#5344074) for benchmarks.
Reliable cloning using a library
--------------------------------
Since cloning objects is not trivial (complex types, circular references, function etc.), most major libraries provide function to clone objects. **Don't reinvent the wheel** - if you're already using a library, check if it has an object cloning function. For example,
* lodash - [`cloneDeep`](https://lodash.com/docs#cloneDeep); can be imported separately via the [lodash.clonedeep](https://www.npmjs.com/package/lodash.clonedeep) module and is probably your best choice if you're not already using a library that provides a deep cloning function
* AngularJS - [`angular.copy`](https://docs.angularjs.org/api/ng/function/angular.copy)
* jQuery - [`jQuery.extend(true, { }, oldObject)`](https://api.jquery.com/jquery.extend/#jQuery-extend-deep-target-object1-objectN); `.clone()` only clones DOM elements
* just library - [`just-clone`](https://www.npmjs.com/package/just-clone); Part of a library of zero-dependency npm modules that do just do one thing.
Guilt-free utilities for every occasion.
|
122,104 |
<p>Say I have a page that display search results. I search for stackoverflow and it returns 5000 results, 10 per page. Now I find myself doing this when building links on that page:</p>
<pre><code><%=Html.ActionLink("Page 1", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Page 2", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Page 3", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Next", "Search", new { query=ViewData["query"], page etc..%>
</code></pre>
<p>I dont like this, I have to build my links with careful consideration to what was posted previously etc.. </p>
<p>What I'd like to do is</p>
<pre><code><%=Html.BuildActionLinkUsingCurrentActionPostData
("Next", "Search", new { Page = 1});
</code></pre>
<p>where the anonymous dictionary overrides anything currently set by previous action. </p>
<p>Essentially I care about what the previous action parameters were, because I want to reuse, it sounds simple, but start adding sort and loads of advance search options and it starts getting messy.</p>
<p>Im probably missing something obvious</p>
|
[
{
"answer_id": 122439,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 1,
"selected": false,
"text": "<p>Whenever you find yourself writing redundant code in your Views, <a href=\"http://blog.wekeroad.com/blog/asp-net-mvc-avoiding-tag-soup/\" rel=\"nofollow noreferrer\">write a helper</a>. The helper could explicitly copy the parameters, as you're doing it now, or it could iterate the entire collection and copy automatically. If it were me, I would probably choose the former. Then you can just call your new helper, instead of rebuilding the parameters every time you make a link.</p>\n"
},
{
"answer_id": 123454,
"author": "Switters",
"author_id": 1860358,
"author_profile": "https://Stackoverflow.com/users/1860358",
"pm_score": 1,
"selected": false,
"text": "<p>I'm a little iffy as to what you are actually trying to do here. I think you are trying to automate the process of creating a list of links with only small changes between them. Apparently in your case the id number of \"Page\". </p>\n\n<p>One way to do it, although possibly not the best is like so (My code makes use of a basic and contrived Product list and the ViewPage and PartialViewPage both use Strongly Typed Models):</p>\n\n<p>On your ViewPage you would add code like this:</p>\n\n<pre><code><div id=\"product_list\">\n <% foreach (TestMVC.Product product in ViewData.Model)\n { %>\n <% Html.RenderPartial(\"ProductEntry\", product); %>\n <% } %>\n</div>\n</code></pre>\n\n<p>Your Partial View, in my case \"ProductEntry\", would then look like this:</p>\n\n<pre><code><div class=\"product\">\n <div class=\"product-name\">\n <%= Html.ActionLink(ViewData.Model.ProductName, \"Detail\", new { id = ViewData.Model.id })%>\n </div> \n <div class=\"product-desc\">\n <%= ViewData.Model.ProductDescription %>\n </div> \n</div>\n</code></pre>\n\n<p>All I'm doing in that Partial View is consuming the model/viewdata that was passed from the parent view by the call to Html.RenderPartial</p>\n\n<p>In your parent view you could modify a parameter on your model object before the call to Html.RenderPartial in order to set the specific value you are interested in.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 1228074,
"author": "Daniel Chambers",
"author_id": 107512,
"author_profile": "https://Stackoverflow.com/users/107512",
"pm_score": 4,
"selected": false,
"text": "<p>I had a similar problem inside an HtmlHelper; I wanted to generate links that linked backed to the current page, with a small adjustment in parameters (think incrementing the page number). So if I had URL /Item/?sort=Name&page=0, I wanted to be able to create links to the same page, but just change the page parameter, and have the sort parameter automatically included (ie /Item/?sort=Name&page=1).</p>\n\n<p>My solution was this (for use in an HtmlHelper extension method, but since you can access the same data almost anywhere in MVC, you can adapt it easily to your uses):</p>\n\n<pre><code>private static RouteValueDictionary CreateRouteToCurrentPage(HtmlHelper html)\n{\n RouteValueDictionary routeValues \n = new RouteValueDictionary(html.ViewContext.RouteData.Values);\n\n NameValueCollection queryString \n = html.ViewContext.HttpContext.Request.QueryString;\n\n foreach (string key in queryString.Cast<string>())\n {\n routeValues[key] = queryString[key];\n }\n\n return routeValues;\n}\n</code></pre>\n\n<p>What the method does is take the RouteValueDictionary for the current request and create a copy of it. Then it adds each of the query parameters found in the query string to this route. It does this because, for some reason, the current request's RouteValueDictionary does not contain them (you'd think it would, but it doesn't).</p>\n\n<p>You can then take the resultant dictionary, modify only a part of it, for example:</p>\n\n<pre><code>routeValues[\"page\"] = 2;\n</code></pre>\n\n<p>and then give that dictionary to the out-of-the-box HtmlHelper methods for them to generate you a URL/etc.</p>\n"
},
{
"answer_id": 1582050,
"author": "Jalal El-Shaer",
"author_id": 95380,
"author_profile": "https://Stackoverflow.com/users/95380",
"pm_score": 1,
"selected": false,
"text": "<p>Following helper method does just that :</p>\n\n<pre><code> public static string EnhancedActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, bool keepQueryStrings)\n {\n ViewContext context = helper.ViewContext;\n IDictionary<string, object> htmlAttributes = null;\n RouteValueDictionary routeValues = null;\n string actionLink = string.Empty;\n if (keepQueryStrings && context.RequestContext.HttpContext.Request.QueryString.Keys.Count > 0)\n {\n routeValues = new RouteValueDictionary(context.RouteData.Values);\n foreach (string key in context.RequestContext.HttpContext.Request.QueryString.Keys)\n {\n routeValues[key] = context.RequestContext.HttpContext.Request.QueryString[key];\n }\n } \n actionLink = helper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes);\n return actionLink;\n }\n</code></pre>\n"
},
{
"answer_id": 4345930,
"author": "Florin Gugui",
"author_id": 529414,
"author_profile": "https://Stackoverflow.com/users/529414",
"pm_score": 0,
"selected": false,
"text": "<p>take a look on this, it's a good example:\n<a href=\"http://nerddinnerbook.s3.amazonaws.com/Part8.htm\" rel=\"nofollow\">http://nerddinnerbook.s3.amazonaws.com/Part8.htm</a></p>\n"
},
{
"answer_id": 6339432,
"author": "Ziad",
"author_id": 144227,
"author_profile": "https://Stackoverflow.com/users/144227",
"pm_score": 0,
"selected": false,
"text": "<p>After hours spent trying different solutions only this one worked for me:\n<a href=\"https://stackoverflow.com/questions/3779932/mvc-actionlink-add-all-optional-paramters-from-current-url\">MVC ActionLink add all (optional) parameters from current url</a></p>\n"
},
{
"answer_id": 11305841,
"author": "h3n",
"author_id": 182332,
"author_profile": "https://Stackoverflow.com/users/182332",
"pm_score": 0,
"selected": false,
"text": "<p>Here's the actionlink extension</p>\n\n<pre>\n<code>\n public static class ActionLinkExtension\n {\n public static MvcHtmlString ActionLinkWithQueryString(this HtmlHelper helper, string linkText, string action, string controller, object routeValues)\n {\n var context = helper.ViewContext;\n\n var currentRouteValues = new RouteValueDictionary(context.RouteData.Values);\n foreach (string key in context.HttpContext.Request.QueryString.Keys)\n {\n currentRouteValues[key] = context.HttpContext.Request.QueryString[key];\n }\n\n var newRouteValues = new RouteValueDictionary(routeValues);\n\n foreach (var route in newRouteValues)\n {\n if (!currentRouteValues.ContainsKey(route.Key))\n {\n currentRouteValues.Add(route.Key, route.Value);\n }\n else\n {\n currentRouteValues[route.Key] = route.Value;\n }\n }\n\n return helper.ActionLink(linkText, action, controller, currentRouteValues, null);\n }\n\n }\n</code>\n</pre>\n"
},
{
"answer_id": 11505239,
"author": "Mr Jones",
"author_id": 1480976,
"author_profile": "https://Stackoverflow.com/users/1480976",
"pm_score": 0,
"selected": false,
"text": "<p>Not exactly an answer, but worth pointing out: If you want paging functionality, use the PagedList Nuget package (No need to re-invent the wheel). The following link provides a really nice example of how to use it: <a href=\"http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application\" rel=\"nofollow\">ASP.NET Tutorial</a></p>\n\n<p>This is especially useful to you because query strings are saved in the URL when switching between pages.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Say I have a page that display search results. I search for stackoverflow and it returns 5000 results, 10 per page. Now I find myself doing this when building links on that page:
```
<%=Html.ActionLink("Page 1", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Page 2", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Page 3", "Search", new { query=ViewData["query"], page etc..%>
<%=Html.ActionLink("Next", "Search", new { query=ViewData["query"], page etc..%>
```
I dont like this, I have to build my links with careful consideration to what was posted previously etc..
What I'd like to do is
```
<%=Html.BuildActionLinkUsingCurrentActionPostData
("Next", "Search", new { Page = 1});
```
where the anonymous dictionary overrides anything currently set by previous action.
Essentially I care about what the previous action parameters were, because I want to reuse, it sounds simple, but start adding sort and loads of advance search options and it starts getting messy.
Im probably missing something obvious
|
I had a similar problem inside an HtmlHelper; I wanted to generate links that linked backed to the current page, with a small adjustment in parameters (think incrementing the page number). So if I had URL /Item/?sort=Name&page=0, I wanted to be able to create links to the same page, but just change the page parameter, and have the sort parameter automatically included (ie /Item/?sort=Name&page=1).
My solution was this (for use in an HtmlHelper extension method, but since you can access the same data almost anywhere in MVC, you can adapt it easily to your uses):
```
private static RouteValueDictionary CreateRouteToCurrentPage(HtmlHelper html)
{
RouteValueDictionary routeValues
= new RouteValueDictionary(html.ViewContext.RouteData.Values);
NameValueCollection queryString
= html.ViewContext.HttpContext.Request.QueryString;
foreach (string key in queryString.Cast<string>())
{
routeValues[key] = queryString[key];
}
return routeValues;
}
```
What the method does is take the RouteValueDictionary for the current request and create a copy of it. Then it adds each of the query parameters found in the query string to this route. It does this because, for some reason, the current request's RouteValueDictionary does not contain them (you'd think it would, but it doesn't).
You can then take the resultant dictionary, modify only a part of it, for example:
```
routeValues["page"] = 2;
```
and then give that dictionary to the out-of-the-box HtmlHelper methods for them to generate you a URL/etc.
|
122,105 |
<p>I want to filter a <code>java.util.Collection</code> based on a predicate.</p>
|
[
{
"answer_id": 122128,
"author": "Kevin Wong",
"author_id": 4792,
"author_profile": "https://Stackoverflow.com/users/4792",
"pm_score": 7,
"selected": false,
"text": "<p>Use <a href=\"https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/CollectionUtils.html#filter(java.lang.Iterable,%20org.apache.commons.collections4.Predicate)\" rel=\"noreferrer\">CollectionUtils.filter(Collection,Predicate)</a>, from Apache Commons.</p>\n"
},
{
"answer_id": 122139,
"author": "Heath Borders",
"author_id": 9636,
"author_profile": "https://Stackoverflow.com/users/9636",
"pm_score": 6,
"selected": false,
"text": "<p>Consider <a href=\"http://code.google.com/p/google-collections/\" rel=\"noreferrer\">Google Collections</a> for an updated Collections framework that supports generics.</p>\n\n<p><strong>UPDATE</strong>: The google collections library is now deprecated. You should use the latest release of <a href=\"https://github.com/google/guava\" rel=\"noreferrer\">Guava</a> instead. It still has all the same extensions to the collections framework including a mechanism for filtering based on a predicate.</p>\n"
},
{
"answer_id": 122200,
"author": "ykaganovich",
"author_id": 10026,
"author_profile": "https://Stackoverflow.com/users/10026",
"pm_score": 3,
"selected": false,
"text": "<p>Are you sure you want to filter the Collection itself, rather than an iterator?</p>\n\n<p>see <a href=\"http://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/iterators/FilterIterator.html\" rel=\"nofollow noreferrer\">org.apache.commons.collections.iterators.FilterIterator</a></p>\n\n<p>or using version 4 of apache commons <a href=\"https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/iterators/FilterIterator.html\" rel=\"nofollow noreferrer\">org.apache.commons.collections4.iterators.FilterIterator</a></p>\n"
},
{
"answer_id": 122204,
"author": "jon",
"author_id": 12215,
"author_profile": "https://Stackoverflow.com/users/12215",
"pm_score": 3,
"selected": false,
"text": "<p>The setup:</p>\n\n<pre><code>public interface Predicate<T> {\n public boolean filter(T t);\n}\n\nvoid filterCollection(Collection<T> col, Predicate<T> predicate) {\n for (Iterator i = col.iterator(); i.hasNext();) {\n T obj = i.next();\n if (predicate.filter(obj)) {\n i.remove();\n }\n }\n}\n</code></pre>\n\n<p>The usage:</p>\n\n<pre><code>List<MyObject> myList = ...;\nfilterCollection(myList, new Predicate<MyObject>() {\n public boolean filter(MyObject obj) {\n return obj.shouldFilter();\n }\n});\n</code></pre>\n"
},
{
"answer_id": 122206,
"author": "Vladimir Dyuzhev",
"author_id": 1163802,
"author_profile": "https://Stackoverflow.com/users/1163802",
"pm_score": 6,
"selected": false,
"text": "<p>\"Best\" way is too wide a request. Is it \"shortest\"? \"Fastest\"? \"Readable\"?\nFilter in place or into another collection?</p>\n\n<p>Simplest (but not most readable) way is to iterate it and use Iterator.remove() method:</p>\n\n<pre><code>Iterator<Foo> it = col.iterator();\nwhile( it.hasNext() ) {\n Foo foo = it.next();\n if( !condition(foo) ) it.remove();\n}\n</code></pre>\n\n<p>Now, to make it more readable, you can wrap it into a utility method. Then invent a IPredicate interface, create an anonymous implementation of that interface and do something like:</p>\n\n<pre><code>CollectionUtils.filterInPlace(col,\n new IPredicate<Foo>(){\n public boolean keepIt(Foo foo) {\n return foo.isBar();\n }\n });\n</code></pre>\n\n<p>where filterInPlace() iterate the collection and calls Predicate.keepIt() to learn if the instance to be kept in the collection.</p>\n\n<p>I don't really see a justification for bringing in a third-party library just for this task.</p>\n"
},
{
"answer_id": 122207,
"author": "Alan",
"author_id": 17205,
"author_profile": "https://Stackoverflow.com/users/17205",
"pm_score": 8,
"selected": false,
"text": "<p>Assuming that you are using <a href=\"http://java.sun.com/j2se/1.5.0/docs/index.html\" rel=\"noreferrer\">Java 1.5</a>, and that you cannot add <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"noreferrer\">Google Collections</a>, I would do something very similar to what the Google guys did. This is a slight variation on Jon's comments.</p>\n\n<p>First add this interface to your codebase.</p>\n\n<pre><code>public interface IPredicate<T> { boolean apply(T type); }\n</code></pre>\n\n<p>Its implementers can answer when a certain predicate is true of a certain type. E.g. If <code>T</code> were <code>User</code> and <code>AuthorizedUserPredicate<User></code> implements <code>IPredicate<T></code>, then <code>AuthorizedUserPredicate#apply</code> returns whether the passed in <code>User</code> is authorized.</p>\n\n<p>Then in some utility class, you could say</p>\n\n<pre><code>public static <T> Collection<T> filter(Collection<T> target, IPredicate<T> predicate) {\n Collection<T> result = new ArrayList<T>();\n for (T element: target) {\n if (predicate.apply(element)) {\n result.add(element);\n }\n }\n return result;\n}\n</code></pre>\n\n<p>So, assuming that you have the use of the above might be</p>\n\n<pre><code>Predicate<User> isAuthorized = new Predicate<User>() {\n public boolean apply(User user) {\n // binds a boolean method in User to a reference\n return user.isAuthorized();\n }\n};\n// allUsers is a Collection<User>\nCollection<User> authorizedUsers = filter(allUsers, isAuthorized);\n</code></pre>\n\n<p>If performance on the linear check is of concern, then I might want to have a domain object that has the target collection. The domain object that has the target collection would have filtering logic for the methods that initialize, add and set the target collection.</p>\n\n<p>UPDATE: </p>\n\n<p>In the utility class (let's say Predicate), I have added a select method with an option for default value when the predicate doesn't return the expected value, and also a static property for params to be used inside the new IPredicate.</p>\n\n<pre><code>public class Predicate {\n public static Object predicateParams;\n\n public static <T> Collection<T> filter(Collection<T> target, IPredicate<T> predicate) {\n Collection<T> result = new ArrayList<T>();\n for (T element : target) {\n if (predicate.apply(element)) {\n result.add(element);\n }\n }\n return result;\n }\n\n public static <T> T select(Collection<T> target, IPredicate<T> predicate) {\n T result = null;\n for (T element : target) {\n if (!predicate.apply(element))\n continue;\n result = element;\n break;\n }\n return result;\n }\n\n public static <T> T select(Collection<T> target, IPredicate<T> predicate, T defaultValue) {\n T result = defaultValue;\n for (T element : target) {\n if (!predicate.apply(element))\n continue;\n result = element;\n break;\n }\n return result;\n }\n}\n</code></pre>\n\n<p>The following example looks for missing objects between collections:</p>\n\n<pre><code>List<MyTypeA> missingObjects = (List<MyTypeA>) Predicate.filter(myCollectionOfA,\n new IPredicate<MyTypeA>() {\n public boolean apply(MyTypeA objectOfA) {\n Predicate.predicateParams = objectOfA.getName();\n return Predicate.select(myCollectionB, new IPredicate<MyTypeB>() {\n public boolean apply(MyTypeB objectOfB) {\n return objectOfB.getName().equals(Predicate.predicateParams.toString());\n }\n }) == null;\n }\n });\n</code></pre>\n\n<p>The following example, looks for an instance in a collection, and returns the first element of the collection as default value when the instance is not found:</p>\n\n<pre><code>MyType myObject = Predicate.select(collectionOfMyType, new IPredicate<MyType>() {\npublic boolean apply(MyType objectOfMyType) {\n return objectOfMyType.isDefault();\n}}, collectionOfMyType.get(0));\n</code></pre>\n\n<p>UPDATE (after Java 8 release):</p>\n\n<p>It's been several years since I (Alan) first posted this answer, and I still cannot believe I am collecting SO points for this answer. At any rate, now that Java 8 has introduced closures to the language, my answer would now be considerably different, and simpler. With Java 8, there is no need for a distinct static utility class. So if you want to find the 1st element that matches your predicate.</p>\n\n<pre><code>final UserService userService = ... // perhaps injected IoC\nfinal Optional<UserModel> userOption = userCollection.stream().filter(u -> {\n boolean isAuthorized = userService.isAuthorized(u);\n return isAuthorized;\n}).findFirst();\n</code></pre>\n\n<p>The JDK 8 API for optionals has the ability to <code>get()</code>, <code>isPresent()</code>, <code>orElse(defaultUser)</code>, <code>orElseGet(userSupplier)</code> and <code>orElseThrow(exceptionSupplier)</code>, as well as other 'monadic' functions such as <code>map</code>, <code>flatMap</code> and <code>filter</code>.</p>\n\n<p>If you want to simply collect all the users which match the predicate, then use the <code>Collectors</code> to terminate the stream in the desired collection.</p>\n\n<pre><code>final UserService userService = ... // perhaps injected IoC\nfinal List<UserModel> userOption = userCollection.stream().filter(u -> {\n boolean isAuthorized = userService.isAuthorized(u);\n return isAuthorized;\n}).collect(Collectors.toList());\n</code></pre>\n\n<p>See <a href=\"http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/\" rel=\"noreferrer\">here</a> for more examples on how Java 8 streams work.</p>\n"
},
{
"answer_id": 122773,
"author": "Kevin Wong",
"author_id": 4792,
"author_profile": "https://Stackoverflow.com/users/4792",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Collections2.html#filter%28java.util.Collection,%20com.google.common.base.Predicate%29\" rel=\"nofollow noreferrer\">Collections2.filter(Collection,Predicate)</a> method in <a href=\"http://code.google.com/p/guava-libraries/\" rel=\"nofollow noreferrer\">Google's Guava library</a> does just what you're looking for.</p>\n"
},
{
"answer_id": 337135,
"author": "akuhn",
"author_id": 24468,
"author_profile": "https://Stackoverflow.com/users/24468",
"pm_score": 3,
"selected": false,
"text": "<p>With the ForEach DSL you may write</p>\n\n<pre><code>import static ch.akuhn.util.query.Query.select;\nimport static ch.akuhn.util.query.Query.$result;\nimport ch.akuhn.util.query.Select;\n\nCollection<String> collection = ...\n\nfor (Select<String> each : select(collection)) {\n each.yield = each.value.length() > 3;\n}\n\nCollection<String> result = $result();\n</code></pre>\n\n<p>Given a collection of [The, quick, brown, fox, jumps, over, the, lazy, dog] this results in [quick, brown, jumps, over, lazy], ie all strings longer than three characters.</p>\n\n<p>All iteration styles supported by the ForEach DSL are</p>\n\n<ul>\n<li><code>AllSatisfy</code></li>\n<li><code>AnySatisfy</code></li>\n<li><code>Collect</code></li>\n<li><code>Counnt</code></li>\n<li><code>CutPieces</code></li>\n<li><code>Detect</code></li>\n<li><code>GroupedBy</code></li>\n<li><code>IndexOf</code></li>\n<li><code>InjectInto</code></li>\n<li><code>Reject</code></li>\n<li><code>Select</code></li>\n</ul>\n\n<p>For more details, please refer to <a href=\"https://www.iam.unibe.ch/scg/svn_repos/Sources/ForEach\" rel=\"noreferrer\">https://www.iam.unibe.ch/scg/svn_repos/Sources/ForEach</a></p>\n"
},
{
"answer_id": 1385698,
"author": "Mario Fusco",
"author_id": 112779,
"author_profile": "https://Stackoverflow.com/users/112779",
"pm_score": 11,
"selected": true,
"text": "<p>Java 8 (<a href=\"https://www.oracle.com/java/technologies/javase/8-whats-new.html\" rel=\"noreferrer\" title=\"What's New in JDK 8\">2014</a>) solves this problem using streams and lambdas in one line of code:</p>\n<pre><code>List<Person> beerDrinkers = persons.stream()\n .filter(p -> p.getAge() > 16).collect(Collectors.toList());\n</code></pre>\n<p>Here's a <a href=\"http://zeroturnaround.com/rebellabs/java-8-explained-applying-lambdas-to-java-collections/\" rel=\"noreferrer\" title=\"Java 8 collections and lambdas\">tutorial</a>.</p>\n<p>Use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-\" rel=\"noreferrer\"><code>Collection#removeIf</code></a> to modify the collection in place. (Notice: In this case, the predicate will remove objects who satisfy the predicate):</p>\n<pre><code>persons.removeIf(p -> p.getAge() <= 16);\n</code></pre>\n<hr />\n<p><a href=\"https://code.google.com/archive/p/lambdaj/\" rel=\"noreferrer\">lambdaj</a> allows filtering collections without writing loops or inner classes:</p>\n<pre><code>List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(),\n greaterThan(16)));\n</code></pre>\n<p>Can you imagine something more readable?</p>\n<p><strong>Disclaimer:</strong> I am a contributor on lambdaj</p>\n"
},
{
"answer_id": 2106948,
"author": "jdc0589",
"author_id": 113173,
"author_profile": "https://Stackoverflow.com/users/113173",
"pm_score": 2,
"selected": false,
"text": "<p>This, combined with the lack of real closures, is my biggest gripe for Java.\nHonestly, most of the methods mentioned above are pretty easy to read and REALLY efficient; however, after spending time with .Net, Erlang, etc... list comprehension integrated at the language level makes everything so much cleaner. Without additions at the language level, Java just cant be as clean as many other languages in this area.</p>\n\n<p>If performance is a huge concern, Google collections is the way to go (or write your own simple predicate utility). Lambdaj syntax is more readable for some people, but it is not quite as efficient.</p>\n\n<p>And then there is a library I wrote. I will ignore any questions in regard to its efficiency (yea, its that bad)...... Yes, i know its clearly reflection based, and no I don't actually use it, but it does work:</p>\n\n<pre><code>LinkedList<Person> list = ......\nLinkedList<Person> filtered = \n Query.from(list).where(Condition.ensure(\"age\", Op.GTE, 21));\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<pre><code>LinkedList<Person> list = ....\nLinkedList<Person> filtered = Query.from(list).where(\"x => x.age >= 21\");\n</code></pre>\n"
},
{
"answer_id": 2578408,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote <a href=\"https://github.com/genezys/functional/blob/master/src/main/java/fr/cantor/functional/Iterable.java#L204\" rel=\"nofollow noreferrer\">an extended Iterable class</a> that support applying functional algorithms without copying the collection content.</p>\n\n<p>Usage:</p>\n\n<pre><code>List<Integer> myList = new ArrayList<Integer>(){ 1, 2, 3, 4, 5 }\n\nIterable<Integer> filtered = Iterable.wrap(myList).select(new Predicate1<Integer>()\n{\n public Boolean call(Integer n) throws FunctionalException\n {\n return n % 2 == 0;\n }\n})\n\nfor( int n : filtered )\n{\n System.out.println(n);\n}\n</code></pre>\n\n<p>The code above will actually execute</p>\n\n<pre><code>for( int n : myList )\n{\n if( n % 2 == 0 ) \n {\n System.out.println(n);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10027150,
"author": "Kamran Ali Khan",
"author_id": 1315040,
"author_profile": "https://Stackoverflow.com/users/1315040",
"pm_score": 2,
"selected": false,
"text": "<p>JFilter <a href=\"http://code.google.com/p/jfilter/\" rel=\"nofollow\">http://code.google.com/p/jfilter/</a> is best suited for your requirement.</p>\n\n<p>JFilter is a simple and high performance open source library to query collection of Java beans.</p>\n\n<p>Key features</p>\n\n<ul>\n<li>Support of collection (java.util.Collection, java.util.Map and Array) properties.</li>\n<li>Support of collection inside collection of any depth.</li>\n<li>Support of inner queries.</li>\n<li>Support of parameterized queries.</li>\n<li>Can filter 1 million records in few 100 ms.</li>\n<li>Filter ( query) is given in simple json format, it is like Mangodb queries. Following are some examples.</li>\n<li>{ \"id\":{\"$le\":\"10\"}\n<ul>\n<li>where object id property is less than equals to 10.</li>\n</ul></li>\n<li>{ \"id\": {\"$in\":[\"0\", \"100\"]}}\n<ul>\n<li>where object id property is 0 or 100.</li>\n</ul></li>\n<li>{\"lineItems\":{\"lineAmount\":\"1\"}}\n<ul>\n<li>where lineItems collection property of parameterized type has lineAmount equals to 1.</li>\n</ul></li>\n<li>{ \"$and\":[{\"id\": \"0\"}, {\"billingAddress\":{\"city\":\"DEL\"}}]}\n<ul>\n<li>where id property is 0 and billingAddress.city property is DEL.</li>\n</ul></li>\n<li>{\"lineItems\":{\"taxes\":{ \"key\":{\"code\":\"GST\"}, \"value\":{\"$gt\": \"1.01\"}}}}\n<ul>\n<li>where lineItems collection property of parameterized type which has taxes map type property of parameteriszed type has code equals to GST value greater than 1.01.</li>\n</ul></li>\n<li>{'$or':[{'code':'10'},{'skus': {'$and':[{'price':{'$in':['20', '40']}}, {'code':'RedApple'}]}}]}\n<ul>\n<li>Select all products where product code is 10 or sku price in 20 and 40 and sku code is \"RedApple\".</li>\n</ul></li>\n</ul>\n"
},
{
"answer_id": 11713441,
"author": "npgall",
"author_id": 812018,
"author_profile": "https://Stackoverflow.com/users/812018",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"https://github.com/npgall/cqengine\" rel=\"nofollow noreferrer\">Collection Query Engine (CQEngine)</a>. It is by far the fastest way to do this.</p>\n\n<p>See also: <a href=\"https://stackoverflow.com/a/11712925/812018\">How do you query object collections in Java (Criteria/SQL-like)?</a></p>\n"
},
{
"answer_id": 12573823,
"author": "Donald Raab",
"author_id": 1570415,
"author_profile": "https://Stackoverflow.com/users/1570415",
"pm_score": 3,
"selected": false,
"text": "<p>Let’s look at how to filter a built-in JDK List and a <a href=\"https://www.eclipse.org/collections/javadoc/10.0.0/org/eclipse/collections/api/list/MutableList.html\" rel=\"nofollow noreferrer\">MutableList</a> using <a href=\"https://www.eclipse.org/collections/\" rel=\"nofollow noreferrer\">Eclipse Collections</a>.</p>\n\n<pre><code>List<Integer> jdkList = Arrays.asList(1, 2, 3, 4, 5);\nMutableList<Integer> ecList = Lists.mutable.with(1, 2, 3, 4, 5);\n</code></pre>\n\n<p>If you wanted to filter the numbers less than 3, you would expect the following outputs.</p>\n\n<pre><code>List<Integer> selected = Lists.mutable.with(1, 2);\nList<Integer> rejected = Lists.mutable.with(3, 4, 5);\n</code></pre>\n\n<p>Here’s how you can filter using a Java 8 lambda as the <code>Predicate</code>.</p>\n\n<pre><code>Assert.assertEquals(selected, Iterate.select(jdkList, each -> each < 3));\nAssert.assertEquals(rejected, Iterate.reject(jdkList, each -> each < 3));\n\nAssert.assertEquals(selected, ecList.select(each -> each < 3));\nAssert.assertEquals(rejected, ecList.reject(each -> each < 3));\n</code></pre>\n\n<p>Here’s how you can filter using an anonymous inner class as the <code>Predicate</code>.</p>\n\n<pre><code>Predicate<Integer> lessThan3 = new Predicate<Integer>()\n{\n public boolean accept(Integer each)\n {\n return each < 3;\n }\n};\n\nAssert.assertEquals(selected, Iterate.select(jdkList, lessThan3));\nAssert.assertEquals(selected, ecList.select(lessThan3));\n</code></pre>\n\n<p>Here are some alternatives to filtering JDK lists and <a href=\"https://www.eclipse.org/collections/\" rel=\"nofollow noreferrer\">Eclipse Collections</a> MutableLists using the <a href=\"https://www.eclipse.org/collections/javadoc/10.0.0/org/eclipse/collections/impl/block/factory/Predicates.html\" rel=\"nofollow noreferrer\">Predicates</a> factory.</p>\n\n<pre><code>Assert.assertEquals(selected, Iterate.select(jdkList, Predicates.lessThan(3)));\nAssert.assertEquals(selected, ecList.select(Predicates.lessThan(3)));\n</code></pre>\n\n<p>Here is a version that doesn't allocate an object for the predicate, by using the <a href=\"https://www.eclipse.org/collections/javadoc/10.0.0/org/eclipse/collections/impl/block/factory/Predicates2.html\" rel=\"nofollow noreferrer\">Predicates2</a> factory instead with the <code>selectWith</code> method that takes a <code>Predicate2</code>.</p>\n\n<pre><code>Assert.assertEquals(\n selected, ecList.selectWith(Predicates2.<Integer>lessThan(), 3));\n</code></pre>\n\n<p>Sometimes you want to filter on a negative condition. There is a special method in Eclipse Collections for that called <code>reject</code>.</p>\n\n<pre><code>Assert.assertEquals(rejected, Iterate.reject(jdkList, lessThan3));\nAssert.assertEquals(rejected, ecList.reject(lessThan3));\n</code></pre>\n\n<p>The method <code>partition</code> will return two collections, containing the elements selected by and rejected by the <code>Predicate</code>.</p>\n\n<pre><code>PartitionIterable<Integer> jdkPartitioned = Iterate.partition(jdkList, lessThan3);\nAssert.assertEquals(selected, jdkPartitioned.getSelected());\nAssert.assertEquals(rejected, jdkPartitioned.getRejected());\n\nPartitionList<Integer> ecPartitioned = gscList.partition(lessThan3);\nAssert.assertEquals(selected, ecPartitioned.getSelected());\nAssert.assertEquals(rejected, ecPartitioned.getRejected());\n</code></pre>\n\n<p>Note: I am a committer for Eclipse Collections.</p>\n"
},
{
"answer_id": 18508956,
"author": "gavenkoa",
"author_id": 173149,
"author_profile": "https://Stackoverflow.com/users/173149",
"pm_score": 5,
"selected": false,
"text": "<p>Wait for Java 8:</p>\n\n<pre><code>List<Person> olderThan30 = \n //Create a Stream from the personList\n personList.stream().\n //filter the element to select only those with age >= 30\n filter(p -> p.age >= 30).\n //put those filtered elements into a new List.\n collect(Collectors.toList());\n</code></pre>\n"
},
{
"answer_id": 19623934,
"author": "Josh M",
"author_id": 1255746,
"author_profile": "https://Stackoverflow.com/users/1255746",
"pm_score": 4,
"selected": false,
"text": "<p>Since the early release of Java 8, you could try something like:</p>\n\n<pre><code>Collection<T> collection = ...;\nStream<T> stream = collection.stream().filter(...);\n</code></pre>\n\n<p>For example, if you had a list of integers and you wanted to filter the numbers that are > 10 and then print out those numbers to the console, you could do something like:</p>\n\n<pre><code>List<Integer> numbers = Arrays.asList(12, 74, 5, 8, 16);\nnumbers.stream().filter(n -> n > 10).forEach(System.out::println);\n</code></pre>\n"
},
{
"answer_id": 23601384,
"author": "Nestor Hernandez Loli",
"author_id": 1434175,
"author_profile": "https://Stackoverflow.com/users/1434175",
"pm_score": 3,
"selected": false,
"text": "<p>How about some plain and straighforward Java</p>\n\n<pre><code> List<Customer> list ...;\n List<Customer> newList = new ArrayList<>();\n for (Customer c : list){\n if (c.getName().equals(\"dd\")) newList.add(c);\n }\n</code></pre>\n\n<p>Simple, readable and easy (and works in Android!)\nBut if you're using Java 8 you can do it in a sweet one line:</p>\n\n<pre><code>List<Customer> newList = list.stream().filter(c -> c.getName().equals(\"dd\")).collect(toList());\n</code></pre>\n\n<p>Note that toList() is statically imported</p>\n"
},
{
"answer_id": 24561326,
"author": "Andrew McKnight",
"author_id": 581986,
"author_profile": "https://Stackoverflow.com/users/581986",
"pm_score": 1,
"selected": false,
"text": "<p>The simple pre-Java8 solution:</p>\n\n<pre><code>ArrayList<Item> filtered = new ArrayList<Item>(); \nfor (Item item : items) if (condition(item)) filtered.add(item);\n</code></pre>\n\n<p>Unfortunately this solution isn't fully generic, outputting a list rather than the type of the given collection. Also, bringing in libraries or writing functions that wrap this code seems like overkill to me unless the condition is complex, but then you can write a function for the condition.</p>\n"
},
{
"answer_id": 24924039,
"author": "anon",
"author_id": 577062,
"author_profile": "https://Stackoverflow.com/users/577062",
"pm_score": 4,
"selected": false,
"text": "<p>I'll throw <a href=\"https://github.com/ReactiveX/RxJava\" rel=\"noreferrer\">RxJava</a> in the ring, which is also available on <a href=\"https://github.com/ReactiveX/RxAndroid\" rel=\"noreferrer\">Android</a>. RxJava might not always be the best option, but it will give you more flexibility if you wish add more transformations on your collection or handle errors while filtering.</p>\n\n<pre><code>Observable.from(Arrays.asList(1, 2, 3, 4, 5))\n .filter(new Func1<Integer, Boolean>() {\n public Boolean call(Integer i) {\n return i % 2 != 0;\n }\n })\n .subscribe(new Action1<Integer>() {\n public void call(Integer i) {\n System.out.println(i);\n }\n });\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1\n3\n5\n</code></pre>\n\n<p>More details on RxJava's <code>filter</code> can be found <a href=\"https://github.com/ReactiveX/RxJava/wiki/Filtering-Observables#filter\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 25645013,
"author": "Low Flying Pelican",
"author_id": 847853,
"author_profile": "https://Stackoverflow.com/users/847853",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://code.google.com/p/joquery/\" rel=\"nofollow\">https://code.google.com/p/joquery/</a></p>\n\n<p>Supports different possibilities,</p>\n\n<p>Given collection,</p>\n\n<pre><code>Collection<Dto> testList = new ArrayList<>();\n</code></pre>\n\n<p>of type,</p>\n\n<pre><code>class Dto\n{\n private int id;\n private String text;\n\n public int getId()\n {\n return id;\n }\n\n public int getText()\n {\n return text;\n }\n}\n</code></pre>\n\n<p><strong>Filter</strong></p>\n\n<p><strong><em>Java 7</em></strong></p>\n\n<pre><code>Filter<Dto> query = CQ.<Dto>filter(testList)\n .where()\n .property(\"id\").eq().value(1);\nCollection<Dto> filtered = query.list();\n</code></pre>\n\n<p><strong><em>Java 8</em></strong></p>\n\n<pre><code>Filter<Dto> query = CQ.<Dto>filter(testList)\n .where()\n .property(Dto::getId)\n .eq().value(1);\nCollection<Dto> filtered = query.list();\n</code></pre>\n\n<p>Also,</p>\n\n<pre><code>Filter<Dto> query = CQ.<Dto>filter()\n .from(testList)\n .where()\n .property(Dto::getId).between().value(1).value(2)\n .and()\n .property(Dto::grtText).in().value(new string[]{\"a\",\"b\"});\n</code></pre>\n\n<p><strong>Sorting</strong> (also available for the Java 7)</p>\n\n<pre><code>Filter<Dto> query = CQ.<Dto>filter(testList)\n .orderBy()\n .property(Dto::getId)\n .property(Dto::getName)\n Collection<Dto> sorted = query.list();\n</code></pre>\n\n<p><strong>Grouping</strong> (also available for the Java 7)</p>\n\n<pre><code>GroupQuery<Integer,Dto> query = CQ.<Dto,Dto>query(testList)\n .group()\n .groupBy(Dto::getId)\n Collection<Grouping<Integer,Dto>> grouped = query.list();\n</code></pre>\n\n<p><strong>Joins</strong> (also available for the Java 7)</p>\n\n<p>Given,</p>\n\n<pre><code>class LeftDto\n{\n private int id;\n private String text;\n\n public int getId()\n {\n return id;\n }\n\n public int getText()\n {\n return text;\n }\n}\n\nclass RightDto\n{\n private int id;\n private int leftId;\n private String text;\n\n public int getId()\n {\n return id;\n }\n\n public int getLeftId()\n {\n return leftId;\n }\n\n public int getText()\n {\n return text;\n }\n}\n\nclass JoinedDto\n{\n private int leftId;\n private int rightId;\n private String text;\n\n public JoinedDto(int leftId,int rightId,String text)\n {\n this.leftId = leftId;\n this.rightId = rightId;\n this.text = text;\n }\n\n public int getLeftId()\n {\n return leftId;\n }\n\n public int getRightId()\n {\n return rightId;\n }\n\n public int getText()\n {\n return text;\n }\n}\n\nCollection<LeftDto> leftList = new ArrayList<>();\n\nCollection<RightDto> rightList = new ArrayList<>();\n</code></pre>\n\n<p>Can be Joined like,</p>\n\n<pre><code>Collection<JoinedDto> results = CQ.<LeftDto, LeftDto>query().from(leftList)\n .<RightDto, JoinedDto>innerJoin(CQ.<RightDto, RightDto>query().from(rightList))\n .on(LeftFyo::getId, RightDto::getLeftId)\n .transformDirect(selection -> new JoinedDto(selection.getLeft().getText()\n , selection.getLeft().getId()\n , selection.getRight().getId())\n )\n .list();\n</code></pre>\n\n<p><strong>Expressions</strong></p>\n\n<pre><code>Filter<Dto> query = CQ.<Dto>filter()\n .from(testList)\n .where()\n .exec(s -> s.getId() + 1).eq().value(2);\n</code></pre>\n"
},
{
"answer_id": 27818083,
"author": "Lawrence",
"author_id": 1435079,
"author_profile": "https://Stackoverflow.com/users/1435079",
"pm_score": 2,
"selected": false,
"text": "<p>Some really great great answers here. Me, I'd like to keep thins as simple and readable as possible:</p>\n\n<pre><code>public abstract class AbstractFilter<T> {\n\n /**\n * Method that returns whether an item is to be included or not.\n * @param item an item from the given collection.\n * @return true if this item is to be included in the collection, false in case it has to be removed.\n */\n protected abstract boolean excludeItem(T item);\n\n public void filter(Collection<T> collection) {\n if (CollectionUtils.isNotEmpty(collection)) {\n Iterator<T> iterator = collection.iterator();\n while (iterator.hasNext()) {\n if (excludeItem(iterator.next())) {\n iterator.remove();\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 29795865,
"author": "vikingsteve",
"author_id": 1993366,
"author_profile": "https://Stackoverflow.com/users/1993366",
"pm_score": 1,
"selected": false,
"text": "<p>My answer builds on that from Kevin Wong, here as a one-liner using <code>CollectionUtils</code> from <em>spring</em> and a Java 8 <em>lambda</em> expression.</p>\n\n<pre><code>CollectionUtils.filter(list, p -> ((Person) p).getAge() > 16);\n</code></pre>\n\n<p>This is as concise and readable as any alternative I have seen (without using aspect-based libraries)</p>\n\n<p>Spring <a href=\"http://docs.spring.io/autorepo/docs/spring/4.0.2.RELEASE/javadoc-api/org/springframework/util/CollectionUtils.html\" rel=\"nofollow\">CollectionUtils</a> is available from spring version 4.0.2.RELEASE, and remember you need JDK 1.8 and language level 8+.</p>\n"
},
{
"answer_id": 34245383,
"author": "hd84335",
"author_id": 1387113,
"author_profile": "https://Stackoverflow.com/users/1387113",
"pm_score": 2,
"selected": false,
"text": "<p>Using <code>java 8</code>, specifically <code>lambda expression</code>, you can do it simply like the below example:</p>\n\n<pre><code>myProducts.stream().filter(prod -> prod.price>10).collect(Collectors.toList())\n</code></pre>\n\n<p>where for each <code>product</code> inside <code>myProducts</code> collection, if <code>prod.price>10</code>, then add this product to the new filtered list.</p>\n"
},
{
"answer_id": 41160462,
"author": "ZhekaKozlov",
"author_id": 706317,
"author_profile": "https://Stackoverflow.com/users/706317",
"pm_score": 0,
"selected": false,
"text": "<p>With Guava:</p>\n\n<pre><code>Collection<Integer> collection = Lists.newArrayList(1, 2, 3, 4, 5);\n\nIterators.removeIf(collection.iterator(), new Predicate<Integer>() {\n @Override\n public boolean apply(Integer i) {\n return i % 2 == 0;\n }\n});\n\nSystem.out.println(collection); // Prints 1, 3, 5\n</code></pre>\n"
},
{
"answer_id": 44570130,
"author": "Fredrik Metcalf",
"author_id": 1200563,
"author_profile": "https://Stackoverflow.com/users/1200563",
"pm_score": 1,
"selected": false,
"text": "<p>I needed to filter a list depending on the values already present in the list. For example, remove all values following that is less than the current value. {2 5 3 4 7 5} -> {2 5 7}. Or for example to remove all duplicates {3 5 4 2 3 5 6} -> {3 5 4 2 6}.</p>\n\n<pre><code>public class Filter {\n public static <T> void List(List<T> list, Chooser<T> chooser) {\n List<Integer> toBeRemoved = new ArrayList<>();\n leftloop:\n for (int right = 1; right < list.size(); ++right) {\n for (int left = 0; left < right; ++left) {\n if (toBeRemoved.contains(left)) {\n continue;\n }\n Keep keep = chooser.choose(list.get(left), list.get(right));\n switch (keep) {\n case LEFT:\n toBeRemoved.add(right);\n continue leftloop;\n case RIGHT:\n toBeRemoved.add(left);\n break;\n case NONE:\n toBeRemoved.add(left);\n toBeRemoved.add(right);\n continue leftloop;\n }\n }\n }\n\n Collections.sort(toBeRemoved, new Comparator<Integer>() {\n @Override\n public int compare(Integer o1, Integer o2) {\n return o2 - o1;\n }\n });\n\n for (int i : toBeRemoved) {\n if (i >= 0 && i < list.size()) {\n list.remove(i);\n }\n }\n }\n\n public static <T> void List(List<T> list, Keeper<T> keeper) {\n Iterator<T> iterator = list.iterator();\n while (iterator.hasNext()) {\n if (!keeper.keep(iterator.next())) {\n iterator.remove();\n }\n }\n }\n\n public interface Keeper<E> {\n boolean keep(E obj);\n }\n\n public interface Chooser<E> {\n Keep choose(E left, E right);\n }\n\n public enum Keep {\n LEFT, RIGHT, BOTH, NONE;\n }\n}\n</code></pre>\n\n<p>This will bee used like this.</p>\n\n<pre><code>List<String> names = new ArrayList<>();\nnames.add(\"Anders\");\nnames.add(\"Stefan\");\nnames.add(\"Anders\");\nFilter.List(names, new Filter.Chooser<String>() {\n @Override\n public Filter.Keep choose(String left, String right) {\n return left.equals(right) ? Filter.Keep.LEFT : Filter.Keep.BOTH;\n }\n});\n</code></pre>\n"
},
{
"answer_id": 50511268,
"author": "yanefedor",
"author_id": 4545552,
"author_profile": "https://Stackoverflow.com/users/4545552",
"pm_score": 3,
"selected": false,
"text": "<p>Since <strong>java 9</strong> <code>Collectors.filtering</code> is enabled:</p>\n\n<pre><code>public static <T, A, R>\n Collector<T, ?, R> filtering(Predicate<? super T> predicate,\n Collector<? super T, A, R> downstream)\n</code></pre>\n\n<p>Thus filtering should be:</p>\n\n<pre><code>collection.stream().collect(Collectors.filtering(predicate, collector))\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>List<Integer> oddNumbers = List.of(1, 19, 15, 10, -10).stream()\n .collect(Collectors.filtering(i -> i % 2 == 1, Collectors.toList()));\n</code></pre>\n"
},
{
"answer_id": 52875398,
"author": "pramod_m",
"author_id": 4312010,
"author_profile": "https://Stackoverflow.com/users/4312010",
"pm_score": 2,
"selected": false,
"text": "<p>In Java 8, You can directly use this filter method and then do that.</p>\n\n<pre><code> List<String> lines = Arrays.asList(\"java\", \"pramod\", \"example\");\n\n List<String> result = lines.stream() \n .filter(line -> !\"pramod\".equals(line)) \n .collect(Collectors.toList()); \n\n result.forEach(System.out::println); \n</code></pre>\n"
},
{
"answer_id": 68547203,
"author": "Muhammad Hamed K",
"author_id": 7988380,
"author_profile": "https://Stackoverflow.com/users/7988380",
"pm_score": 1,
"selected": false,
"text": "<p>In my case, I was looking for list with specific field null excluded.\nThis could be done with for loop and fill the temporary list of objects who have no null addresses.\nbut Thanks to Java 8 Streams</p>\n<pre><code>List<Person> personsList = persons.stream()\n.filter(p -> p.getAdrress() != null).collect(Collectors.toList());\n</code></pre>\n<p>#java #collection #collections #java8 #streams</p>\n"
},
{
"answer_id": 69423954,
"author": "Kevin Lano",
"author_id": 14192015,
"author_profile": "https://Stackoverflow.com/users/14192015",
"pm_score": 0,
"selected": false,
"text": "<p>An alternative (more lightweight) alternative to Java collection streams is the Ocl.java library, which uses vanilla collections and lambdas: <a href=\"https://github.com/eclipse/agileuml/blob/master/Ocl.java\" rel=\"nofollow noreferrer\">https://github.com/eclipse/agileuml/blob/master/Ocl.java</a></p>\n<p>For example, a simple filter and sum on an ArrayList words\ncould be:</p>\n<pre><code>ArrayList<Word> sel = Ocl.selectSequence(words, \n w -> w.pos.equals("NN")); \nint total = Ocl.sumint(Ocl.collectSequence(sel,\n w -> w.text.length())); \n</code></pre>\n<p>Where Word has String pos; String text; attributes. Efficiency seems similar to the streams option, eg, 10000 words are processed in about 50ms in both versions.</p>\n<p>There are equivalent OCL libraries for Python, Swift, etc. Basically Java collection streams has re-invented the OCL operations ->select, ->collect, etc, which existed in OCL since 1998.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4792/"
] |
I want to filter a `java.util.Collection` based on a predicate.
|
Java 8 ([2014](https://www.oracle.com/java/technologies/javase/8-whats-new.html "What's New in JDK 8")) solves this problem using streams and lambdas in one line of code:
```
List<Person> beerDrinkers = persons.stream()
.filter(p -> p.getAge() > 16).collect(Collectors.toList());
```
Here's a [tutorial](http://zeroturnaround.com/rebellabs/java-8-explained-applying-lambdas-to-java-collections/ "Java 8 collections and lambdas").
Use [`Collection#removeIf`](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-) to modify the collection in place. (Notice: In this case, the predicate will remove objects who satisfy the predicate):
```
persons.removeIf(p -> p.getAge() <= 16);
```
---
[lambdaj](https://code.google.com/archive/p/lambdaj/) allows filtering collections without writing loops or inner classes:
```
List<Person> beerDrinkers = select(persons, having(on(Person.class).getAge(),
greaterThan(16)));
```
Can you imagine something more readable?
**Disclaimer:** I am a contributor on lambdaj
|
122,107 |
<p><strong>"It is not possible to check out a single file. The finest level of checkouts you can do is at the directory level."</strong></p>
<p>How do I get around this issue when using Subversion?</p>
<p>We have this folder in Subversion where we keep all our images. I just want to check out one file (image) from that. This folder is really big and has ton of other stuff which I don't need now.</p>
|
[
{
"answer_id": 122126,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 6,
"selected": false,
"text": "<p>Use <code>svn cat</code> or <code>svn export</code>.</p>\n\n<p>For that, you don't need to fetch the working directory, but you will not be able to commit any changes you make. If you need to make changes and commit them, you need a working directory, but you don't have to fetch it completely. Checkout the revision where the directory was still/almost empty, and then use 'svn cat' to extract the file from HEAD.</p>\n"
},
{
"answer_id": 122134,
"author": "Mnementh",
"author_id": 21005,
"author_profile": "https://Stackoverflow.com/users/21005",
"pm_score": 7,
"selected": false,
"text": "<p>Try <code>svn export</code> instead of <code>svn checkout</code>. That works for single files.</p>\n\n<p>The reason for the limitation is that <code>checkout</code> creates a working copy, that contains meta-information about repository, revision, attributes, etc. That metadata is stored in subdirectories named '.svn'. And single files don't have subdirectories.</p>\n"
},
{
"answer_id": 122142,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>If you want to view readme.txt in your\n repository without checking it out:</p>\n \n <p>$ svn cat\n <a href=\"http://svn.red-bean.com/repos/test/readme.txt\" rel=\"noreferrer\">http://svn.red-bean.com/repos/test/readme.txt</a><br>\n This is a README file. You should read\n this.</p>\n \n <p>Tip:\n If your working copy is out of date\n (or you have local modifications) and\n you want to see the HEAD revision of a\n file in your working copy, svn cat\n will automatically fetch the HEAD\n revision when you give it a path:</p>\n \n <p>$ cat foo.c<br>\n This file is in my local\n working copy and has changes that\n I've made.</p>\n \n <p>$ svn cat foo.c<br>\n Latest revision fresh\n from the repository!</p>\n</blockquote>\n\n<p><a href=\"http://svnbook.red-bean.com/en/1.0/re03.html\" rel=\"noreferrer\">Source</a></p>\n"
},
{
"answer_id": 122149,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 2,
"selected": false,
"text": "<p>I'd just browse it and export the single file. If you have HTTP access, just use the web browser to find the file and grab it. </p>\n\n<p>If you need to get it back in after editing it, that might be slightly more tedious, but I'm sure there might be an <code>svn import</code> function...</p>\n"
},
{
"answer_id": 122156,
"author": "Ted",
"author_id": 8965,
"author_profile": "https://Stackoverflow.com/users/8965",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want a file without revision information use</p>\n\n<pre><code>svn export <URL>\n</code></pre>\n"
},
{
"answer_id": 122193,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 2,
"selected": false,
"text": "<p>Go to the repo-browser right-click the file and use 'Save As', I'm using TortoiseSVN though.</p>\n"
},
{
"answer_id": 122291,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 10,
"selected": true,
"text": "<p>The simple answer is that you <code>svn export</code> the file instead of checking it out.</p>\n\n<p>But that might not be what you want. You might want to work on the file and check it back in, without having to download GB of junk you don't need.</p>\n\n<p>If you have Subversion 1.5+, then do a sparse checkout:</p>\n\n<pre><code>svn checkout <url_of_big_dir> <target> --depth empty\ncd <target>\nsvn up <file_you_want>\n</code></pre>\n\n<p>For an older version of SVN, you might benefit from the following:</p>\n\n<ul>\n<li>Checkout the directory using a revision back in the distant past, when it was less full of junk you don't need.</li>\n<li>Update the file you want, to create a mixed revision. This works even if the file didn't exist in the revision you checked out.</li>\n<li>Profit!</li>\n</ul>\n\n<p>An alternative (for instance if the directory has too much junk right from the revision in which it was created) is to do a URL->URL copy of the file you want into a new place in the repository (effectively this is a working branch of the file). Check out that directory and do your modifications.</p>\n\n<p>I'm not sure whether you can then merge your modified copy back entirely in the repository without a working copy of the target - I've never needed to. If so then do that.</p>\n\n<p>If not then unfortunately you may have to find someone else who does have the whole directory checked out and get them to do it. Or maybe by the time you've made your modifications, the rest of it will have finished downloading...</p>\n"
},
{
"answer_id": 123981,
"author": "jackr",
"author_id": 9205,
"author_profile": "https://Stackoverflow.com/users/9205",
"pm_score": 2,
"selected": false,
"text": "<p>With Subversion 1.5, it becomes possible to check out (all) the files of a directory without checking out any subdirectories (the various --depth flags). Not quite what you asked for, but a form of \"less than all.\"</p>\n"
},
{
"answer_id": 369681,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>cd C:\\path\\dir\nsvn checkout https://server/path/to/trunk/dir/dir/parent_dir--depth empty\ncd C:\\path\\dir\\parent_dir\nsvn update filename.log\n</code></pre>\n\n<p>(Edit filename.log)</p>\n\n<pre><code>svn commit -m \"this is a comment.\"\n</code></pre>\n"
},
{
"answer_id": 1135765,
"author": "devXen",
"author_id": 50021,
"author_profile": "https://Stackoverflow.com/users/50021",
"pm_score": 2,
"selected": false,
"text": "<p>Using the sparse check out technique, you CAN check out a particular file that is already checked out or exists...with a simple trick:</p>\n\n<p>After checkout of the top level of your repository using the 'this item only' option, in Windows explorer, you MUST first right-click on the file you need to update; choose Repo Browser in context menu; find that file AGAIN in repository browser, and right-click. You should now see the \"update item to revision\" in context menu.</p>\n\n<p>I'm not sure whether it is an undocumented feature or simply a bug. It took me an extended after-work hours to finally find this trick. I'm using <a href=\"http://en.wikipedia.org/wiki/TortoiseSVN\" rel=\"nofollow noreferrer\">TortoiseSVN</a> 1.6.2.</p>\n"
},
{
"answer_id": 1831229,
"author": "KG -",
"author_id": 159825,
"author_profile": "https://Stackoverflow.com/users/159825",
"pm_score": 3,
"selected": false,
"text": "<p>A TortoiseSVN equivalent solution of the accepted answer (I had written this in an internal document for my company as we are newly adopting SVN) follows. I thought it would be helpful to share here as well:</p>\n\n<p>Checking out a single file:\nSubversion does not support checkout of a single file, it only supports checkout of directory structures. (Reference: <a href=\"http://subversion.tigris.org/faq.html#single-file-checkout\" rel=\"nofollow noreferrer\">http://subversion.tigris.org/faq.html#single-file-checkout</a>). <em>This is because with every directory that is checked out as a working copy, the metadata regarding modifications/file revisions is stored as an internal hidden folder (.svn/_svn). This is not supported currently (v1.6) for single files.</em></p>\n\n<p>Alternate recommended strategy: You will have to do the checkout directory part only once, following that you can directly go and checkout your single files. Do a sparse checkout of the parent folder and directory structure. A sparse checkout is basically checking out only the folder structure without populating the content files. So you checkout only the directory structures and need not checkout ALL the files as was the concern.\nReference: <a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-checkout.html\" rel=\"nofollow noreferrer\">http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-checkout.html</a></p>\n\n<p><strong>Step 1</strong>: Proceed to repository browser</p>\n\n<p><strong>Step 2</strong>: Right click the parent folder within the repository containing all the files that you wish to work on and Select Checkout.</p>\n\n<p><strong>Step 3</strong>: Within new popup window, ensure that the checkout directory points to the correct location on your local PC. There will also be a dropdown menu labeled “checkout depth”. Choose “Only this item” or “Immediate children, including folders” depending on your requirement. Second option is recommended as, if you want to work on nested folder, you can directly proceed the next time otherwise you will have to follow this whole procedure again for the nested folder.</p>\n\n<p><strong>Step 4</strong>: The parent folder(s) should now be available within your locally chosen folder and is now being monitored with SVN (a hidden folder “.svn” or “_svn” should now be present). Within the repository now, right click the single file that you wish to have checked out alone and select the “Update Item to revision” option. The single file can now be worked on and checked back into the repository.</p>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 1959045,
"author": "ddkilzer",
"author_id": 140494,
"author_profile": "https://Stackoverflow.com/users/140494",
"pm_score": 2,
"selected": false,
"text": "<p>This issue is covered by issue #823 "svn checkout a single file" originally reported July 27, 2002 by Eric Gillespie [1].</p>\n<p>There is a Perl script attached [2] that lets you check out a single file from svn, make changes, and commit the changes back to the repository, but you can't run "svn up" to checkout the rest of the directory. It's been tested with svn-1.3, 1.4 and 1.6.</p>\n<p>Note the Subversion project originally hosted on tigris.org got moved to apache.org. The original URL of issue # 823 was on tigris.org at this non defunct URL [3]. The Internet Archive Wayback Machine has a copy of this original link [4].</p>\n<p>1 - <a href=\"https://issues.apache.org/jira/browse/SVN-823?issueNumber=823\" rel=\"nofollow noreferrer\">https://issues.apache.org/jira/browse/SVN-823?issueNumber=823</a></p>\n<p>2 - <a href=\"https://issues.apache.org/jira/secure/attachment/12762717/2_svn-co-one-file.txt\" rel=\"nofollow noreferrer\">https://issues.apache.org/jira/secure/attachment/12762717/2_svn-co-one-file.txt</a></p>\n<p>3 - <a href=\"http://subversion.tigris.org/issues/show_bug.cgi?id=823\" rel=\"nofollow noreferrer\">http://subversion.tigris.org/issues/show_bug.cgi?id=823</a></p>\n<p>4 - <a href=\"https://web.archive.org/web/20170401115732/http://subversion.tigris.org/issues/show_bug.cgi?id=823\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20170401115732/http://subversion.tigris.org/issues/show_bug.cgi?id=823</a></p>\n"
},
{
"answer_id": 3591876,
"author": "Vass",
"author_id": 410975,
"author_profile": "https://Stackoverflow.com/users/410975",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/122107/checkout-one-file-from-subversion/122291#122291\">Steve Jessop's answer</a> did not work for me. I read the help files for SVN and if you just have an image you probably don't want to check it in again unless you're doing Photoshop, so <strong>export</strong> is a better command than checkout as it's unversioned (but that is minor). </p>\n\n<p>And the <strong>--depth</strong> ARG should not be <strong>empty</strong> but <strong>files</strong> to get the files in the immediate directory. So you'll get all the fields, not just the one, but <strong>empty</strong> returns <em>nothing</em> from the repository. </p>\n\n<pre><code> svn co --depth files <source> <local dest>\n</code></pre>\n\n<p>or</p>\n\n<pre><code>svn export --depth files <source> <local dest>\n</code></pre>\n\n<p>As for the other answers, <strong>cat</strong> lets you read the content which is good only for text, not images of all things.</p>\n"
},
{
"answer_id": 3974032,
"author": "blanne",
"author_id": 400068,
"author_profile": "https://Stackoverflow.com/users/400068",
"pm_score": 3,
"selected": false,
"text": "<p>An update in case what you really need can be covered by having the file included in a checkout of another folder.</p>\n\n<p>Since SVN 1.6 you can make <a href=\"http://svnbook.red-bean.com/nightly/en/svn.advanced.externals.html\" rel=\"noreferrer\">file externals</a>, a kind of svn links. It means that you can have another versioned folder that includes a single file. Committing changes to the file in a checkout of this folder is also possible.</p>\n\n<p>It's very simple, checkout the folder you want to include the file, and simply add a property to the folder</p>\n\n<pre><code>svn propedit svn:externals .\n</code></pre>\n\n<p>with content like this:</p>\n\n<pre><code>file.txt /repos/path/to/file.txt\n</code></pre>\n\n<p>After you commit this, the file will appear in future checkouts of the folder. Basically it works, but there are some limitations as described in the documentation linked above.</p>\n"
},
{
"answer_id": 9144620,
"author": "hendergassler",
"author_id": 1189892,
"author_profile": "https://Stackoverflow.com/users/1189892",
"pm_score": 2,
"selected": false,
"text": "<p>I wanted to checkout a single file to a directory, which was not part of a working copy.</p>\n\n<p>Let's get the file at the following URL: <a href=\"http://subversion.repository.server/repository/module/directory/myfile\" rel=\"nofollow\">http://subversion.repository.server/repository/module/directory/myfile</a></p>\n\n<pre><code>svn co http://subversion.repository.server/repository/module/directory/myfile /**directoryb**\n</code></pre>\n\n<p>So I checked out the given directory containing the target file I wanted to get to a dummy directory, (say etcb for the URL ending with <code>/etc</code>).</p>\n\n<p>Then I emptied the file <strong>.svn/entries</strong> from all files of the target directory I didn't needed, to leave just the file I wanted. In this <strong>.svn/entries</strong> file, you have a record for each file with its attributes so leave just the record concerning the file you want to get and save.</p>\n\n<p>Now you need just to copy then ''.svn'' to the directory which will be a new \"working copy\". Then you just need to:</p>\n\n<pre><code>cp .svn /directory\ncd /directory\nsvn update myfile\n</code></pre>\n\n<p>Now the directory <strong>directory</strong> is under version control. Do not forget to remove the directory <strong>directoryb</strong> which was just a ''temporary working copy''.</p>\n"
},
{
"answer_id": 10313106,
"author": "Manish Singh",
"author_id": 1307864,
"author_profile": "https://Stackoverflow.com/users/1307864",
"pm_score": 2,
"selected": false,
"text": "<p>Do something like this:</p>\n\n<pre><code>mkdir <your directory>/repos/test\n\nsvn cat http://svn.red-bean.com/repos/test/readme.txt > <your directory>/repos/test/readme.txt\n</code></pre>\n\n<p>Basically the idea is create the directory where you want to grab the file from SVN.\nUse the <code>svn cat</code> command and redirect the output to the same named file. By default, the cat will dump information on stdio.</p>\n"
},
{
"answer_id": 19690880,
"author": "Arthur Niu",
"author_id": 2920375,
"author_profile": "https://Stackoverflow.com/users/2920375",
"pm_score": 4,
"selected": false,
"text": "<p>You can do it in two steps:</p>\n\n<ol>\n<li><p>Checkout an empty SVN repository with meta information only:</p>\n\n<pre><code>$ cd /tmp\n\n$ svn co --depth empty http://svn.your.company.ca/training/trunk/sql\n</code></pre></li>\n<li><p>Run <code>svn up</code> to update specified file:</p>\n\n<pre><code>$ svn up http://svn.your.company.ca/training/trunk/sql/showSID.sql\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 29472793,
"author": "Daniel",
"author_id": 3806453,
"author_profile": "https://Stackoverflow.com/users/3806453",
"pm_score": 1,
"selected": false,
"text": "<p>If you just want to export the file, and you won't need to update it later, you can do it without having to use SVN commands.</p>\n\n<p>Using <strong>TortoiseSVN Repository Browser</strong>, select the file, right click, and then select \"<strong>Copy URL to clipboard</strong>\". Paste that URL to your browser, and after login you should be prompted with the file download.</p>\n\n<p>This way you can also select desired revision and download an older version of the file.</p>\n\n<p><em>Note that this is valid if your SVN server has a web interface.</em> </p>\n"
},
{
"answer_id": 41439465,
"author": "LachoTomov",
"author_id": 931409,
"author_profile": "https://Stackoverflow.com/users/931409",
"pm_score": 2,
"selected": false,
"text": "<p>Since none of the other answers worked for me I did it using this hack:</p>\n\n<pre><code>$ cd /yourfolder\nsvn co https://path-to-folder-which-has-your-files/ --depth files\n</code></pre>\n\n<p>This will create a new local folder which has only the files from the remote path.\nThen you can do a symbolic link to the files you want to have here.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175964/"
] |
**"It is not possible to check out a single file. The finest level of checkouts you can do is at the directory level."**
How do I get around this issue when using Subversion?
We have this folder in Subversion where we keep all our images. I just want to check out one file (image) from that. This folder is really big and has ton of other stuff which I don't need now.
|
The simple answer is that you `svn export` the file instead of checking it out.
But that might not be what you want. You might want to work on the file and check it back in, without having to download GB of junk you don't need.
If you have Subversion 1.5+, then do a sparse checkout:
```
svn checkout <url_of_big_dir> <target> --depth empty
cd <target>
svn up <file_you_want>
```
For an older version of SVN, you might benefit from the following:
* Checkout the directory using a revision back in the distant past, when it was less full of junk you don't need.
* Update the file you want, to create a mixed revision. This works even if the file didn't exist in the revision you checked out.
* Profit!
An alternative (for instance if the directory has too much junk right from the revision in which it was created) is to do a URL->URL copy of the file you want into a new place in the repository (effectively this is a working branch of the file). Check out that directory and do your modifications.
I'm not sure whether you can then merge your modified copy back entirely in the repository without a working copy of the target - I've never needed to. If so then do that.
If not then unfortunately you may have to find someone else who does have the whole directory checked out and get them to do it. Or maybe by the time you've made your modifications, the rest of it will have finished downloading...
|
122,108 |
<p>I have implemented the WMD control that Stack Overflow uses into a project of mine, it <strong>almost</strong> works like a charm, but when I save the changes to the database it is saving the HTML version and not the Markdown version.</p>
<p>So where I have this in my text box:</p>
<pre><code>**boldtext**
</code></pre>
<p>It is really saving this:</p>
<pre><code><b>boldtext</b>
</code></pre>
<p>How do I make it save the Markdown version?</p>
|
[
{
"answer_id": 122572,
"author": "Clinton Dreisbach",
"author_id": 6262,
"author_profile": "https://Stackoverflow.com/users/6262",
"pm_score": 4,
"selected": true,
"text": "<p>Before you include <code>wmd.js</code>, or whatever you've named the WMD editor JavaScript code locally, add one line of JavaScript code:</p>\n\n<pre><code>wmd_options = {\"output\": \"Markdown\"};\n</code></pre>\n\n<p>This will force the output of the editor to Markdown.</p>\n"
},
{
"answer_id": 5369774,
"author": "Ryan Yonzon",
"author_id": 668358,
"author_profile": "https://Stackoverflow.com/users/668358",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using the new WMD from <a href=\"http://code.google.com/p/wmd-new/\" rel=\"nofollow\">http://code.google.com/p/wmd-new/</a>, open <strong>wmd.js</strong> and add this line:</p>\n\n<pre><code>wmd.wmd_env.output = 'markdown';\n</code></pre>\n\n<p>Excerpt:</p>\n\n<pre><code>...\nwmd.ieCachedRange = null; // cached textarea selection\nwmd.ieRetardedClick = false; // flag\n\nwmd.wmd_env.output = 'markdown'; // force markdown output\n\n// Returns true if the DOM element is visible, false if it's hidden.\n// Checks if display is anything other than none.\nutil.isVisible = function (elem) {\n...\n</code></pre>\n\n<p>That should do the trick.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] |
I have implemented the WMD control that Stack Overflow uses into a project of mine, it **almost** works like a charm, but when I save the changes to the database it is saving the HTML version and not the Markdown version.
So where I have this in my text box:
```
**boldtext**
```
It is really saving this:
```
<b>boldtext</b>
```
How do I make it save the Markdown version?
|
Before you include `wmd.js`, or whatever you've named the WMD editor JavaScript code locally, add one line of JavaScript code:
```
wmd_options = {"output": "Markdown"};
```
This will force the output of the editor to Markdown.
|
122,115 |
<p>Ruby's standard popen3 module does not work on Windows. Is there a maintained replacement that allows for separating stdin, stdout, and stderr?</p>
|
[
{
"answer_id": 122222,
"author": "Max Caceres",
"author_id": 4842,
"author_profile": "https://Stackoverflow.com/users/4842",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://popen4.rubyforge.org/\" rel=\"nofollow noreferrer\">POpen4</a> gem has a common interface between unix and Windows. The following example (from their website) works like a charm.</p>\n\n<pre><code>require 'rubygems'\nrequire 'popen4'\n\nstatus =\n POpen4::popen4(\"cmd\") do |stdout, stderr, stdin, pid|\n stdin.puts \"echo hello world!\"\n stdin.puts \"echo ERROR! 1>&2\"\n stdin.puts \"exit\"\n stdin.close\n\n puts \"pid : #{ pid }\"\n puts \"stdout : #{ stdout.read.strip }\"\n puts \"stderr : #{ stderr.read.strip }\"\n end\n\nputs \"status : #{ status.inspect }\"\nputs \"exitstatus : #{ status.exitstatus }\"\n</code></pre>\n"
},
{
"answer_id": 3096011,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 1,
"selected": false,
"text": "<p>popen3 works with MRI 1.9.x on windows. See <a href=\"http://en.wikibooks.org/wiki/Ruby_Programming/Running_Multiple_Processes\" rel=\"nofollow noreferrer\">http://en.wikibooks.org/wiki/Ruby_Programming/Running_Multiple_Processes</a></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4842/"
] |
Ruby's standard popen3 module does not work on Windows. Is there a maintained replacement that allows for separating stdin, stdout, and stderr?
|
[POpen4](http://popen4.rubyforge.org/) gem has a common interface between unix and Windows. The following example (from their website) works like a charm.
```
require 'rubygems'
require 'popen4'
status =
POpen4::popen4("cmd") do |stdout, stderr, stdin, pid|
stdin.puts "echo hello world!"
stdin.puts "echo ERROR! 1>&2"
stdin.puts "exit"
stdin.close
puts "pid : #{ pid }"
puts "stdout : #{ stdout.read.strip }"
puts "stderr : #{ stderr.read.strip }"
end
puts "status : #{ status.inspect }"
puts "exitstatus : #{ status.exitstatus }"
```
|
122,127 |
<p>In order to create the proper queries I need to be able to run a query against the same datasource that the report is using. How do I get that information <strong>programatically</strong>? Preferably the connection string or pieces of data used to build the connection string.</p>
|
[
{
"answer_id": 122171,
"author": "Erikk Ross",
"author_id": 18772,
"author_profile": "https://Stackoverflow.com/users/18772",
"pm_score": 0,
"selected": false,
"text": "<p>If you have the right privileges you can can go to <a href=\"http://servername/reports/\" rel=\"nofollow noreferrer\">http://servername/reports/</a> and view the data source connection details through there. </p>\n"
},
{
"answer_id": 122191,
"author": "CodeRedick",
"author_id": 17145,
"author_profile": "https://Stackoverflow.com/users/17145",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using visual studio just look at the data tab.</p>\n\n<p>If you just have access to the report on the SSRS server you can navigate to the report, click the Properties tab, then the Data Sources option on the left.</p>\n\n<p>If it's a custom data source you can get the connection info from there. </p>\n\n<p>If it's shared, you'll need to navigate to the data source path shown, and can get the connection info from there.</p>\n\n<p>EDIT: Also, if you just have the report file itself you should be able to open it in notepad and find the data source information inside. Unless it uses a shared data source I guess... in which case you'll need to find that.</p>\n\n<p>EDIT: This answer applied to the question as originally written, before \"programmatically\" was added.</p>\n"
},
{
"answer_id": 122423,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 2,
"selected": true,
"text": "<pre><code>DataSourceDefinition dataSourceDefinition \n = reportingService.GetDataSourceContents(\"DataSourceName\");\n\nstring connectionString = dataSourceDefinition.ConnectString;\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7756/"
] |
In order to create the proper queries I need to be able to run a query against the same datasource that the report is using. How do I get that information **programatically**? Preferably the connection string or pieces of data used to build the connection string.
|
```
DataSourceDefinition dataSourceDefinition
= reportingService.GetDataSourceContents("DataSourceName");
string connectionString = dataSourceDefinition.ConnectString;
```
|
122,144 |
<p>Im calling a locally hosted wcf service from silverlight and I get the exception below.</p>
<p>Iv created a clientaccesspolicy.xml, which is situated in the route of my host.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
</code></pre>
<blockquote>
<p>An error occurred while trying to make
a request to URI
'<a href="http://localhost:8005/Service1.svc" rel="nofollow noreferrer">http://localhost:8005/Service1.svc</a>'.
This could be due to a cross domain
configuration error. Please see the
inner exception for more details. ---></p>
<p>{System.Security.SecurityException
---> System.Security.SecurityException:
Security error. at
MS.Internal.InternalWebRequest.Send()
at
System.Net.BrowserHttpWebRequest.BeginGetResponseImplementation()
at
System.Net.BrowserHttpWebRequest.InternalBeginGetResponse(AsyncCallback
callback, Object state) at
System.Net.AsyncHelper.<>c__DisplayClass4.b__3(Object sendState) --- End of inner
exception stack trace --- at
System.Net.AsyncHelper.BeginOnUI(BeginMethod
beginMethod, AsyncCallback callback,
Object state) at
System.Net.BrowserHttpWebRequest.BeginGetResponse(AsyncCallback
callback, Object state) at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteSend(IAsyncResult
result) at
System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnSend(IAsyncResult
result)}</p>
</blockquote>
<p>Any ideas on how to progress?</p>
|
[
{
"answer_id": 122165,
"author": "C. Dragon 76",
"author_id": 5682,
"author_profile": "https://Stackoverflow.com/users/5682",
"pm_score": 0,
"selected": false,
"text": "<p>I'd start by making sure Silverlight is actually finding your client access policy file by inspecting the network calls using Fiddler, FireBug, or a similar tool.</p>\n"
},
{
"answer_id": 122180,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 3,
"selected": false,
"text": "<p>there are some debugging techniques <a href=\"http://timheuer.com/blog/archive/2008/06/10/silverlight-services-cross-domain-404-not-found.aspx\" rel=\"nofollow noreferrer\">listed here</a>..one more <a href=\"http://timheuer.com/blog/archive/2008/04/09/silverlight-cannot-access-web-service.aspx\" rel=\"nofollow noreferrer\">useful post</a>..</p>\n"
},
{
"answer_id": 122189,
"author": "Maurice",
"author_id": 19676,
"author_profile": "https://Stackoverflow.com/users/19676",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using a WCF service at the same location the Silverlight app was served from you don't need a cross domain policy. I have had similar errors when returning LINQ to SQL data from the client where there was a relation between multiple entities.</p>\n\n<p>First make sure you WCF service is working properly. Do this by creating a simple ping function that just echos its input. Make sure you can call this first. If this works and your other function doesn't its something, either with the parameters or return of the function. If the first function also fails use a tool like Fiddler to see what data is send over the wire. Use a . at the end of the host to see the data from localhost. So something like http//localhost:1234./default.aspx and use the same for the WCF address.</p>\n"
},
{
"answer_id": 122816,
"author": "Tim Heuer",
"author_id": 705,
"author_profile": "https://Stackoverflow.com/users/705",
"pm_score": 1,
"selected": false,
"text": "<p>Some debugging techniques available via a webcast I did that attempted to demonstrate some of the techniques I wrote about: <a href=\"https://www.livemeeting.com/cc/mseventsbmo/view?id=1032386656&role=attend&pw=F3D2F263\" rel=\"nofollow noreferrer\">https://www.livemeeting.com/cc/mseventsbmo/view?id=1032386656&role=attend&pw=F3D2F263</a></p>\n"
},
{
"answer_id": 123432,
"author": "Dan",
"author_id": 230,
"author_profile": "https://Stackoverflow.com/users/230",
"pm_score": 2,
"selected": false,
"text": "<p>I know the service is working correctly, because I added it as a reference to a basic website and it worked. I'll try to play with Fiddler, although there is a slight issue as the xaml control is not embedded into a web page, its using the inbuilt testpage renderer.</p>\n\n<p>Here is a few pointers that iv found that need to be checked:</p>\n\n<p>Adding a clientaccesspolicy.xml as a shown my question.</p>\n\n<p>Adding a crossdomain.xml to the host route:</p>\n\n<pre><code><!DOCTYPE cross-domain-policy SYSTEM \"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\">\n<cross-domain-policy>\n <allow-http-request-headers-from domain=\"*\" headers=\"*\"/>\n</cross-domain-policy>\n</code></pre>\n\n<p>Ensure binding is basicHttp as this is the only one supported by silverlight(currently)</p>\n\n<p>The service needs this attribute:</p>\n\n<pre><code>[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] \n</code></pre>\n\n<p>Useful reads:\n<a href=\"http://weblogs.asp.net/tolgakoseoglu/archive/2008/03/18/silverlight-2-0-and-wcf.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/tolgakoseoglu/archive/2008/03/18/silverlight-2-0-and-wcf.aspx</a></p>\n\n<p><a href=\"http://timheuer.com/blog/archive/2008/06/06/changes-to-accessing-services-in-silverlight-2-beta-2.aspx\" rel=\"nofollow noreferrer\">http://timheuer.com/blog/archive/2008/06/06/changes-to-accessing-services-in-silverlight-2-beta-2.aspx</a></p>\n\n<p><a href=\"http://silverlight.net/forums/t/19191.aspx\" rel=\"nofollow noreferrer\">http://silverlight.net/forums/t/19191.aspx</a></p>\n\n<p><a href=\"http://timheuer.com/blog/archive/2008/04/09/silverlight-cannot-access-web-service.aspx\" rel=\"nofollow noreferrer\">http://timheuer.com/blog/archive/2008/04/09/silverlight-cannot-access-web-service.aspx</a></p>\n"
},
{
"answer_id": 284920,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>i have same problem. I do see that clientaccesspolicy.xml is fetched by silverlight client app successfully. I did ensure clientaccesspolicy.xml is not malformed by requesting it directly via firefox. The policy is wide open, same as the one above.</p>\n\n<p>Now here comes the bizarre twist. If I remove clientaccesspolicy.xml and instead add the Flash style crossdomain.xml policy file then it works. I do see through inspecting the network, how clientaccesspolicy.xml is requested first unsuccessfully and then silverlight falls back to crossdomain.xml.</p>\n\n<p>So I do have a work around, but I prefer making clientaccesspolicy.xml work so that there is no additional unneeded network round trip.</p>\n\n<p>Any suggestions?</p>\n"
},
{
"answer_id": 417946,
"author": "ScottG",
"author_id": 3047,
"author_profile": "https://Stackoverflow.com/users/3047",
"pm_score": 0,
"selected": false,
"text": "<p>I found the book, <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596523092\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Data-Driven Services with Silverlight 2</a> by John Papa to go over this extensively. I had the same issues and this excellent book explains it all.</p>\n"
},
{
"answer_id": 600027,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Don't know if your issue is the same but I've just blogged about the major pain I had this weekend trying to get cross-domain happening with my SL app talking to my Console hosted WCF service.</p>\n\n<p><a href=\"http://wallism.wordpress.com/2009/03/01/silverlight-communication-exception/\" rel=\"nofollow noreferrer\">http://wallism.wordpress.com/2009/03/01/silverlight-communication-exception/</a></p>\n\n<p>In a nutshell though, you must have a crossdomain.xml and don't have 'headers=\"*\"'</p>\n\n<pre><code>Bad:\n <allow-access-from domain=\"\"*\"\" headers=\"*\" />\n\nGood:\n <allow-access-from domain=\"\"*\"\" />\n <allow-http-request-headers-from domain=\"\"*\"\" headers=\"\"*\"\" />\n</code></pre>\n\n<p>Instead of * for headers you can have \"SOAPAction\" (work's either way)</p>\n\n<p>Oh and when you do get it working you may want to make it a bit more secure :-)</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 1879605,
"author": "Manoj Attal",
"author_id": 164811,
"author_profile": "https://Stackoverflow.com/users/164811",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure Endpoints and Binding of WCF service are defined correctly. To call WCF service from same application does not need cross domain policy file.</p>\n"
},
{
"answer_id": 15027712,
"author": "Uğur Gümüşhan",
"author_id": 964196,
"author_profile": "https://Stackoverflow.com/users/964196",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem and removing the service reference and adding it back again solved the problem for me.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] |
Im calling a locally hosted wcf service from silverlight and I get the exception below.
Iv created a clientaccesspolicy.xml, which is situated in the route of my host.
```
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
```
>
> An error occurred while trying to make
> a request to URI
> '<http://localhost:8005/Service1.svc>'.
> This could be due to a cross domain
> configuration error. Please see the
> inner exception for more details. --->
>
>
> {System.Security.SecurityException
> ---> System.Security.SecurityException:
> Security error. at
> MS.Internal.InternalWebRequest.Send()
> at
> System.Net.BrowserHttpWebRequest.BeginGetResponseImplementation()
> at
> System.Net.BrowserHttpWebRequest.InternalBeginGetResponse(AsyncCallback
> callback, Object state) at
> System.Net.AsyncHelper.<>c\_\_DisplayClass4.b\_\_3(Object sendState) --- End of inner
> exception stack trace --- at
> System.Net.AsyncHelper.BeginOnUI(BeginMethod
> beginMethod, AsyncCallback callback,
> Object state) at
> System.Net.BrowserHttpWebRequest.BeginGetResponse(AsyncCallback
> callback, Object state) at
> System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteSend(IAsyncResult
> result) at
> System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnSend(IAsyncResult
> result)}
>
>
>
Any ideas on how to progress?
|
there are some debugging techniques [listed here](http://timheuer.com/blog/archive/2008/06/10/silverlight-services-cross-domain-404-not-found.aspx)..one more [useful post](http://timheuer.com/blog/archive/2008/04/09/silverlight-cannot-access-web-service.aspx)..
|
122,154 |
<p>I'm using Team Foundation Build but we aren't yet using TFS for problem tracking, so I would like to disable the work item creation on a failed build. Is there any way to do this? I tried commenting out the work item info in the TFSBuild.proj file for the build type but that didn't do the trick.</p>
|
[
{
"answer_id": 122660,
"author": "Tim Booker",
"author_id": 10046,
"author_profile": "https://Stackoverflow.com/users/10046",
"pm_score": 6,
"selected": true,
"text": "<p>Try adding this inside the PropertyGroup in your TFSBuild.proj:</p>\n\n<pre><code><SkipWorkItemCreation>true</SkipWorkItemCreation>\n</code></pre>\n\n<hr>\n\n<p>If you are curious as to how this works, Microsoft.TeamFoundation.Build.targets contians the following:</p>\n\n<pre><code> <Target Name=\"CoreCreateWorkItem\"\n Condition=\" '$(SkipWorkItemCreation)'!='true' and '$(IsDesktopBuild)'!='true' \"\n DependsOnTargets=\"$(CoreCreateWorkItemDependsOn)\">\n\n <PropertyGroup>\n <WorkItemTitle>$(WorkItemTitle) $(BuildNumber)</WorkItemTitle>\n <BuildLogText>$(BuildlogText) &lt;a href='file:///$(DropLocation)\\$(BuildNumber)\\BuildLog.txt'&gt;$(DropLocation)\\$(BuildNumber)\\BuildLog.txt&lt;/a &gt;.</BuildLogText>\n <ErrorWarningLogText Condition=\"!Exists('$(MSBuildProjectDirectory)\\ErrorsWarningsLog.txt')\"></ErrorWarningLogText>\n <ErrorWarningLogText Condition=\"Exists('$(MSBuildProjectDirectory)\\ErrorsWarningsLog.txt')\">$(ErrorWarningLogText) &lt;a href='file:///$(DropLocation)\\$(BuildNumber)\\ErrorsWarningsLog.txt'&gt;$(DropLocation)\\$(BuildNumber)\\ErrorsWarningsLog.txt&lt;/a &gt;.</ErrorWarningLogText>\n <WorkItemDescription>$(DescriptionText) %3CBR%2F%3E $(BuildlogText) %3CBR%2F%3E $(ErrorWarningLogText)</WorkItemDescription>\n </PropertyGroup>\n\n <CreateNewWorkItem\n TeamFoundationServerUrl=\"$(TeamFoundationServerUrl)\"\n BuildUri=\"$(BuildUri)\"\n BuildNumber=\"$(BuildNumber)\"\n Description=\"$(WorkItemDescription)\"\n TeamProject=\"$(TeamProject)\"\n Title=\"$(WorkItemTitle)\"\n WorkItemFieldValues=\"$(WorkItemFieldValues)\"\n WorkItemType=\"$(WorkItemType)\"\n ContinueOnError=\"true\" />\n\n </Target>\n</code></pre>\n\n<p>You can override any of this functionality in your own build script, but Microsoft provide the handy SkipWorkItemCreation condition at the top, which you can use to cancel execution of the whole target.</p>\n"
},
{
"answer_id": 51420939,
"author": "Beingnin",
"author_id": 7441056,
"author_profile": "https://Stackoverflow.com/users/7441056",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using tfs2010 or above you can do this in the build definition itself.</p>\n\n<p>In the <strong>Process tab</strong> of Build Definition set the <code>Create Work Item on failure</code> property to <code>false</code> (under the Advanced section)</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] |
I'm using Team Foundation Build but we aren't yet using TFS for problem tracking, so I would like to disable the work item creation on a failed build. Is there any way to do this? I tried commenting out the work item info in the TFSBuild.proj file for the build type but that didn't do the trick.
|
Try adding this inside the PropertyGroup in your TFSBuild.proj:
```
<SkipWorkItemCreation>true</SkipWorkItemCreation>
```
---
If you are curious as to how this works, Microsoft.TeamFoundation.Build.targets contians the following:
```
<Target Name="CoreCreateWorkItem"
Condition=" '$(SkipWorkItemCreation)'!='true' and '$(IsDesktopBuild)'!='true' "
DependsOnTargets="$(CoreCreateWorkItemDependsOn)">
<PropertyGroup>
<WorkItemTitle>$(WorkItemTitle) $(BuildNumber)</WorkItemTitle>
<BuildLogText>$(BuildlogText) <a href='file:///$(DropLocation)\$(BuildNumber)\BuildLog.txt'>$(DropLocation)\$(BuildNumber)\BuildLog.txt</a >.</BuildLogText>
<ErrorWarningLogText Condition="!Exists('$(MSBuildProjectDirectory)\ErrorsWarningsLog.txt')"></ErrorWarningLogText>
<ErrorWarningLogText Condition="Exists('$(MSBuildProjectDirectory)\ErrorsWarningsLog.txt')">$(ErrorWarningLogText) <a href='file:///$(DropLocation)\$(BuildNumber)\ErrorsWarningsLog.txt'>$(DropLocation)\$(BuildNumber)\ErrorsWarningsLog.txt</a >.</ErrorWarningLogText>
<WorkItemDescription>$(DescriptionText) %3CBR%2F%3E $(BuildlogText) %3CBR%2F%3E $(ErrorWarningLogText)</WorkItemDescription>
</PropertyGroup>
<CreateNewWorkItem
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
BuildNumber="$(BuildNumber)"
Description="$(WorkItemDescription)"
TeamProject="$(TeamProject)"
Title="$(WorkItemTitle)"
WorkItemFieldValues="$(WorkItemFieldValues)"
WorkItemType="$(WorkItemType)"
ContinueOnError="true" />
</Target>
```
You can override any of this functionality in your own build script, but Microsoft provide the handy SkipWorkItemCreation condition at the top, which you can use to cancel execution of the whole target.
|
122,160 |
<p>I'm a big fan of the way Visual Studio will give you the comment documentation / parameter names when completing code that you have written and ALSO code that you are referencing (various libraries/assemblies).</p>
<p>Is there an easy way to get inline javadoc/parameter names in Eclipse when doing code complete or hovering over methods? Via plugin? Via some setting? It's extremely annoying to use a lot of libraries (as happens often in Java) and then have to go to the website or local javadoc location to lookup information when you have it in the source jars right there!</p>
|
[
{
"answer_id": 122182,
"author": "Henry B",
"author_id": 6414,
"author_profile": "https://Stackoverflow.com/users/6414",
"pm_score": 7,
"selected": false,
"text": "<p>Short answer would be yes.</p>\n\n<p>You can attach source using the properties for a project.</p>\n\n<p>Go to Properties (for the Project) -> Java Build Path -> Libraries</p>\n\n<p>Select the Library you want to attach source/javadoc for and then expand it, you'll see a list like so:</p>\n\n<pre><code>Source Attachment: (none)\nJavadoc location: (none)\nNative library location: (none)\nAccess rules: (No restrictions)\n</code></pre>\n\n<p>Select Javadoc location and then click Edit on the right hahnd side. It should be quite straight forward from there.</p>\n\n<p>Good luck :)</p>\n"
},
{
"answer_id": 122194,
"author": "Matt",
"author_id": 20630,
"author_profile": "https://Stackoverflow.com/users/20630",
"pm_score": 2,
"selected": false,
"text": "<p>When you add a jar file to a classpath you can attach a source directory or zip or jar file to that jar. In the Java Build Path properties, on the Libraries tab, expand the entry for the jar and you'll see there's an item for the source attachment. Select this item and then click the Edit button. This lets you select the folder, jar or zip that contains the source.</p>\n\n<p>Additionally, if you select a class or a method in the jar and CTRL+CLICK on it (or press F3) then you'll go into the bytecode view which has an option to attach the source code.</p>\n\n<p>Doing these things will give you all the parameter names as well as full javadoc.</p>\n\n<p>If you don't have the source but do have the javadoc, you can attach the javadoc via the first method. It can even reference an external URL if you don't have it downloaded.</p>\n"
},
{
"answer_id": 492844,
"author": "Akrikos",
"author_id": 54641,
"author_profile": "https://Stackoverflow.com/users/54641",
"pm_score": 0,
"selected": false,
"text": "<p>Another thought for making that easier when using an automated build:</p>\n\n<p>When you create a jar of one of your projects, also create a source files jar:<br/>\nproject.jar<br/>\nproject-src.jar</p>\n\n<p>Instead of going into the build path options dialog to add a source reference to each jar, try the following: add one source reference through the dialog. Edit your .classpath and using the first jar entry as a template, add the source jar files to each of your other jars. </p>\n\n<p>This way you can use Eclipse's navigation aids to their fullest while still using something more standalone to build your projects.</p>\n"
},
{
"answer_id": 3289563,
"author": "stolsvik",
"author_id": 39334,
"author_profile": "https://Stackoverflow.com/users/39334",
"pm_score": 3,
"selected": false,
"text": "<p>I've found that sometimes, you point to the directory you'd assume was correct, and then it still states that it can't find the file in the attached source blah blah.</p>\n\n<p>These times, I've realized that the last path element was \"src\". Just removing this path element (thus indeed pointing one level above the actual path where the \"org\" or \"com\" folder is located) magically makes it work.</p>\n\n<p>Somehow, Eclipse seems to imply this \"src\" path element if present, and if you then have it included in the source path, Eclipse chokes. Or something like that.</p>\n"
},
{
"answer_id": 6307463,
"author": "Nilesh Tailor",
"author_id": 411119,
"author_profile": "https://Stackoverflow.com/users/411119",
"pm_score": 1,
"selected": false,
"text": "<p>Another option is to right click on your jar file which would be under (Your Project)->Referenced Libraries->(your jar) and click on properties. Then click on Java Source Attachment. And then in location path put in the location for your source jar file.</p>\n\n<p>This is just another approach to attaching your source file.</p>\n"
},
{
"answer_id": 6632008,
"author": "nevets1219",
"author_id": 82952,
"author_profile": "https://Stackoverflow.com/users/82952",
"pm_score": 0,
"selected": false,
"text": "<p>I was going to ask for an alternative to attaching sources to the same JAR being used across multiple projects. Originally, I had thought that the only alternative is to re-build the JAR with the source included but looking at the \"user library\" feature, you don't have to build the JAR with the source.</p>\n\n<p>This is an alternative when you have multiple projects (related or not) that reference the same JAR. Create an \"user library\" for each JAR and attach the source to them. Next time you need a specific JAR, instead of using \"Add JARs...\" or \"Add External JARs...\" you add the \"user library\" that you have previously created.</p>\n\n<p>You would only have to attach the source ONCE per JAR and can re-use it for any number of projects.</p>\n"
},
{
"answer_id": 7408226,
"author": "Alex Argo",
"author_id": 5885,
"author_profile": "https://Stackoverflow.com/users/5885",
"pm_score": -1,
"selected": false,
"text": "<p>It may seem like overkill, but if you use maven and include source, the mvn eclipse plugin will generate all the source configuration needed to give you all the in-line documentation you could ask for.</p>\n"
},
{
"answer_id": 8677488,
"author": "Muzikant",
"author_id": 624109,
"author_profile": "https://Stackoverflow.com/users/624109",
"pm_score": 1,
"selected": false,
"text": "<p>Another way is to add the folder to your source lookup path:\n<a href=\"http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fviews%2Fdebug%2Fref-editsourcelookup.htm\" rel=\"nofollow\">http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fviews%2Fdebug%2Fref-editsourcelookup.htm</a></p>\n"
},
{
"answer_id": 13371980,
"author": "Ambika",
"author_id": 1822529,
"author_profile": "https://Stackoverflow.com/users/1822529",
"pm_score": 3,
"selected": false,
"text": "<p>yes there is a easy way... go to ... <a href=\"http://sourceforge.net/projects/jdk7src/\" rel=\"noreferrer\">http://sourceforge.net/projects/jdk7src/</a> and download the zip file. Then attach this to the eclipse. Give the path where you have downloaded the zip file in eclipse. We can then browse through the source. </p>\n"
},
{
"answer_id": 14649805,
"author": "tterrace",
"author_id": 318619,
"author_profile": "https://Stackoverflow.com/users/318619",
"pm_score": 7,
"selected": false,
"text": "<p>Up until yesterday I was stuck painstakingly downloading source zips for tons of jars and attaching them manually for every project. Then a colleague turned me on to <a href=\"http://marketplace.eclipse.org/content/java-source-attacher\">The Java Source Attacher</a>. It does what eclipse should do - a right click context menu that says \"Attach Java Source\". </p>\n\n<p><img src=\"https://i.stack.imgur.com/uA7P8.png\" alt=\"enter image description here\"></p>\n\n<p>It automatically downloads the source for you and attaches it. I've only hit a couple libraries it doesn't know about and when that happens it lets you contribute the url back to the community so no one else will have a problem with that library.</p>\n"
},
{
"answer_id": 15201158,
"author": "N.M",
"author_id": 2115286,
"author_profile": "https://Stackoverflow.com/users/2115286",
"pm_score": 4,
"selected": false,
"text": "<p>An easy way of doing this is : </p>\n\n<ol>\n<li><p>Download the respective SRC files/folder.</p></li>\n<li><p>In the eclipse editor, Ctrl+click or F3 on a method/class you need the source for. A new tab opens up which says \"No attached source found\". </p></li>\n<li><p>Click the \"attach sources\" button, click the \"attach source folder\" button, browse to the location of the downloaded SRC folder. Done!</p></li>\n</ol>\n\n<p>(p.s : Button labels may vary slightly, but this is pretty much it.)</p>\n"
},
{
"answer_id": 26747235,
"author": "Joshua Richardson",
"author_id": 973402,
"author_profile": "https://Stackoverflow.com/users/973402",
"pm_score": 1,
"selected": false,
"text": "<p>If you build your libraries with gradle, you can attach sources to the jars you create and then eclipse will automatically use them. See the answer by @MichaelOryl <a href=\"https://stackoverflow.com/questions/11474729/how-to-build-sources-jar-with-gradle\">How to build sources jar with gradle</a>.</p>\n\n<p>Copied here for your reference:</p>\n\n<pre><code>jar {\n from sourceSets.main.allSource\n}\n</code></pre>\n\n<p>The solution shown is for use with the gradle java plugin. Mileage may vary if you're not using that plugin.</p>\n"
},
{
"answer_id": 30691052,
"author": "Ranga",
"author_id": 4813055,
"author_profile": "https://Stackoverflow.com/users/4813055",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Put source files into a zip file (as it does for java source)</li>\n<li>Go to Project properties -> Libraries</li>\n<li>Select Source attachment and click 'Edit'</li>\n<li>On Source Attachment Configuration click 'Variable'</li>\n<li>On \"Variable Selection\" click 'New'</li>\n<li>Put a meaningful name and select the zip file created in step 1</li>\n</ol>\n"
},
{
"answer_id": 40799209,
"author": "BSM",
"author_id": 6607547,
"author_profile": "https://Stackoverflow.com/users/6607547",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Click on the JAVA code you want to see. (Click on List to open List.java if you want to check source code for java.util.List)</li>\n<li>Click on \"Attach Source\" button.</li>\n<li>You will be asked to \"Select the location (folder, JAR or zip) containing the source for rt.jar).</li>\n<li>Select \"External location\" option. Locate the src.zip file.</li>\n<li>Path for src.zip is : *\\Java\\jdk1.8.0_45\\src.zip</li>\n</ol>\n"
},
{
"answer_id": 46089674,
"author": "Stefan",
"author_id": 2876079,
"author_profile": "https://Stackoverflow.com/users/2876079",
"pm_score": 0,
"selected": false,
"text": "<p>For those who are writing Eclipse plugins and want to include the source...\nin the feature ExportWizard there is an option for including the source:\n<a href=\"https://i.stack.imgur.com/4QFF4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4QFF4.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 47785087,
"author": "Gene",
"author_id": 2057089,
"author_profile": "https://Stackoverflow.com/users/2057089",
"pm_score": 3,
"selected": false,
"text": "<p>1) Hold Control+ left click on the method you want to see. Then Eclipse will bring you to the Source Not Found page. </p>\n\n<p>2) Click on \"Attach Source\"\n<a href=\"https://i.stack.imgur.com/MT3o1.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/MT3o1.png\" alt=\"enter image description here\"></a></p>\n\n<p>3) <a href=\"https://i.stack.imgur.com/SxAXz.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/SxAXz.png\" alt=\"enter image description here\"></a></p>\n\n<p>4) Navigate to C:\\Program Files\\Java\\jdk-9.0.1\\lib\\src.zip</p>\n\n<p>5) Click OK\n<a href=\"https://i.stack.imgur.com/aoKuJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/aoKuJ.png\" alt=\"enter image description here\"></a>\nNow you should see the source code. </p>\n"
},
{
"answer_id": 48864148,
"author": "Gaurav Deshmukh",
"author_id": 6547194,
"author_profile": "https://Stackoverflow.com/users/6547194",
"pm_score": 0,
"selected": false,
"text": "<p>Just click on attach source and select folder path ... name will be same as folder name (in my case). Remember one thing you need to select path upto project folder base location with \"\\\" at suffix ex D:\\MyProject\\ </p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5885/"
] |
I'm a big fan of the way Visual Studio will give you the comment documentation / parameter names when completing code that you have written and ALSO code that you are referencing (various libraries/assemblies).
Is there an easy way to get inline javadoc/parameter names in Eclipse when doing code complete or hovering over methods? Via plugin? Via some setting? It's extremely annoying to use a lot of libraries (as happens often in Java) and then have to go to the website or local javadoc location to lookup information when you have it in the source jars right there!
|
Short answer would be yes.
You can attach source using the properties for a project.
Go to Properties (for the Project) -> Java Build Path -> Libraries
Select the Library you want to attach source/javadoc for and then expand it, you'll see a list like so:
```
Source Attachment: (none)
Javadoc location: (none)
Native library location: (none)
Access rules: (No restrictions)
```
Select Javadoc location and then click Edit on the right hahnd side. It should be quite straight forward from there.
Good luck :)
|
122,175 |
<p>I'm trying to setup some friendly URLs on a SharePoint website. I know that I can do the ASP.Net 2.0 friendly URLs using RewritePath, but I was wondering if it was possible to make use of the System.Web.Routing that comes with ASP.NET 3.5 SP1. </p>
<p>I think I've figured out how to get my route table loaded, but I'm not clear on what method to use to get the correct IHttpHandler to pass out.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 127897,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It should be as easy as the below.</p>\n\n<pre><code>var route = new Route(\"blah/{*path}\", new MyRouteHandler());\nRouteTable.Routes.Add(route);\n\npublic class MyRouteHandler : IRouteHandler\n{\n public IHttpHandler GetHttpHandler(RequestContext requestContext)\n {\n // return some HTTP handler here\n }\n}\n</code></pre>\n\n<p>Then register System.Web.Routing.UrlRoutingModule under HTTP modules in web.config and you should be good to go.</p>\n\n<pre><code><add name=\"Routing\" type=\"System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n</code></pre>\n"
},
{
"answer_id": 417333,
"author": "Ed Blackburn",
"author_id": 27962,
"author_profile": "https://Stackoverflow.com/users/27962",
"pm_score": 1,
"selected": false,
"text": "<p>I've been asked to look at this as part of an Share Point evaluation process.</p>\n\n<p>My understanding is that the <em>uri template</em> is essentially host name followed by the recursive folder structure. </p>\n\n<p>This is further complicated by Share Point truncating the uri at 255 characters. So if you have a particularly deep or verbose folder structure then your uri can become invalid.</p>\n\n<p>I was thinking about essentially prettifying / tidying up the uri by follow a human readable convention and convert to the Share Point convention. i.e:</p>\n\n<p><a href=\"http://myhostname.com/docs/human-resources/case-files/2009/reviews/ed-blackburn.docx\" rel=\"nofollow noreferrer\">http://myhostname.com/docs/human-resources/case-files/2009/reviews/ed-blackburn.docx</a></p>\n\n<p>converts to Share Points:</p>\n\n<p><a href=\"http://myhostname.com/human%20resources/case%20files/2009/reviews/ed%20blackburn.docx\" rel=\"nofollow noreferrer\">http://myhostname.com/human%20resources/case%20files/2009/reviews/ed%20blackburn.docx</a></p>\n\n<p>Any additional required services can be controlled by the controller.</p>\n\n<p>If longer than 255 characters some kind of tinyurl approach would be my initial suggestion.</p>\n"
},
{
"answer_id": 1082237,
"author": "Daniel Pollard",
"author_id": 2758,
"author_profile": "https://Stackoverflow.com/users/2758",
"pm_score": 1,
"selected": true,
"text": "<p>I ended up taking what Ryan had:</p>\n\n<pre><code>var route = new Route(\"blah/{*path}\", new MyRouteHandler());\nRouteTable.Routes.Add(route);\npublic class MyRouteHandler : IRouteHandler\n{ \npublic IHttpHandler GetHttpHandler(RequestContext requestContext) \n{ \n //rewrite to some know sharepoint path\n HttpContext.Current.RewritePath(\"~/Pages/Default.aspx\");\n\n // return some HTTP handler here \n return new DefaultHttpHandler(); \n\n}}\n</code></pre>\n\n<p>That seems to work ok for me.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10893/"
] |
I'm trying to setup some friendly URLs on a SharePoint website. I know that I can do the ASP.Net 2.0 friendly URLs using RewritePath, but I was wondering if it was possible to make use of the System.Web.Routing that comes with ASP.NET 3.5 SP1.
I think I've figured out how to get my route table loaded, but I'm not clear on what method to use to get the correct IHttpHandler to pass out.
Thanks!
|
I ended up taking what Ryan had:
```
var route = new Route("blah/{*path}", new MyRouteHandler());
RouteTable.Routes.Add(route);
public class MyRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//rewrite to some know sharepoint path
HttpContext.Current.RewritePath("~/Pages/Default.aspx");
// return some HTTP handler here
return new DefaultHttpHandler();
}}
```
That seems to work ok for me.
|
122,208 |
<p>In C++, what's the easiest way to get the local computer's IP address and subnet mask?</p>
<p>I want to be able to detect the local machine's IP address in my local network. In my particular case, I have a network with a subnet mask of 255.255.255.0 and my computer's IP address is 192.168.0.5. I need to get these had two values programmatically in order to send a broadcast message to my network (in the form 192.168.0.255, for my particular case)</p>
<p>Edit: Many answers were not giving the results I expected because I had two different network IP's. <a href="https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122235">Torial</a>'s code did the trick (it gave me both IP addresses).</p>
<p>Edit 2: Thanks to <a href="https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122225">Brian R. Bondy</a> for the info about the subnet mask.</p>
|
[
{
"answer_id": 122225,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": false,
"text": "<p>You can use gethostname followed by gethostbyname to get your local interface internal IP. </p>\n\n<p>This returned IP may be different from your external IP though. To get your external IP you would have to communicate with an external server that will tell you what your external IP is. Because the external IP is not yours but it is your routers.</p>\n\n<pre><code>//Example: b1 == 192, b2 == 168, b3 == 0, b4 == 100\nstruct IPv4\n{\n unsigned char b1, b2, b3, b4;\n};\n\nbool getMyIP(IPv4 & myIP)\n{\n char szBuffer[1024];\n\n #ifdef WIN32\n WSADATA wsaData;\n WORD wVersionRequested = MAKEWORD(2, 0);\n if(::WSAStartup(wVersionRequested, &wsaData) != 0)\n return false;\n #endif\n\n\n if(gethostname(szBuffer, sizeof(szBuffer)) == SOCKET_ERROR)\n {\n #ifdef WIN32\n WSACleanup();\n #endif\n return false;\n }\n\n struct hostent *host = gethostbyname(szBuffer);\n if(host == NULL)\n {\n #ifdef WIN32\n WSACleanup();\n #endif\n return false;\n }\n\n //Obtain the computer's IP\n myIP.b1 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b1;\n myIP.b2 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b2;\n myIP.b3 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b3;\n myIP.b4 = ((struct in_addr *)(host->h_addr))->S_un.S_un_b.s_b4;\n\n #ifdef WIN32\n WSACleanup();\n #endif\n return true;\n}\n</code></pre>\n\n<p>You can also always just use 127.0.0.1 which represents the local machine always.</p>\n\n<p><strong>Subnet mask in Windows:</strong></p>\n\n<p>You can get the subnet mask (and gateway and other info) by querying subkeys of this registry entry:</p>\n\n<p>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces</p>\n\n<p>Look for the registry value SubnetMask.</p>\n\n<p><strong>Other methods to get interface information in Windows:</strong></p>\n\n<p>You could also retrieve the information you're looking for by using: \n<a href=\"http://msdn.microsoft.com/en-us/library/ms741621(VS.85).aspx\" rel=\"noreferrer\">WSAIoctl</a> with this option: SIO_GET_INTERFACE_LIST </p>\n"
},
{
"answer_id": 122240,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 2,
"selected": false,
"text": "<p>Winsock specific:</p>\n\n<pre><code>// Init WinSock\nWSADATA wsa_Data;\nint wsa_ReturnCode = WSAStartup(0x101,&wsa_Data);\n\n// Get the local hostname\nchar szHostName[255];\ngethostname(szHostName, 255);\nstruct hostent *host_entry;\nhost_entry=gethostbyname(szHostName);\nchar * szLocalIP;\nszLocalIP = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);\nWSACleanup();\n</code></pre>\n"
},
{
"answer_id": 122256,
"author": "nymacro",
"author_id": 10499,
"author_profile": "https://Stackoverflow.com/users/10499",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <blockquote>\n <p>from torial:\n If you use winsock, here's a way: <a href=\"http://tangentsoft.net/wskfaq/examples/ipaddr.html\" rel=\"nofollow noreferrer\">http://tangentsoft.net/wskfaq/examples/ipaddr.html</a></p>\n </blockquote>\n</blockquote>\n\n<p>As for the subnet portion of the question; there is not platform agnostic way to retrieve the subnet mask as the POSIX socket API (which all modern operating systems implement) does not specify this. So you will have to use whatever method is available on the platform you are using.</p>\n"
},
{
"answer_id": 122560,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": -1,
"selected": false,
"text": "<p>Can't you just send to <a href=\"http://msdn.microsoft.com/en-us/library/ms740148(VS.85).aspx\" rel=\"nofollow noreferrer\">INADDR_BROADCAST</a>? Admittedly, that'll send on all interfaces - but that's rarely a problem.</p>\n\n<p>Otherwise, ioctl and SIOCGIFBRDADDR should get you the address on *nix, and <a href=\"http://msdn.microsoft.com/en-us/library/ms741621(VS.85).aspx\" rel=\"nofollow noreferrer\">WSAioctl and SIO_GET_BROADCAST_ADDRESS</a> on win32.</p>\n"
},
{
"answer_id": 221540,
"author": "jakobengblom2",
"author_id": 23054,
"author_profile": "https://Stackoverflow.com/users/23054",
"pm_score": 2,
"selected": false,
"text": "<p>Also, note that \"the local IP\" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces. </p>\n"
},
{
"answer_id": 1317246,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>In DEV C++, I used pure C with WIN32, with this given piece of code:</p>\n\n<pre><code>case IDC_IP:\n\n gethostname(szHostName, 255);\n host_entry=gethostbyname(szHostName);\n szLocalIP = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);\n //WSACleanup(); \n writeInTextBox(\"\\n\");\n writeInTextBox(\"IP: \"); \n writeInTextBox(szLocalIP);\n break;\n</code></pre>\n\n<p>When I click the button 'show ip', it works. But on the second time, the program quits (without warning or error). When I do:</p>\n\n<pre><code>//WSACleanup(); \n</code></pre>\n\n<p>The program does not quit, even clicking the same button multiple times with fastest speed.\nSo WSACleanup() may not work well with Dev-C++..</p>\n"
},
{
"answer_id": 1317284,
"author": "Jeremy Friesner",
"author_id": 131930,
"author_profile": "https://Stackoverflow.com/users/131930",
"pm_score": 5,
"selected": false,
"text": "<p>The question is trickier than it appears, because in many cases there isn't \"an IP address for the local computer\" so much as a number of different IP addresses. For example, the Mac I'm typing on right now (which is a pretty basic, standard Mac setup) has the following IP addresses associated with it:</p>\n\n<pre><code>fe80::1%lo0 \n127.0.0.1 \n::1 \nfe80::21f:5bff:fe3f:1b36%en1 \n10.0.0.138 \n172.16.175.1\n192.168.27.1\n</code></pre>\n\n<p>... and it's not just a matter of figuring out which of the above is \"the real IP address\", either... they are all \"real\" and useful; some more useful than others depending on what you are going to use the addresses for.</p>\n\n<p>In my experience often the best way to get \"an IP address\" for your local computer is not to query the local computer at all, but rather to ask the computer your program is talking to what it sees your computer's IP address as. e.g. if you are writing a client program, send a message to the server asking the server to send back as data the IP address that your request came from. That way you will know what the <em>relevant</em> IP address is, given the context of the computer you are communicating with.</p>\n\n<p>That said, that trick may not be appropriate for some purposes (e.g. when you're not communicating with a particular computer) so sometimes you just need to gather the list of all the IP addresses associated with your machine. The best way to do that under Unix/Mac (AFAIK) is by calling getifaddrs() and iterating over the results. Under Windows, try GetAdaptersAddresses() to get similar functionality. For example usages of both, see the GetNetworkInterfaceInfos() function in <a href=\"https://public.msli.com/lcs/muscle/muscle/util/NetworkUtilityFunctions.cpp\" rel=\"noreferrer\">this file</a>.</p>\n"
},
{
"answer_id": 10838854,
"author": "kgriffs",
"author_id": 21784,
"author_profile": "https://Stackoverflow.com/users/21784",
"pm_score": 5,
"selected": false,
"text": "<p>The problem with all the approaches based on gethostbyname is that you will not get all IP addresses assigned to a particular machine. Servers usually have more than one adapter.</p>\n\n<p>Here is an example of how you can iterate through all Ipv4 and Ipv6 addresses on the host machine:</p>\n\n<pre><code>void ListIpAddresses(IpAddresses& ipAddrs)\n{\n IP_ADAPTER_ADDRESSES* adapter_addresses(NULL);\n IP_ADAPTER_ADDRESSES* adapter(NULL);\n\n // Start with a 16 KB buffer and resize if needed -\n // multiple attempts in case interfaces change while\n // we are in the middle of querying them.\n DWORD adapter_addresses_buffer_size = 16 * KB;\n for (int attempts = 0; attempts != 3; ++attempts)\n {\n adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(adapter_addresses_buffer_size);\n assert(adapter_addresses);\n\n DWORD error = ::GetAdaptersAddresses(\n AF_UNSPEC, \n GAA_FLAG_SKIP_ANYCAST | \n GAA_FLAG_SKIP_MULTICAST | \n GAA_FLAG_SKIP_DNS_SERVER |\n GAA_FLAG_SKIP_FRIENDLY_NAME, \n NULL, \n adapter_addresses,\n &adapter_addresses_buffer_size);\n\n if (ERROR_SUCCESS == error)\n {\n // We're done here, people!\n break;\n }\n else if (ERROR_BUFFER_OVERFLOW == error)\n {\n // Try again with the new size\n free(adapter_addresses);\n adapter_addresses = NULL;\n\n continue;\n }\n else\n {\n // Unexpected error code - log and throw\n free(adapter_addresses);\n adapter_addresses = NULL;\n\n // @todo\n LOG_AND_THROW_HERE();\n }\n }\n\n // Iterate through all of the adapters\n for (adapter = adapter_addresses; NULL != adapter; adapter = adapter->Next)\n {\n // Skip loopback adapters\n if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)\n {\n continue;\n }\n\n // Parse all IPv4 and IPv6 addresses\n for (\n IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; \n NULL != address;\n address = address->Next)\n {\n auto family = address->Address.lpSockaddr->sa_family;\n if (AF_INET == family)\n {\n // IPv4\n SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);\n\n char str_buffer[INET_ADDRSTRLEN] = {0};\n inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, INET_ADDRSTRLEN);\n ipAddrs.mIpv4.push_back(str_buffer);\n }\n else if (AF_INET6 == family)\n {\n // IPv6\n SOCKADDR_IN6* ipv6 = reinterpret_cast<SOCKADDR_IN6*>(address->Address.lpSockaddr);\n\n char str_buffer[INET6_ADDRSTRLEN] = {0};\n inet_ntop(AF_INET6, &(ipv6->sin6_addr), str_buffer, INET6_ADDRSTRLEN);\n\n std::string ipv6_str(str_buffer);\n\n // Detect and skip non-external addresses\n bool is_link_local(false);\n bool is_special_use(false);\n\n if (0 == ipv6_str.find(\"fe\"))\n {\n char c = ipv6_str[2];\n if (c == '8' || c == '9' || c == 'a' || c == 'b')\n {\n is_link_local = true;\n }\n }\n else if (0 == ipv6_str.find(\"2001:0:\"))\n {\n is_special_use = true;\n }\n\n if (! (is_link_local || is_special_use))\n {\n ipAddrs.mIpv6.push_back(ipv6_str);\n }\n }\n else\n {\n // Skip all other types of addresses\n continue;\n }\n }\n }\n\n // Cleanup\n free(adapter_addresses);\n adapter_addresses = NULL;\n\n // Cheers!\n}\n</code></pre>\n"
},
{
"answer_id": 28849513,
"author": "sashoalm",
"author_id": 492336,
"author_profile": "https://Stackoverflow.com/users/492336",
"pm_score": 4,
"selected": false,
"text": "<h2>You cannot do that in Standard C++.</h2>\n\n<p>I'm posting this because it is the only correct answer. Your question asks how to do it in C++. Well, you can't do it in C++. You can do it in Windows, POSIX, Linux, Android, but all those are <strong>OS-specific solutions</strong> and not part of the language standard.</p>\n\n<p>Standard C++ <strong>does not have a networking layer</strong> at all.</p>\n\n<p>I assume you have this wrong assumption that C++ Standard defines the same scope of features as other language standards, Java. While Java might have built-in networking (and even a GUI framework) in the language's own standard library, C++ does not.</p>\n\n<p>While there are third-party APIs and libraries which can be used by a C++ program, this is in no way the same as saying that you can do it in C++.</p>\n\n<p>Here is an example to clarify what I mean. You can open a file in C++ because it has an <code>fstream</code> class as part of its standard library. This is not the same thing as using <code>CreateFile()</code>, which is a Windows-specific function and available only for WINAPI.</p>\n"
},
{
"answer_id": 33042829,
"author": "Zac",
"author_id": 971443,
"author_profile": "https://Stackoverflow.com/users/971443",
"pm_score": 0,
"selected": false,
"text": "<p>I was able to do it using DNS service under VS2013 with the following code:</p>\n\n<pre><code>#include <Windns.h>\n\nWSADATA wsa_Data;\n\nint wsa_ReturnCode = WSAStartup(0x101, &wsa_Data);\n\ngethostname(hostName, 256);\nPDNS_RECORD pDnsRecord;\n\nDNS_STATUS statsus = DnsQuery(hostName, DNS_TYPE_A, DNS_QUERY_STANDARD, NULL, &pDnsRecord, NULL);\nIN_ADDR ipaddr;\nipaddr.S_un.S_addr = (pDnsRecord->Data.A.IpAddress);\nprintf(\"The IP address of the host %s is %s \\n\", hostName, inet_ntoa(ipaddr));\n\nDnsRecordListFree(&pDnsRecord, DnsFreeRecordList);\n</code></pre>\n\n<p>I had to add Dnsapi.lib as addictional dependency in linker option.</p>\n\n<p>Reference <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms682016%28v=vs.85%29.aspx\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 48160317,
"author": "Mark Yang",
"author_id": 1461744,
"author_profile": "https://Stackoverflow.com/users/1461744",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest my code.</p>\n\n<pre><code>DllExport void get_local_ips(boost::container::vector<wstring>& ips)\n{\n IP_ADAPTER_ADDRESSES* adapters = NULL;\n IP_ADAPTER_ADDRESSES* adapter = NULL;\n IP_ADAPTER_UNICAST_ADDRESS* adr = NULL;\n ULONG adapter_size = 0;\n ULONG err = 0;\n SOCKADDR_IN* sockaddr = NULL;\n\n err = ::GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, NULL, &adapter_size);\n adapters = (IP_ADAPTER_ADDRESSES*)malloc(adapter_size);\n err = ::GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, adapters, &adapter_size);\n\n for (adapter = adapters; NULL != adapter; adapter = adapter->Next)\n {\n if (adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue; // Skip Loopback\n if (adapter->OperStatus != IfOperStatusUp) continue; // Live connection only \n\n for (adr = adapter->FirstUnicastAddress;adr != NULL; adr = adr->Next)\n {\n sockaddr = (SOCKADDR_IN*)(adr->Address.lpSockaddr);\n char ipstr [INET6_ADDRSTRLEN] = { 0 };\n wchar_t ipwstr[INET6_ADDRSTRLEN] = { 0 };\n inet_ntop(AF_INET, &(sockaddr->sin_addr), ipstr, INET_ADDRSTRLEN);\n mbstowcs(ipwstr, ipstr, INET6_ADDRSTRLEN);\n wstring wstr(ipwstr);\n if (wstr != \"0.0.0.0\") ips.push_back(wstr); \n }\n }\n\n free(adapters);\n adapters = NULL; }\n</code></pre>\n"
},
{
"answer_id": 66954688,
"author": "mortalis",
"author_id": 1106547,
"author_profile": "https://Stackoverflow.com/users/1106547",
"pm_score": 0,
"selected": false,
"text": "<p>A modified version of <a href=\"https://stackoverflow.com/a/10838854/1106547\">this answer</a>.<br />\nAdded headers and libs.</p>\n<p>It's also based on these pages:<br />\n<a href=\"https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses\" rel=\"nofollow noreferrer\">GetAdaptersAddresses</a><br />\n<a href=\"https://learn.microsoft.com/en-us/windows/win32/api/iptypes/ns-iptypes-ip_adapter_addresses_lh\" rel=\"nofollow noreferrer\">IP_ADAPTER_ADDRESSES_LH</a><br />\n<a href=\"https://learn.microsoft.com/en-us/windows/win32/api/iptypes/ns-iptypes-ip_adapter_unicast_address_lh\" rel=\"nofollow noreferrer\">IP_ADAPTER_UNICAST_ADDRESS_LH</a></p>\n<p>In short, to get an IPv4 address, you call <code>GetAdaptersAddresses()</code> to get the adapters, then run through the <code>IP_ADAPTER_UNICAST_ADDRESS</code> structures starting with <code>FirstUnicastAddress</code> and get the <code>Address</code> field to then convert it to a readable format with <code>inet_ntop()</code>.</p>\n<p>Prints info in the format:</p>\n<pre><code>[ADAPTER]: Realtek PCIe\n[NAME]: Ethernet 3\n[IP]: 123.123.123.123\n</code></pre>\n<p>Can be compiled with:</p>\n<pre><code>cl test.cpp\n</code></pre>\n<p>or, if you need to add libs dependencies in the command line:</p>\n<pre><code>cl test.cpp Iphlpapi.lib ws2_32.lib\n</code></pre>\n<pre><code>#include <winsock2.h>\n#include <iphlpapi.h>\n#include <stdio.h>\n#include <ws2tcpip.h>\n\n// Link with Iphlpapi.lib and ws2_32.lib\n#pragma comment(lib, "Iphlpapi.lib")\n#pragma comment(lib, "ws2_32.lib")\n\nvoid ListIpAddresses() {\n IP_ADAPTER_ADDRESSES* adapter_addresses(NULL);\n IP_ADAPTER_ADDRESSES* adapter(NULL);\n \n DWORD adapter_addresses_buffer_size = 16 * 1024;\n \n // Get adapter addresses\n for (int attempts = 0; attempts != 3; ++attempts) {\n adapter_addresses = (IP_ADAPTER_ADDRESSES*) malloc(adapter_addresses_buffer_size);\n\n DWORD error = ::GetAdaptersAddresses(AF_UNSPEC, \n GAA_FLAG_SKIP_ANYCAST | \n GAA_FLAG_SKIP_MULTICAST | \n GAA_FLAG_SKIP_DNS_SERVER | \n GAA_FLAG_SKIP_FRIENDLY_NAME,\n NULL, \n adapter_addresses,\n &adapter_addresses_buffer_size);\n \n if (ERROR_SUCCESS == error) {\n break;\n }\n else if (ERROR_BUFFER_OVERFLOW == error) {\n // Try again with the new size\n free(adapter_addresses);\n adapter_addresses = NULL;\n continue;\n }\n else {\n // Unexpected error code - log and throw\n free(adapter_addresses);\n adapter_addresses = NULL;\n return;\n }\n }\n\n // Iterate through all of the adapters\n for (adapter = adapter_addresses; NULL != adapter; adapter = adapter->Next) {\n // Skip loopback adapters\n if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType) continue;\n \n printf("[ADAPTER]: %S\\n", adapter->Description);\n printf("[NAME]: %S\\n", adapter->FriendlyName);\n\n // Parse all IPv4 addresses\n for (IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; NULL != address; address = address->Next) {\n auto family = address->Address.lpSockaddr->sa_family;\n if (AF_INET == family) {\n SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);\n char str_buffer[16] = {0};\n inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, 16);\n\n printf("[IP]: %s\\n", str_buffer);\n }\n }\n printf("\\n");\n }\n\n free(adapter_addresses);\n adapter_addresses = NULL;\n}\n\nint main() {\n ListIpAddresses();\n return 0;\n}\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4880/"
] |
In C++, what's the easiest way to get the local computer's IP address and subnet mask?
I want to be able to detect the local machine's IP address in my local network. In my particular case, I have a network with a subnet mask of 255.255.255.0 and my computer's IP address is 192.168.0.5. I need to get these had two values programmatically in order to send a broadcast message to my network (in the form 192.168.0.255, for my particular case)
Edit: Many answers were not giving the results I expected because I had two different network IP's. [Torial](https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122235)'s code did the trick (it gave me both IP addresses).
Edit 2: Thanks to [Brian R. Bondy](https://stackoverflow.com/questions/122208/get-the-ip-address-of-local-computer#122225) for the info about the subnet mask.
|
The question is trickier than it appears, because in many cases there isn't "an IP address for the local computer" so much as a number of different IP addresses. For example, the Mac I'm typing on right now (which is a pretty basic, standard Mac setup) has the following IP addresses associated with it:
```
fe80::1%lo0
127.0.0.1
::1
fe80::21f:5bff:fe3f:1b36%en1
10.0.0.138
172.16.175.1
192.168.27.1
```
... and it's not just a matter of figuring out which of the above is "the real IP address", either... they are all "real" and useful; some more useful than others depending on what you are going to use the addresses for.
In my experience often the best way to get "an IP address" for your local computer is not to query the local computer at all, but rather to ask the computer your program is talking to what it sees your computer's IP address as. e.g. if you are writing a client program, send a message to the server asking the server to send back as data the IP address that your request came from. That way you will know what the *relevant* IP address is, given the context of the computer you are communicating with.
That said, that trick may not be appropriate for some purposes (e.g. when you're not communicating with a particular computer) so sometimes you just need to gather the list of all the IP addresses associated with your machine. The best way to do that under Unix/Mac (AFAIK) is by calling getifaddrs() and iterating over the results. Under Windows, try GetAdaptersAddresses() to get similar functionality. For example usages of both, see the GetNetworkInterfaceInfos() function in [this file](https://public.msli.com/lcs/muscle/muscle/util/NetworkUtilityFunctions.cpp).
|
122,215 |
<p>In my tests I need to test what happens when an OracleException is thrown (due to a stored procedure failure). I am trying to setup Rhino Mocks to </p>
<pre><code>Expect.Call(....).Throw(new OracleException());
</code></pre>
<p>For whatever reason however, OracleException seems to be sealed with no public constructor. What can I do to test this?</p>
<p><strong>Edit:</strong> Here is exactly what I'm trying to instantiate:</p>
<pre><code>public sealed class OracleException : DbException {
private OracleException(string message, int code) { ...}
}
</code></pre>
|
[
{
"answer_id": 122224,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": -1,
"selected": false,
"text": "<p>Can you write a trivial stored procedure that fails/errors each time, then use that to test?</p>\n"
},
{
"answer_id": 122231,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 2,
"selected": false,
"text": "<p>Use reflection to instantiate the OracleException object? Replace</p>\n\n<pre><code>new OracleException()\n</code></pre>\n\n<p>with</p>\n\n<pre><code>object[] args = ... ;\n(OracleException)Activator.CreateInstance(typeof(OracleException), args)\n</code></pre>\n"
},
{
"answer_id": 122242,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 2,
"selected": false,
"text": "<p>Use reflection to instantiate OracleException. See <a href=\"http://webcache.googleusercontent.com/search?q=cache:http://www.canerten.com/reflection-with-private-members/&hl=en&strip=1\" rel=\"nofollow noreferrer\">this blog post</a></p>\n"
},
{
"answer_id": 122469,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 3,
"selected": false,
"text": "<p>Here is how you do it:</p>\n\n<pre><code> ConstructorInfo ci = typeof(OracleException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {typeof(string), typeof(int)}, null);\n var c = (OracleException)ci.Invoke(new object[] { \"some message\", 123 });\n</code></pre>\n\n<p>Thanks to all that helped, you have been upvoted</p>\n"
},
{
"answer_id": 1004956,
"author": "David Gardiner",
"author_id": 25702,
"author_profile": "https://Stackoverflow.com/users/25702",
"pm_score": 2,
"selected": false,
"text": "<p>Good solution George. This also works for SqlException too:</p>\n\n<pre><code> ConstructorInfo ci = typeof( SqlErrorCollection ).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null );\n SqlErrorCollection errorCollection = (SqlErrorCollection) ci.Invoke(new object[]{});\n\n ci = typeof( SqlException ).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof( string ), typeof( SqlErrorCollection ) }, null );\n return (SqlException) ci.Invoke( new object[] { \"some message\", errorCollection } );\n</code></pre>\n\n<p>-dave</p>\n"
},
{
"answer_id": 3160057,
"author": "Charles Crawford",
"author_id": 381331,
"author_profile": "https://Stackoverflow.com/users/381331",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using the Oracle.DataAccess.Client data provider client. I am having trouble constructing a new instance of an OracleException object, but it keeps telling me that there are no public constructors. I tried all of the ideas shown above and keep getting a null reference exception. </p>\n\n<pre><code>object[] args = { 1, \"Test Message\" };\nConstructorInfo ci = typeof(OracleException).GetConstructor(BindingFlags.NonPublic \n | BindingFlags.Instance, null, System.Type.GetTypeArray(args), null);\nvar e = (OracleException)ci.Invoke(args);\n</code></pre>\n\n<p>When debugging the test code, I always get a NULL value for 'ci'.</p>\n\n<p>Has Oracle changed the library to not allow this? What am I doing wrong and what do I need to do to instantiate an OracleException object to use with NMock?</p>\n\n<p>By the way, I'm using the Client library for version 10g.</p>\n\n<p>Thanks,</p>\n\n<p>Charlie</p>\n"
},
{
"answer_id": 5908499,
"author": "Morten Cools",
"author_id": 576855,
"author_profile": "https://Stackoverflow.com/users/576855",
"pm_score": 3,
"selected": true,
"text": "<p>It seems that Oracle changed their constructors in later versions, therefore the solution above will not work.</p>\n\n<p>If you only want to set the error code, the following will do the trick for 2.111.7.20:</p>\n\n<pre><code>ConstructorInfo ci = typeof(OracleException)\n .GetConstructor(\n BindingFlags.NonPublic | BindingFlags.Instance, \n null, \n new Type[] { typeof(int) }, \n null\n );\n\nException ex = (OracleException)ci.Invoke(new object[] { 3113 });\n</code></pre>\n"
},
{
"answer_id": 26288906,
"author": "Kingpin2k",
"author_id": 1257694,
"author_profile": "https://Stackoverflow.com/users/1257694",
"pm_score": 3,
"selected": false,
"text": "<p>For oracle's managed data access (v 4.121.1.0) the constructor changed again</p>\n\n<pre><code>var ci = typeof(OracleException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(string), typeof(string), typeof(string) }, null);\nvar c = (OracleException)ci.Invoke(new object[] { 1234, \"\", \"\", \"\" });\n</code></pre>\n"
},
{
"answer_id": 44820695,
"author": "Fredrik Hedblad",
"author_id": 318425,
"author_profile": "https://Stackoverflow.com/users/318425",
"pm_score": 2,
"selected": false,
"text": "<p>You can always get all the constructors like this</p>\n\n<pre><code>ConstructorInfo[] all = typeof(OracleException).GetConstructors(\n BindingFlags.NonPublic | BindingFlags.Instance);`\n</code></pre>\n\n<p>For <code>Oracle.DataAccess</code> 4.112.3.0 this returned 7 constructors</p>\n\n<p><a href=\"https://i.stack.imgur.com/FAEdJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FAEdJ.png\" alt=\"enter image description here\"></a></p>\n\n<p>The one I wanted was the second one in the list which took 5 arguments, <code>int, string, string, string, int</code>. I was surprised by the fifth argument because in ILSpy it looked like this</p>\n\n<pre><code>internal OracleException(int errCode, string dataSrc, string procedure, string errMsg)\n{\n this.m_errors = new OracleErrorCollection();\n this.m_errors.Add(new OracleError(errCode, dataSrc, procedure, errMsg));\n}\n</code></pre>\n\n<p>So, to get the constructor I wanted I ended up using</p>\n\n<pre><code>ConstructorInfo constructorInfo =\n typeof(OracleException).GetConstructor(\n BindingFlags.NonPublic | BindingFlags.Instance,\n null,\n new Type[] { typeof(int), typeof(string), typeof(string), typeof(string), typeof(int) },\n null);`\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
In my tests I need to test what happens when an OracleException is thrown (due to a stored procedure failure). I am trying to setup Rhino Mocks to
```
Expect.Call(....).Throw(new OracleException());
```
For whatever reason however, OracleException seems to be sealed with no public constructor. What can I do to test this?
**Edit:** Here is exactly what I'm trying to instantiate:
```
public sealed class OracleException : DbException {
private OracleException(string message, int code) { ...}
}
```
|
It seems that Oracle changed their constructors in later versions, therefore the solution above will not work.
If you only want to set the error code, the following will do the trick for 2.111.7.20:
```
ConstructorInfo ci = typeof(OracleException)
.GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new Type[] { typeof(int) },
null
);
Exception ex = (OracleException)ci.Invoke(new object[] { 3113 });
```
|
122,216 |
<p>So I have a large 2d array that i serialize, but when I attempt to unserialize the array it just throws the same error to the point of nearly crashing Firefox.</p>
<p>The error is:</p>
<pre><code>Warning: unserialize() [function.unserialize]: Node no longer exists in /var/www/dev/wc_paul/inc/analyzerTester.php on line 24
</code></pre>
<p>I would include the entire serialized array that I echo out but last time I tried that on this form it crashed my Firefox.</p>
<p>Does anyone have any idea why this might be happening?</p>
<p>I'm sure this is an array. However, it was originally an XML response from another server that I then pulled values from to build the array. If it can't be serialized I can accept that I guess... but how should I go about saving it then?</p>
|
[
{
"answer_id": 122241,
"author": "JimmyJ",
"author_id": 2083,
"author_profile": "https://Stackoverflow.com/users/2083",
"pm_score": 0,
"selected": false,
"text": "<p>to answer your second question about how else you could save the data</p>\n\n<p>why not output the xml responce directly to a file and save it locally, then read from the local file when required.</p>\n"
},
{
"answer_id": 122244,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 3,
"selected": true,
"text": "<p>Usually, when you get an error message, you can figure out a great deal by simply searching the web for that very message. For example, when you put <a href=\"http://www.google.co.uk/search?q=Node+no+longer+exists\" rel=\"nofollow noreferrer\">Node no longer exists</a> into Google, you end up with <a href=\"http://www.rhinocerus.net/node/16347\" rel=\"nofollow noreferrer\">a concise explanation of why this is happening, along with a solution</a>, as the very first hit.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20895/"
] |
So I have a large 2d array that i serialize, but when I attempt to unserialize the array it just throws the same error to the point of nearly crashing Firefox.
The error is:
```
Warning: unserialize() [function.unserialize]: Node no longer exists in /var/www/dev/wc_paul/inc/analyzerTester.php on line 24
```
I would include the entire serialized array that I echo out but last time I tried that on this form it crashed my Firefox.
Does anyone have any idea why this might be happening?
I'm sure this is an array. However, it was originally an XML response from another server that I then pulled values from to build the array. If it can't be serialized I can accept that I guess... but how should I go about saving it then?
|
Usually, when you get an error message, you can figure out a great deal by simply searching the web for that very message. For example, when you put [Node no longer exists](http://www.google.co.uk/search?q=Node+no+longer+exists) into Google, you end up with [a concise explanation of why this is happening, along with a solution](http://www.rhinocerus.net/node/16347), as the very first hit.
|
122,229 |
<p>I'm the only developer supporting a website that's a mix of classic asp and .NET. I had to add some .net pages to a classic asp application. This application requires users to login. The login page, written in classic asp, creates a cookie that .net pages use to identify the logged in user and stores information in session vars for the other classic asp pages to use. In classic asp the cookie code is as follows:</p>
<pre><code>response.cookies("foo")("value1") = value1
response.cookies("foo")("value2") = value2
response.cookies("foo").Expires = DateAdd("N", 15, Now())
response.cookies("foo").Path = "/"
</code></pre>
<p>In the .NET codebehind Page_Load code, I check for the cookie using the code below.</p>
<blockquote>
<p>if(!IsPostBack) {<br>
if(Request.Cookies["foo"] != null) {
... } else { //redirect to cookie creation page, cookiefoo.asp
} }</p>
</blockquote>
<p>The vast majority of the time this works with no problems. However, we have some users that get redirected to a cookie creation page because the Page_Load code can't find the cookie. No matter how many times the user is redirected to the cookie creation page, the referring page still can find the cookie, foo. The problem is happening in IE7 and I've tried modifying the privacy and cookie settings in the browser but can't seem to recreate the problem the user is having.</p>
<p>Does anyone have any ideas why this could be happening with IE7?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 122252,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>Using <a href=\"http://www.fiddlertool.com/fiddler/\" rel=\"nofollow noreferrer\">Fiddler</a> is a good way to try to figure out what's going on. You can see the exact Set-Cookie that the browser is getting.</p>\n"
},
{
"answer_id": 122259,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 0,
"selected": false,
"text": "<p>General rule of cross-platform cookie testing: dump all the cookies to screen so you can see your data. It might not explain exactly why it's happening, but it should tell you what is happening.</p>\n"
},
{
"answer_id": 122305,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 0,
"selected": false,
"text": "<p>Okay second answer: If it's a really small subset of users, you might want to see what software they have installed on their computer. There might be a common anti-spyware/adware application on all their machines that is messing with your cookies.</p>\n\n<p>If you can't get answers from those users on that, or there's nothing suspect it might be worth creating a special little test script to write a cookie and post the result back to you on the next page-load. </p>\n\n<p>You want to keep it as simple as possible (no user interaction after loading the link) so make it:</p>\n\n<ol>\n<li>Set the cookie in classic ASP</li>\n<li>Redirect to another ASP page.</li>\n<li>Read the cookies and email it to you.</li>\n<li>Redirect to a ASPNET page.</li>\n<li>Read the cookie and email it.</li>\n</ol>\n\n<p>You might want to set a cookie in ASPNET too and try reading it back out.</p>\n"
},
{
"answer_id": 129846,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 0,
"selected": false,
"text": "<p>The code you posted should break if the IE7 privacy settings is set to block first party cookies. Did you try that in your experiments?</p>\n\n<p>Using Fiddler as Lou said it a good idea although the Set-Cookie response header is less interesting than subsequent Cookie request headers to see whether the client is fowarding them to the server.</p>\n"
},
{
"answer_id": 143076,
"author": "Metro Smurf",
"author_id": 9664,
"author_profile": "https://Stackoverflow.com/users/9664",
"pm_score": 0,
"selected": false,
"text": "<p>I recall this happening in a similar application I had written; some pages were classic ASP, while others ASP.NET. The cookies were seemingly disappearing between the .NET and classic ASP pages.</p>\n\n<p>IIRC, the .NET side needed to Server.HTMLEncode/HTMLDecode the cookies. Sorry, but I don't have the exact code I used, but this should get you going in the right direction.</p>\n"
},
{
"answer_id": 2906948,
"author": "Toby Artisan",
"author_id": 243992,
"author_profile": "https://Stackoverflow.com/users/243992",
"pm_score": 1,
"selected": false,
"text": "<p>One thing about cookies that can be very hard to debug is that cookies are case-sensitive when it comes to the domain. So, a cookie that was issued for \"www.abc.com/dir1/alpha/\" can not be accessed from code if the user typed \"www.abc.com/dir1/Alpha/\".</p>\n\n<p>Another thing to watch out for in your ASP.NET pages is</p>\n\n<pre><code>Page.Response.Redirect(\"~/alpha\");\n</code></pre>\n\n<p>ASP.NET will modify the case of the relative URL based on the case of the actual filepath. If you have mixed-cases in your directory structure, then use</p>\n\n<pre><code>Page.Response.Redirect(Page.ResolveUrl(\"~/alpha\").ToLower());\n</code></pre>\n"
},
{
"answer_id": 63600916,
"author": "Pedro Rodrigues",
"author_id": 3343753,
"author_profile": "https://Stackoverflow.com/users/3343753",
"pm_score": 0,
"selected": false,
"text": "<p><em>decades later</em> (this surely deserves a medal)</p>\n<p>It turn out for me it was <strong>special characters in the cookie key</strong>.</p>\n<p>Specificaly the case that got my atention was a cookie with the key <code>utlização</code>, it would always come as <code>null</code>.</p>\n<p>So we've added a fail safe, <code>.Replace("ç", "c").Replace("ã", "a")</code> when generating the cookie key. And it fixed it.</p>\n<p><em>The cookie had always shown in the browser, so it took a while to observe this pattern. Thanks MS.</em></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9809/"
] |
I'm the only developer supporting a website that's a mix of classic asp and .NET. I had to add some .net pages to a classic asp application. This application requires users to login. The login page, written in classic asp, creates a cookie that .net pages use to identify the logged in user and stores information in session vars for the other classic asp pages to use. In classic asp the cookie code is as follows:
```
response.cookies("foo")("value1") = value1
response.cookies("foo")("value2") = value2
response.cookies("foo").Expires = DateAdd("N", 15, Now())
response.cookies("foo").Path = "/"
```
In the .NET codebehind Page\_Load code, I check for the cookie using the code below.
>
> if(!IsPostBack) {
>
> if(Request.Cookies["foo"] != null) {
> ... } else { //redirect to cookie creation page, cookiefoo.asp
> } }
>
>
>
The vast majority of the time this works with no problems. However, we have some users that get redirected to a cookie creation page because the Page\_Load code can't find the cookie. No matter how many times the user is redirected to the cookie creation page, the referring page still can find the cookie, foo. The problem is happening in IE7 and I've tried modifying the privacy and cookie settings in the browser but can't seem to recreate the problem the user is having.
Does anyone have any ideas why this could be happening with IE7?
Thanks.
|
Using [Fiddler](http://www.fiddlertool.com/fiddler/) is a good way to try to figure out what's going on. You can see the exact Set-Cookie that the browser is getting.
|
122,238 |
<p>JSF is setting the ID of an input field to <code>search_form:expression</code>. I need to specify some styling on that element, but that colon looks like the beginning of a pseudo-element to the browser so it gets marked invalid and ignored. Is there anyway to escape the colon or something?</p>
<pre><code>input#search_form:expression {
///...
}
</code></pre>
|
[
{
"answer_id": 122266,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 8,
"selected": true,
"text": "<p>Backslash: </p>\n\n<pre><code>input#search_form\\:expression { ///...}\n</code></pre>\n\n<ul>\n<li>See also <em><a href=\"http://msdn.microsoft.com/en-us/library/ms762307(VS.85).aspx\" rel=\"noreferrer\">Using Namespaces with CSS</a></em> (MSDN)</li>\n</ul>\n"
},
{
"answer_id": 122268,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 3,
"selected": false,
"text": "<p>You can escape it with a backslash</p>\n\n<pre><code>input#search_form\\:expression {\n ///...\n}\n</code></pre>\n\n<p>From the <a href=\"http://www.w3.org/TR/CSS21/syndata.html#characters\" rel=\"noreferrer\">CSS Spec</a><br /></p>\n\n<p>4.1.3 Characters and case</p>\n\n<p>The following rules always hold:</p>\n\n<p>All CSS style sheets are case-insensitive, except for parts that are not under the control of CSS. For example, the case-sensitivity of values of the HTML attributes \"id\" and \"class\", of font names, and of URIs lies outside the scope of this specification. Note in particular that element names are case-insensitive in HTML, but case-sensitive in XML.\nIn CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier \"B&W?\" may be written as \"B\\&W\\?\" or \"B\\26 W\\3F\".\nNote that Unicode is code-by-code equivalent to ISO 10646 (see [UNICODE] and [ISO10646]).</p>\n\n<p>In CSS 2.1, a backslash () character indicates three types of character escapes.\nFirst, inside a string, a backslash followed by a newline is ignored (i.e., the string is deemed not to contain either the backslash or the newline).</p>\n\n<p>Second, it cancels the meaning of special CSS characters. Any character (except a hexadecimal digit) can be escaped with a backslash to remove its special meaning. For example, \"\\\"\" is a string consisting of one double quote. Style sheet preprocessors must not remove these backslashes from a style sheet since that would change the style sheet's meaning.</p>\n\n<p>Third, backslash escapes allow authors to refer to characters they can't easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-f] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:</p>\n\n<p>with a space (or other whitespace character): \"\\26 B\" (\"&B\"). In this case, user agents should treat a \"CR/LF\" pair (U+000D/U+000A) as a single whitespace character.\nby providing exactly 6 hexadecimal digits: \"\\000026B\" (\"&B\")\nIn fact, these two methods may be combined. Only one whitespace character is ignored after a hexadecimal escape. Note that this means that a \"real\" space after the escape sequence must itself either be escaped or doubled.</p>\n\n<p>If the number is outside the range allowed by Unicode (e.g., \"\\110000\" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the \"replacement character\" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a \"missing character\" glyph (cf. 15.2, point 5).</p>\n\n<p>Note: Backslash escapes, where allowed, are always considered to be part of an identifier or a string (i.e., \"\\7B\" is not punctuation, even though \"{\" is, and \"\\32\" is allowed at the start of a class name, even though \"2\" is not).\nThe identifier \"te\\st\" is exactly the same identifier as \"test\".</p>\n"
},
{
"answer_id": 656463,
"author": "jeremyh",
"author_id": 3802,
"author_profile": "https://Stackoverflow.com/users/3802",
"pm_score": 7,
"selected": false,
"text": "<p>Using a backslash before the colon doesn't work in many versions of IE (particularly 6 and 7; possibly others).</p>\n\n<p>A workaround is to use the hexadecimal code for the colon - which is \\3A</p>\n\n<p>example:</p>\n\n<pre><code>input#search_form\\3A expression { }\n</code></pre>\n\n<p>This works in all browsers: Including IE6+ (and possibly earlier?), Firefox, Chrome, Opera, etc. It's part of the <a href=\"http://www.w3.org/TR/CSS2/syndata.html#characters\" rel=\"noreferrer\">CSS2 standard</a>.</p>\n"
},
{
"answer_id": 2228717,
"author": "naugtur",
"author_id": 173077,
"author_profile": "https://Stackoverflow.com/users/173077",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem with colons, and I was unable to change them (couldn't access the code outputing colons) and I wanted to fetch them with CSS3 selectors with jQuery. </p>\n\n<p>I put it here, cause it might be helpful for someone</p>\n\n<p><code>input[id=\"something:something\"]</code> \nworked fine in jQuery selectors, and it might work in stylesheets as well (might have browser issues)</p>\n"
},
{
"answer_id": 4777839,
"author": "Krishna",
"author_id": 421753,
"author_profile": "https://Stackoverflow.com/users/421753",
"pm_score": 2,
"selected": false,
"text": "<p>In JSF 2,0, you can specify the separator using the web.xml file as init-param of javax.faces.SEPARATOR_CHAR</p>\n\n<p>Read this:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/2142929/is-it-possible-to-change-the-element-id-separator-in-jsf\">Is it possible to change the element id separator in JSF?</a></li>\n</ul>\n"
},
{
"answer_id": 6231670,
"author": "Charles",
"author_id": 531656,
"author_profile": "https://Stackoverflow.com/users/531656",
"pm_score": -1,
"selected": false,
"text": "<p>I found only this format worked for me for IE7 (Firefox too), and I use JSF/Icefaces 1.8.2.</p>\n\n<pre>\nSay form id=FFF, element id=EEE\n\nvar jq=jQuery.noConflict();\njq(document).ready(function() {\njq(\"[id=FFF:EEE]\").someJQueryLibFunction({ jQuery lib function options go here })\n});\n\n</pre>\n"
},
{
"answer_id": 6241898,
"author": "Mathias Bynens",
"author_id": 96656,
"author_profile": "https://Stackoverflow.com/users/96656",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://mathiasbynens.be/notes/css-escapes\">This article</a> will tell you how to escape any character in CSS.</p>\n\n<p>Now, there’s even a tool for it: <a href=\"http://mothereff.in/css-escapes#0search%5fform%3Aexpression\">http://mothereff.in/css-escapes#0search%5fform%3Aexpression</a></p>\n\n<p>TL;DR All the other answers to this question are incorrect. You need to escape both the underscore (to prevent IE6 from ignoring the rule altogether in some edge cases) and the colon character for the selector to work properly across different browsers.</p>\n\n<p>Technically, the colon character can be escaped as <code>\\:</code>, but that doesn’t work in IE < 8, so you’ll have to use <code>\\3a</code>:</p>\n\n<pre><code>#search\\_form\\3a expression {}\n</code></pre>\n"
},
{
"answer_id": 19452643,
"author": "mbokil",
"author_id": 1672318,
"author_profile": "https://Stackoverflow.com/users/1672318",
"pm_score": 0,
"selected": false,
"text": "<p>I work in a ADF framework and I often times have to use JQuery to select elements. This format works for me. This works in IE8 also.</p>\n\n<pre><code>$('[id*=\"gantt1::majorAxis\"]').css('border-top', 'solid 1px ' + mediumGray);\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
JSF is setting the ID of an input field to `search_form:expression`. I need to specify some styling on that element, but that colon looks like the beginning of a pseudo-element to the browser so it gets marked invalid and ignored. Is there anyway to escape the colon or something?
```
input#search_form:expression {
///...
}
```
|
Backslash:
```
input#search_form\:expression { ///...}
```
* See also *[Using Namespaces with CSS](http://msdn.microsoft.com/en-us/library/ms762307(VS.85).aspx)* (MSDN)
|
122,239 |
<p>Within a table cell that is vertical-align:bottom, I have one or two divs. Each div is floated right.<br>
Supposedly, the divs should not align to the bottom, but they do (which I don't understand, but is good).<br>
However, when I have two floated divs in the cell, they align themselves to the same top line.<br>
I want the first, smaller, div to sit all the way at the bottom. Another acceptable solution is to make it full height of the table cell.</p>
<p>It's difficult to explain, so here's the code:</p>
<blockquote>
<pre><code><style type="text/css">
table {
border-collapse: collapse;
}
td {
border:1px solid black;
vertical-align:bottom;
}
.h {
float:right;
background: #FFFFCC;
}
.ha {
float:right;
background: #FFCCFF;
}
</style>
<table>
<tr>
<td>
<div class="ha">@</div>
<div class="h">Title Text<br />Line 2</div>
</td>
<td>
<div class="ha">@</div>
<div class="h">Title Text<br />Line 2<br />Line 3</div>
</td>
<td>
<div class="h">Title Text<br />Line 2</div>
</td>
<td>
<div class="h">Title Text<br />Line 2</div>
</td>
<td>
<div class="h">Title Text<br />Line 2</div>
</td>
</tr>
<tr>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
<td>
<div class="d">123456789</div>
</td>
</tr>
</table>
</code></pre>
</blockquote>
<p>Here are the problems:</p>
<ol>
<li>Why does the @ sign sit at the same level as the yellow div?</li>
<li>Supposedly vertical-align doesn't apply to block elements (like a floated div) 1. But it does!</li>
<li>How can I make the @ sit at the bottom or make it full height of the table cell?</li>
</ol>
<p>I am testing in IE7 and FF2. Target support is IE6/7, FF2/3.</p>
<p><strong>Clarification:</strong> The goal is to have the red @ on the bottom line of the table cell, <em>next</em> to the yellow box. Using clear on either div will put them on different lines.
Additionally, the cells can have variable lines of text - therefore, <em>line-height</em> will not help.</p>
|
[
{
"answer_id": 122263,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>Add <code>clear: both</code> to the second element. If you want to @ to be below the yellow box, put it last in HTML code.</p>\n"
},
{
"answer_id": 122269,
"author": "Matthew Rapati",
"author_id": 15000,
"author_profile": "https://Stackoverflow.com/users/15000",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't want both divs on the same line then don't float them both right.\nIf you put the @ below the text in the markup and then set the float to 'clear' it would put it below the text.</p>\n"
},
{
"answer_id": 122279,
"author": "David Alpert",
"author_id": 8997,
"author_profile": "https://Stackoverflow.com/users/8997",
"pm_score": 3,
"selected": false,
"text": "<p>i've found this article to be extremely useful in understanding and troubleshooting vertical-align:</p>\n\n<p><a href=\"http://phrogz.net/CSS/vertical-align/index.html\" rel=\"noreferrer\">Understanding vertical-align, or \"How (Not) To Vertically Center Content\"</a></p>\n"
},
{
"answer_id": 122290,
"author": "nymacro",
"author_id": 10499,
"author_profile": "https://Stackoverflow.com/users/10499",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <blockquote>\n <p><a href=\"http://www.w3.org/TR/CSS2/visudet.html#line-height\" rel=\"nofollow noreferrer\">http://www.w3.org/TR/CSS2/visudet.html#line-height</a></p>\n \n <p>This property affects the vertical positioning inside a line box of the boxes generated by an inline-level element. The following values only have meaning with respect to a parent inline-level element, or to a parent block-level element, if that element generates anonymous inline boxes; they have no effect if no such parent exists.</p>\n </blockquote>\n</blockquote>\n\n<p>There is always confusion about the vertical-align property in CSS, because in most cases it doesn't do what you expect it to do. This is because it isn't the same as valign, which is allowable in many HTML 4 tags.</p>\n\n<p>For further information, you can check out:</p>\n\n<p><a href=\"http://www.ibloomstudios.com/articles/vertical-align_misuse/\" rel=\"nofollow noreferrer\">http://www.ibloomstudios.com/articles/vertical-align_misuse/</a>\n<a href=\"http://www.ibloomstudios.com/articles/applied_css_vertical-align/\" rel=\"nofollow noreferrer\">http://www.ibloomstudios.com/articles/applied_css_vertical-align/</a></p>\n\n<p>The link which David Alpert posted is incredibly useful in this matter.</p>\n"
},
{
"answer_id": 127277,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": true,
"text": "<p>I never answered the first two questions, so feel free to give your answers below. But I <em>did</em> solve the last problem, of how to make it work. </p>\n\n<p>I added a containing div to the two divs inside the table cells like so:</p>\n\n<blockquote>\n<pre><code><table>\n <tr>\n <td>\n <div class=\"t\">\n <div class=\"h\">Title Text<br />Line 2</div>\n <div class=\"ha\">@</div>\n </div>\n </td>\n</code></pre>\n</blockquote>\n\n<p>Then I used the following CSS</p>\n\n<blockquote>\n<pre><code><style type=\"text/css\">\ntable {\n border-collapse: collapse;\n}\ntd {\n border:1px solid black;\n vertical-align:bottom;\n}\n.t {\n position: relative;\n width:150px;\n}\n.h {\n background: #FFFFCC;\n width:135px;\n margin-right:15px;\n text-align:right;\n}\n.ha {\n background: #FFCCFF;\n width:15px;\n height:18px;\n position:absolute;\n right:0px;\n bottom:0px;\n}\n</style>\n</code></pre>\n</blockquote>\n\n<p>The key to it all is <strong>for a div to be position absolutely relative to it's <em>parent</em> the parent must be declared position:relative</strong></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8435/"
] |
Within a table cell that is vertical-align:bottom, I have one or two divs. Each div is floated right.
Supposedly, the divs should not align to the bottom, but they do (which I don't understand, but is good).
However, when I have two floated divs in the cell, they align themselves to the same top line.
I want the first, smaller, div to sit all the way at the bottom. Another acceptable solution is to make it full height of the table cell.
It's difficult to explain, so here's the code:
>
>
> ```
> <style type="text/css">
> table {
> border-collapse: collapse;
> }
> td {
> border:1px solid black;
> vertical-align:bottom;
> }
> .h {
> float:right;
> background: #FFFFCC;
> }
> .ha {
> float:right;
> background: #FFCCFF;
> }
> </style>
>
> <table>
> <tr>
> <td>
> <div class="ha">@</div>
> <div class="h">Title Text<br />Line 2</div>
> </td>
> <td>
> <div class="ha">@</div>
> <div class="h">Title Text<br />Line 2<br />Line 3</div>
> </td>
> <td>
> <div class="h">Title Text<br />Line 2</div>
> </td>
> <td>
> <div class="h">Title Text<br />Line 2</div>
> </td>
> <td>
> <div class="h">Title Text<br />Line 2</div>
> </td>
> </tr>
> <tr>
> <td>
> <div class="d">123456789</div>
> </td>
> <td>
> <div class="d">123456789</div>
> </td>
> <td>
> <div class="d">123456789</div>
> </td>
> <td>
> <div class="d">123456789</div>
> </td>
> <td>
> <div class="d">123456789</div>
> </td>
> </tr>
> </table>
>
> ```
>
>
Here are the problems:
1. Why does the @ sign sit at the same level as the yellow div?
2. Supposedly vertical-align doesn't apply to block elements (like a floated div) 1. But it does!
3. How can I make the @ sit at the bottom or make it full height of the table cell?
I am testing in IE7 and FF2. Target support is IE6/7, FF2/3.
**Clarification:** The goal is to have the red @ on the bottom line of the table cell, *next* to the yellow box. Using clear on either div will put them on different lines.
Additionally, the cells can have variable lines of text - therefore, *line-height* will not help.
|
I never answered the first two questions, so feel free to give your answers below. But I *did* solve the last problem, of how to make it work.
I added a containing div to the two divs inside the table cells like so:
>
>
> ```
> <table>
> <tr>
> <td>
> <div class="t">
> <div class="h">Title Text<br />Line 2</div>
> <div class="ha">@</div>
> </div>
> </td>
>
> ```
>
>
Then I used the following CSS
>
>
> ```
> <style type="text/css">
> table {
> border-collapse: collapse;
> }
> td {
> border:1px solid black;
> vertical-align:bottom;
> }
> .t {
> position: relative;
> width:150px;
> }
> .h {
> background: #FFFFCC;
> width:135px;
> margin-right:15px;
> text-align:right;
> }
> .ha {
> background: #FFCCFF;
> width:15px;
> height:18px;
> position:absolute;
> right:0px;
> bottom:0px;
> }
> </style>
>
> ```
>
>
The key to it all is **for a div to be position absolutely relative to it's *parent* the parent must be declared position:relative**
|
122,253 |
<p>After installing a third-party SDK, it very discourteously makes one if its templates the default item in "Add New Item..." dialog in Visual Studio 2005. This is also the case for all other similar dialogs - "Add Class...", "Add User Control..." etc.</p>
<p>Is there a way to change this behavior?</p>
|
[
{
"answer_id": 122270,
"author": "Asaf R",
"author_id": 6827,
"author_profile": "https://Stackoverflow.com/users/6827",
"pm_score": -1,
"selected": false,
"text": "<p>Try looking at the registry under </p>\n\n<pre><code>HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\\n</code></pre>\n\n<p>I see some relevant entries on my machine under</p>\n\n<pre><code>HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\9.0\n</code></pre>\n\n<p>for VS2008.</p>\n"
},
{
"answer_id": 246281,
"author": "Charles Anderson",
"author_id": 11677,
"author_profile": "https://Stackoverflow.com/users/11677",
"pm_score": 0,
"selected": false,
"text": "<p>I've just noticed this file on my PC: </p>\n\n<pre><code>C:\\Program Files\\Microsoft Visual Studio 8\\VC\\VCNewItems\\NewItems.vsdir\n</code></pre>\n\n<p>It's a text file, so you could check if the offending third-party stuff is in there.</p>\n"
},
{
"answer_id": 421161,
"author": "shackett",
"author_id": 52194,
"author_profile": "https://Stackoverflow.com/users/52194",
"pm_score": 2,
"selected": false,
"text": "<p>You may have to manually modify the SortOrder on the Item templates yourself. You can do this by following these directions:</p>\n\n<p>1) Find the Item Template(s)</p>\n\n<p>Item Templates for VS2005 are stored in the following locations:</p>\n\n<p><code></p>\n\n<pre><code> (Installed Templates) <VisualStudioInstallDir>\\Common7\\IDE\\ItemTemplates\\Language\\Locale\\\n (Custom Templates) My Documents\\Visual Studio 2005\\Templates\\ItemTemplates\\Language\\\n</code></pre>\n\n<p></code></p>\n\n<p>2) Open the template zip file to modify the .vstemplate file.</p>\n\n<p>Each Item Template is stored in a .zip file, so you will need to open the zip file that pertains to the template you want to modify.</p>\n\n<p>Open the template's .vstemplate file and find the SortOrder property under the TemplateData section. The following is a sample file:</p>\n\n<p><code></p>\n\n<p><TemplateData><br/>\n <Name>SomeITem</Name><br/>\n <Description>Description</Description><br/>\n <ProjectType>>CSharp</ProjectType><br/>\n <strong><SortOrder>1000</SortOrder></strong><br/>\n <DefaultName></DefaultName><br/>\n <ProvideDefaultName>true</ProvideDefaultName><br/>\n </TemplateData><br/></p>\n\n<p></code></p>\n\n<p>Modify the SortOrder value using the following rules:</p>\n\n<ul>\n<li>The default value is 100, and all values must be multiples of 10.</li>\n<li>The SortOrder element is ignored for user-created templates. All user-created templates are sorted alphabetically.</li>\n<li>Templates that have low sort order values appear in either the New Project or New Add Item dialog box before templates that have high sort order values.</li>\n</ul>\n\n<p>Once you've made edits to the template definitions you'll need to open a command prompt and navigate to the directory that contains devenv.exe, and type \"devenv /setup\". This presumably rebuilds some internal settings and until you do this you won't see any difference.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497/"
] |
After installing a third-party SDK, it very discourteously makes one if its templates the default item in "Add New Item..." dialog in Visual Studio 2005. This is also the case for all other similar dialogs - "Add Class...", "Add User Control..." etc.
Is there a way to change this behavior?
|
You may have to manually modify the SortOrder on the Item templates yourself. You can do this by following these directions:
1) Find the Item Template(s)
Item Templates for VS2005 are stored in the following locations:
```
(Installed Templates) <VisualStudioInstallDir>\Common7\IDE\ItemTemplates\Language\Locale\
(Custom Templates) My Documents\Visual Studio 2005\Templates\ItemTemplates\Language\
```
2) Open the template zip file to modify the .vstemplate file.
Each Item Template is stored in a .zip file, so you will need to open the zip file that pertains to the template you want to modify.
Open the template's .vstemplate file and find the SortOrder property under the TemplateData section. The following is a sample file:
<TemplateData>
<Name>SomeITem</Name>
<Description>Description</Description>
<ProjectType>>CSharp</ProjectType>
**<SortOrder>1000</SortOrder>**
<DefaultName></DefaultName>
<ProvideDefaultName>true</ProvideDefaultName>
</TemplateData>
Modify the SortOrder value using the following rules:
* The default value is 100, and all values must be multiples of 10.
* The SortOrder element is ignored for user-created templates. All user-created templates are sorted alphabetically.
* Templates that have low sort order values appear in either the New Project or New Add Item dialog box before templates that have high sort order values.
Once you've made edits to the template definitions you'll need to open a command prompt and navigate to the directory that contains devenv.exe, and type "devenv /setup". This presumably rebuilds some internal settings and until you do this you won't see any difference.
|
122,254 |
<p>I have a class that defines the names of various session attributes, e.g.</p>
<pre><code>class Constants {
public static final String ATTR_CURRENT_USER = "current.user";
}
</code></pre>
<p>I would like to use these constants within a JSP to test for the presence of these attributes, something like:</p>
<pre><code><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.example.Constants" %>
<c:if test="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}">
<%-- Do somthing --%>
</c:if>
</code></pre>
<p>But I can't seem to get the sytax correct. Also, to avoid repeating the rather lengthy tests above in multiple places, I'd like to assign the result to a local (page-scoped) variable, and refer to that instead. I believe I can do this with <code><c:set></code>, but again I'm struggling to find the correct syntax.</p>
<p><strong>UPDATE:</strong> Further to the suggestion below, I tried:</p>
<pre><code><c:set var="nullUser" scope="session"
value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" />
</code></pre>
<p>which didn't work. So instead, I tried substituting the literal value of the constant. I also added the constant to the content of the page, so I could verify the constant's value when the page is being rendered</p>
<pre><code><c:set var="nullUser" scope="session"
value="${sessionScope['current.user'] eq null}" />
<%= "Constant value: " + WebHelper.ATTR_CURRENT_PARTNER %>
</code></pre>
<p>This worked fine and it printed the expected value "current.user" on the page. I'm at a loss to explain why using the String literal works, but a reference to the constant doesn't, when the two appear to have the same value. Help.....</p>
|
[
{
"answer_id": 122863,
"author": "Matt N",
"author_id": 20605,
"author_profile": "https://Stackoverflow.com/users/20605",
"pm_score": -1,
"selected": false,
"text": "<p>First, your syntax had an extra \"]\" which was causing an error. </p>\n\n<p>To fix that, and to set a variable you would do this:</p>\n\n<pre><code><c:set var=\"nullUser\" \n scope=\"session\" \n value=\"${sessionScope[Constants.ATTR_CURRENT_USER] eq null}\" />\n\n<c:if test=\"${nullUser}\">\n <h2>First Test</h2>\n</c:if>\n<c:if test=\"${nullUser}\">\n <h2>Another Test</h2>\n</c:if>\n</code></pre>\n"
},
{
"answer_id": 125161,
"author": "Athena",
"author_id": 17846,
"author_profile": "https://Stackoverflow.com/users/17846",
"pm_score": 5,
"selected": true,
"text": "<p>It's not working in your example because the <code>ATTR_CURRENT_USER</code> constant is not visible to the JSTL tags, which expect properties to be exposed by getter functions. I haven't tried it, but the cleanest way to expose your constants appears to be the <a href=\"http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/index.html#useConstants\" rel=\"nofollow noreferrer\" title=\"Unstandard tag library from Apache\">unstandard tag library</a>.</p>\n\n<p>ETA: Old link I gave didn't work. New links can be found in this answer: <a href=\"https://stackoverflow.com/questions/127328/java-constants-in-jsp\">Java constants in JSP</a></p>\n\n<p>Code snippets to clarify the behavior you're seeing:\nSample class:</p>\n\n<pre><code>package com.example;\n\npublic class Constants\n{\n // attribute, visible to the scriptlet\n public static final String ATTR_CURRENT_USER = \"current.user\";\n\n // getter function;\n // name modified to make it clear, later on, \n // that I am calling this function\n // and not accessing the constant\n public String getATTR_CURRENT_USER_FUNC()\n {\n return ATTR_CURRENT_USER;\n }\n\n\n} \n</code></pre>\n\n<p>Snippet of the JSP page, showing sample usage: </p>\n\n<pre><code><%-- Set up the current user --%>\n<%\n session.setAttribute(\"current.user\", \"Me\");\n%>\n\n<%-- scriptlets --%>\n<%@ page import=\"com.example.Constants\" %>\n<h1>Using scriptlets</h1>\n<h3>Constants.ATTR_CURRENT_USER</h3>\n<%=Constants.ATTR_CURRENT_USER%> <br />\n<h3>Session[Constants.ATTR_CURRENT_USER]</h3>\n<%=session.getAttribute(Constants.ATTR_CURRENT_USER)%>\n\n<%-- JSTL --%>\n<%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %>\n<jsp:useBean id=\"cons\" class=\"com.example.Constants\" scope=\"session\"/>\n\n<h1>Using JSTL</h1>\n<h3>Constants.getATTR_CURRENT_USER_FUNC()</h3>\n<c:out value=\"${cons.ATTR_CURRENT_USER_FUNC}\"/>\n<h3>Session[Constants.getATTR_CURRENT_USER_FUNC()]</h3>\n<c:out value=\"${sessionScope[cons.ATTR_CURRENT_USER_FUNC]}\"/>\n<h3>Constants.ATTR_CURRENT_USER</h3>\n<c:out value=\"${sessionScope[Constants.ATTR_CURRENT_USER]}\"/>\n<%--\nCommented out, because otherwise will error:\nThe class 'com.example.Constants' does not have the property 'ATTR_CURRENT_USER'.\n\n<h3>cons.ATTR_CURRENT_USER</h3>\n<c:out value=\"${sessionScope[cons.ATTR_CURRENT_USER]}\"/>\n--%>\n<hr />\n</code></pre>\n\n<p>This outputs: </p>\n\n<h1>Using scriptlets</h1>\n\n<h3>Constants.ATTR_CURRENT_USER</h3>\n\n<p>current.user <br /></p>\n\n<h3>Session[Constants.ATTR_CURRENT_USER]</h3>\n\n<p>Me</p>\n\n<hr />\n\n<h1>Using JSTL</h1>\n\n<h3>Constants.getATTR_CURRENT_USER_FUNC()</h3>\n\n<p>current.user</p>\n\n<h3>Session[Constants.getATTR_CURRENT_USER_FUNC()]</h3>\n\n<p>Me</p>\n\n<h3>Constants.ATTR_CURRENT_USER</h3>\n\n<p><br /><hr /></p>\n"
},
{
"answer_id": 6056348,
"author": "Ramesh PVK",
"author_id": 760656,
"author_profile": "https://Stackoverflow.com/users/760656",
"pm_score": 1,
"selected": false,
"text": "<p>Plugin a Custom EL Resolver to the EL resolver chain, which will resolve the constants. An EL Resolver is Java class extending <a href=\"http://docs.oracle.com/javaee/6/api/javax/el/ELResolver.html\" rel=\"nofollow\">javax.el.ELResolver</a> class.</p>\n\n<p>Thanks,</p>\n"
},
{
"answer_id": 7119638,
"author": "Edgar",
"author_id": 461612,
"author_profile": "https://Stackoverflow.com/users/461612",
"pm_score": 2,
"selected": false,
"text": "<p>the topic is quite old, but anyway..:)</p>\n\n<p>I found nice solution to have Constants available through JSTL. You should prepare a map using reflection and put it wherever you want. </p>\n\n<p>The map will always contain all the constants you define in Constants class. You can put it into ServletContext using listener and enjoy constants in JSTL like: </p>\n\n<pre><code>${CONSTANTS[\"CONSTANT_NAME_IN_JAVA_CLASS_AS_A_STRING\"]}\n</code></pre>\n\n<p><br/>\nCONSTANTS here is a key you used putting map into Context :-)\n<br/><br/></p>\n\n<hr>\n\n<p>The following is a piece of my code building a map of the constant fields:</p>\n\n<pre><code>Map<String, Object> map = new HashMap<String, Object>();\nClass c = Constants.class;\nField[] fields = c.getDeclaredFields();\nfor (Field field : fields) {\n int modifier = field.getModifiers();\n if (Modifier.isPublic(modifier) && Modifier.isStatic(modifier) && Modifier.isFinal(modifier)) {\n try {\n map.put(field.getName(), field.get(null));//Obj param of get method is ignored for static fields\n } catch (IllegalAccessException e) { /* ignorable due to modifiers check */ }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 11489129,
"author": "daniel.deng",
"author_id": 1101166,
"author_profile": "https://Stackoverflow.com/users/1101166",
"pm_score": 3,
"selected": false,
"text": "<p>You can define Constants.ATTR_CURRENT_USER as a variable with c:set,just as below:</p>\n\n<pre><code><c:set var=\"ATTR_CURRENT_USER\" value=\"<%=Constants.ATTR_CURRENT_USER%>\" />\n<c:if test=\"${sessionScope[ATTR_CURRENT_USER] eq null}\"> \n <%-- Do somthing --%> \n</c:if> \n</code></pre>\n"
},
{
"answer_id": 11512392,
"author": "Roger Keays",
"author_id": 1104885,
"author_profile": "https://Stackoverflow.com/users/1104885",
"pm_score": 1,
"selected": false,
"text": "<p>Static properties aren't accessible in EL. The workaround I use is to create a non-static variable which assigns itself to the static value.</p>\n<pre><code>public final static String MANAGER_ROLE = 'manager';\npublic String manager_role = MANAGER_ROLE;\n</code></pre>\n<p>I use lombok to generate the getter and setter so that's pretty well it. Your EL looks like this:</p>\n<pre><code>${bean.manager_role}\n</code></pre>\n<p>Full code at <a href=\"https://rogerkeays.com/access-java-static-methods-and-constants-from-el\" rel=\"nofollow noreferrer\">https://rogerkeays.com/access-java-static-methods-and-constants-from-el</a></p>\n"
},
{
"answer_id": 18497680,
"author": "hb5fa",
"author_id": 112951,
"author_profile": "https://Stackoverflow.com/users/112951",
"pm_score": 1,
"selected": false,
"text": "<p>I am late to the discussion, but my approach is a little different. I use a custom tag handler to give JSP pages the constant values (numeric or string) it needs. Here is how I did it:</p>\n\n<p>Supposed I have a class that keeps all the constants:</p>\n\n<pre><code>public class AppJspConstants implements Serializable {\n public static final int MAXLENGTH_SIGNON_ID = 100;\n public static final int MAXLENGTH_PASSWORD = 100;\n public static final int MAXLENGTH_FULLNAME = 30;\n public static final int MAXLENGTH_PHONENUMBER = 30;\n public static final int MAXLENGTH_EXTENSION = 10;\n public static final int MAXLENGTH_EMAIL = 235;\n}\n</code></pre>\n\n<p>I also have this extremely simple custom tag:</p>\n\n<pre><code>public class JspFieldAttributes extends SimpleTagSupport {\n public void doTag() throws JspException, IOException {\n getJspContext().setAttribute(\"maxlength_signon_id\", AppJspConstants.MAXLENGTH_SIGNON_ID);\n getJspContext().setAttribute(\"maxlength_password\", AppJspConstants.MAXLENGTH_PASSWORD);\n getJspContext().setAttribute(\"maxlength_fullname\", AppJspConstants.MAXLENGTH_FULLNAME);\n getJspContext().setAttribute(\"maxlength_phonenumber\", AppJspConstants.MAXLENGTH_PHONENUMBER);\n getJspContext().setAttribute(\"maxlength_extension\", AppJspConstants.MAXLENGTH_EXTENSION);\n getJspContext().setAttribute(\"maxlength_email\", AppJspConstants.MAXLENGTH_EMAIL);\n\n getJspBody().invoke(null);\n }\n}\n</code></pre>\n\n<p>Then I have a StringHelper.tld. Inside, I have this :</p>\n\n<pre><code><tag>\n <name>fieldAttributes</name>\n <tag-class>package.path.JspFieldAttributes</tag-class>\n <body-content>scriptless</body-content>\n <info>This tag provide HTML field attributes that CCS is unable to do.</info>\n</tag>\n</code></pre>\n\n<p>On the JSP, I include the StringHelper.tld the normal way:</p>\n\n<pre><code><%@ taglib uri=\"/WEB-INF/tags/StringHelper.tld\" prefix=\"stringHelper\" %>\n</code></pre>\n\n<p>Finally, I use the tag and apply the needed values using EL. </p>\n\n<pre><code> <stringHelper:fieldAttributes>\n[snip]\n <form:input path=\"emailAddress\" cssClass=\"formeffect\" cssErrorClass=\"formEffect error\" maxlength=\"**${maxlength_email}**\"/>&nbsp;\n <form:errors path=\"emailAddress\" cssClass=\"error\" element=\"span\"/>\n[snip]\n </stringHelper:fieldAttributes>\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
I have a class that defines the names of various session attributes, e.g.
```
class Constants {
public static final String ATTR_CURRENT_USER = "current.user";
}
```
I would like to use these constants within a JSP to test for the presence of these attributes, something like:
```
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.example.Constants" %>
<c:if test="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}">
<%-- Do somthing --%>
</c:if>
```
But I can't seem to get the sytax correct. Also, to avoid repeating the rather lengthy tests above in multiple places, I'd like to assign the result to a local (page-scoped) variable, and refer to that instead. I believe I can do this with `<c:set>`, but again I'm struggling to find the correct syntax.
**UPDATE:** Further to the suggestion below, I tried:
```
<c:set var="nullUser" scope="session"
value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" />
```
which didn't work. So instead, I tried substituting the literal value of the constant. I also added the constant to the content of the page, so I could verify the constant's value when the page is being rendered
```
<c:set var="nullUser" scope="session"
value="${sessionScope['current.user'] eq null}" />
<%= "Constant value: " + WebHelper.ATTR_CURRENT_PARTNER %>
```
This worked fine and it printed the expected value "current.user" on the page. I'm at a loss to explain why using the String literal works, but a reference to the constant doesn't, when the two appear to have the same value. Help.....
|
It's not working in your example because the `ATTR_CURRENT_USER` constant is not visible to the JSTL tags, which expect properties to be exposed by getter functions. I haven't tried it, but the cleanest way to expose your constants appears to be the [unstandard tag library](http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/index.html#useConstants "Unstandard tag library from Apache").
ETA: Old link I gave didn't work. New links can be found in this answer: [Java constants in JSP](https://stackoverflow.com/questions/127328/java-constants-in-jsp)
Code snippets to clarify the behavior you're seeing:
Sample class:
```
package com.example;
public class Constants
{
// attribute, visible to the scriptlet
public static final String ATTR_CURRENT_USER = "current.user";
// getter function;
// name modified to make it clear, later on,
// that I am calling this function
// and not accessing the constant
public String getATTR_CURRENT_USER_FUNC()
{
return ATTR_CURRENT_USER;
}
}
```
Snippet of the JSP page, showing sample usage:
```
<%-- Set up the current user --%>
<%
session.setAttribute("current.user", "Me");
%>
<%-- scriptlets --%>
<%@ page import="com.example.Constants" %>
<h1>Using scriptlets</h1>
<h3>Constants.ATTR_CURRENT_USER</h3>
<%=Constants.ATTR_CURRENT_USER%> <br />
<h3>Session[Constants.ATTR_CURRENT_USER]</h3>
<%=session.getAttribute(Constants.ATTR_CURRENT_USER)%>
<%-- JSTL --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="cons" class="com.example.Constants" scope="session"/>
<h1>Using JSTL</h1>
<h3>Constants.getATTR_CURRENT_USER_FUNC()</h3>
<c:out value="${cons.ATTR_CURRENT_USER_FUNC}"/>
<h3>Session[Constants.getATTR_CURRENT_USER_FUNC()]</h3>
<c:out value="${sessionScope[cons.ATTR_CURRENT_USER_FUNC]}"/>
<h3>Constants.ATTR_CURRENT_USER</h3>
<c:out value="${sessionScope[Constants.ATTR_CURRENT_USER]}"/>
<%--
Commented out, because otherwise will error:
The class 'com.example.Constants' does not have the property 'ATTR_CURRENT_USER'.
<h3>cons.ATTR_CURRENT_USER</h3>
<c:out value="${sessionScope[cons.ATTR_CURRENT_USER]}"/>
--%>
<hr />
```
This outputs:
Using scriptlets
================
### Constants.ATTR\_CURRENT\_USER
current.user
### Session[Constants.ATTR\_CURRENT\_USER]
Me
---
Using JSTL
==========
### Constants.getATTR\_CURRENT\_USER\_FUNC()
current.user
### Session[Constants.getATTR\_CURRENT\_USER\_FUNC()]
Me
### Constants.ATTR\_CURRENT\_USER
---
|
122,267 |
<p>(using the IMAP commands, not with the assistance of any other mail package)</p>
|
[
{
"answer_id": 122289,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 2,
"selected": false,
"text": "<p>I guess you COPY the message to the new folder and then delete (EXPUNGE) it in the old one.</p>\n\n<p><a href=\"http://www.networksorcery.com/enp/rfc/rfc3501.txt\" rel=\"nofollow noreferrer\">RFC3501</a></p>\n\n<p><strong>HINT</strong> There's no DELETE command that does what you mean, you have to flag the message as deleted and then EXPUNGE the mailbox. Have a look at the RFC. Be careful with DELETE, as it deletes whole mailboxes, not single mails.</p>\n"
},
{
"answer_id": 122296,
"author": "Sec",
"author_id": 20555,
"author_profile": "https://Stackoverflow.com/users/20555",
"pm_score": 5,
"selected": true,
"text": "<p>I'm not sure how well-versed you are in imap-speak, but basically after login, \"SELECT\" the source mailbox, \"COPY\" the messages, and \"EXPUNGE\" the messages (or \"DELETE\" the old mailbox if it is empty now :-).</p>\n\n<pre><code>a login a s\nb select source\nc copy 1 othermbox\nd store 1 +flags (\\Deleted)\ne expunge\n</code></pre>\n\n<p>would be an example of messages to send. (<strong>Note</strong>: imap messages require a uniqe prefix before each command, thus the \"a b c\" in front)</p>\n\n<p>See <a href=\"http://james.apache.org/server/rfclist/imap4/rfc2060.txt\" rel=\"noreferrer\">RFC 2060</a> for details.</p>\n"
},
{
"answer_id": 3156528,
"author": "Avadhesh",
"author_id": 365148,
"author_profile": "https://Stackoverflow.com/users/365148",
"pm_score": 4,
"selected": false,
"text": "<p>If you have the uid of the email which is going to be moved.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import imaplib\n\nobj = imaplib.IMAP4_SSL('imap.gmail.com', 993)\nobj.login('username', 'password')\nobj.select(src_folder_name)\napply_lbl_msg = obj.uid('COPY', msg_uid, desti_folder_name)\nif apply_lbl_msg[0] == 'OK':\n mov, data = obj.uid('STORE', msg_uid , '+FLAGS', '(\\Deleted)')\n obj.expunge()\n</code></pre>\n\n<p>Where <strong>msg_uid</strong> is the uid of the mail.</p>\n"
},
{
"answer_id": 15816045,
"author": "Jan Kundrát",
"author_id": 2245623,
"author_profile": "https://Stackoverflow.com/users/2245623",
"pm_score": 5,
"selected": false,
"text": "<p>There are multiple ways to do that. The best one is the <code>UID MOVE</code> command defined in <a href=\"https://www.rfc-editor.org/rfc/rfc6851\" rel=\"nofollow noreferrer\">RFC 6851</a> from early 2013:</p>\n<pre><code>C: a UID MOVE 42:69 foo\nS: * OK [COPYUID 432432 42:69 1202:1229]\nS: * 22 EXPUNGE\nS: (more expunges)\nS: a OK Done\n</code></pre>\n<p>Presence of this extension is indicated by the <code>MOVE</code> capability.</p>\n<p>If it isn't available, but <code>UIDPLUS</code> (<a href=\"https://www.rfc-editor.org/rfc/rfc4315\" rel=\"nofollow noreferrer\">RFC 4315</a>) is, the second best option is to use the combination of <code>UID STORE</code>, <code>UID COPY</code> and <code>UID EXPUNGE</code>:</p>\n<pre><code>C: a01 UID COPY 42:69 foo\nS: a01 OK [COPYUID 432432 42:69 1202:1229] Copied\nC: a02 UID STORE 42:69 +FLAGS.SILENT (\\Deleted)\nS: a02 OK Stored\nC: a03 UID EXPUNGE 42:69\nS: * 10 EXPUNGE\nS: * 10 EXPUNGE\nS: * 10 EXPUNGE\nS: a03 Expunged\n</code></pre>\n<p>If the <code>UIDPLUS</code> is missing, there is nothing reasonable that you can do -- the <code>EXPUNGE</code> command permanently removes all messages which are marked for deletion, including those which you have not touched. The best this is to just use the <code>UID COPY</code> and <code>UID STORE</code> in that case.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
(using the IMAP commands, not with the assistance of any other mail package)
|
I'm not sure how well-versed you are in imap-speak, but basically after login, "SELECT" the source mailbox, "COPY" the messages, and "EXPUNGE" the messages (or "DELETE" the old mailbox if it is empty now :-).
```
a login a s
b select source
c copy 1 othermbox
d store 1 +flags (\Deleted)
e expunge
```
would be an example of messages to send. (**Note**: imap messages require a uniqe prefix before each command, thus the "a b c" in front)
See [RFC 2060](http://james.apache.org/server/rfclist/imap4/rfc2060.txt) for details.
|
122,273 |
<p>Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container? </p>
<p>I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself.</p>
|
[
{
"answer_id": 122361,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 5,
"selected": true,
"text": "<p>You can use poor-man's dependency injection:</p>\n\n<pre><code>public ProductController() : this( new Foo() )\n{\n //the framework calls this\n}\n\npublic ProductController(IFoo foo)\n{\n _foo = foo;\n}\n</code></pre>\n"
},
{
"answer_id": 123763,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 1,
"selected": false,
"text": "<p>You can create an IModelBinder that spins up an instance from a factory - or, yes, the container. =)</p>\n"
},
{
"answer_id": 126905,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 4,
"selected": false,
"text": "<p>One way is to create a ControllerFactory:</p>\n\n<pre><code>public class MyControllerFactory : DefaultControllerFactory\n{\n public override IController CreateController(\n RequestContext requestContext, string controllerName)\n {\n return [construct your controller here] ;\n }\n}\n</code></pre>\n\n<p>Then, in Global.asax.cs:</p>\n\n<pre><code> private void Application_Start(object sender, EventArgs e)\n {\n RegisterRoutes(RouteTable.Routes);\n ControllerBuilder.Current.SetControllerFactory(\n new MyNamespace.MyControllerFactory());\n }\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17902/"
] |
Does anyone have any code examples on how to create controllers that have parameters other than using a Dependency Injection Container?
I see plenty of samples with using containers like StructureMap, but nothing if you wanted to pass in the dependency class yourself.
|
You can use poor-man's dependency injection:
```
public ProductController() : this( new Foo() )
{
//the framework calls this
}
public ProductController(IFoo foo)
{
_foo = foo;
}
```
|
122,276 |
<p>I want to be able to quickly check whether I both have sudo access and my password is already authenticated. I'm not worried about having sudo access specifically for the operation I'm about to perform, but that would be a nice bonus.</p>
<p>Specifically what I'm trying to use this for is a script that I want to be runnable by a range of users. Some have sudo access. All know the root password.</p>
<p>When they run my script, I want it to use sudo permissions without prompting for a password if that is possible, and otherwise to fall back to asking for the <em>root</em> password (because they might not have sudo access).</p>
<p>My first non-working attempt was to fork off <code>sudo -S true</code> with STDIN closed or reading from /dev/null. But that still prompts for the password and waits a couple of seconds.</p>
<p>I've tried several other things, including waiting 0.3sec to see whether it succeeded immediately, but everything I try ends up failing in some situation. (And not because my timeout is too short.) It's difficult to figure out what goes on, because I can't just strace like I normally would.</p>
<p>One thing I <em>know</em> doesn't work is to close STDIN or attach it to a pipe before running <code>sudo -S true</code>. I was hoping that would make the password prompt immediately fail, but it still prompts and behaves strangely. I think it might want a terminal.</p>
|
[
{
"answer_id": 122300,
"author": "dirtside",
"author_id": 20903,
"author_profile": "https://Stackoverflow.com/users/20903",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know what the ultimate reason is for needing to do this, but I think maybe you might need to rethink whatever the core reason is. Trying to do complicated, unusual things with permissions frequently leads to security holes.</p>\n\n<p>More specifically, whatever it is the script is trying to do might be better done with setuid instead of sudo. (I'd also have to wonder why so many people have the root password. Sudo is there specifically to avoid giving people the root password.)</p>\n"
},
{
"answer_id": 122329,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": -1,
"selected": false,
"text": "<pre><code>getent group admin | grep $particular_user\n</code></pre>\n\n<p>You could use whoami to get the current user.</p>\n\n<p>Edit: But that doesn't help you find if you're still authed to do sudo tasks... Hmm..</p>\n"
},
{
"answer_id": 1677127,
"author": "bobomastoras",
"author_id": 203020,
"author_profile": "https://Stackoverflow.com/users/203020",
"pm_score": 0,
"selected": false,
"text": "<p>Running</p>\n\n<pre><code>sudo -S true < /dev/null &>/dev/null\n</code></pre>\n\n<p>seems to work, although it delays for a second before failing.</p>\n"
},
{
"answer_id": 22311192,
"author": "Dennis Williamson",
"author_id": 26428,
"author_profile": "https://Stackoverflow.com/users/26428",
"pm_score": 3,
"selected": true,
"text": "<p>With newer versions of <a href=\"http://www.sudo.ws/sudo/sudo.man.html\" rel=\"nofollow\"><code>sudo</code></a> there's an option for this purpose:</p>\n\n<pre><code>sudo -n true\n</code></pre>\n\n<p>I use <code>true</code> here for a no-op, but you could use any command.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14528/"
] |
I want to be able to quickly check whether I both have sudo access and my password is already authenticated. I'm not worried about having sudo access specifically for the operation I'm about to perform, but that would be a nice bonus.
Specifically what I'm trying to use this for is a script that I want to be runnable by a range of users. Some have sudo access. All know the root password.
When they run my script, I want it to use sudo permissions without prompting for a password if that is possible, and otherwise to fall back to asking for the *root* password (because they might not have sudo access).
My first non-working attempt was to fork off `sudo -S true` with STDIN closed or reading from /dev/null. But that still prompts for the password and waits a couple of seconds.
I've tried several other things, including waiting 0.3sec to see whether it succeeded immediately, but everything I try ends up failing in some situation. (And not because my timeout is too short.) It's difficult to figure out what goes on, because I can't just strace like I normally would.
One thing I *know* doesn't work is to close STDIN or attach it to a pipe before running `sudo -S true`. I was hoping that would make the password prompt immediately fail, but it still prompts and behaves strangely. I think it might want a terminal.
|
With newer versions of [`sudo`](http://www.sudo.ws/sudo/sudo.man.html) there's an option for this purpose:
```
sudo -n true
```
I use `true` here for a no-op, but you could use any command.
|
122,277 |
<p>I switched from Perl to Python about a year ago and haven't looked back. There is only <i>one</i> idiom that I've ever found I can do more easily in Perl than in Python:</p>
<pre><code>if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
</code></pre>
<p>The corresponding Python code is not so elegant since the if statements keep getting nested:</p>
<pre><code>m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
</code></pre>
<p>Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...</p>
|
[
{
"answer_id": 122294,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 4,
"selected": false,
"text": "<p>Using named groups and a dispatch table:</p>\n\n<pre><code>r = re.compile(r'(?P<cmd>foo|bar|baz)(?P<data>.+)')\n\ndef do_foo(data):\n ...\n\ndef do_bar(data):\n ...\n\ndef do_baz(data):\n ...\n\ndispatch = {\n 'foo': do_foo,\n 'bar': do_bar,\n 'baz': do_baz,\n}\n\n\nm = r.match(var)\nif m:\n dispatch[m.group('cmd')](m.group('data'))\n</code></pre>\n\n<p>With a little bit of introspection you can auto-generate the regexp and the dispatch table.</p>\n"
},
{
"answer_id": 122345,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 2,
"selected": false,
"text": "<p>Alternatively, something not using regular expressions at all:</p>\n\n<pre><code>prefix, data = var[:3], var[3:]\nif prefix == 'foo':\n # do something with data\nelif prefix == 'bar':\n # do something with data\nelif prefix == 'baz':\n # do something with data\nelse:\n # do something with var\n</code></pre>\n\n<p>Whether that is suitable depends on your actual problem. Don't forget, regular expressions aren't the swiss army knife that they are in Perl; Python has different constructs for doing string manipulation.</p>\n"
},
{
"answer_id": 122364,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 2,
"selected": false,
"text": "<pre><code>def find_first_match(string, *regexes):\n for regex, handler in regexes:\n m = re.search(regex, string):\n if m:\n handler(m)\n return\n else:\n raise ValueError\n\nfind_first_match(\n foo, \n (r'foo(.+)', handle_foo), \n (r'bar(.+)', handle_bar), \n (r'baz(.+)', handle_baz))\n</code></pre>\n\n<p>To speed it up, one could turn all regexes into one internally and create the dispatcher on the fly. Ideally, this would be turned into a class then.</p>\n"
},
{
"answer_id": 123083,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 3,
"selected": false,
"text": "<p>Yeah, it's kind of annoying. Perhaps this will work for your case. </p>\n\n<pre><code>\nimport re\n\nclass ReCheck(object):\n def __init__(self):\n self.result = None\n def check(self, pattern, text):\n self.result = re.search(pattern, text)\n return self.result\n\nvar = 'bar stuff'\nm = ReCheck()\nif m.check(r'foo(.+)',var):\n print m.result.group(1)\nelif m.check(r'bar(.+)',var):\n print m.result.group(1)\nelif m.check(r'baz(.+)',var):\n print m.result.group(1)\n</code></pre>\n\n<p><strong>EDIT:</strong> Brian correctly pointed out that my first attempt did not work. Unfortunately, this attempt is longer.</p>\n"
},
{
"answer_id": 124128,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 3,
"selected": false,
"text": "<p>I'd suggest this, as it uses the least regex to accomplish your goal. It is still functional code, but no worse then your old Perl.</p>\n\n<pre><code>import re\nvar = \"barbazfoo\"\n\nm = re.search(r'(foo|bar|baz)(.+)', var)\nif m.group(1) == 'foo':\n print m.group(1)\n # do something with m.group(1)\nelif m.group(1) == \"bar\":\n print m.group(1)\n # do something with m.group(1)\nelif m.group(1) == \"baz\":\n print m.group(2)\n # do something with m.group(2)\n</code></pre>\n"
},
{
"answer_id": 135720,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": false,
"text": "<pre><code>r\"\"\"\nThis is an extension of the re module. It stores the last successful\nmatch object and lets you access it's methods and attributes via\nthis module.\n\nThis module exports the following additional functions:\n expand Return the string obtained by doing backslash substitution on a\n template string.\n group Returns one or more subgroups of the match.\n groups Return a tuple containing all the subgroups of the match.\n start Return the indices of the start of the substring matched by\n group.\n end Return the indices of the end of the substring matched by group.\n span Returns a 2-tuple of (start(), end()) of the substring matched\n by group.\n\nThis module defines the following additional public attributes:\n pos The value of pos which was passed to the search() or match()\n method.\n endpos The value of endpos which was passed to the search() or\n match() method.\n lastindex The integer index of the last matched capturing group.\n lastgroup The name of the last matched capturing group.\n re The regular expression object which as passed to search() or\n match().\n string The string passed to match() or search().\n\"\"\"\n\nimport re as re_\n\nfrom re import *\nfrom functools import wraps\n\n__all__ = re_.__all__ + [ \"expand\", \"group\", \"groups\", \"start\", \"end\", \"span\",\n \"last_match\", \"pos\", \"endpos\", \"lastindex\", \"lastgroup\", \"re\", \"string\" ]\n\nlast_match = pos = endpos = lastindex = lastgroup = re = string = None\n\ndef _set_match(match=None):\n global last_match, pos, endpos, lastindex, lastgroup, re, string\n if match is not None:\n last_match = match\n pos = match.pos\n endpos = match.endpos\n lastindex = match.lastindex\n lastgroup = match.lastgroup\n re = match.re\n string = match.string\n return match\n\n@wraps(re_.match)\ndef match(pattern, string, flags=0):\n return _set_match(re_.match(pattern, string, flags))\n\n\n@wraps(re_.search)\ndef search(pattern, string, flags=0):\n return _set_match(re_.search(pattern, string, flags))\n\n@wraps(re_.findall)\ndef findall(pattern, string, flags=0):\n matches = re_.findall(pattern, string, flags)\n if matches:\n _set_match(matches[-1])\n return matches\n\n@wraps(re_.finditer)\ndef finditer(pattern, string, flags=0):\n for match in re_.finditer(pattern, string, flags):\n yield _set_match(match)\n\ndef expand(template):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.expand(template)\n\ndef group(*indices):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.group(*indices)\n\ndef groups(default=None):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.groups(default)\n\ndef groupdict(default=None):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.groupdict(default)\n\ndef start(group=0):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.start(group)\n\ndef end(group=0):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.end(group)\n\ndef span(group=0):\n if last_match is None:\n raise TypeError, \"No successful match yet.\"\n return last_match.span(group)\n\ndel wraps # Not needed past module compilation\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>if gre.match(\"foo(.+)\", var):\n # do something with gre.group(1)\nelif gre.match(\"bar(.+)\", var):\n # do something with gre.group(1)\nelif gre.match(\"baz(.+)\", var):\n # do something with gre.group(1)\n</code></pre>\n"
},
{
"answer_id": 1806345,
"author": "Craig McQueen",
"author_id": 60075,
"author_profile": "https://Stackoverflow.com/users/60075",
"pm_score": 3,
"selected": false,
"text": "<p>With thanks to <a href=\"https://stackoverflow.com/questions/1663995/python-variable-assignment-and-if-statement\">this other SO question</a>:</p>\n\n<pre><code>import re\n\nclass DataHolder:\n def __init__(self, value=None, attr_name='value'):\n self._attr_name = attr_name\n self.set(value)\n def __call__(self, value):\n return self.set(value)\n def set(self, value):\n setattr(self, self._attr_name, value)\n return value\n def get(self):\n return getattr(self, self._attr_name)\n\nstring = u'test bar 123'\nsave_match = DataHolder(attr_name='match')\nif save_match(re.search('foo (\\d+)', string)):\n print \"Foo\"\n print save_match.match.group(1)\nelif save_match(re.search('bar (\\d+)', string)):\n print \"Bar\"\n print save_match.match.group(1)\nelif save_match(re.search('baz (\\d+)', string)):\n print \"Baz\"\n print save_match.match.group(1)\n</code></pre>\n"
},
{
"answer_id": 2021009,
"author": "Daniel Bingham",
"author_id": 156678,
"author_profile": "https://Stackoverflow.com/users/156678",
"pm_score": 2,
"selected": false,
"text": "<p>Here's the way I solved this issue:</p>\n\n<pre><code>matched = False;\n\nm = re.match(\"regex1\");\nif not matched and m:\n #do something\n matched = True;\n\nm = re.match(\"regex2\");\nif not matched and m:\n #do something else\n matched = True;\n\nm = re.match(\"regex3\");\nif not matched and m:\n #do yet something else\n matched = True;\n</code></pre>\n\n<p>Not nearly as clean as the original pattern. However, it is simple, straightforward and doesn't require extra modules or that you change the original regexs.</p>\n"
},
{
"answer_id": 4195819,
"author": "Matus",
"author_id": 477800,
"author_profile": "https://Stackoverflow.com/users/477800",
"pm_score": 1,
"selected": false,
"text": "<p>how about using a dictionary?</p>\n\n<pre><code>match_objects = {}\n\nif match_objects.setdefault( 'mo_foo', re_foo.search( text ) ):\n # do something with match_objects[ 'mo_foo' ]\n\nelif match_objects.setdefault( 'mo_bar', re_bar.search( text ) ):\n # do something with match_objects[ 'mo_bar' ]\n\nelif match_objects.setdefault( 'mo_baz', re_baz.search( text ) ):\n # do something with match_objects[ 'mo_baz' ]\n\n...\n</code></pre>\n\n<p>however, you must ensure there are no duplicate match_objects dictionary keys ( mo_foo, mo_bar, ... ), best by giving each regular expression its own name and naming the match_objects keys accordingly, otherwise match_objects.setdefault() method would return existing match object instead of creating new match object by running re_xxx.search( text ).</p>\n"
},
{
"answer_id": 30799800,
"author": "Mike Robins",
"author_id": 5002578,
"author_profile": "https://Stackoverflow.com/users/5002578",
"pm_score": 0,
"selected": false,
"text": "<p>My solution would be:</p>\n\n<pre><code>import re\n\nclass Found(Exception): pass\n\ntry: \n for m in re.finditer('bar(.+)', var):\n # Do something\n raise Found\n\n for m in re.finditer('foo(.+)', var):\n # Do something else\n raise Found\n\nexcept Found: pass\n</code></pre>\n"
},
{
"answer_id": 38849153,
"author": "Yirkha",
"author_id": 3543211,
"author_profile": "https://Stackoverflow.com/users/3543211",
"pm_score": 1,
"selected": false,
"text": "<p>Expanding on the solution by Pat Notz a bit, I found it even the more elegant to:<br>\n - name the methods the same as <code>re</code> provides (e.g. <code>search()</code> vs. <code>check()</code>) and<br>\n - implement the necessary methods like <code>group()</code> on the holder object itself:</p>\n\n<pre><code>class Re(object):\n def __init__(self):\n self.result = None\n\n def search(self, pattern, text):\n self.result = re.search(pattern, text)\n return self.result\n\n def group(self, index):\n return self.result.group(index)\n</code></pre>\n\n<hr>\n\n<h3>Example</h3>\n\n<p>Instead of e.g. this:</p>\n\n<pre><code>m = re.search(r'set ([^ ]+) to ([^ ]+)', line)\nif m:\n vars[m.group(1)] = m.group(2)\nelse:\n m = re.search(r'print ([^ ]+)', line)\n if m:\n print(vars[m.group(1)])\n else:\n m = re.search(r'add ([^ ]+) to ([^ ]+)', line)\n if m:\n vars[m.group(2)] += vars[m.group(1)]\n</code></pre>\n\n<p>One does just this:</p>\n\n<pre><code>m = Re()\n...\nif m.search(r'set ([^ ]+) to ([^ ]+)', line):\n vars[m.group(1)] = m.group(2)\nelif m.search(r'print ([^ ]+)', line):\n print(vars[m.group(1)])\nelif m.search(r'add ([^ ]+) to ([^ ]+)', line):\n vars[m.group(2)] += vars[m.group(1)]\n</code></pre>\n\n<p>Looks very natural in the end, does not need too many code changes when moving from Perl and avoids the problems with global state like some other solutions.</p>\n"
},
{
"answer_id": 44837090,
"author": "Mike Robins",
"author_id": 5002578,
"author_profile": "https://Stackoverflow.com/users/5002578",
"pm_score": 1,
"selected": false,
"text": "<p>A minimalist DataHolder:</p>\n\n<pre><code>class Holder(object):\n def __call__(self, *x):\n if x:\n self.x = x[0]\n return self.x\n\ndata = Holder()\n\nif data(re.search('foo (\\d+)', string)):\n print data().group(1)\n</code></pre>\n\n<p>or as a singleton function:</p>\n\n<pre><code>def data(*x):\n if x:\n data.x = x[0]\n return data.x\n</code></pre>\n"
},
{
"answer_id": 45798441,
"author": "Jim Arlow",
"author_id": 8495441,
"author_profile": "https://Stackoverflow.com/users/8495441",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a RegexDispatcher class that dispatches its subclass methods by regular expression. </p>\n\n<p>Each dispatchable method is annotated with a regular expression e.g.</p>\n\n<pre><code>def plus(self, regex: r\"\\+\", **kwargs):\n...\n</code></pre>\n\n<p>In this case, the annotation is called 'regex' and its value is the regular expression to match on, '\\+', which is the + sign. These annotated methods are put in subclasses, not in the base class.</p>\n\n<p>When the dispatch(...) method is called on a string, the class finds the method with an annotation regular expression that matches the string and calls it. Here is the class:</p>\n\n<pre><code>import inspect\nimport re\n\n\nclass RegexMethod:\n def __init__(self, method, annotation):\n self.method = method\n self.name = self.method.__name__\n self.order = inspect.getsourcelines(self.method)[1] # The line in the source file\n self.regex = self.method.__annotations__[annotation]\n\n def match(self, s):\n return re.match(self.regex, s)\n\n # Make it callable\n def __call__(self, *args, **kwargs):\n return self.method(*args, **kwargs)\n\n def __str__(self):\n return str.format(\"Line: %s, method name: %s, regex: %s\" % (self.order, self.name, self.regex))\n\n\nclass RegexDispatcher:\n def __init__(self, annotation=\"regex\"):\n self.annotation = annotation\n # Collect all the methods that have an annotation that matches self.annotation\n # For example, methods that have the annotation \"regex\", which is the default\n self.dispatchMethods = [RegexMethod(m[1], self.annotation) for m in\n inspect.getmembers(self, predicate=inspect.ismethod) if\n (self.annotation in m[1].__annotations__)]\n # Be sure to process the dispatch methods in the order they appear in the class!\n # This is because the order in which you test regexes is important.\n # The most specific patterns must always be tested BEFORE more general ones\n # otherwise they will never match.\n self.dispatchMethods.sort(key=lambda m: m.order)\n\n # Finds the FIRST match of s against a RegexMethod in dispatchMethods, calls the RegexMethod and returns\n def dispatch(self, s, **kwargs):\n for m in self.dispatchMethods:\n if m.match(s):\n return m(self.annotation, **kwargs)\n return None\n</code></pre>\n\n<p>To use this class, subclass it to create a class with annotated methods. By way of example, here is a simple RPNCalculator that inherits from RegexDispatcher. The methods to be dispatched are (of course) the ones with the 'regex' annotation. The parent dispatch() method is invoked in <strong>call</strong>.</p>\n\n<pre><code>from RegexDispatcher import *\nimport math\n\nclass RPNCalculator(RegexDispatcher):\n def __init__(self):\n RegexDispatcher.__init__(self)\n self.stack = []\n\n def __str__(self):\n return str(self.stack)\n\n # Make RPNCalculator objects callable\n def __call__(self, expression):\n # Calculate the value of expression\n for t in expression.split():\n self.dispatch(t, token=t)\n return self.top() # return the top of the stack\n\n # Stack management\n def top(self):\n return self.stack[-1] if len(self.stack) > 0 else []\n\n def push(self, x):\n return self.stack.append(float(x))\n\n def pop(self, n=1):\n return self.stack.pop() if n == 1 else [self.stack.pop() for n in range(n)]\n\n # Handle numbers\n def number(self, regex: r\"[-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?\", **kwargs):\n self.stack.append(float(kwargs['token']))\n\n # Binary operators\n def plus(self, regex: r\"\\+\", **kwargs):\n a, b = self.pop(2)\n self.push(b + a)\n\n def minus(self, regex: r\"\\-\", **kwargs):\n a, b = self.pop(2)\n self.push(b - a)\n\n def multiply(self, regex: r\"\\*\", **kwargs):\n a, b = self.pop(2)\n self.push(b * a)\n\n def divide(self, regex: r\"\\/\", **kwargs):\n a, b = self.pop(2)\n self.push(b / a)\n\n def pow(self, regex: r\"exp\", **kwargs):\n a, b = self.pop(2)\n self.push(a ** b)\n\n def logN(self, regex: r\"logN\", **kwargs):\n a, b = self.pop(2)\n self.push(math.log(a,b))\n\n # Unary operators\n def neg(self, regex: r\"neg\", **kwargs):\n self.push(-self.pop())\n\n def sqrt(self, regex: r\"sqrt\", **kwargs):\n self.push(math.sqrt(self.pop()))\n\n def log2(self, regex: r\"log2\", **kwargs):\n self.push(math.log2(self.pop()))\n\n def log10(self, regex: r\"log10\", **kwargs):\n self.push(math.log10(self.pop()))\n\n def pi(self, regex: r\"pi\", **kwargs):\n self.push(math.pi)\n\n def e(self, regex: r\"e\", **kwargs):\n self.push(math.e)\n\n def deg(self, regex: r\"deg\", **kwargs):\n self.push(math.degrees(self.pop()))\n\n def rad(self, regex: r\"rad\", **kwargs):\n self.push(math.radians(self.pop()))\n\n # Whole stack operators\n def cls(self, regex: r\"c\", **kwargs):\n self.stack=[]\n\n def sum(self, regex: r\"sum\", **kwargs):\n self.stack=[math.fsum(self.stack)]\n\n\nif __name__ == '__main__':\n calc = RPNCalculator()\n\n print(calc('2 2 exp 3 + neg'))\n\n print(calc('c 1 2 3 4 5 sum 2 * 2 / pi'))\n\n print(calc('pi 2 * deg'))\n\n print(calc('2 2 logN'))\n</code></pre>\n\n<p>I like this solution because there are no separate lookup tables. The regular expression to match on is embedded in the method to be called as an annotation. For me, this is as it should be. It would be nice if Python allowed more flexible annotations, because I would rather put the regex annotation on the method itself rather than embed it in the method parameter list. However, this isn't possible at the moment.</p>\n\n<p>For interest, take a look at the Wolfram language in which functions are polymorphic on arbitrary patterns, not just on argument types. A function that is polymorphic on a regex is a very powerful idea, but we can't get there cleanly in Python. The RegexDispatcher class is the best I could do.</p>\n"
},
{
"answer_id": 55887489,
"author": "Xavier Guihot",
"author_id": 9297144,
"author_profile": "https://Stackoverflow.com/users/9297144",
"pm_score": 4,
"selected": true,
"text": "<p>Starting <code>Python 3.8</code>, and the introduction of <a href=\"https://www.python.org/dev/peps/pep-0572/\" rel=\"nofollow noreferrer\">assignment expressions (PEP 572)</a> (<code>:=</code> operator), we can now capture the condition value <code>re.search(pattern, text)</code> in a variable <code>match</code> in order to both check if it's not <code>None</code> and then re-use it within the body of the condition:</p>\n\n<pre><code>if match := re.search(r'foo(.+)', text):\n # do something with match.group(1)\nelif match := re.search(r'bar(.+)', text):\n # do something with match.group(1)\nelif match := re.search(r'baz(.+)', text)\n # do something with match.group(1)\n</code></pre>\n"
},
{
"answer_id": 59789328,
"author": "joe-purl",
"author_id": 562210,
"author_profile": "https://Stackoverflow.com/users/562210",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import re\n\ns = '1.23 Million equals to 1230000'\n\ns = re.sub(\"([\\d.]+)(\\s*)Million\", lambda m: str(round(float(m.groups()[0]) * 1000_000))+m.groups()[1], s)\n\nprint(s)\n</code></pre>\n\n<hr>\n\n<p>1230000 equals to 1230000</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20789/"
] |
I switched from Perl to Python about a year ago and haven't looked back. There is only *one* idiom that I've ever found I can do more easily in Perl than in Python:
```
if ($var =~ /foo(.+)/) {
# do something with $1
} elsif ($var =~ /bar(.+)/) {
# do something with $1
} elsif ($var =~ /baz(.+)/) {
# do something with $1
}
```
The corresponding Python code is not so elegant since the if statements keep getting nested:
```
m = re.search(r'foo(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'bar(.+)', var)
if m:
# do something with m.group(1)
else:
m = re.search(r'baz(.+)', var)
if m:
# do something with m.group(2)
```
Does anyone have an elegant way to reproduce this pattern in Python? I've seen anonymous function dispatch tables used, but those seem kind of unwieldy to me for a small number of regular expressions...
|
Starting `Python 3.8`, and the introduction of [assignment expressions (PEP 572)](https://www.python.org/dev/peps/pep-0572/) (`:=` operator), we can now capture the condition value `re.search(pattern, text)` in a variable `match` in order to both check if it's not `None` and then re-use it within the body of the condition:
```
if match := re.search(r'foo(.+)', text):
# do something with match.group(1)
elif match := re.search(r'bar(.+)', text):
# do something with match.group(1)
elif match := re.search(r'baz(.+)', text)
# do something with match.group(1)
```
|
122,301 |
<p>Is there an easy way to get a conflict summary after running a <code>cvs update</code>? </p>
<p>I work on a large project and after doing some work I need to do an update. The list of changes coming back from the cvs update command is several pages long and I'd like to see only the list of conflicts (starts with 'C') repeated at the end of the cvs update command output.</p>
<p>The solution needs to work from the command line.</p>
<p>If my normal output is:</p>
<pre><code>M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt
</code></pre>
<p>I want my new output to be:</p>
<pre><code>M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt
Conflict Summary:
C src/file3.txt
</code></pre>
<p>I want this to be a single command (possibly a short script or alias) that outputs the normal cvs output as it happens followed by a summary of conflicts.</p>
|
[
{
"answer_id": 122337,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have cvs handy what is the exact format of the output of cvs update</p>\n\n<p>I seem to remember C <filename><br>\nIf so you could use:</p>\n\n<blockquote>\n <p>cvs update | tee log | grep \"^C\"</p>\n</blockquote>\n\n<p>The full output of cvs is saved into log for use at another point.\nThen we grep for all lines <b>beginning</b> with 'C'</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 169551,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": true,
"text": "<p>Given the specification, it seems that you need a minor adaptation of Martin York's solution (because that only shows the conflicts and not the normal log information). Something like this - which might be called 'cvsupd':</p>\n\n<pre><code>tmp=${TMPDIR:-/tmp}/cvsupd.$$\ntrap \"rm -f $tmp; exit 1\" 0 1 2 3 13 15\ncvs update \"$@\" | tee $tmp\nif grep -s '^C' $tmp\nthen\n echo\n echo Conflict Summary:\n grep '^C' $tmp\nfi\nrm -f $tmp\ntrap 0\nexit 0\n</code></pre>\n\n<p>The trap commands ensure that the log file is not left around. It catches the normal signals - HUP, INT, QUIT, PIPE and TERM (respectively) and 0 traps any other exit from the shell.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] |
Is there an easy way to get a conflict summary after running a `cvs update`?
I work on a large project and after doing some work I need to do an update. The list of changes coming back from the cvs update command is several pages long and I'd like to see only the list of conflicts (starts with 'C') repeated at the end of the cvs update command output.
The solution needs to work from the command line.
If my normal output is:
```
M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt
```
I want my new output to be:
```
M src/file1.txt
M src/file2.txt
cvs server: conflicts found ...
C src/file3.txt
M src/file4.txt
M src/file5.txt
Conflict Summary:
C src/file3.txt
```
I want this to be a single command (possibly a short script or alias) that outputs the normal cvs output as it happens followed by a summary of conflicts.
|
Given the specification, it seems that you need a minor adaptation of Martin York's solution (because that only shows the conflicts and not the normal log information). Something like this - which might be called 'cvsupd':
```
tmp=${TMPDIR:-/tmp}/cvsupd.$$
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15
cvs update "$@" | tee $tmp
if grep -s '^C' $tmp
then
echo
echo Conflict Summary:
grep '^C' $tmp
fi
rm -f $tmp
trap 0
exit 0
```
The trap commands ensure that the log file is not left around. It catches the normal signals - HUP, INT, QUIT, PIPE and TERM (respectively) and 0 traps any other exit from the shell.
|
122,302 |
<p>According to select name from system_privilege_map System has been granted:</p>
<pre><code>SELECT ANY TABLE
</code></pre>
<p>...and lots of other * ANY TABLES.</p>
<p>Plainly running</p>
<pre><code>select * from the_table;
select * from the_table;
</code></pre>
<p>...nets the given response:</p>
<blockquote>
<p>ERROR at line 1:
ORA-00942: table or view does not exist</p>
</blockquote>
<p>I can log in as that user and run the same command just fine.</p>
<p>I'm running under the assumption I should be able to run queries (select in this case) agaisnt a general user's DB table. Is my assumption correct, and if so, how do I do it?</p>
|
[
{
"answer_id": 122309,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": true,
"text": "<p>If the_table is owned by user \"some_user\" then:</p>\n\n<pre><code>select * from some_user.the_table;\n</code></pre>\n"
},
{
"answer_id": 122310,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 2,
"selected": false,
"text": "<p>You need to do:</p>\n\n<pre><code>SELECT * FROM schema_name.the_table;\n</code></pre>\n\n<p>Or use SYNONYMs...</p>\n\n<pre><code>CREATE SYNONYM the_table FOR schema_name.the_table;\n</code></pre>\n"
},
{
"answer_id": 233552,
"author": "Gazmo",
"author_id": 31175,
"author_profile": "https://Stackoverflow.com/users/31175",
"pm_score": 3,
"selected": false,
"text": "<p>As the previous responses have said, you can prefix the object name with the schema name:</p>\n\n<pre><code>SELECT * FROM schema_name.the_table;\n</code></pre>\n\n<p>Or you can use a synonym (private or public):</p>\n\n<pre><code>CREATE (PUBLIC) SYNONYM the_table FOR schema_name.the_table;\n</code></pre>\n\n<p>Or you can issue an alter session command to set the default schema to the the one you want:</p>\n\n<pre><code>ALTER SESSION SET current_schema=schema_name;\n</code></pre>\n\n<p>Note that this just sets the default schema, and is the equivalent of prefixing all (unqualified) object names with <code>schema_name</code>. You can still prefix objects with a different schema name to access an object from another schema. Using <code>SET current_schema</code> does not affect your privileges: you still have the privileges of the user you logged in as, not the schema you have set.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
According to select name from system\_privilege\_map System has been granted:
```
SELECT ANY TABLE
```
...and lots of other \* ANY TABLES.
Plainly running
```
select * from the_table;
select * from the_table;
```
...nets the given response:
>
> ERROR at line 1:
> ORA-00942: table or view does not exist
>
>
>
I can log in as that user and run the same command just fine.
I'm running under the assumption I should be able to run queries (select in this case) agaisnt a general user's DB table. Is my assumption correct, and if so, how do I do it?
|
If the\_table is owned by user "some\_user" then:
```
select * from some_user.the_table;
```
|
122,313 |
<p>I'm getting confused with the include/exclude jargon, and my actual SVN client doesn't seem to have (or I've been unable to find it easily) a simple option to add or remove a certain type of files for version control.</p>
<p>Let's say for example I've added the entire Visual Studio folder, with its solutions, projects, debug files, etc., but I only want to version the actual source files. What would be the simplest way to do that?</p>
|
[
{
"answer_id": 122328,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 1,
"selected": false,
"text": "<p>At the lowest level, SVN allows you to ignore certain files or patterns with <a href=\"http://www.petefreitag.com/item/662.cfm\" rel=\"nofollow noreferrer\">svn:ignore</a> attribute. VS add-ins for SVN such as <a href=\"http://www.visualsvn.com/\" rel=\"nofollow noreferrer\">VisualSVN</a> will automatically ignore those files on your behalf. If you're using <a href=\"http://tortoisesvn.tigris.org/\" rel=\"nofollow noreferrer\">TortoiseSVN</a>, you can right-click files and folders in Explorer and choose <em>Add to Ignore List</em>.</p>\n"
},
{
"answer_id": 122330,
"author": "Max Cantor",
"author_id": 16034,
"author_profile": "https://Stackoverflow.com/users/16034",
"pm_score": 3,
"selected": false,
"text": "<p>This can be achieved using the <a href=\"http://svnbook.red-bean.com/en/1.1/ch07s02.html#svn-ch-7-sect-2.3.3\" rel=\"nofollow noreferrer\">svn:ignore</a> property, or the global-ignores property in your <code>~/.subversion/config</code> file. (Scroll to the top of that first link to see instructions on editing properties.)</p>\n\n<p>By using <code>svn propset</code> or <code>svn propedit</code> on a directory, you will be able to make Subversion ignore all files matching that pattern within the specific directory. If you change global-ignores in <code>~/.subversion/config</code>'s <code>[miscellany]</code> section, however, Subversion will ignore such files no matter where they are located.</p>\n"
},
{
"answer_id": 122331,
"author": "Prody",
"author_id": 21240,
"author_profile": "https://Stackoverflow.com/users/21240",
"pm_score": 1,
"selected": false,
"text": "<p>Using the <code>svn:ignore</code> property, you can use wildcards.</p>\n"
},
{
"answer_id": 122335,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 7,
"selected": true,
"text": "<p>You're probably safest excluding particular filetypes, rather than picking those you want to include, as you could then add a new type and not realize it wasn't versioned.</p>\n\n<p>On a per-directory basis, you can edit the <a href=\"http://svnbook.red-bean.com/en/1.1/ch07s02.html#svn-ch-7-sect-2.3.3\" rel=\"noreferrer\">svn:ignore</a> property.</p>\n\n<p>Run</p>\n\n<pre><code>svn propedit svn:ignore .\n</code></pre>\n\n<p>for each relevant directory to bring up an editor with a list of patterns to ignore.</p>\n\n<p>Then put a pattern on each line corresponding to the filetype you'd like to ignore:</p>\n\n<pre><code>*.user\n*.exe\n*.dll\n</code></pre>\n\n<p>and what have you.</p>\n\n<p>Alternatively, as has been suggested, you can add those patterns to the <code>global-ignores</code> property in your ~/.subversion/config file (or <code>\"%APPDATA%\\Subversion\\config\"</code> on Windows - see <a href=\"http://svnbook.red-bean.com/en/1.1/ch07.html#svn-ch-7-sect-1.1\" rel=\"noreferrer\">Configuration Area Layout in the red bean book for more information</a>). In that case, separate the patterns with spaces. Here's mine. <code>#</code> at the beginning of the line introduces a comment. I've ignored Ankh .Load files and all *.resharper.user files:</p>\n\n<pre><code>### Set global-ignores to a set of whitespace-delimited globs\n### which Subversion will ignore in its 'status' output, and\n### while importing or adding files and directories.\n# global-ignores = *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store\nglobal-ignores = Ankh.Load *.resharper.user\n</code></pre>\n"
},
{
"answer_id": 122342,
"author": "MattC",
"author_id": 21126,
"author_profile": "https://Stackoverflow.com/users/21126",
"pm_score": 2,
"selected": false,
"text": "<p>See blog post <em><a href=\"http://athenageek.wordpress.com/2008/04/16/svnignore/\" rel=\"nofollow noreferrer\">svn:ignore</a></em>.</p>\n\n<p>I know using TortoiseSVN that I can click on a root folder where I have something checked out and can add arbitrary properties by selecting the \"Properties\" menu item. In this case you would just specify file patterns to exclude.</p>\n\n<p>The blog post for command line stuff, but I'm sure it will work fine with whatever client you're using.</p>\n"
},
{
"answer_id": 39579817,
"author": "John Henckel",
"author_id": 1812732,
"author_profile": "https://Stackoverflow.com/users/1812732",
"pm_score": 1,
"selected": false,
"text": "<p>Another way, when using TortoiseSVN, you can select \"Commit...\" and then right click on a file and move to changelist \"ignore-on-commit\". </p>\n"
},
{
"answer_id": 70987353,
"author": "mwarren",
"author_id": 1617550,
"author_profile": "https://Stackoverflow.com/users/1617550",
"pm_score": 0,
"selected": false,
"text": "<p>If you use Eclipse (I use Spring Tool Suite):</p>\n<pre><code>Preferences > Team > Ignored Resources\n</code></pre>\n<p>click on <code>Add Pattern</code>, write <strong>.DS_Store</strong> (or whatever) and Save.\nThis acts globally in your workspace.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] |
I'm getting confused with the include/exclude jargon, and my actual SVN client doesn't seem to have (or I've been unable to find it easily) a simple option to add or remove a certain type of files for version control.
Let's say for example I've added the entire Visual Studio folder, with its solutions, projects, debug files, etc., but I only want to version the actual source files. What would be the simplest way to do that?
|
You're probably safest excluding particular filetypes, rather than picking those you want to include, as you could then add a new type and not realize it wasn't versioned.
On a per-directory basis, you can edit the [svn:ignore](http://svnbook.red-bean.com/en/1.1/ch07s02.html#svn-ch-7-sect-2.3.3) property.
Run
```
svn propedit svn:ignore .
```
for each relevant directory to bring up an editor with a list of patterns to ignore.
Then put a pattern on each line corresponding to the filetype you'd like to ignore:
```
*.user
*.exe
*.dll
```
and what have you.
Alternatively, as has been suggested, you can add those patterns to the `global-ignores` property in your ~/.subversion/config file (or `"%APPDATA%\Subversion\config"` on Windows - see [Configuration Area Layout in the red bean book for more information](http://svnbook.red-bean.com/en/1.1/ch07.html#svn-ch-7-sect-1.1)). In that case, separate the patterns with spaces. Here's mine. `#` at the beginning of the line introduces a comment. I've ignored Ankh .Load files and all \*.resharper.user files:
```
### Set global-ignores to a set of whitespace-delimited globs
### which Subversion will ignore in its 'status' output, and
### while importing or adding files and directories.
# global-ignores = *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store
global-ignores = Ankh.Load *.resharper.user
```
|
122,316 |
<p>In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints:</p>
<pre><code>interface IFoo
{
}
class Foo<T> where T : IFoo
{
}
class Bar : IFoo
{
}
class Simpson
{
}
class Program
{
static void Main(string[] args)
{
Foo<Bar> a = new Foo<Bar>();
Foo<Simpson> b = new Foo<Simpson>(); // error CS0309
}
}
</code></pre>
<p>Is there a way we can impose constraints for template parameters in C++.</p>
<hr>
<p>C++0x has native support for this but I am talking about current standard C++.</p>
|
[
{
"answer_id": 122347,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 1,
"selected": false,
"text": "<p>Only implicitly.<br>\nAny method you use in a method that is actually called is imposed on the template parameter. </p>\n"
},
{
"answer_id": 122351,
"author": "Nemanja Trifunovic",
"author_id": 8899,
"author_profile": "https://Stackoverflow.com/users/8899",
"pm_score": 3,
"selected": false,
"text": "<p>Check out <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/concept_check/concept_check.htm\" rel=\"nofollow noreferrer\">Boost</a></p>\n<blockquote>\n<p>The Boost Concept Check Library (BCCL)</p>\n<p>The Concept Check library allows one to add explicit statement and checking of <a href=\"http://www.boost.org/more/generic_programming.html#concept\" rel=\"nofollow noreferrer\">concepts</a> in the style of the <a href=\"http://www.generic-programming.org/languages/conceptcpp/specification/\" rel=\"nofollow noreferrer\">proposed C++ language extension</a>.</p>\n</blockquote>\n"
},
{
"answer_id": 122356,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>Sort of. If you static_cast to an IFoo*, then it will be impossible to instantiate the template unless the caller passes a class that can be assigned to an IFoo *.</p>\n"
},
{
"answer_id": 122368,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 6,
"selected": true,
"text": "<p>As someone else has mentioned, C++0x is getting this built into the language. Until then, I'd recommend <a href=\"http://en.wikipedia.org/wiki/Bjarne_Stroustrup\" rel=\"noreferrer\">Bjarne Stroustrup</a>'s <a href=\"http://www.stroustrup.com/bs_faq2.html#constraints\" rel=\"noreferrer\">suggestions for template constraints</a>.</p>\n\n<p>Edit: <a href=\"http://boost.org\" rel=\"noreferrer\">Boost</a> also has an <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/concept_check/concept_check.htm\" rel=\"noreferrer\">alternative of its own</a>.</p>\n\n<p>Edit2: Looks like <a href=\"http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=441\" rel=\"noreferrer\">concepts have been removed from C++0x</a>.</p>\n"
},
{
"answer_id": 122386,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 6,
"selected": false,
"text": "<p>\"Implicitly\" is the correct answer. Templates effectively create a \"duck typing\" scenario, due to the way in which they are compiled. You can call any functions you want upon a template-typed value, and the only instantiations that will be accepted are those for which that method is defined. For example:</p>\n\n<pre><code>template <class T>\nint compute_length(T *value)\n{\n return value->length();\n}\n</code></pre>\n\n<p>We can call this method on a pointer to any type which declares the <code>length()</code> method to return an <code>int</code>. Thusly:</p>\n\n<pre><code>string s = \"test\";\nvector<int> vec;\nint i = 0;\n\ncompute_length(&s);\ncompute_length(&vec);\n</code></pre>\n\n<p>...but not on a pointer to a type which does <em>not</em> declare <code>length()</code>:</p>\n\n<pre><code>compute_length(&i);\n</code></pre>\n\n<p>This third example will not compile.</p>\n\n<p>This works because C++ compiles a new version of the templatized function (or class) for each instantiation. As it performs that compilation, it makes a direct, almost macro-like substitution of the template instantiation into the code prior to type-checking. If everything still works with that template, then compilation proceeds and we eventually arrive at a result. If anything fails (like <code>int*</code> not declaring <code>length()</code>), then we get the dreaded six page template compile-time error.</p>\n"
},
{
"answer_id": 122406,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 4,
"selected": false,
"text": "<p>You can put a guard type on IFoo that does nothing, make sure it's there on T in Foo:</p>\n\n<pre><code>class IFoo\n{\npublic:\n typedef int IsDerivedFromIFoo;\n};\n\ntemplate <typename T>\nclass Foo<T>\n{\n typedef typename T::IsDerivedFromIFoo IFooGuard;\n}\n</code></pre>\n"
},
{
"answer_id": 152742,
"author": "OldMan",
"author_id": 23415,
"author_profile": "https://Stackoverflow.com/users/23415",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it. Create the base template. Make it have only Private constructors. Then create specializations for each case you want to allow (or make the opposite if the disallowed list is much smaller than the allowed list).</p>\n\n<p>The compiler will not allow you to instantiate the templates that use the version with private constructors.</p>\n\n<p>This example only allow instantiation with int and float.</p>\n\n<pre><code>template<class t> class FOO { private: FOO(){}};\n\ntemplate<> class FOO<int>{public: FOO(){}};\n\ntemplate<> class FOO<float>{public: FOO(){}};\n</code></pre>\n\n<p>Its not a short and elegant way of doing it, but its possible.</p>\n"
},
{
"answer_id": 341630,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Look at the CRTP pattern (Curiously Recursive Template Pattern). It is designed to help support static inheritence.</p>\n"
},
{
"answer_id": 22934960,
"author": "Venemo",
"author_id": 202919,
"author_profile": "https://Stackoverflow.com/users/202919",
"pm_score": 6,
"selected": false,
"text": "<p>If you use C++11, you can use <code>static_assert</code> with <code>std::is_base_of</code> for this purpose.</p>\n\n<p>For example,</p>\n\n<pre><code>#include <type_traits>\n\ntemplate<typename T>\nclass YourClass {\n\n YourClass() {\n // Compile-time check\n static_assert(std::is_base_of<BaseClass, T>::value, \"type parameter of this class must derive from BaseClass\");\n\n // ...\n }\n}\n</code></pre>\n"
},
{
"answer_id": 71100711,
"author": "Hugo",
"author_id": 7261360,
"author_profile": "https://Stackoverflow.com/users/7261360",
"pm_score": 2,
"selected": false,
"text": "<p>Using C++20, yes there is: <a href=\"https://en.cppreference.com/w/cpp/language/constraints\" rel=\"nofollow noreferrer\">Constraints and concepts</a></p>\n<p>Perhaps you want to guarantee a template is derived from a specific class:</p>\n<pre><code>#include <concepts>\n\ntemplate<class T, class U>\nconcept Derived = std::is_base_of<U, T>::value;\n\nclass ABase { };\nclass ADerived : ABase { };\n\ntemplate<Derived<ABase> T>\nclass AClass {\n T aMemberDerivedFromABase;\n};\n</code></pre>\n<p>The following then compiles like normal:</p>\n<pre><code>int main () {\n AClass<ADerived> aClass;\n return 0;\n}\n</code></pre>\n<p>But now when you do something against the contraint:</p>\n<pre><code>class AnotherClass {\n\n};\nint main () {\n AClass<AnotherClass> aClass;\n return 0;\n}\n</code></pre>\n<p>AnotherClass is not derived from ABase, therefore my compiler (GCC) gives roughly the following error:</p>\n<blockquote>\n<p>In function 'int main()': note: constraints not satisfied\nnote: the expression 'std::is_base_of<U, T>::value\n[with U = ABase; T = AnotherClass]' evaluated to 'false'\n9 | concept Derived = std::is_base_of<U, T>::value;</p>\n</blockquote>\n<p>As you can imagine this feature is very useful and can do much more than constraining a class to have a specific base.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6508/"
] |
In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints:
```
interface IFoo
{
}
class Foo<T> where T : IFoo
{
}
class Bar : IFoo
{
}
class Simpson
{
}
class Program
{
static void Main(string[] args)
{
Foo<Bar> a = new Foo<Bar>();
Foo<Simpson> b = new Foo<Simpson>(); // error CS0309
}
}
```
Is there a way we can impose constraints for template parameters in C++.
---
C++0x has native support for this but I am talking about current standard C++.
|
As someone else has mentioned, C++0x is getting this built into the language. Until then, I'd recommend [Bjarne Stroustrup](http://en.wikipedia.org/wiki/Bjarne_Stroustrup)'s [suggestions for template constraints](http://www.stroustrup.com/bs_faq2.html#constraints).
Edit: [Boost](http://boost.org) also has an [alternative of its own](http://www.boost.org/doc/libs/1_36_0/libs/concept_check/concept_check.htm).
Edit2: Looks like [concepts have been removed from C++0x](http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=441).
|
122,324 |
<p>Would having a nice little feature that makes it quicker to write code like Automatic Properties fit very nicely with the mantra of VB.NET?</p>
<p>Something like this would work perfect:</p>
<pre><code>Public Property FirstName() As String
Get
Set
End Property
</code></pre>
<p><strong>UPDATE:</strong> VB.NET 10 (coming with Visual Studio 2010 and .NET 4.0) will have Automatic Properties. Here's a link that shows a little info about the feature: <a href="https://web.archive.org/web/20200119055303/http://geekswithblogs.net:80/DarrenFieldhouse/archive/2008/12/01/new-features-in-vb.net-10-.net-4.0.aspx" rel="nofollow noreferrer">http://geekswithblogs.net/DarrenFieldhouse/archive/2008/12/01/new-features-in-vb.net-10-.net-4.0.aspx</a></p>
<p>In VB.NET 10 Automatic Properties will be defines like this:</p>
<pre><code>Public Property CustomerID As Integer
</code></pre>
|
[
{
"answer_id": 122339,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 1,
"selected": false,
"text": "<p>C# and VB.NET don't exactly line up on new features in their first versions. Usually, by the next version C# catches up with some VB.NET features and vice versa. I kind of like literal XML from VB.NET, and hoping they add that to C#.</p>\n"
},
{
"answer_id": 122381,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to do properties a little quicker, try code snippets.\nType:\nProperty\nand just after typing the \"y\", press the Tab key :-).</p>\n\n<p>I realize this doesn't answer the particular question, but does give you what the VB team provided...</p>\n"
},
{
"answer_id": 122382,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 1,
"selected": false,
"text": "<p>There's no particular reason really. It's been always been the case that even when VB.NET and C# are touted to be equally powerful (and to be fair, they <em>are</em>) their syntaxes and some of the structures sometimes differ. You have two different development teams working on the languages, so it's something you can expect to happen.</p>\n"
},
{
"answer_id": 122405,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": true,
"text": "<p>One reason many features get delayed in VB is that the development structure is much different than in C# and additionally, that often more thought goes into details. The same seems to be true in this case, as suggested by <a href=\"http://www.panopticoncentral.net/archive/2008/03/27/23050.aspx\" rel=\"noreferrer\">Paul Vick's post</a> on the matter. This is unfortunate because it means a delay in many cases (automatic properties, iterator methods, multiline lambdas, to name but a few) but on the other hand, the VB developers usually get a much more mature feature in the long run (looking at the discussion, this will be especially true for iterator methods).</p>\n\n<p>So, long story short: VB 10 will (hopefully!) see automatic properties.</p>\n"
},
{
"answer_id": 141806,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>It also wasn't as big of a pain point in vb.net, since visual studio will automatically create 90% of the skeleton code of a property for you whereas with C# you used to have to type it all out.</p>\n"
},
{
"answer_id": 412656,
"author": "soccerazy",
"author_id": 51580,
"author_profile": "https://Stackoverflow.com/users/51580",
"pm_score": 2,
"selected": false,
"text": "<p>I know this post is old so you may already know but VB is getting Auto Properties in next version of VS.</p>\n\n<p>Based on <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=354620&wa=wsignin1.0\" rel=\"nofollow noreferrer\">response to feedback</a> and <a href=\"http://channel9.msdn.com/posts/Dan/Lucian-Wischik-and-Lisa-Feigenbaum-Whats-new-in-Visual-Basic-10/\" rel=\"nofollow noreferrer\">Channel9</a>.</p>\n"
},
{
"answer_id": 2530742,
"author": "greg",
"author_id": 302894,
"author_profile": "https://Stackoverflow.com/users/302894",
"pm_score": -1,
"selected": false,
"text": "<p>automatic properties are not necessary in vb\nthe concession one makes by using an automatic property is that you can not modify the Get and Set. </p>\n\n<p>If you dont require those, just make a public data field. </p>\n\n<p>VB has had automatic properties for years. They just called them something else. </p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7831/"
] |
Would having a nice little feature that makes it quicker to write code like Automatic Properties fit very nicely with the mantra of VB.NET?
Something like this would work perfect:
```
Public Property FirstName() As String
Get
Set
End Property
```
**UPDATE:** VB.NET 10 (coming with Visual Studio 2010 and .NET 4.0) will have Automatic Properties. Here's a link that shows a little info about the feature: [http://geekswithblogs.net/DarrenFieldhouse/archive/2008/12/01/new-features-in-vb.net-10-.net-4.0.aspx](https://web.archive.org/web/20200119055303/http://geekswithblogs.net:80/DarrenFieldhouse/archive/2008/12/01/new-features-in-vb.net-10-.net-4.0.aspx)
In VB.NET 10 Automatic Properties will be defines like this:
```
Public Property CustomerID As Integer
```
|
One reason many features get delayed in VB is that the development structure is much different than in C# and additionally, that often more thought goes into details. The same seems to be true in this case, as suggested by [Paul Vick's post](http://www.panopticoncentral.net/archive/2008/03/27/23050.aspx) on the matter. This is unfortunate because it means a delay in many cases (automatic properties, iterator methods, multiline lambdas, to name but a few) but on the other hand, the VB developers usually get a much more mature feature in the long run (looking at the discussion, this will be especially true for iterator methods).
So, long story short: VB 10 will (hopefully!) see automatic properties.
|
122,327 |
<p>How do I find the location of my <code>site-packages</code> directory?</p>
|
[
{
"answer_id": 122340,
"author": "Daryl Spitzer",
"author_id": 4766,
"author_profile": "https://Stackoverflow.com/users/4766",
"pm_score": 9,
"selected": false,
"text": "<p>A solution that:</p>\n\n<ul>\n<li>outside of virtualenv - provides the path of <strong>global</strong> site-packages,</li>\n<li>insidue a virtualenv - provides the <strong>virtualenv's</strong> site-packages</li>\n</ul>\n\n<p>...is this one-liner:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>python -c \"from distutils.sysconfig import get_python_lib; print(get_python_lib())\"\n</code></pre>\n\n<p>Formatted for readability (rather than use as a one-liner), that looks like the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from distutils.sysconfig import get_python_lib\nprint(get_python_lib())\n</code></pre>\n\n<p><br/></p>\n\n<p><em>Source:</em> an very old version of <a href=\"http://web.archive.org/web/20100723105725/http://docs.djangoproject.com/en/1.2/topics/install#removing-old-versions-of-django\" rel=\"noreferrer\">\"How to Install Django\" documentation</a> (though this is useful to more than just Django installation)</p>\n"
},
{
"answer_id": 122360,
"author": "Florian Bösch",
"author_id": 19435,
"author_profile": "https://Stackoverflow.com/users/19435",
"pm_score": 3,
"selected": false,
"text": "<pre><code>from distutils.sysconfig import get_python_lib\nprint get_python_lib()\n</code></pre>\n"
},
{
"answer_id": 122377,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 5,
"selected": false,
"text": "<p>As others have noted, <code>distutils.sysconfig</code> has the relevant settings:</p>\n\n<pre><code>import distutils.sysconfig\nprint distutils.sysconfig.get_python_lib()\n</code></pre>\n\n<p>...though the default <code>site.py</code> does something a bit more crude, paraphrased below:</p>\n\n<pre><code>import sys, os\nprint os.sep.join([sys.prefix, 'lib', 'python' + sys.version[:3], 'site-packages'])\n</code></pre>\n\n<p>(it also adds <code>${sys.prefix}/lib/site-python</code> and adds both paths for <code>sys.exec_prefix</code> as well, should that constant be different).</p>\n\n<p>That said, what's the context? You shouldn't be messing with your <code>site-packages</code> directly; setuptools/distutils will work for installation, and your program may be running in a virtualenv where your pythonpath is completely user-local, so it shouldn't assume use of the system site-packages directly either.</p>\n"
},
{
"answer_id": 122387,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 4,
"selected": false,
"text": "<p>An additional note to the <code>get_python_lib</code> function mentioned already: on some platforms different directories are used for platform specific modules (eg: modules that require compilation). If you pass <code>plat_specific=True</code> to the function you get the site packages for platform specific packages.</p>\n"
},
{
"answer_id": 1711808,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>A side-note: The proposed solution (<code>distutils.sysconfig.get_python_lib()</code>) does not work when there is more than one site-packages directory (as <a href=\"http://pythonsimple.noucleus.net/python-install/python-site-packages-what-they-are-and-where-to-put-them\" rel=\"nofollow noreferrer\">recommended by this article</a>). It will only return the main site-packages directory.</p>\n\n<p>Alas, I have no better solution either. Python doesn't seem to keep track of site-packages directories, just the packages within them.</p>\n"
},
{
"answer_id": 4611382,
"author": "David Hollander",
"author_id": 564833,
"author_profile": "https://Stackoverflow.com/users/564833",
"pm_score": 7,
"selected": false,
"text": "<p><em>For Ubuntu</em>,</p>\n\n<pre><code>python -c \"from distutils.sysconfig import get_python_lib; print get_python_lib()\"\n</code></pre>\n\n<p>...is not correct.</p>\n\n<p>It will point you to <code>/usr/lib/pythonX.X/dist-packages</code></p>\n\n<p>This folder only contains packages your operating system has automatically installed for programs to run.</p>\n\n<p><em>On ubuntu</em>, the site-packages folder that contains packages installed via setup_tools\\easy_install\\pip will be in <code>/usr/local/lib/pythonX.X/dist-packages</code></p>\n\n<p>The second folder is probably the more useful one if the use case is related to installation or reading source code.</p>\n\n<p>If you do not use Ubuntu, you are probably safe copy-pasting the first code box into the terminal.</p>\n"
},
{
"answer_id": 5095375,
"author": "Sumod",
"author_id": 418832,
"author_profile": "https://Stackoverflow.com/users/418832",
"pm_score": 5,
"selected": false,
"text": "<p>Let's say you have installed the package 'django'. import it and type in dir(django). It will show you, all the functions and attributes with that module. Type in the python interpreter - </p>\n\n<pre><code>>>> import django\n>>> dir(django)\n['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version']\n>>> print django.__path__\n['/Library/Python/2.6/site-packages/django']\n</code></pre>\n\n<p>You can do the same thing if you have installed mercurial.</p>\n\n<p>This is for Snow Leopard. But I think it should work in general as well.</p>\n"
},
{
"answer_id": 9155056,
"author": "cheater",
"author_id": 389169,
"author_profile": "https://Stackoverflow.com/users/389169",
"pm_score": 4,
"selected": false,
"text": "<p>All the answers (or: the same answer repeated over and over) are inadequate. What you want to do is this:</p>\n\n<pre><code>from setuptools.command.easy_install import easy_install\nclass easy_install_default(easy_install):\n \"\"\" class easy_install had problems with the fist parameter not being\n an instance of Distribution, even though it was. This is due to\n some import-related mess.\n \"\"\"\n\n def __init__(self):\n from distutils.dist import Distribution\n dist = Distribution()\n self.distribution = dist\n self.initialize_options()\n self._dry_run = None\n self.verbose = dist.verbose\n self.force = None\n self.help = 0\n self.finalized = 0\n\ne = easy_install_default()\nimport distutils.errors\ntry:\n e.finalize_options()\nexcept distutils.errors.DistutilsError:\n pass\n\nprint e.install_dir\n</code></pre>\n\n<p>The final line shows you the installation dir. Works on Ubuntu, whereas the above ones don't. Don't ask me about windows or other dists, but since it's the exact same dir that easy_install uses by default, it's probably correct everywhere where easy_install works (so, everywhere, even macs). Have fun. Note: original code has many swearwords in it.</p>\n"
},
{
"answer_id": 9946505,
"author": "just_an_old_guy",
"author_id": 1303682,
"author_profile": "https://Stackoverflow.com/users/1303682",
"pm_score": 4,
"selected": false,
"text": "<p>This works for me.\nIt will get you both dist-packages and site-packages folders.\nIf the folder is not on Python's path, it won't be\ndoing you much good anyway.</p>\n\n<pre><code>import sys; \nprint [f for f in sys.path if f.endswith('packages')]\n</code></pre>\n\n<p>Output (Ubuntu installation):</p>\n\n<pre><code>['/home/username/.local/lib/python2.7/site-packages',\n '/usr/local/lib/python2.7/dist-packages',\n '/usr/lib/python2.7/dist-packages']\n</code></pre>\n"
},
{
"answer_id": 10694208,
"author": "Ramashri",
"author_id": 1409043,
"author_profile": "https://Stackoverflow.com/users/1409043",
"pm_score": 6,
"selected": false,
"text": "<p>This is what worked for me:</p>\n\n<pre><code>python -m site --user-site\n</code></pre>\n"
},
{
"answer_id": 12950101,
"author": "eudoxos",
"author_id": 761090,
"author_profile": "https://Stackoverflow.com/users/761090",
"pm_score": 9,
"selected": false,
"text": "<pre><code>>>> import site; site.getsitepackages()\n['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']\n</code></pre>\n\n<p>(or just first item with <code>site.getsitepackages()[0]</code>)</p>\n"
},
{
"answer_id": 18130809,
"author": "fnatic_shank",
"author_id": 1062108,
"author_profile": "https://Stackoverflow.com/users/1062108",
"pm_score": 5,
"selected": false,
"text": "<p>The native system packages installed with python installation in Debian based systems can be found at :</p>\n\n<blockquote>\n <p>/usr/lib/python2.7/dist-packages/</p>\n</blockquote>\n\n<p>In OSX - <code>/Library/Python/2.7/site-packages</code></p>\n\n<p>by using this small code :</p>\n\n<pre><code>from distutils.sysconfig import get_python_lib\nprint get_python_lib()\n</code></pre>\n\n<p>However, the list of packages installed via <code>pip</code> can be found at :</p>\n\n<blockquote>\n <p>/usr/local/bin/</p>\n</blockquote>\n\n<p>Or one can simply write the following command to list all paths where python packages are.</p>\n\n<pre><code>>>> import site; site.getsitepackages()\n['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']\n</code></pre>\n\n<p><em>Note: the location might vary based on your OS, like in OSX</em></p>\n\n<pre><code>>>> import site; site.getsitepackages()\n['/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/site-python', '/Library/Python/2.7/site-packages']\n</code></pre>\n"
},
{
"answer_id": 29062571,
"author": "Pyramid Newbie",
"author_id": 1258009,
"author_profile": "https://Stackoverflow.com/users/1258009",
"pm_score": 4,
"selected": false,
"text": "<p>This should work on all distributions in and out of virtual environment due to it's \"low-tech\" nature. The os module always resides in the parent directory of 'site-packages'</p>\n\n<pre><code>import os; print(os.path.dirname(os.__file__) + '/site-packages')\n</code></pre>\n\n<p>To change dir to the site-packages dir I use the following alias (on *nix systems):</p>\n\n<pre><code>alias cdsp='cd $(python -c \"import os; print(os.path.dirname(os.__file__))\"); cd site-packages'\n</code></pre>\n"
},
{
"answer_id": 38432782,
"author": "Sahil Agarwal",
"author_id": 6003362,
"author_profile": "https://Stackoverflow.com/users/6003362",
"pm_score": 3,
"selected": false,
"text": "<p>Answer to old question. But use ipython for this. </p>\n\n<pre><code>pip install ipython\nipython \nimport imaplib\nimaplib?\n</code></pre>\n\n<p>This will give the following output about imaplib package -</p>\n\n<pre><code>Type: module\nString form: <module 'imaplib' from '/usr/lib/python2.7/imaplib.py'>\nFile: /usr/lib/python2.7/imaplib.py\nDocstring: \nIMAP4 client.\n\nBased on RFC 2060.\n\nPublic class: IMAP4\nPublic variable: Debug\nPublic functions: Internaldate2tuple\n Int2AP\n ParseFlags\n Time2Internaldate\n</code></pre>\n"
},
{
"answer_id": 46071447,
"author": "Peterino",
"author_id": 202834,
"author_profile": "https://Stackoverflow.com/users/202834",
"pm_score": 11,
"selected": true,
"text": "<p>There are two types of site-packages directories, <em>global</em> and <em>per user</em>.</p>\n<ol>\n<li><p><strong>Global</strong> site-packages ("<a href=\"https://stackoverflow.com/questions/9387928/whats-the-difference-between-dist-packages-and-site-packages\">dist-packages</a>") directories are listed in <code>sys.path</code> when you run:</p>\n<pre><code> python -m site\n</code></pre>\n<p>For a more concise list run <code>getsitepackages</code> from the <a href=\"https://docs.python.org/3/library/site.html#site.getsitepackages\" rel=\"noreferrer\">site module</a> in Python code:</p>\n<pre><code> python -c 'import site; print(site.getsitepackages())'\n</code></pre>\n<p><em>Caution:</em> In virtual environments <a href=\"https://github.com/pypa/virtualenv/issues/228\" rel=\"noreferrer\">getsitepackages is not available</a> with <a href=\"https://github.com/pypa/virtualenv/pull/2379/files\" rel=\"noreferrer\">older versions of <code>virtualenv</code></a>, <code>sys.path</code> from above will list the virtualenv's site-packages directory correctly, though. In Python 3, you may use the <a href=\"https://docs.python.org/3/library/sysconfig.html#using-sysconfig-as-a-script\" rel=\"noreferrer\">sysconfig module</a> instead:</p>\n<pre><code> python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'\n</code></pre>\n</li>\n<li><p>The <strong>per user</strong> site-packages directory (<a href=\"https://www.python.org/dev/peps/pep-0370/\" rel=\"noreferrer\">PEP 370</a>) is where Python installs your local packages:</p>\n<pre><code> python -m site --user-site\n</code></pre>\n<p>If this points to a non-existing directory check the exit status of Python and see <code>python -m site --help</code> for explanations.</p>\n<p><em>Hint:</em> Running <code>pip list --user</code> or <code>pip freeze --user</code> gives you a list of all installed <em>per user</em> site-packages.</p>\n</li>\n</ol>\n<hr />\n<h2>Practical Tips</h2>\n<ul>\n<li><p><code><package>.__path__</code> lets you identify the location(s) of a specific package: (<a href=\"https://stackoverflow.com/questions/2699287/what-is-path-useful-for\">details</a>)</p>\n<pre><code> $ python -c "import setuptools as _; print(_.__path__)"\n ['/usr/lib/python2.7/dist-packages/setuptools']\n</code></pre>\n</li>\n<li><p><code><module>.__file__</code> lets you identify the location of a specific module: (<a href=\"https://softwareengineering.stackexchange.com/questions/111871/module-vs-package\">difference</a>)</p>\n<pre><code> $ python3 -c "import os as _; print(_.__file__)"\n /usr/lib/python3.6/os.py\n</code></pre>\n</li>\n<li><p>Run <code>pip show <package></code> to show Debian-style package information:</p>\n<pre><code> $ pip show pytest\n Name: pytest\n Version: 3.8.2\n Summary: pytest: simple powerful testing with Python\n Home-page: https://docs.pytest.org/en/latest/\n Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others\n Author-email: None\n License: MIT license\n Location: /home/peter/.local/lib/python3.4/site-packages\n Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy\n</code></pre>\n</li>\n</ul>\n"
},
{
"answer_id": 47844391,
"author": "MultipleMonomials",
"author_id": 7083698,
"author_profile": "https://Stackoverflow.com/users/7083698",
"pm_score": 2,
"selected": false,
"text": "<p>I had to do something slightly different for a project I was working on: find the <em>relative</em> site-packages directory relative to the base install prefix. If the site-packages folder was in <code>/usr/lib/python2.7/site-packages</code>, I wanted the <code>/lib/python2.7/site-packages</code> part. I have, in fact, encountered systems where <code>site-packages</code> was in <code>/usr/lib64</code>, and the accepted answer did NOT work on those systems. </p>\n\n<p>Similar to cheater's answer, my solution peeks deep into the guts of Distutils, to find the path that actually gets passed around inside <code>setup.py</code>. It was such a pain to figure out that I don't want anyone to ever have to figure this out again.</p>\n\n<pre><code>import sys\nimport os\nfrom distutils.command.install import INSTALL_SCHEMES\n\nif os.name == 'nt':\n scheme_key = 'nt'\nelse:\n scheme_key = 'unix_prefix'\n\nprint(INSTALL_SCHEMES[scheme_key]['purelib'].replace('$py_version_short', (str.split(sys.version))[0][0:3]).replace('$base', ''))\n</code></pre>\n\n<p>That should print something like <code>/Lib/site-packages</code> or <code>/lib/python3.6/site-packages</code>.</p>\n"
},
{
"answer_id": 52638888,
"author": "wim",
"author_id": 674039,
"author_profile": "https://Stackoverflow.com/users/674039",
"pm_score": 6,
"selected": false,
"text": "<p>A modern stdlib way is using <a href=\"https://docs.python.org/3/library/sysconfig.html\" rel=\"noreferrer\"><code>sysconfig</code></a> module, available in version 2.7 and 3.2+. <strong>Unlike the current accepted answer, this method still works regardless of whether or not you have a virtual environment active.</strong></p>\n<p><em>Note</em>: <code>sysconfig</code> (<a href=\"https://github.com/python/cpython/blob/master/Lib/sysconfig.py\" rel=\"noreferrer\">source</a>) is not to be confused with the <code>distutils.sysconfig</code> submodule (<a href=\"https://github.com/python/cpython/blob/master/Lib/distutils/sysconfig.py\" rel=\"noreferrer\">source</a>) mentioned in several other answers here. The latter is an entirely different module and it's lacking the <code>get_paths</code> function discussed below. Additionally, <code>distutils</code> is <a href=\"https://peps.python.org/pep-0632/\" rel=\"noreferrer\">deprecated in 3.10</a> and will be unavailable soon.</p>\n<p>Python currently uses <em>eight</em> paths (<a href=\"https://docs.python.org/3/library/sysconfig.html#installation-paths\" rel=\"noreferrer\">docs</a>):</p>\n<blockquote>\n<ul>\n<li><em>stdlib</em>: directory containing the standard Python library files that are not platform-specific.</li>\n<li><em>platstdlib</em>: directory containing the standard Python library files that are platform-specific.</li>\n<li><em>platlib</em>: directory for site-specific, platform-specific files.</li>\n<li><em>purelib</em>: directory for site-specific, non-platform-specific files.</li>\n<li><em>include</em>: directory for non-platform-specific header files.</li>\n<li><em>platinclude</em>: directory for platform-specific header files.</li>\n<li><em>scripts</em>: directory for script files.</li>\n<li><em>data</em>: directory for data files.</li>\n</ul>\n</blockquote>\n<p>In most cases, users finding this question would be interested in the 'purelib' path (in <a href=\"https://stackoverflow.com/a/122387/674039\">some cases</a>, you might be interested in 'platlib' too). The purelib path is where ordinary Python packages will be installed by tools like <a href=\"https://pip.pypa.io/en/stable/\" rel=\"noreferrer\"><code>pip</code></a>.</p>\n<p>At system level, you'll see something like this:</p>\n<pre><code># Linux\n$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"\n/usr/local/lib/python3.8/site-packages\n\n# macOS (brew installed python3.8)\n$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"\n/usr/local/Cellar/python@3.8/3.8.3/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages\n\n# Windows\nC:\\> py -c "import sysconfig; print(sysconfig.get_path('purelib'))"\nC:\\Users\\wim\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\site-packages\n</code></pre>\n<p>With a venv, you'll get something like this</p>\n<pre><code># Linux\n/tmp/.venv/lib/python3.8/site-packages\n\n# macOS\n/private/tmp/.venv/lib/python3.8/site-packages\n\n# Windows\nC:\\Users\\wim\\AppData\\Local\\Temp\\.venv\\Lib\\site-packages\n</code></pre>\n<p>The function <a href=\"https://docs.python.org/3/library/sysconfig.html#sysconfig.get_paths\" rel=\"noreferrer\"><code>sysconfig.get_paths()</code></a> returns a dict of all of the relevant installation paths, example on Linux:</p>\n<pre><code>>>> import sysconfig\n>>> sysconfig.get_paths()\n{'stdlib': '/usr/local/lib/python3.8',\n 'platstdlib': '/usr/local/lib/python3.8',\n 'purelib': '/usr/local/lib/python3.8/site-packages',\n 'platlib': '/usr/local/lib/python3.8/site-packages',\n 'include': '/usr/local/include/python3.8',\n 'platinclude': '/usr/local/include/python3.8',\n 'scripts': '/usr/local/bin',\n 'data': '/usr/local'}\n</code></pre>\n<p>A shell script is also available to display these details, which you can invoke by executing <code>sysconfig</code> as a module:</p>\n<pre><code>python -m sysconfig\n</code></pre>\n<h4><em>Addendum</em>: What about Debian / Ubuntu?</h4>\n<p>As some commenters point out, the sysconfig results for Debian systems (and Ubuntu, as a derivative) are not accurate. When a user pip installs a package it will go into <em>dist-packages</em> not <em>site-packages</em>, as per <a href=\"https://www.debian.org/doc/packaging-manuals/python-policy/index.html#module-path\" rel=\"noreferrer\">Debian policies on Python packaging</a>.</p>\n<p>The root cause of the discrepancy is because Debian <a href=\"https://salsa.debian.org/cpython-team/python3/-/blob/master/debian/patches/distutils-install-layout.diff\" rel=\"noreferrer\">patch the distutils install layout</a>, to correctly reflect their changes to the site, but they fail to patch the sysconfig module.</p>\n<p>For example, on <em>Ubuntu 20.04.4 LTS (Focal Fossa)</em>:</p>\n<pre><code>root@cb5e85f17c7f:/# python3 -m sysconfig | grep packages\n platlib = "/usr/lib/python3.8/site-packages"\n purelib = "/usr/lib/python3.8/site-packages"\n\nroot@cb5e85f17c7f:/# python3 -m site | grep packages\n '/usr/local/lib/python3.8/dist-packages',\n '/usr/lib/python3/dist-packages',\nUSER_SITE: '/root/.local/lib/python3.8/site-packages' (doesn't exist)\n</code></pre>\n<p>It looks like the patched Python installation that Debian/Ubuntu are distributing is a bit hacked up, and they will need to figure out a new plan for 3.12+ when distutils is completely unavailable. Probably, they will have to <a href=\"https://salsa.debian.org/cpython-team/python3/-/blob/master/debian/patches/sysconfig-debian-schemes.diff\" rel=\"noreferrer\">start patching sysconfig as well</a>, since this is what pip will be using for install locations.</p>\n"
},
{
"answer_id": 54019959,
"author": "Sourabh Potnis",
"author_id": 3322308,
"author_profile": "https://Stackoverflow.com/users/3322308",
"pm_score": 5,
"selected": false,
"text": "<p>pip show will give all the details about a package:\n<a href=\"https://pip.pypa.io/en/stable/reference/pip_show/\" rel=\"noreferrer\">https://pip.pypa.io/en/stable/reference/pip_show/</a> [pip show][1]</p>\n<p>To get the location:</p>\n<pre><code>pip show <package_name>| grep Location\n</code></pre>\n<p>In Linux, you can go to site-packages folder by:</p>\n<pre><code>cd $(python -c "import site; print(site.getsitepackages()[0])")\n</code></pre>\n"
},
{
"answer_id": 56011087,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>You should try this command to determine pip's install location</p>\n\n<p>Python 2</p>\n\n<pre><code>pip show six | grep \"Location:\" | cut -d \" \" -f2\n</code></pre>\n\n<p>Python <strong>3</strong></p>\n\n<pre><code>pip3 show six | grep \"Location:\" | cut -d \" \" -f2\n</code></pre>\n"
},
{
"answer_id": 63923577,
"author": "Stamatis Tiniakos",
"author_id": 11536058,
"author_profile": "https://Stackoverflow.com/users/11536058",
"pm_score": 2,
"selected": false,
"text": "<p>Something that has not been mentioned which I believe is useful, if you have two versions of Python installed e.g. both 3.8 and 3.5 there might be two folders called site-packages on your machine. In that case you can specify the python version by using the following:</p>\n<pre><code>py -3.5 -c "import site; print(site.getsitepackages()[1])\n</code></pre>\n"
},
{
"answer_id": 64917912,
"author": "cglacet",
"author_id": 1720199,
"author_profile": "https://Stackoverflow.com/users/1720199",
"pm_score": 2,
"selected": false,
"text": "<p>For those who are using <a href=\"https://python-poetry.org/\" rel=\"nofollow noreferrer\">poetry</a>, you can find your virtual environment path with <code>poetry debug</code>:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ poetry debug\n\nPoetry\nVersion: 1.1.4\nPython: 3.8.2\n\nVirtualenv\nPython: 3.8.2\nImplementation: CPython\nPath: /Users/cglacet/.pyenv/versions/3.8.2/envs/my-virtualenv\nValid: True\n\nSystem\nPlatform: darwin\nOS: posix\nPython: /Users/cglacet/.pyenv/versions/3.8.2\n</code></pre>\n<p>Using this information you can list site packages:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>ls /Users/cglacet/.pyenv/versions/3.8.2/envs/my-virtualenv/lib/python3.8/site-packages/\n</code></pre>\n"
},
{
"answer_id": 68426881,
"author": "Angel",
"author_id": 12234006,
"author_profile": "https://Stackoverflow.com/users/12234006",
"pm_score": 2,
"selected": false,
"text": "<h1>I made a really simple function that gets the job done</h1>\n<pre class=\"lang-py prettyprint-override\"><code>import site\n\n\ndef get_site_packages_dir():\n return [p for p in site.getsitepackages()\n if p.endswith(("site-packages", "dist-packages"))][0]\n\nget_site_packages_dir()\n# '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages'\n</code></pre>\n<h1>If you want to retrieve the results using the terminal:</h1>\n<pre class=\"lang-sh prettyprint-override\"><code>python3 -c "import site;print([p for p in site.getsitepackages() if p.endswith(('site-packages', 'dist-packages')) ][0])"\n\n/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages\n\n\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
] |
How do I find the location of my `site-packages` directory?
|
There are two types of site-packages directories, *global* and *per user*.
1. **Global** site-packages ("[dist-packages](https://stackoverflow.com/questions/9387928/whats-the-difference-between-dist-packages-and-site-packages)") directories are listed in `sys.path` when you run:
```
python -m site
```
For a more concise list run `getsitepackages` from the [site module](https://docs.python.org/3/library/site.html#site.getsitepackages) in Python code:
```
python -c 'import site; print(site.getsitepackages())'
```
*Caution:* In virtual environments [getsitepackages is not available](https://github.com/pypa/virtualenv/issues/228) with [older versions of `virtualenv`](https://github.com/pypa/virtualenv/pull/2379/files), `sys.path` from above will list the virtualenv's site-packages directory correctly, though. In Python 3, you may use the [sysconfig module](https://docs.python.org/3/library/sysconfig.html#using-sysconfig-as-a-script) instead:
```
python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'
```
2. The **per user** site-packages directory ([PEP 370](https://www.python.org/dev/peps/pep-0370/)) is where Python installs your local packages:
```
python -m site --user-site
```
If this points to a non-existing directory check the exit status of Python and see `python -m site --help` for explanations.
*Hint:* Running `pip list --user` or `pip freeze --user` gives you a list of all installed *per user* site-packages.
---
Practical Tips
--------------
* `<package>.__path__` lets you identify the location(s) of a specific package: ([details](https://stackoverflow.com/questions/2699287/what-is-path-useful-for))
```
$ python -c "import setuptools as _; print(_.__path__)"
['/usr/lib/python2.7/dist-packages/setuptools']
```
* `<module>.__file__` lets you identify the location of a specific module: ([difference](https://softwareengineering.stackexchange.com/questions/111871/module-vs-package))
```
$ python3 -c "import os as _; print(_.__file__)"
/usr/lib/python3.6/os.py
```
* Run `pip show <package>` to show Debian-style package information:
```
$ pip show pytest
Name: pytest
Version: 3.8.2
Summary: pytest: simple powerful testing with Python
Home-page: https://docs.pytest.org/en/latest/
Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others
Author-email: None
License: MIT license
Location: /home/peter/.local/lib/python3.4/site-packages
Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy
```
|
122,348 |
<p>I have a command which includes an includegraphics command - I can pass an image to my command, and it will do some standard formatting for me before actually including the image. Some of the images that I'm including via this command are smaller than \textwidth, while some are larger. I'd like to scale the larger images down to \textwidth, while not scaling the smaller images up - this means I can't just do </p>
<pre><code>\includegraphics[width=\textwidth]{img}
</code></pre>
<p>Is there a way to specify a maxwidth? Or, can I get the width of the image somehow so I can do something like </p>
<pre><code>\ifthenelse{\imagewidth > \textwidth}{%
\includegraphics[width=\textwidth]{img}}{%
\includegraphics{img}}
</code></pre>
|
[
{
"answer_id": 122653,
"author": "Steve Landey",
"author_id": 8061,
"author_profile": "https://Stackoverflow.com/users/8061",
"pm_score": -1,
"selected": false,
"text": "<p>After a few minutes of searching through CTAN manuals and Google results, I think I can safely say that what you want to do is either impossible or very hard. My only recommendation is that you have two commands, one for small images and one for large, or one command with an option.</p>\n\n<p>There may be a way, but I leave it to other S.O. LaTeX wizards to provide a better answer.</p>\n\n<p>Edit: I am wrong, see above.</p>\n"
},
{
"answer_id": 123184,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 6,
"selected": true,
"text": "<p>To get the width of the image you can use this code:</p>\n\n<pre><code>\\newlength{\\imgwidth}\n\\settowidth{\\imgwidth}{\\includegraphics{img}}\n</code></pre>\n\n<p>You could use this in the document preamble to create a new command to automatically set the width:</p>\n\n<pre><code>\\usepackage{graphicx}\n\\usepackage{calc}\n\n\\newlength{\\imgwidth}\n\n\\newcommand\\scalegraphics[1]{% \n \\settowidth{\\imgwidth}{\\includegraphics{#1}}%\n \\setlength{\\imgwidth}{\\minof{\\imgwidth}{\\textwidth}}%\n \\includegraphics[width=\\imgwidth]{#1}%\n}\n</code></pre>\n\n<p>and then, in your document:</p>\n\n<pre><code>\\scalegraphics{img}\n</code></pre>\n\n<p>I hope this helps!</p>\n"
},
{
"answer_id": 5732912,
"author": "TauPan",
"author_id": 565224,
"author_profile": "https://Stackoverflow.com/users/565224",
"pm_score": 1,
"selected": false,
"text": "<p>I like an additional parameter for optionally scaling the image down or up a bit, so my version of \\scalegraphics looks like this:</p>\n\n<pre><code>\\newcommand\\scalegraphics[2][]{%\n \\settowidth{\\imgwidth}{\\includegraphics{#2}}%\n \\setlength{\\imgwidth}{\\minof{#1\\imgwidth}{\\textwidth}}%\n \\includegraphics[width=\\imgwidth]{#2}%\n}\n</code></pre>\n"
},
{
"answer_id": 17909454,
"author": "ted",
"author_id": 258418,
"author_profile": "https://Stackoverflow.com/users/258418",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://get-software.net/macros/latex/contrib/adjustbox/adjustbox.pdf\" rel=\"nofollow\"><code>adjustbox</code></a> package is usefull for this. Below you will find a short example. It allows the following (besides triming, clipping, adding margins and relative scaling:</p>\n\n<pre><code>\\documentclass[a4paper]{article}\n\n\n\\usepackage[demo]{graphicx}\n\\usepackage[export]{adjustbox}\n\n\\begin{document}\n\n\\adjustbox{max width=\\linewidth}{\\includegraphics[width=.5\\linewidth,height=3cm]{}}\n\n\\adjustbox{max width=\\linewidth}{\\includegraphics[width=2\\linewidth,height=3cm]{}}\n\n\\includegraphics[width=2\\linewidth,height=3cm,max width=\\linewidth]{}\n\\end{document}\n</code></pre>\n\n<p>If you use the <code>export</code> package option most of its keys can be used directly with <code>\\includegraphics</code>. FOr instance the key relevant to you, <code>max width</code>.</p>\n"
},
{
"answer_id": 54532404,
"author": "Casimir",
"author_id": 4034025,
"author_profile": "https://Stackoverflow.com/users/4034025",
"pm_score": 0,
"selected": false,
"text": "<p>If what you want to constrain is not an image but a standalone <code>.tex</code> file, you can slightly modify ChrisN's <code>\\scalegraphics</code> to</p>\n\n<pre><code>\\newlength{\\inputwidth}\n\\newcommand\\maxwidthinput[2][\\linewidth]{% \n \\settowidth{\\inputwidth}{#2}%\n \\setlength{\\inputwidth}{\\minof{\\inputwidth}{#1}}%\n \\resizebox{\\inputwidth}{!}{#2}\n}\n</code></pre>\n\n<p>and then use it like so</p>\n\n<pre><code>\\maxwidthinput{\\input{standalone}}\n\\maxwidthinput[0.5\\textwidth]{\\input{standalone}}\n</code></pre>\n\n<p>And of course, <code>adjustbox</code> as suggested by ted will work as well:</p>\n\n<pre><code>\\usepackage{adjustbox}\n...\n\\adjustbox{max width=\\linewidth}{\\input{standalone}}\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1322/"
] |
I have a command which includes an includegraphics command - I can pass an image to my command, and it will do some standard formatting for me before actually including the image. Some of the images that I'm including via this command are smaller than \textwidth, while some are larger. I'd like to scale the larger images down to \textwidth, while not scaling the smaller images up - this means I can't just do
```
\includegraphics[width=\textwidth]{img}
```
Is there a way to specify a maxwidth? Or, can I get the width of the image somehow so I can do something like
```
\ifthenelse{\imagewidth > \textwidth}{%
\includegraphics[width=\textwidth]{img}}{%
\includegraphics{img}}
```
|
To get the width of the image you can use this code:
```
\newlength{\imgwidth}
\settowidth{\imgwidth}{\includegraphics{img}}
```
You could use this in the document preamble to create a new command to automatically set the width:
```
\usepackage{graphicx}
\usepackage{calc}
\newlength{\imgwidth}
\newcommand\scalegraphics[1]{%
\settowidth{\imgwidth}{\includegraphics{#1}}%
\setlength{\imgwidth}{\minof{\imgwidth}{\textwidth}}%
\includegraphics[width=\imgwidth]{#1}%
}
```
and then, in your document:
```
\scalegraphics{img}
```
I hope this helps!
|
122,407 |
<p>I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?</p>
|
[
{
"answer_id": 122414,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 9,
"selected": true,
"text": "<p>Anonymous inner class</p>\n\n<p>Say you want to have a function passed in with a <code>String</code> param that returns an <code>int</code>.<br>\nFirst you have to define an interface with the function as its only member, if you can't reuse an existing one.</p>\n\n<pre><code>interface StringFunction {\n int func(String param);\n}\n</code></pre>\n\n<p>A method that takes the pointer would just accept <code>StringFunction</code> instance like so:</p>\n\n<pre><code>public void takingMethod(StringFunction sf) {\n int i = sf.func(\"my string\");\n // do whatever ...\n}\n</code></pre>\n\n<p>And would be called like so:</p>\n\n<pre><code>ref.takingMethod(new StringFunction() {\n public int func(String param) {\n // body\n }\n});\n</code></pre>\n\n<p><em>EDIT:</em> In Java 8, you could call it with a lambda expression:</p>\n\n<pre><code>ref.takingMethod(param -> bodyExpression);\n</code></pre>\n"
},
{
"answer_id": 122447,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 5,
"selected": false,
"text": "<p>For each \"function pointer\", I'd create a small <a href=\"http://en.wikipedia.org/wiki/Function_object#In_Java\" rel=\"nofollow noreferrer\">functor class</a> that implements your calculation.\nDefine an interface that all the classes will implement, and pass instances of those objects into your larger function. This is a combination of the \"<a href=\"http://en.wikipedia.org/wiki/Command_pattern\" rel=\"nofollow noreferrer\">command pattern</a>\", and \"<a href=\"https://stackoverflow.com/questions/91932/how-does-the-strategy-pattern-work\">strategy pattern</a>\".</p>\n\n<p>@sblundy's example is good.</p>\n"
},
{
"answer_id": 122470,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 5,
"selected": false,
"text": "<p>You need to create an interface that provides the function(s) that you want to pass around. eg:</p>\n\n<pre><code>/**\n * A simple interface to wrap up a function of one argument.\n * \n * @author rcreswick\n *\n */\npublic interface Function1<S, T> {\n\n /**\n * Evaluates this function on it's arguments.\n * \n * @param a The first argument.\n * @return The result.\n */\n public S eval(T a);\n\n}\n</code></pre>\n\n<p>Then, when you need to pass a function, you can implement that interface:</p>\n\n<pre><code>List<Integer> result = CollectionUtilities.map(list,\n new Function1<Integer, Integer>() {\n @Override\n public Integer eval(Integer a) {\n return a * a;\n }\n });\n</code></pre>\n\n<p>Finally, the map function uses the passed in Function1 as follows:</p>\n\n<pre><code> public static <K,R,S,T> Map<K, R> zipWith(Function2<R,S,T> fn, \n Map<K, S> m1, Map<K, T> m2, Map<K, R> results){\n Set<K> keySet = new HashSet<K>();\n keySet.addAll(m1.keySet());\n keySet.addAll(m2.keySet());\n\n results.clear();\n\n for (K key : keySet) {\n results.put(key, fn.eval(m1.get(key), m2.get(key)));\n }\n return results;\n }\n</code></pre>\n\n<p>You can often use Runnable instead of your own interface if you don't need to pass in parameters, or you can use various other techniques to make the param count less \"fixed\" but it's usually a trade-off with type safety. (Or you can override the constructor for your function object to pass in the params that way.. there are lots of approaches, and some work better in certain circumstances.)</p>\n"
},
{
"answer_id": 123980,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 4,
"selected": false,
"text": "<p>You may also be interested to hear about work going on for Java 7 involving closures:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/116865/whats-the-current-state-of-closures-in-java\">What’s the current state of closures in Java?</a></p>\n\n<p><a href=\"http://gafter.blogspot.com/2006/08/closures-for-java.html\" rel=\"nofollow noreferrer\">http://gafter.blogspot.com/2006/08/closures-for-java.html</a><br>\n<a href=\"http://tech.puredanger.com/java7/#closures\" rel=\"nofollow noreferrer\">http://tech.puredanger.com/java7/#closures</a></p>\n"
},
{
"answer_id": 131310,
"author": "Dennis S",
"author_id": 21935,
"author_profile": "https://Stackoverflow.com/users/21935",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like a strategy pattern to me. Check out fluffycat.com Java patterns.</p>\n"
},
{
"answer_id": 687655,
"author": "TofuBeer",
"author_id": 65868,
"author_profile": "https://Stackoverflow.com/users/65868",
"pm_score": 4,
"selected": false,
"text": "<p>You can also do this (which in some <strong><em>RARE</em></strong> occasions makes sense). The issue (and it is a big issue) is that you lose all the typesafety of using a class/interface and you have to deal with the case where the method does not exist. </p>\n\n<p>It does have the \"benefit\" that you can ignore access restrictions and call private methods (not shown in the example, but you can call methods that the compiler would normally not let you call). </p>\n\n<p>Again, it is a rare case that this makes sense, but on those occasions it is a nice tool to have.</p>\n\n<pre><code>import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\n\nclass Main\n{\n public static void main(final String[] argv)\n throws NoSuchMethodException,\n IllegalAccessException,\n IllegalArgumentException,\n InvocationTargetException\n {\n final String methodName;\n final Method method;\n final Main main;\n\n main = new Main();\n\n if(argv.length == 0)\n {\n methodName = \"foo\";\n }\n else\n {\n methodName = \"bar\";\n }\n\n method = Main.class.getDeclaredMethod(methodName, int.class);\n\n main.car(method, 42);\n }\n\n private void foo(final int x)\n {\n System.out.println(\"foo: \" + x);\n }\n\n private void bar(final int x)\n {\n System.out.println(\"bar: \" + x);\n }\n\n private void car(final Method method,\n final int val)\n throws IllegalAccessException,\n IllegalArgumentException,\n InvocationTargetException\n {\n method.invoke(this, val);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 687715,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 4,
"selected": false,
"text": "<p>If you have just one line which is different you could add a parameter such as a flag and a if(flag) statement which calls one line or the other.</p>\n"
},
{
"answer_id": 688035,
"author": "javashlook",
"author_id": 24815,
"author_profile": "https://Stackoverflow.com/users/24815",
"pm_score": 5,
"selected": false,
"text": "<p>When there is a predefined number of different calculations you can do in that one line, using an enum is a quick, yet clear way to implement a strategy pattern.</p>\n\n<pre><code>public enum Operation {\n PLUS {\n public double calc(double a, double b) {\n return a + b;\n }\n },\n TIMES {\n public double calc(double a, double b) {\n return a * b;\n }\n }\n ...\n\n public abstract double calc(double a, double b);\n}\n</code></pre>\n\n<p>Obviously, the strategy method declaration, as well as exactly one instance of each implementation are all defined in a single class/file.</p>\n"
},
{
"answer_id": 1414566,
"author": "Mario Fusco",
"author_id": 112779,
"author_profile": "https://Stackoverflow.com/users/112779",
"pm_score": 2,
"selected": false,
"text": "<p>Check out lambdaj </p>\n\n<p><a href=\"http://code.google.com/p/lambdaj/\" rel=\"nofollow noreferrer\">http://code.google.com/p/lambdaj/</a></p>\n\n<p>and in particular its new closure feature</p>\n\n<p><a href=\"http://code.google.com/p/lambdaj/wiki/Closures\" rel=\"nofollow noreferrer\">http://code.google.com/p/lambdaj/wiki/Closures</a></p>\n\n<p>and you will find a very readable way to define closure or function pointer without creating meaningless interface or use ugly inner classes</p>\n"
},
{
"answer_id": 2152081,
"author": "Lawrence Dol",
"author_id": 8946,
"author_profile": "https://Stackoverflow.com/users/8946",
"pm_score": 3,
"selected": false,
"text": "<p>One of the things I really miss when programming in Java is function callbacks. One situation where the need for these kept presenting itself was in recursively processing hierarchies where you want to perform some specific action for each item. Like walking a directory tree, or processing a data structure. The minimalist inside me hates having to define an interface and then an implementation for each specific case.</p>\n\n<p>One day I found myself wondering why not? We have method pointers - the Method object. With optimizing JIT compilers, reflective invocation really doesn't carry a huge performance penalty anymore. And besides next to, say, copying a file from one location to another, the cost of the reflected method invocation pales into insignificance.</p>\n\n<p>As I thought more about it, I realized that a callback in the OOP paradigm requires binding an object and a method together - enter the Callback object.</p>\n\n<p>Check out my reflection based solution for <a href=\"http://www.softwaremonkey.org/Code/Callback\" rel=\"noreferrer\">Callbacks in Java</a>. Free for any use.</p>\n"
},
{
"answer_id": 2768052,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 3,
"selected": false,
"text": "<p>@sblundy's answer is great, but anonymous inner classes have two small flaws, the primary being that they tend not to be reusable and the secondary is a bulky syntax.</p>\n\n<p>The nice thing is that his pattern expands into full classes without any change in the main class (the one performing the calculations).</p>\n\n<p>When you instantiate a new class you can pass parameters into that class which can act as constants in your equation--so if one of your inner classes look like this:</p>\n\n<pre><code>f(x,y)=x*y\n</code></pre>\n\n<p>but sometimes you need one that is:</p>\n\n<pre><code>f(x,y)=x*y*2\n</code></pre>\n\n<p>and maybe a third that is:</p>\n\n<pre><code>f(x,y)=x*y/2\n</code></pre>\n\n<p>rather than making two anonymous inner classes or adding a \"passthrough\" parameter, you can make a single ACTUAL class that you instantiate as:</p>\n\n<pre><code>InnerFunc f=new InnerFunc(1.0);// for the first\ncalculateUsing(f);\nf=new InnerFunc(2.0);// for the second\ncalculateUsing(f);\nf=new InnerFunc(0.5);// for the third\ncalculateUsing(f);\n</code></pre>\n\n<p>It would simply store the constant in the class and use it in the method specified in the interface.</p>\n\n<p>In fact, if KNOW that your function won't be stored/reused, you could do this:</p>\n\n<pre><code>InnerFunc f=new InnerFunc(1.0);// for the first\ncalculateUsing(f);\nf.setConstant(2.0);\ncalculateUsing(f);\nf.setConstant(0.5);\ncalculateUsing(f);\n</code></pre>\n\n<p>But immutable classes are safer--I can't come up with a justification to make a class like this mutable.</p>\n\n<p>I really only post this because I cringe whenever I hear anonymous inner class--I've seen a lot of redundant code that was \"Required\" because the first thing the programmer did was go anonymous when he should have used an actual class and never rethought his decision.</p>\n"
},
{
"answer_id": 4465570,
"author": "Adrian Petrescu",
"author_id": 12171,
"author_profile": "https://Stackoverflow.com/users/12171",
"pm_score": 3,
"selected": false,
"text": "<p>The Google <a href=\"http://code.google.com/p/guava-libraries/\">Guava libraries</a>, which are becoming very popular, have a generic <a href=\"http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Function.html\">Function</a> and <a href=\"http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Predicate.html\">Predicate</a> object that they have worked into many parts of their API.</p>\n"
},
{
"answer_id": 5163297,
"author": "Robert",
"author_id": 646307,
"author_profile": "https://Stackoverflow.com/users/646307",
"pm_score": 2,
"selected": false,
"text": "<p>Wow, why not just create a Delegate class which is not all that hard given that I already did for java and use it to pass in parameter where T is return type. I am sorry but as a C++/C# programmer in general just learning java, I need function pointers because they are very handy. If you are familiar with any class which deals with Method Information you can do it. In java libraries that would be java.lang.reflect.method.</p>\n\n<p>If you always use an interface, you always have to implement it. In eventhandling there really isn't a better way around registering/unregistering from the list of handlers but for delegates where you need to pass in functions and not the value type, making a delegate class to handle it for outclasses an interface.</p>\n"
},
{
"answer_id": 5347558,
"author": "vwvan",
"author_id": 591223,
"author_profile": "https://Stackoverflow.com/users/591223",
"pm_score": 2,
"selected": false,
"text": "<p>To do the same thing without interfaces for an array of functions:</p>\n\n<pre><code>class NameFuncPair\n{\n public String name; // name each func\n void f(String x) {} // stub gets overridden\n public NameFuncPair(String myName) { this.name = myName; }\n}\n\npublic class ArrayOfFunctions\n{\n public static void main(String[] args)\n {\n final A a = new A();\n final B b = new B();\n\n NameFuncPair[] fArray = new NameFuncPair[]\n {\n new NameFuncPair(\"A\") { @Override void f(String x) { a.g(x); } },\n new NameFuncPair(\"B\") { @Override void f(String x) { b.h(x); } },\n };\n\n // Go through the whole func list and run the func named \"B\"\n for (NameFuncPair fInstance : fArray)\n {\n if (fInstance.name.equals(\"B\"))\n {\n fInstance.f(fInstance.name + \"(some args)\");\n }\n }\n }\n}\n\nclass A { void g(String args) { System.out.println(args); } }\nclass B { void h(String args) { System.out.println(args); } }\n</code></pre>\n"
},
{
"answer_id": 8066845,
"author": "yogibimbi",
"author_id": 1037921,
"author_profile": "https://Stackoverflow.com/users/1037921",
"pm_score": 2,
"selected": false,
"text": "<p>oK, this thread is already old enough, so <em>very probably</em> my answer is not helpful for the question. But since this thread helped me to find my solution, I'll put it out here anyway.</p>\n\n<p>I needed to use a variable static method with known input and known output (both <strong>double</strong>). So then, knowing the method package and name, I could work as follows:</p>\n\n<pre><code>java.lang.reflect.Method Function = Class.forName(String classPath).getMethod(String method, Class[] params);\n</code></pre>\n\n<p>for a function that accepts one double as a parameter.</p>\n\n<p>So, in my concrete situation I initialized it with</p>\n\n<pre><code>java.lang.reflect.Method Function = Class.forName(\"be.qan.NN.ActivationFunctions\").getMethod(\"sigmoid\", double.class);\n</code></pre>\n\n<p>and invoked it later in a more complex situation with</p>\n\n<pre><code>return (java.lang.Double)this.Function.invoke(null, args);\n\njava.lang.Object[] args = new java.lang.Object[] {activity};\nsomeOtherFunction() + 234 + (java.lang.Double)Function.invoke(null, args);\n</code></pre>\n\n<p>where activity is an arbitrary double value. I am thinking of maybe doing this a bit more abstract and generalizing it, as SoftwareMonkey has done, but currently I am happy enough with the way it is. Three lines of code, no classes and interfaces necessary, that's not too bad.</p>\n"
},
{
"answer_id": 21974187,
"author": "The Guy with The Hat",
"author_id": 2846923,
"author_profile": "https://Stackoverflow.com/users/2846923",
"pm_score": 4,
"selected": false,
"text": "<h2>Method references using the <code>::</code> operator</h2>\n\n<p>You can use method references in method arguments where the method accepts a <em>functional interface</em>. A functional interface is any interface that contains only one abstract method. (A functional interface may contain one or more default methods or static methods.)</p>\n\n<p><a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/function/IntBinaryOperator.html\" rel=\"noreferrer\"><code>IntBinaryOperator</code></a> is a functional interface. Its abstract method, <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/function/IntBinaryOperator.html#applyAsInt-int-int-\" rel=\"noreferrer\"><code>applyAsInt</code></a>, accepts two <code>int</code>s as its parameters and returns an <code>int</code>. <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#max-int-int-\" rel=\"noreferrer\"><code>Math.max</code></a> also accepts two <code>int</code>s and returns an <code>int</code>. In this example, <code>A.method(Math::max);</code> makes <code>parameter.applyAsInt</code> send its two input values to <code>Math.max</code> and return the result of that <code>Math.max</code>.</p>\n\n<pre><code>import java.util.function.IntBinaryOperator;\n\nclass A {\n static void method(IntBinaryOperator parameter) {\n int i = parameter.applyAsInt(7315, 89163);\n System.out.println(i);\n }\n}\n</code></pre>\n\n\n\n<pre><code>import java.lang.Math;\n\nclass B {\n public static void main(String[] args) {\n A.method(Math::max);\n }\n}\n</code></pre>\n\n<p>In general, you can use:</p>\n\n<pre><code>method1(Class1::method2);\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>method1((arg1, arg2) -> Class1.method2(arg1, arg2));\n</code></pre>\n\n<p>which is short for:</p>\n\n<pre><code>method1(new Interface1() {\n int method1(int arg1, int arg2) {\n return Class1.method2(arg1, agr2);\n }\n});\n</code></pre>\n\n<p>For more information, see <a href=\"https://stackoverflow.com/q/20001427/2846923\">:: (double colon) operator in Java 8</a> and <a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.13\" rel=\"noreferrer\">Java Language Specification §15.13</a>.</p>\n"
},
{
"answer_id": 24152239,
"author": "Scott Emmons",
"author_id": 3025865,
"author_profile": "https://Stackoverflow.com/users/3025865",
"pm_score": 1,
"selected": false,
"text": "<p>If anyone is struggling to pass a function that takes one set of parameters to define its behavior but another set of parameters on which to execute, like Scheme's:</p>\n\n<pre><code>(define (function scalar1 scalar2)\n (lambda (x) (* x scalar1 scalar2)))\n</code></pre>\n\n<p>see <a href=\"https://stackoverflow.com/questions/24148175/pass-function-with-parameter-defined-behavior-in-java\" title=\"Pass Function with Parameter-Defined Behavior in Java\">Pass Function with Parameter-Defined Behavior in Java</a></p>\n"
},
{
"answer_id": 25381389,
"author": "user3002379",
"author_id": 3002379,
"author_profile": "https://Stackoverflow.com/users/3002379",
"pm_score": 4,
"selected": false,
"text": "<p><strong>New Java 8 <em>Functional Interfaces</em> and <em>Method References</em> using the <code>::</code> operator.</strong></p>\n\n<p>Java 8 is able to maintain method references ( MyClass::new ) with \"<em>@ Functional Interface</em>\" pointers. There are no need for same method name, only same method signature required.</p>\n\n<p>Example:</p>\n\n<pre><code>@FunctionalInterface\ninterface CallbackHandler{\n public void onClick();\n}\n\npublic class MyClass{\n public void doClick1(){System.out.println(\"doClick1\");;}\n public void doClick2(){System.out.println(\"doClick2\");}\n public CallbackHandler mClickListener = this::doClick;\n\n public static void main(String[] args) {\n MyClass myObjectInstance = new MyClass();\n CallbackHandler pointer = myObjectInstance::doClick1;\n Runnable pointer2 = myObjectInstance::doClick2;\n pointer.onClick();\n pointer2.run();\n }\n}\n</code></pre>\n\n<p>So, what we have here?</p>\n\n<ol>\n<li>Functional Interface - this is interface, annotated or not with <em>@FunctionalInterface</em>, which contains only one method declaration.</li>\n<li>Method References - this is just special syntax, looks like this, <em>objectInstance::methodName</em>, nothing more nothing less.</li>\n<li>Usage example - just an assignment operator and then interface method call.</li>\n</ol>\n\n<p>YOU SHOULD USE FUNCTIONAL INTERFACES FOR LISTENERS ONLY AND ONLY FOR THAT!</p>\n\n<p>Because all other such function pointers are really bad for code readability and for ability to understand. However, direct method references sometimes come handy, with foreach for example.</p>\n\n<p>There are several predefined Functional Interfaces:</p>\n\n<pre><code>Runnable -> void run( );\nSupplier<T> -> T get( );\nConsumer<T> -> void accept(T);\nPredicate<T> -> boolean test(T);\nUnaryOperator<T> -> T apply(T);\nBinaryOperator<T,U,R> -> R apply(T, U);\nFunction<T,R> -> R apply(T);\nBiFunction<T,U,R> -> R apply(T, U);\n//... and some more of it ...\nCallable<V> -> V call() throws Exception;\nReadable -> int read(CharBuffer) throws IOException;\nAutoCloseable -> void close() throws Exception;\nIterable<T> -> Iterator<T> iterator();\nComparable<T> -> int compareTo(T);\nComparator<T> -> int compare(T,T);\n</code></pre>\n\n<p>For earlier Java versions you should try Guava Libraries, which has similar functionality, and syntax, as Adrian Petrescu has mentioned above.</p>\n\n<p>For additional research look at <a href=\"http://www.java8.org/\" rel=\"noreferrer\">Java 8 Cheatsheet</a></p>\n\n<p>and thanks to The Guy with The Hat for the <a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.13\" rel=\"noreferrer\">Java Language Specification §15.13</a> link.</p>\n"
},
{
"answer_id": 30151628,
"author": "Alex",
"author_id": 4884360,
"author_profile": "https://Stackoverflow.com/users/4884360",
"pm_score": 1,
"selected": false,
"text": "<p>Since Java8, you can use lambdas, which also have libraries in the official SE 8 API.</p>\n\n<p><strong>Usage:</strong>\nYou need to use a interface with only one abstract method.\nMake an instance of it (you may want to use the one java SE 8 already provided) like this:</p>\n\n<pre><code>Function<InputType, OutputType> functionname = (inputvariablename) {\n... \nreturn outputinstance;\n}\n</code></pre>\n\n<p>For more information checkout the documentation: <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html\" rel=\"nofollow\">https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html</a></p>\n"
},
{
"answer_id": 31001089,
"author": "akhil_mittal",
"author_id": 1216775,
"author_profile": "https://Stackoverflow.com/users/1216775",
"pm_score": 1,
"selected": false,
"text": "<p>Prior to Java 8, nearest substitute for function-pointer-like functionality was an anonymous class. For example:</p>\n\n<pre><code>Collections.sort(list, new Comparator<CustomClass>(){\n public int compare(CustomClass a, CustomClass b)\n {\n // Logic to compare objects of class CustomClass which returns int as per contract.\n }\n});\n</code></pre>\n\n<p>But now in Java 8 we have a very neat alternative known as <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html\" rel=\"nofollow\">lambda expression</a>, which can be used as:</p>\n\n<pre><code>list.sort((a, b) -> { a.isBiggerThan(b) } );\n</code></pre>\n\n<p>where isBiggerThan is a method in <code>CustomClass</code>. We can also use method references here:</p>\n\n<pre><code>list.sort(MyClass::isBiggerThan);\n</code></pre>\n"
},
{
"answer_id": 39922622,
"author": "mrts",
"author_id": 258772,
"author_profile": "https://Stackoverflow.com/users/258772",
"pm_score": 2,
"selected": false,
"text": "<p>None of the Java 8 answers have given a full, cohesive example, so here it comes.</p>\n\n<p>Declare the method that accepts the \"function pointer\" as follows:</p>\n\n<pre><code>void doCalculation(Function<Integer, String> calculation, int parameter) {\n final String result = calculation.apply(parameter);\n}\n</code></pre>\n\n<p>Call it by providing the function with a lambda expression:</p>\n\n<pre><code>doCalculation((i) -> i.toString(), 2);\n</code></pre>\n"
},
{
"answer_id": 63776249,
"author": "Hervian",
"author_id": 6095334,
"author_profile": "https://Stackoverflow.com/users/6095334",
"pm_score": 0,
"selected": false,
"text": "<p>The open source <a href=\"https://github.com/Hervian/safety-mirror\" rel=\"nofollow noreferrer\">safety-mirror</a> project generalizes some of the above mentioned solutions into a library that adds functions, delegates and events to Java.</p>\n<p>See the README, or <a href=\"https://stackoverflow.com/a/63775875/6095334\">this stackoverflow answer</a>, for a cheat sheet of features.</p>\n<p>As for functions, the library introduces a Fun interface, and some sub-interfaces that (together with generics) make up a fluent API for using methods as types.</p>\n<pre><code>Fun.With0Params<String> myFunctionField = " hello world "::trim;` \nFun.With2Params<Boolean, Object, Object> equals = Objects::equals;` \n \npublic void foo(Fun.With1ParamAndVoid<String> printer) throws Exception {\n printer.invoke("hello world);\n} \n\npublic void test(){\n foo(System.out::println);\n} \n</code></pre>\n<p>Notice:</p>\n<ol>\n<li>that you must choose the sub-interface that matches the number of parameters in the signature you are targeting. Fx, if it has one parameter, choose Fun.With1Param.</li>\n<li>that Generics are used to define A) the return type and B) the parameters of the signature.</li>\n</ol>\n<p>Also, notice that the signature of the Method Reference passed to the call to the foo() method must match the the Fun defined by method Foo. If it do not, the compiler will emit an error.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?
|
Anonymous inner class
Say you want to have a function passed in with a `String` param that returns an `int`.
First you have to define an interface with the function as its only member, if you can't reuse an existing one.
```
interface StringFunction {
int func(String param);
}
```
A method that takes the pointer would just accept `StringFunction` instance like so:
```
public void takingMethod(StringFunction sf) {
int i = sf.func("my string");
// do whatever ...
}
```
And would be called like so:
```
ref.takingMethod(new StringFunction() {
public int func(String param) {
// body
}
});
```
*EDIT:* In Java 8, you could call it with a lambda expression:
```
ref.takingMethod(param -> bodyExpression);
```
|
122,422 |
<p>Is there any way to change the default datatype when importing an Excel file into Access? (I'm using Access 2003, by the way).</p>
<p>I know that I sometimes have the freedom to assign any datatype to each column that is being imported, but that could only be when I'm importing non-Excel files. </p>
<p><strong>EDIT:</strong> To be clear, I understand that there is a step in the import process where you are allowed to change the datatype of the imported column. </p>
<p>In fact, that's what I'm asking about. For some reason - maybe it's always Excel files, maybe there's something else - I am sometimes not allowed to change the datatype: the dropdown box is grayed out and I just have to live with whatever datatype Access assumes is correct.</p>
<p>For example, I just tried importing a large-ish Excel file (<strong>12000+ rows, ~200 columns</strong>) in Access where column #105 (or something similar) was filled with mostly numbers (codes: <code>1=foo, 2=bar</code>, etc), though there are a handful of alpha codes in there too (A=boo, B=far, etc). Access assumed it was a <code>Number</code> datatype (even after I changed the <code>Format</code> value in the Excel file itself) and so gave me errors on those alpha codes. If I had been allowed to change the datatype on import, it would have saved me some trouble.</p>
<p>Am I asking for something that Access just won't do, or am I missing something? Thanks.</p>
<p><strong>EDIT:</strong> There are two answers below that give useful advice. Saving the Excel file as a CSV and then importing that works well and is straightforward like <a href="https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122588">Chris OC</a> says. The advice for saving an import specification is very helpful too. However, I chose the registry setting answer by <a href="https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122504">DK</a> as the "Accepted Answer". I liked it as an answer because it's a <em>one-time-only step</em> that can be used to solve my major problem (having Access incorrectly assign a datatype). In short, this solution doesn't allow me to change the datatype myself, but it makes Access accurately guess the datatype so that there are fewer issues.</p>
|
[
{
"answer_id": 122442,
"author": "theo",
"author_id": 7870,
"author_profile": "https://Stackoverflow.com/users/7870",
"pm_score": -1,
"selected": false,
"text": "<p>Access will do this.</p>\n\n<p>In your import process you can define what the data type of each column is.</p>\n"
},
{
"answer_id": 122504,
"author": "DK.",
"author_id": 16886,
"author_profile": "https://Stackoverflow.com/users/16886",
"pm_score": 3,
"selected": true,
"text": "<p>This <em>may</em> be caused by Excel Jet driver default settings. Check out the following registry key and change it's value from default 8 to 0, meaning \"guess column data type based on all values, not just first 8 rows.\"</p>\n\n<pre><code>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Jet\\4.0\\Engines\\Excel]\n\"TypeGuessRows\"=dword:00000000\n</code></pre>\n\n<p>Please, tell if this works.</p>\n"
},
{
"answer_id": 122588,
"author": "Chris OC",
"author_id": 11041,
"author_profile": "https://Stackoverflow.com/users/11041",
"pm_score": 2,
"selected": false,
"text": "<p>There are a couple of ways to do this. The most straightforward way is to convert the .xls file to a .csv file in Excel, so you can import into Access using the Import Text Wizard, which allows you to choose the data types of every column during the import.</p>\n\n<p>The other benefit to doing this is that the import of a csv (or text) file is <em>so</em> much faster than the import of an xls file. If you're going to do this import more than once, save the import setup settings as an import specification. (When in the Import Text Wizard, click on the \"Advanced...\" button on the bottom left, then click on \"Save As\" and give a specification name to save the changes you just made.)</p>\n"
},
{
"answer_id": 123439,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 0,
"selected": false,
"text": "<p>Access can do what you need, but there is no straightforward way for that. You'd have to manage some recordsets, one being your Excel data, the other one being your final Access table. Once both recordsets are open, you can transfer data from one recordset to the other by browsing your Excel data and adding it to your Access table. At this stage, it will be possible to change datatype as requested. </p>\n"
},
{
"answer_id": 126150,
"author": "Birger",
"author_id": 11485,
"author_profile": "https://Stackoverflow.com/users/11485",
"pm_score": 0,
"selected": false,
"text": "<p>When importing from CSV files you can also have a look at <a href=\"http://msdn.microsoft.com/en-us/library/ms709353.aspx\" rel=\"nofollow noreferrer\">schema.ini</a> you will find that with this you can control every aspect of the import process.</p>\n"
},
{
"answer_id": 50125793,
"author": "Michael Habib",
"author_id": 9727944,
"author_profile": "https://Stackoverflow.com/users/9727944",
"pm_score": 0,
"selected": false,
"text": "<p>Access will let you specify the datatype at the import process. the problem is at the \"Append\" process for the following times, it will not ask about the import to datatype, and it will forget you changed it. I think it is a bug in MS Access.</p>\n"
},
{
"answer_id": 66298512,
"author": "Deepak",
"author_id": 15251577,
"author_profile": "https://Stackoverflow.com/users/15251577",
"pm_score": 1,
"selected": false,
"text": "<p>open your excel file. In Home tab change format from General to Text. then import into access</p>\n"
},
{
"answer_id": 68834334,
"author": "Christo",
"author_id": 13048688,
"author_profile": "https://Stackoverflow.com/users/13048688",
"pm_score": 0,
"selected": false,
"text": "<p>This is an old post but the issue persists! I agree with Deepak. To continue that thought:</p>\n<p>Access determines the field types when linking to or importing Excel files based on the field types in Excel. If they are all default, it looks at the first X rows of data. A few ways to fix this:</p>\n<ol>\n<li><p>Open the Excel file and add about 6 rows (under the field headers if any) that emulate the type you want. If you prefer all text, enter 'abcdef' in each cell of those first six rows.</p>\n</li>\n<li><p>Open the Excel file, highlight all cells, right click, and change format to 'Text' or whatever format you like. Save, then link/import into Access.</p>\n</li>\n<li><p>Use a macro (VBA script) to do step 2 for you each time:</p>\n</li>\n</ol>\n<pre><code>Public Function fcn_ChangeExcelFormat()\nOn Error GoTo ErrorExit\n\nDim strExcelFile As String\nDim XL_App As Excel.Application\nDim XL_WB As Excel.Workbook\nDim XL_WS As Excel.Worksheet\n\nstrExcelFile = "C:\\My Files\\MyExcelFile.xlsx"\n\nSet XL_App = New Excel.Application\n\nSet XL_WB = XL_App.Workbooks.Open(strExcelFile, , False)\nSet XL_WS = XL_WB.Sheets(1) ' 1 can be changed to "Your Worksheet Name"\n\nWith XL_WS\n .Cells.NumberFormat = "@" 'Equiv to Right Click...Format Cells...Text\nEnd With\n\nXL_WB.Close True\nXL_App.Quit\n\nNormalExit:\nSet XL_WB = Nothing\nSet XL_App = Nothing\nExit Function\n \nErrorExit:\nstrMsg = "There was an error updating the Excel file! " & vbCr & vbCr & _\n "Error " & Err.Number & ": " & Err.Description\nMsgBox strMsg, vbExclamation, "Error"\nResume NormalExit\nEnd Function\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3930756/"
] |
Is there any way to change the default datatype when importing an Excel file into Access? (I'm using Access 2003, by the way).
I know that I sometimes have the freedom to assign any datatype to each column that is being imported, but that could only be when I'm importing non-Excel files.
**EDIT:** To be clear, I understand that there is a step in the import process where you are allowed to change the datatype of the imported column.
In fact, that's what I'm asking about. For some reason - maybe it's always Excel files, maybe there's something else - I am sometimes not allowed to change the datatype: the dropdown box is grayed out and I just have to live with whatever datatype Access assumes is correct.
For example, I just tried importing a large-ish Excel file (**12000+ rows, ~200 columns**) in Access where column #105 (or something similar) was filled with mostly numbers (codes: `1=foo, 2=bar`, etc), though there are a handful of alpha codes in there too (A=boo, B=far, etc). Access assumed it was a `Number` datatype (even after I changed the `Format` value in the Excel file itself) and so gave me errors on those alpha codes. If I had been allowed to change the datatype on import, it would have saved me some trouble.
Am I asking for something that Access just won't do, or am I missing something? Thanks.
**EDIT:** There are two answers below that give useful advice. Saving the Excel file as a CSV and then importing that works well and is straightforward like [Chris OC](https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122588) says. The advice for saving an import specification is very helpful too. However, I chose the registry setting answer by [DK](https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122504) as the "Accepted Answer". I liked it as an answer because it's a *one-time-only step* that can be used to solve my major problem (having Access incorrectly assign a datatype). In short, this solution doesn't allow me to change the datatype myself, but it makes Access accurately guess the datatype so that there are fewer issues.
|
This *may* be caused by Excel Jet driver default settings. Check out the following registry key and change it's value from default 8 to 0, meaning "guess column data type based on all values, not just first 8 rows."
```
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel]
"TypeGuessRows"=dword:00000000
```
Please, tell if this works.
|
122,424 |
<p>Right now, we are using Perforce for version control. It has the handy feature of a strictly increasing change number that we can use to refer to builds, eg "you'll get the bugfix if your build is at least 44902".</p>
<p>I'd like to switch over to using a distributed system (probably git) to make it easier to branch and to work from home. (Both of which are perfectly possible with Perforce, but the git workflow has some advantages.) So although "tributary development" would be distributed and not refer to a common revision sequencing, we'd still maintain a master git repo that all changes would need to feed into before a build was created.</p>
<p>What's the best way to preserve strictly increasing build ids? The most straightforward way I can think of is to have some sort of post-commit hook that fires off whenever the master repo gets updated, and it registers (the hash of) the new tree object (or commit object? I'm new to git) with a centralized database that hands out ids. (I say "database", but I'd probably do it with git tags, and just look for the next available tag number or something. So the "database" would really be .git/refs/tags/build-id/.)</p>
<p>This is workable, but I'm wondering if there is an easier, or already-implemented, or standard/"best practice" way of accomplishing this.</p>
|
[
{
"answer_id": 122508,
"author": "foxxtrot",
"author_id": 10369,
"author_profile": "https://Stackoverflow.com/users/10369",
"pm_score": 1,
"selected": false,
"text": "<p>I'd use \"Labels\" Create a label whenever you have a successful (or even unsuccessful) build, and you'll be able to identify that build forever. It's not quite the same, but it does provide those build numbers, while still providing the benefits of distributed development.</p>\n"
},
{
"answer_id": 122673,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 2,
"selected": false,
"text": "<p><code>git tag</code> may be enough for what you need. Pick a tag format that everyone will agree not to use otherwise. </p>\n\n<p>Note: when you tag locally, a <code>git push</code> will not update the tags on the server. Use <code>git push --tags</code> for that.</p>\n"
},
{
"answer_id": 123594,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 2,
"selected": false,
"text": "<p>You should investigate <code>git describe</code>. It gives a unique string that describes the current branch (or any passed commit id) in terms of the latest annotated tag, the number of commits since that tag and an abbreviated commit id of the head of the branch.</p>\n\n<p>Presumably you have a single branch that you perform controlled build releases off. In this case I would tag an early commit with a known tag format and then use git describe with the --match option to describe the current HEAD relative to a the known tag. You can then use the result of git describe as is or if you really want just a single number you can use a regex to chop the number out of the tag.</p>\n\n<p>Assuming that you never rewind the branch the number of following commits will always identify a unique point in the branch's history.</p>\n\n<p>e.g. (using bash or similar)</p>\n\n<pre><code># make an annotated tag to an early build in the repository:\ngit tag -a build-origin \"$some_old_commitid\"\n\n# describe the current HEAD against this tag and pull out a build number\nexpr \"$(git describe --match build-origin)\" : 'build-origin-\\([0-9]*\\)-g'\n</code></pre>\n"
},
{
"answer_id": 124642,
"author": "EfForEffort",
"author_id": 14113,
"author_profile": "https://Stackoverflow.com/users/14113",
"pm_score": 0,
"selected": false,
"text": "<p>As you probably know, git computes a hash (a number) that uniquely identifies a node of the history. Using these, although they are not strictly increasing, seems like it would be good enough. (Even better, they <em>always</em> correspond to the source, so if you have the hash, you have the same code.) They're big numbers, but mostly you can get by with 6 or so of the leading digits.</p>\n\n<p>For example,</p>\n\n<blockquote>\n <p>That bug was fixed at 064f2ea...</p>\n</blockquote>\n"
},
{
"answer_id": 124747,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 6,
"selected": true,
"text": "<p>I second the suggestion of using <code>git describe</code>. Provided that you have a sane versioning policy, and you don't do any crazy stuff with your repository, <code>git describe</code> will always be monotonic (at least as monotonic as you can be, when your revision history is a DAG instead of a tree) and unique.</p>\n\n<p>A little demonstration:</p>\n\n<pre><code>git init\ngit commit --allow-empty -m'Commit One.'\ngit tag -a -m'Tag One.' 1.2.3\ngit describe # => 1.2.3\ngit commit --allow-empty -m'Commit Two.'\ngit describe # => 1.2.3-1-gaac161d\ngit commit --allow-empty -m'Commit Three.'\ngit describe # => 1.2.3-2-g462715d\ngit tag -a -m'Tag Two.' 2.0.0\ngit describe # => 2.0.0\n</code></pre>\n\n<p>The output of <code>git describe</code> consists of the following components:</p>\n\n<ol>\n<li>The newest tag reachable from the commit you are asking to describe</li>\n<li>The number of commits between the commit and the tag (if non-zero)</li>\n<li>The (abbreviated) id of the commit (if #2 is non-zero)</li>\n</ol>\n\n<p>#2 is what makes the output monotonic, #3 is what makes it unique. #2 and #3 are omitted, when the commit <em>is</em> the tag, making <code>git describe</code> also suitable for production releases.</p>\n"
},
{
"answer_id": 1048950,
"author": "yanjost",
"author_id": 16718,
"author_profile": "https://Stackoverflow.com/users/16718",
"pm_score": 0,
"selected": false,
"text": "<p>With Mercurial you can use the following command :</p>\n\n<pre><code># get the parents id, the local revision number and the tags\n[yjost@myhost:~/my-repo]$ hg id -nibt\n03b6399bc32b+ 23716+ default tip\n</code></pre>\n\n<p>See <a href=\"http://www.selenic.com/mercurial/hg.1.html#identify\" rel=\"nofollow noreferrer\">hg identify</a></p>\n"
},
{
"answer_id": 14997849,
"author": "squadette",
"author_id": 7754,
"author_profile": "https://Stackoverflow.com/users/7754",
"pm_score": 5,
"selected": false,
"text": "<p>Monotonically increasing number corresponding to the current commit could be generated with</p>\n\n<pre><code>git log --pretty=oneline | wc -l\n</code></pre>\n\n<p>which returns a single number. You can also append current sha1 to that number, to add uniqueness.</p>\n\n<p>This approach is better than <code>git describe</code>, because it does not require you to add any tags, and it automatically handles merges. </p>\n\n<p>It could have problems with rebasing, but rebasing is \"dangerous\" operation anyway.</p>\n"
},
{
"answer_id": 22082992,
"author": "joegiralt",
"author_id": 2340298,
"author_profile": "https://Stackoverflow.com/users/2340298",
"pm_score": 3,
"selected": false,
"text": "<pre><code> git rev-list BRANCHNAME --count\n</code></pre>\n\n<p>this is much less resource intensive than </p>\n\n<pre><code> git log --pretty=oneline | wc -l\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14528/"
] |
Right now, we are using Perforce for version control. It has the handy feature of a strictly increasing change number that we can use to refer to builds, eg "you'll get the bugfix if your build is at least 44902".
I'd like to switch over to using a distributed system (probably git) to make it easier to branch and to work from home. (Both of which are perfectly possible with Perforce, but the git workflow has some advantages.) So although "tributary development" would be distributed and not refer to a common revision sequencing, we'd still maintain a master git repo that all changes would need to feed into before a build was created.
What's the best way to preserve strictly increasing build ids? The most straightforward way I can think of is to have some sort of post-commit hook that fires off whenever the master repo gets updated, and it registers (the hash of) the new tree object (or commit object? I'm new to git) with a centralized database that hands out ids. (I say "database", but I'd probably do it with git tags, and just look for the next available tag number or something. So the "database" would really be .git/refs/tags/build-id/.)
This is workable, but I'm wondering if there is an easier, or already-implemented, or standard/"best practice" way of accomplishing this.
|
I second the suggestion of using `git describe`. Provided that you have a sane versioning policy, and you don't do any crazy stuff with your repository, `git describe` will always be monotonic (at least as monotonic as you can be, when your revision history is a DAG instead of a tree) and unique.
A little demonstration:
```
git init
git commit --allow-empty -m'Commit One.'
git tag -a -m'Tag One.' 1.2.3
git describe # => 1.2.3
git commit --allow-empty -m'Commit Two.'
git describe # => 1.2.3-1-gaac161d
git commit --allow-empty -m'Commit Three.'
git describe # => 1.2.3-2-g462715d
git tag -a -m'Tag Two.' 2.0.0
git describe # => 2.0.0
```
The output of `git describe` consists of the following components:
1. The newest tag reachable from the commit you are asking to describe
2. The number of commits between the commit and the tag (if non-zero)
3. The (abbreviated) id of the commit (if #2 is non-zero)
#2 is what makes the output monotonic, #3 is what makes it unique. #2 and #3 are omitted, when the commit *is* the tag, making `git describe` also suitable for production releases.
|
122,445 |
<p>I'm implementing charts using <a href="http://www.ziya.liquidrail.com/" rel="nofollow noreferrer">The Ziya Charts Gem</a>. Unfortunately, the documentation isn't really helpful or I haven't had enough coffee to figure out theming. I know I can set a theme using</p>
<pre><code>chart.add(:theme, 'whatever')
</code></pre>
<p>Problem: I haven't found any predefined themes, nor have I found a reference to the required format. </p>
|
[
{
"answer_id": 122491,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 0,
"selected": false,
"text": "<p>To partly answer my own question, there are some themes in the website sources which can be checked out at </p>\n\n<pre><code>svn co svn://rubyforge.org/var/svn/liquidrail/samples/charting \n</code></pre>\n\n<p>(then go to /public/charts/themes/)</p>\n"
},
{
"answer_id": 122795,
"author": "PJ.",
"author_id": 3230,
"author_profile": "https://Stackoverflow.com/users/3230",
"pm_score": 2,
"selected": true,
"text": "<p>As I understand it, the themes are used by initializing the theme directory in your ziya.rb file like so: </p>\n\n<p><code>Ziya.initialize(:themes_dir => File.join( File.dirname(__FILE__), %w[.. .. public charts themes]) )\n</code></p>\n\n<p>And you'll need to set up the proper directory, in this case public/charts/themes. It doesn't come with any in there to start with as I recall. Are you having problems past this?</p>\n"
},
{
"answer_id": 123123,
"author": "Ryan Leavengood",
"author_id": 20891,
"author_profile": "https://Stackoverflow.com/users/20891",
"pm_score": 2,
"selected": false,
"text": "<p>If you install the ZiYa plug-in into your Rails application there should be a themes directory where you said. Just copy one of the existing themes, change its name to whatever you want, and then modify it however you like.</p>\n\n<p>Another options for nice Flash charts is <a href=\"http://teethgrinder.co.uk/open-flash-chart/\" rel=\"nofollow noreferrer\">Open Flash Chart</a>. I moved from Ziya/SWF Charts to Open Flash Chart when working on Flash charts in a Rails app I was working on. There is also a <a href=\"http://pullmonkey.com/projects/open_flash_chart\" rel=\"nofollow noreferrer\">Rails plug-in for Open Flash Chart</a>. Besides the fact that it is easier to work with, Open Flash Chart is open source, so if you can hack Flash you can customize it.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4494/"
] |
I'm implementing charts using [The Ziya Charts Gem](http://www.ziya.liquidrail.com/). Unfortunately, the documentation isn't really helpful or I haven't had enough coffee to figure out theming. I know I can set a theme using
```
chart.add(:theme, 'whatever')
```
Problem: I haven't found any predefined themes, nor have I found a reference to the required format.
|
As I understand it, the themes are used by initializing the theme directory in your ziya.rb file like so:
`Ziya.initialize(:themes_dir => File.join( File.dirname(__FILE__), %w[.. .. public charts themes]) )`
And you'll need to set up the proper directory, in this case public/charts/themes. It doesn't come with any in there to start with as I recall. Are you having problems past this?
|
122,463 |
<p>I have an XML file that starts like this:</p>
<pre><code><Elements name="Entities" xmlns="XS-GenerationToolElements">
</code></pre>
<p>I'll have to open a lot of these files. Each of these have a different namespace but will only have one namespace at a time (I'll never find two namespaces defined in one xml file).</p>
<p>Using XPath I'd like to have an automatic way to add the given namespace to the namespace manager.
So far, i could only get the namespace by parsing the xml file but I have a XPathNavigator instance and it should have a nice and clean way to get the namespaces, right?</p>
<p>-- OR --</p>
<p>Given that I only have one namespace, somehow make XPath use the only one that is present in the xml, thus avoiding cluttering the code by always appending the namespace.</p>
|
[
{
"answer_id": 122786,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately, XPath doesn't have any concept of \"default namespace\". You need to register namespaces with prefixes with the XPath context, and then use those prefixes in your XPath expressions. It means for very verbose xpath, but it's a basic shortcoming of XPath 1. Apparently XPath 2 will address this, but that's no use to you right now.</p>\n\n<p>I suggest that you programmatically examine your XML document for the namespace, associate that namespace with a prefix in the XPath context, then use the prefix in the xpath expressions.</p>\n"
},
{
"answer_id": 123005,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 8,
"selected": true,
"text": "<p>There are a few techniques that you might try; which you use will depend on exactly what information you need to get out of the document, how rigorous you want to be, and how conformant the XPath implementation you're using is.</p>\n\n<p>One way to get the namespace URI associated with a particular prefix is using the <code>namespace::</code> axis. This will give you a namespace node whose name is the prefix and whose value is the namespace URI. For example, you could get the default namespace URI on the document element using the path:</p>\n\n<pre><code>/*/namespace::*[name()='']\n</code></pre>\n\n<p>You might be able to use that to set up the namespace associations for your XPathNavigator. Be warned, though, that the <code>namespace::</code> axis is one of those corners of XPath 1.0 that isn't always implemented.</p>\n\n<p>A second way of getting that namespace URI is to use the <code>namespace-uri()</code> function on the document element (which you've said will always be in that namespace). The expression:</p>\n\n<pre><code>namespace-uri(/*)\n</code></pre>\n\n<p>will give you that namespace.</p>\n\n<p>An alternative would be to forget about associating a prefix with that namespace, and just make your path namespace-free. You can do this by using the <code>local-name()</code> function whenever you need to refer to an element whose namespace you don't know. For example:</p>\n\n<pre><code>//*[local-name() = 'Element']\n</code></pre>\n\n<p>You could go one step further and test the namespace URI of the element against the one of the document element, if you really wanted:</p>\n\n<pre><code>//*[local-name() = 'Element' and namespace-uri() = namespace-uri(/*)]\n</code></pre>\n\n<p>A final option, given that the namespace seems to mean nothing to you, would be to run your XML through a filter that strips out the namespaces. Then you won't have to worry about them in your XPath at all. The easiest way to do that would be simply to remove the <code>xmlns</code> attribute with a regular expression, but you could do something more complex if you needed to do other tidying at the same time.</p>\n"
},
{
"answer_id": 289120,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 4,
"selected": false,
"text": "<p><strong>This 40-line xslt transformation provides all the useful information about the namespaces in a given XML document</strong>:</p>\n<pre class=\"lang-xml prettyprint-override\"><code> <xsl:stylesheet version="1.0"\n xmlns:xsl="http://www.w3.org/1999/XSL/Transform"\n xmlns:ext="http://exslt.org/common"\n exclude-result-prefixes="ext"\n >\n\n <xsl:output omit-xml-declaration="yes" indent="yes"/>\n\n <xsl:strip-space elements="*"/>\n\n <xsl:key name="kNsByNsUri" match="ns" use="@uri"/>\n\n <xsl:variable name="vXmlNS" \n select="'http://www.w3.org/XML/1998/namespace'"/>\n\n <xsl:template match="/">\n <xsl:variable name="vrtfNamespaces">\n <xsl:for-each select=\n "//namespace::*\n [not(. = $vXmlNS)\n and\n . = namespace-uri(..)\n ]">\n <ns element="{name(..)}"\n prefix="{name()}" uri="{.}"/>\n </xsl:for-each>\n </xsl:variable>\n\n <xsl:variable name="vNamespaces"\n select="ext:node-set($vrtfNamespaces)/*"/>\n\n <namespaces>\n <xsl:for-each select=\n "$vNamespaces[generate-id()\n =\n generate-id(key('kNsByNsUri',@uri)[1])\n ]">\n <namespace uri="{@uri}">\n <xsl:for-each select="key('kNsByNsUri',@uri)/@element">\n <element name="{.}" prefix="{../@prefix}"/>\n </xsl:for-each>\n </namespace>\n </xsl:for-each>\n </namespaces>\n </xsl:template>\n </xsl:stylesheet>\n</code></pre>\n<p>When applied on the following XML document:</p>\n<pre><code><a xmlns="my:def1" xmlns:n1="my:n1"\n xmlns:n2="my:n2" xmlns:n3="my:n3">\n <b>\n <n1:d/>\n </b>\n <n1:c>\n <n2:e>\n <f/>\n </n2:e>\n </n1:c>\n <n2:g/>\n</a>\n</code></pre>\n<p>the wanted result is produced:</p>\n<pre><code><namespaces>\n <namespace uri="my:def1">\n <element name="a" prefix=""/>\n <element name="b" prefix=""/>\n <element name="f" prefix=""/>\n </namespace>\n <namespace uri="my:n1">\n <element name="n1:d" prefix="n1"/>\n <element name="n1:c" prefix="n1"/>\n </namespace>\n <namespace uri="my:n2">\n <element name="n2:e" prefix="n2"/>\n <element name="n2:g" prefix="n2"/>\n </namespace>\n</namespaces>\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20335/"
] |
I have an XML file that starts like this:
```
<Elements name="Entities" xmlns="XS-GenerationToolElements">
```
I'll have to open a lot of these files. Each of these have a different namespace but will only have one namespace at a time (I'll never find two namespaces defined in one xml file).
Using XPath I'd like to have an automatic way to add the given namespace to the namespace manager.
So far, i could only get the namespace by parsing the xml file but I have a XPathNavigator instance and it should have a nice and clean way to get the namespaces, right?
-- OR --
Given that I only have one namespace, somehow make XPath use the only one that is present in the xml, thus avoiding cluttering the code by always appending the namespace.
|
There are a few techniques that you might try; which you use will depend on exactly what information you need to get out of the document, how rigorous you want to be, and how conformant the XPath implementation you're using is.
One way to get the namespace URI associated with a particular prefix is using the `namespace::` axis. This will give you a namespace node whose name is the prefix and whose value is the namespace URI. For example, you could get the default namespace URI on the document element using the path:
```
/*/namespace::*[name()='']
```
You might be able to use that to set up the namespace associations for your XPathNavigator. Be warned, though, that the `namespace::` axis is one of those corners of XPath 1.0 that isn't always implemented.
A second way of getting that namespace URI is to use the `namespace-uri()` function on the document element (which you've said will always be in that namespace). The expression:
```
namespace-uri(/*)
```
will give you that namespace.
An alternative would be to forget about associating a prefix with that namespace, and just make your path namespace-free. You can do this by using the `local-name()` function whenever you need to refer to an element whose namespace you don't know. For example:
```
//*[local-name() = 'Element']
```
You could go one step further and test the namespace URI of the element against the one of the document element, if you really wanted:
```
//*[local-name() = 'Element' and namespace-uri() = namespace-uri(/*)]
```
A final option, given that the namespace seems to mean nothing to you, would be to run your XML through a filter that strips out the namespaces. Then you won't have to worry about them in your XPath at all. The easiest way to do that would be simply to remove the `xmlns` attribute with a regular expression, but you could do something more complex if you needed to do other tidying at the same time.
|
122,483 |
<p>In crontab, I can use an asterisk to mean every value, or "*/2" to mean every even value.</p>
<p>Is there a way to specify every <strong>odd</strong> value? (Would something like "1+*/2" work?)</p>
|
[
{
"answer_id": 122496,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>1-23/2\n</code></pre>\n\n<p>From your question, I'm assuming Vixie Cron. I doubt this will work with any other cron.</p>\n"
},
{
"answer_id": 122499,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 8,
"selected": true,
"text": "<p>Depending on your version of cron, you should be able to do (for hours, say):</p>\n\n<pre><code> 1-23/2\n</code></pre>\n\n<p>Going by the EXTENSIONS section in the crontab(5) manpage:</p>\n\n<pre><code> Ranges can include \"steps\", so \"1-9/2\" is the same as \"1,3,5,7,9\".\n</code></pre>\n\n<p>For a more portable solution, I suspect you just have to use the simple list:</p>\n\n<pre><code> 1,3,5,7,9,11,13,15,17,19,21,23\n</code></pre>\n\n<p>But it might be easier to wrap your command in a shell script that will immediately exit if it's not called in an odd minute.</p>\n"
},
{
"answer_id": 122500,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 2,
"selected": false,
"text": "<p>As I read the manual \"1-23/2\" (for hours) would do the trick.</p>\n"
},
{
"answer_id": 5071478,
"author": "grigb",
"author_id": 627013,
"author_profile": "https://Stackoverflow.com/users/627013",
"pm_score": 6,
"selected": false,
"text": "<p>Every odd minute would be:</p>\n\n<pre><code>1-59/2 * * * * \n</code></pre>\n\n<p>Every even minute would be:</p>\n\n<pre><code>0-58/2 * * * * \n</code></pre>\n"
},
{
"answer_id": 10427443,
"author": "Tomas Jensen",
"author_id": 1371897,
"author_profile": "https://Stackoverflow.com/users/1371897",
"pm_score": 0,
"selected": false,
"text": "<p>Works on Cronie\nEven with 5 minutes interval e.g.</p>\n\n<pre><code>3-58/5 * * * * /home/test/bin/do_some_thing_every_five_minute\n</code></pre>\n"
},
{
"answer_id": 56839339,
"author": "pbjolsby",
"author_id": 11330991,
"author_profile": "https://Stackoverflow.com/users/11330991",
"pm_score": 3,
"selected": false,
"text": "<p>I realize this is almost 10 years old, but I was having trouble getting 1-23/2 for an every two hour, odd hour job.</p>\n\n<p>For all you users where, <em>exact</em> odd hour precision is not needed. I did the following which suited my teams needs.</p>\n\n<pre><code>59 */2 * * *\n</code></pre>\n\n<p>Execute the job every two hours, at the 59th Minute.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4465/"
] |
In crontab, I can use an asterisk to mean every value, or "\*/2" to mean every even value.
Is there a way to specify every **odd** value? (Would something like "1+\*/2" work?)
|
Depending on your version of cron, you should be able to do (for hours, say):
```
1-23/2
```
Going by the EXTENSIONS section in the crontab(5) manpage:
```
Ranges can include "steps", so "1-9/2" is the same as "1,3,5,7,9".
```
For a more portable solution, I suspect you just have to use the simple list:
```
1,3,5,7,9,11,13,15,17,19,21,23
```
But it might be easier to wrap your command in a shell script that will immediately exit if it's not called in an odd minute.
|
122,514 |
<p>I have already posted something similar <a href="https://stackoverflow.com/questions/118051/c-grid-binding-not-update">here</a> but I would like to ask the question more general over here.</p>
<p>Have you try to serialize an object that implement INotifyPropertyChanged and to get it back from serialization and to bind it to a DataGridView? When I do it, I have no refresh from the value that change (I need to minimize the windows and open it back).</p>
<p>Do you have any trick? </p>
|
[
{
"answer_id": 122522,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "<p>The trick of having it's own <a href=\"https://stackoverflow.com/questions/118051/c-grid-binding-not-update#118438\">Event and binding it after serialization</a> works but is not elegant because require an other event that I would not like to have...</p>\n"
},
{
"answer_id": 122594,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Serializing interfaces gets tricky when you deal with objects that have internal states. Can you post an example of the serialization code you're talking about?</p>\n"
},
{
"answer_id": 179462,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 3,
"selected": true,
"text": "<p>Use the <code>DataContractSerializer</code> and create a method for OnDeserialized</p>\n\n<pre><code>[OnDeserialized]\nprivate void OnDeserialized(StreamingContext c) {}\n</code></pre>\n\n<p>This will let you raise the PropertyChanged event when deserialization is complete</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
I have already posted something similar [here](https://stackoverflow.com/questions/118051/c-grid-binding-not-update) but I would like to ask the question more general over here.
Have you try to serialize an object that implement INotifyPropertyChanged and to get it back from serialization and to bind it to a DataGridView? When I do it, I have no refresh from the value that change (I need to minimize the windows and open it back).
Do you have any trick?
|
Use the `DataContractSerializer` and create a method for OnDeserialized
```
[OnDeserialized]
private void OnDeserialized(StreamingContext c) {}
```
This will let you raise the PropertyChanged event when deserialization is complete
|
122,523 |
<p>Howdy, I have a DataRow pulled out of a DataTable from a DataSet. I am accessing a column that is defined in SQL as a float datatype. I am trying to assign that value to a local variable (c# float datatype) but am getting an InvalidCastExecption </p>
<pre><code>DataRow exercise = _exerciseDataSet.Exercise.FindByExerciseID(65);
_AccelLimit = (float)exercise["DefaultAccelLimit"];
</code></pre>
<p>Now, playing around with this I did make it work but it did not make any sense and it didn't feel right. </p>
<pre><code>_AccelLimit = (float)(double)exercise["DefaultAccelLimit"];
</code></pre>
<p>Can anyone explain what I am missing here?</p>
|
[
{
"answer_id": 122536,
"author": "Austin Salonen",
"author_id": 4068,
"author_profile": "https://Stackoverflow.com/users/4068",
"pm_score": 7,
"selected": true,
"text": "<p>A SQL float is a double according to <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx#Mtps_DropDownFilterText\" rel=\"noreferrer\"> the documentation for SQLDbType</a>.</p>\n"
},
{
"answer_id": 122585,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": false,
"text": "<p>A float in SQL is a <a href=\"http://msdn.microsoft.com/en-us/library/system.double.aspx\" rel=\"noreferrer\">Double</a> in the CLR (C#/VB). There's <a href=\"http://msdn.microsoft.com/en-us/library/ms131092.aspx\" rel=\"noreferrer\">a table of SQL data types with the CLR equivalents</a> on MSDN.</p>\n"
},
{
"answer_id": 122681,
"author": "pdavis",
"author_id": 7819,
"author_profile": "https://Stackoverflow.com/users/7819",
"pm_score": 2,
"selected": false,
"text": "<p>The float in Microsoft SQL Server is equivalent to a Double in C#. The reason for this is that a floating-point number can only approximate a decimal number, the <strong>precision</strong> of a floating-point number determines how accurately that number <strong>approximates</strong> a decimal number. The Double type represents a double-precision 64-bit floating-point number with values ranging from negative 1.79769313486232e308 to positive 1.79769313486232e308, as well as positive or negative zero, PositiveInfinity, NegativeInfinity, and Not-a-Number (NaN). </p>\n"
},
{
"answer_id": 122747,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 2,
"selected": false,
"text": "<p>And normally you would never want to use float in SQL Server (or real) if you plan to perform math calculations on the data as it is an inexact datatype and it will introduce calculation errors. Use a decimal datatype instead if you need precision.</p>\n"
},
{
"answer_id": 33017280,
"author": "David Bridge",
"author_id": 1194583,
"author_profile": "https://Stackoverflow.com/users/1194583",
"pm_score": 0,
"selected": false,
"text": "<p>I think the main question has been answered here but I feel compelled to add something for the section of the question that states that this works.</p>\n\n<blockquote>\n <p>_AccelLimit = (float)(double)exercise[\"DefaultAccelLimit\"];</p>\n</blockquote>\n\n<p>The reason this \"works\" and the reason it \"doesn't feel right\" is that you are downgrading the double to a float by the second cast (the one on the left) so you are losing precision and effectively telling the compiler that it is ok to truncate the value returned.</p>\n\n<p>In words this line states...\nGet an object (that happens to hold a double in this case)\nCast the object in to a double (losing all the object wrapping)\nCast the double in to a float (losing all the fine precision of a double)</p>\n\n<p>e.g. If the value is say \n0.0124022806089461\nand you do the above then the value of AccelLimit will be\n0.01240228</p>\n\n<p>as that is the extent of what a float in c# can get from the double value.\nIts a dangerous thing to do and I am pretty sure its a truncation too rather than a rounding but someone may want to confirm this as I am not sure.</p>\n"
},
{
"answer_id": 33133446,
"author": "dubrowgn",
"author_id": 4704196,
"author_profile": "https://Stackoverflow.com/users/4704196",
"pm_score": 0,
"selected": false,
"text": "<p>The reason it \"doesn't feel right\" is because C# uses the same syntax for <em>unboxing</em> and for <em>casting</em>, which are two very different things. <code>exercise[\"DefaultAccelLimit\"]</code> contains a double value, boxed as an object. <code>(double)</code> is required to <em>unbox</em> the object back into a double. The <code>(float)</code> in front of that then <em>casts</em> the double to a float value. C# does not allow boxing and casting in the same operation, so you must unbox, then cast.</p>\n\n<p>The same is true even if the cast is nondestructive. If a float was boxed as an object that you wanted to cast into a double, you would do it like so: <code>(double)(float)object_var</code>.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] |
Howdy, I have a DataRow pulled out of a DataTable from a DataSet. I am accessing a column that is defined in SQL as a float datatype. I am trying to assign that value to a local variable (c# float datatype) but am getting an InvalidCastExecption
```
DataRow exercise = _exerciseDataSet.Exercise.FindByExerciseID(65);
_AccelLimit = (float)exercise["DefaultAccelLimit"];
```
Now, playing around with this I did make it work but it did not make any sense and it didn't feel right.
```
_AccelLimit = (float)(double)exercise["DefaultAccelLimit"];
```
Can anyone explain what I am missing here?
|
A SQL float is a double according to [the documentation for SQLDbType](http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx#Mtps_DropDownFilterText).
|
122,533 |
<p>Is there any way to down-format a Subversion repository to avoid messages like this:</p>
<pre>
svn: Expected format '3' of repository; found format '5'
</pre>
<p>This happens when you access repositories from more than one machine, and you aren't able to use a consistent version of Subversion across all of those machines. </p>
<p>Worse still, there are multiple repositories with various formats on different servers, and I'm not at liberty to upgrade some of these servers.
~~~</p>
|
[
{
"answer_id": 122549,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 2,
"selected": false,
"text": "<p>I suspect you have to export the repository and re-import it into the older version. There might be some format incompatibilities in the export format though - but since it's just a big text file, it would hopefully not be too difficult to strip those out.</p>\n"
},
{
"answer_id": 122573,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 2,
"selected": false,
"text": "<p>According to the Subversion book, there's no way to do that. You will have to export the whole repository and then proceed to re-import it when you have the older version up and running. </p>\n\n<p>In any case, I suggest you upgrade your SVN tools accordingly in the client machines, instead of playing dangerous games with your repository.</p>\n\n<p>Decide upon a version and don't touch it until you're ready to upgrade to a newer version. </p>\n"
},
{
"answer_id": 122609,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 5,
"selected": true,
"text": "<p>If you can't use the same version of Subversion across all machines, then you should set up a server process (either svnserve or Apache) and access the repository only through the server. The server can mediate between different versions of Subversion; it's only when you're using direct repository access that you run into this issue.</p>\n\n<p>If the server will be an older version than the current repository format (which I don't recommend), then you'll need to export the repository using the newer version and import it using the older version.</p>\n"
},
{
"answer_id": 127497,
"author": "Sander Rijken",
"author_id": 5555,
"author_profile": "https://Stackoverflow.com/users/5555",
"pm_score": 3,
"selected": false,
"text": "<p>The svnbook says <a href=\"http://svnbook.red-bean.com/en/1.5/svn.serverconfig.choosing.html\" rel=\"nofollow noreferrer\">this</a> (about file:/// access vs setting up a server)</p>\n\n<blockquote>\n <p>Do <em>not</em> be seduced by the simple idea\n of having all of your users access a\n repository directly via file:// URLs.\n Even if the repository is readily\n available to everyone via a network\n share, this is a bad idea. It removes\n any layers of protection between the\n users and the repository: users can\n accidentally (or intentionally)\n corrupt the repository database, it\n becomes hard to take the repository\n offline for inspection or upgrade, and\n it can lead to a mess of file\n permission problems (see <a href=\"http://svnbook.red-bean.com/en/1.5/svn.serverconfig.multimethod.html\" rel=\"nofollow noreferrer\">the section\n called “Supporting Multiple Repository\n Access Methods”</a>). Note that this is\n also one of the reasons we warn\n against accessing repositories via\n svn+ssh:// URLs—from a security\n standpoint, it's effectively the same\n as local users accessing via file://,\n and it can entail all the same\n problems if the administrator isn't\n careful.</p>\n</blockquote>\n\n<p>Subversion guarantees that any 1.X client can talk to any 1.X server. By using a server you can upgrade server at a time, and clients independent of the server.</p>\n"
},
{
"answer_id": 4863023,
"author": "ccpizza",
"author_id": 191246,
"author_profile": "https://Stackoverflow.com/users/191246",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned in this thread <a href=\"https://stackoverflow.com/questions/4861677/how-to-downgrade-a-subversion-tree-from-v1-7-to-v1-6/4862561\">How to downgrade a subversion tree from v1.7 to v1.6?</a> there is python script on <a href=\"http://svn.apache.org/repos/asf/subversion/trunk/tools/client-side/change-svn-wc-format.py\" rel=\"nofollow noreferrer\">http://svn.apache.org/repos/asf/subversion/trunk/tools/client-side/change-svn-wc-format.py</a> which can downgrade the work copy but it will only work for up to version 1.6x.</p>\n"
},
{
"answer_id": 7293832,
"author": "admon_org",
"author_id": 802596,
"author_profile": "https://Stackoverflow.com/users/802596",
"pm_score": 0,
"selected": false,
"text": "<p>If you downgrade to v1.4x, here's another way that may help you:\n<a href=\"https://www.admon.org/scripts/downgrade-svn-from-1-6-to-1-4/\" rel=\"nofollow noreferrer\">https://www.admon.org/scripts/downgrade-svn-from-1-6-to-1-4/</a></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7255/"
] |
Is there any way to down-format a Subversion repository to avoid messages like this:
```
svn: Expected format '3' of repository; found format '5'
```
This happens when you access repositories from more than one machine, and you aren't able to use a consistent version of Subversion across all of those machines.
Worse still, there are multiple repositories with various formats on different servers, and I'm not at liberty to upgrade some of these servers.
~~~
|
If you can't use the same version of Subversion across all machines, then you should set up a server process (either svnserve or Apache) and access the repository only through the server. The server can mediate between different versions of Subversion; it's only when you're using direct repository access that you run into this issue.
If the server will be an older version than the current repository format (which I don't recommend), then you'll need to export the repository using the newer version and import it using the older version.
|
122,546 |
<p>We've written a plugin to the Xinha text editor to handle footnotes. You can take a look at:
<a href="http://www.nicholasbs.com/xinha/examples/Newbie.html" rel="nofollow noreferrer">http://www.nicholasbs.com/xinha/examples/Newbie.html</a></p>
<p>In order to handle some problems with the way Webkit and IE handle links at the end of lines (there's no way to use the cursor to get out of the link on the same line) we insert a blank element and move the selection to that, than collapse right. This works fine in Webkit and Gecko, but for some reason moveToElementText is spitting out an Invalid Argument exception. It doesn't matter which element we pass to it, the function seems to be completely broken. In other code paths, however, this function seems to work.</p>
<p>To reproduce the error using the link above, click in the main text input area, type anything, then click on the yellow page icon with the green plus sign, type anything into the lightbox dialog, and click on Insert. An example of the code that causes the problem is below:</p>
<pre><code> if (Xinha.is_ie)
{
var mysel = editor.getSelection();
var myrange = doc.body.createTextRange();
myrange.moveToElementText(newel);
} else
{
editor.selectNodeContents(newel, false);
}
</code></pre>
<p>The code in question lives in svn at:
<a href="https://svn.openplans.org/svn/xinha_dev/InsertNote" rel="nofollow noreferrer">https://svn.openplans.org/svn/xinha_dev/InsertNote</a></p>
<p>This plugin is built against a branch of Xinha available from svn at:
<a href="http://svn.xinha.webfactional.com/branches/new-dialogs" rel="nofollow noreferrer">http://svn.xinha.webfactional.com/branches/new-dialogs</a></p>
|
[
{
"answer_id": 122876,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": true,
"text": "<p>It's not visible in the snippet above, but newel has been appended to the dom using another element that was itself appended to the DOM. When inserting a dom element, you have to re-retrieve your handle if you wish to reference its siblings, since the handle is invalid (I'm not sure, but I think it refers to a DOM element inside of a document fragment and not the one inside of the document.) After re-retrieving the handle from the insert operation, moveToElementText stopped throwing an exception.</p>\n"
},
{
"answer_id": 125172,
"author": "kamens",
"author_id": 1335,
"author_profile": "https://Stackoverflow.com/users/1335",
"pm_score": 2,
"selected": false,
"text": "<p>I've had the unfortunate experience of debugging this IE exception many different times while implementing a WYSIWYG editor, and it always arises from accessing a property on a DOM node (such as .parentNode) or passing a DOM node to a function (such as moveToElementText) while the DOM node is not currently in the document being rendered.</p>\n\n<p>As you said, sometimes the DOM node is a piece of a document fragment that has been removed from the \"actual\" DOM being rendered by the browser, and sometimes the node has simply not been inserted yet. <strong>Either way, there are a number of properties and methods on DOM nodes that cannot be safely accessed in IE6 until the node has been properly inserted and rendered in the \"actual\" DOM.</strong></p>\n\n<p>The real kicker is that often this manifestation of IE6's \"Invalid Argument\" exception cannot be protected by try/catch.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8458/"
] |
We've written a plugin to the Xinha text editor to handle footnotes. You can take a look at:
<http://www.nicholasbs.com/xinha/examples/Newbie.html>
In order to handle some problems with the way Webkit and IE handle links at the end of lines (there's no way to use the cursor to get out of the link on the same line) we insert a blank element and move the selection to that, than collapse right. This works fine in Webkit and Gecko, but for some reason moveToElementText is spitting out an Invalid Argument exception. It doesn't matter which element we pass to it, the function seems to be completely broken. In other code paths, however, this function seems to work.
To reproduce the error using the link above, click in the main text input area, type anything, then click on the yellow page icon with the green plus sign, type anything into the lightbox dialog, and click on Insert. An example of the code that causes the problem is below:
```
if (Xinha.is_ie)
{
var mysel = editor.getSelection();
var myrange = doc.body.createTextRange();
myrange.moveToElementText(newel);
} else
{
editor.selectNodeContents(newel, false);
}
```
The code in question lives in svn at:
<https://svn.openplans.org/svn/xinha_dev/InsertNote>
This plugin is built against a branch of Xinha available from svn at:
<http://svn.xinha.webfactional.com/branches/new-dialogs>
|
It's not visible in the snippet above, but newel has been appended to the dom using another element that was itself appended to the DOM. When inserting a dom element, you have to re-retrieve your handle if you wish to reference its siblings, since the handle is invalid (I'm not sure, but I think it refers to a DOM element inside of a document fragment and not the one inside of the document.) After re-retrieving the handle from the insert operation, moveToElementText stopped throwing an exception.
|
122,571 |
<p>Right now I'm making an extremely simple website- about 5 pages. Question is if it's overkill and worth the time to integrate some sort of database mapping solution or if it would be better to just use plain old JNDI. I'll have maybe a dozen things I need to read/write from the database. I guess I have a basic understanding of these technologies but it would still take a lot of referring to the documentation. Anyone else faced with the decision before?</p>
<p>EDIT: Sorry, I should've specified JNDI to lookup the DB connection and JDBC to perform the operations.</p>
|
[
{
"answer_id": 122709,
"author": "ColinD",
"author_id": 13792,
"author_profile": "https://Stackoverflow.com/users/13792",
"pm_score": 1,
"selected": false,
"text": "<p>It does seem like it would be overkill for a very simple application, especially if you don't have plans to expand on it ever. However, it also seems like it could be worthwhile to use those with this simple application so that you have a better understanding of how they work for next time you have something that could use them.</p>\n"
},
{
"answer_id": 122731,
"author": "Hank",
"author_id": 7610,
"author_profile": "https://Stackoverflow.com/users/7610",
"pm_score": 1,
"selected": false,
"text": "<p>Do you mean plain old JDBC?\nA small project might be a good opportunity to pick up one of the ORM frameworks, especially if you have the time.</p>\n\n<p>Without more information it's hard to provide a recommendation one way or another however.</p>\n"
},
{
"answer_id": 122888,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 5,
"selected": true,
"text": "<p>Short answer: It depends on the complexity you want to support.</p>\n\n<p>Long answer:</p>\n\n<p>First of all, ORM ( object relational mapping - database mapping as you call it - ) and JNDI ( Java Naming and Directory Interfaces ) are two different things. </p>\n\n<p>The first as you already know, is used to map the Database tables to classes and objects. The second is to provide a lookup mechanism for resources, they may be DataSources, Ejb, Queues or others.</p>\n\n<p>Maybe your mean \"JDBC\".</p>\n\n<p>Now as for your question: If it is that simple may be it wouldn't be necessary to implement an ORM. The number tables would be around 5 - 10 at most, and the operations really simple, I guess. </p>\n\n<p>Probably using plain JDBC would be enough.</p>\n\n<p>If you use the DAO pattern you may change it later to support the ORM strategy if needed. </p>\n\n<p>Like this:\nSay you have the Employee table</p>\n\n<p>You create the Employee.java with all the fields of the DB by hand ( it should not take too long ) and a EmployeeDaO.java with methods like: </p>\n\n<pre><code>+findById( id ): Employee\n+insert( Employee ) \n+update( Employee )\n+delete( Employee ) \n+findAll():List<Employee>\n</code></pre>\n\n<p>And the implementation is quite straight forward: </p>\n\n<pre><code>select * from employee where id = ?\ninsert into employee ( bla, bla, bla ) values ( ? , ? , ? )\nupdate etc. etc \n</code></pre>\n\n<p>When ( and If ) your application becomes too complex you may change the DAO implementation . For instance in the \"select\" method you change the code to use the ORM object that performs the operation.</p>\n\n<pre><code>public Employee selectById( int id ) {\n // Commenting out the previous implementation...\n // String query = select * from employee where id = ? \n // execute( query ) \n\n // Using the ORM solution\n\n Session session = getSession();\n Employee e = ( Employee ) session.get( Employee.clas, id );\n return e;\n}\n</code></pre>\n\n<p>This is just an example, in real life you may let the abstact factory create the ORM DAO, but that is offtopic. The point is you may start simple and by using the desing patterns you may change the implementation later if needed. </p>\n\n<p>Of course if you want to learn the technology you may start rigth away with even 1 table.</p>\n\n<p>The choice of one or another ( ORM solution that is ) depend basically on the technology you're using. For instance for JBoss or other opensource products Hibernate is great. It is opensource, there's a lot of resources where to learn from. But if you're using something that already has Toplink ( like the oracle application server ) or if the base is already built on Toplink you should stay with that framework. </p>\n\n<p>By the way, since Oracle bought BEA, they said they're replacing Kodo ( weblogic peresistence framework ) with toplink in the now called \"Oracle Weblogic Application Server\".</p>\n\n<p>I leave you some resources where you can get more info about this:</p>\n\n<p><hr>\nIn this \"Patterns of Enterprise Application Architecture\" book, Martin Fowler, explains where to use one or another, here is the catalog. Take a look at Data Source Architectural Patterns vs. Object-Relational Behavioral Patterns:</p>\n\n<p><a href=\"http://martinfowler.com/eaaCatalog/index.html\" rel=\"noreferrer\">PEAA Catalog</a></p>\n\n<p><hr>\nDAO ( Data Access Object ) is part of the core J2EE patterns catalog:</p>\n\n<p><a href=\"http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html\" rel=\"noreferrer\">The DAO pattern</a></p>\n\n<hr>\n\n<p>This is a starter tutorial for Hibernate:</p>\n\n<p><a href=\"http://hibernate.org/152.html\" rel=\"noreferrer\">Hibernate</a></p>\n\n<hr>\n\n<p>The official page of Toplink:</p>\n\n<p><a href=\"http://www.oracle.com/technology/products/ias/toplink/index.html\" rel=\"noreferrer\">Toplink</a></p>\n\n<hr>\n\n<p>Finally I \"think\" the good think of JPA is that you may change providers lately. </p>\n\n<p>Start simple and then evolve. </p>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 124058,
"author": "Brian Deterling",
"author_id": 14619,
"author_profile": "https://Stackoverflow.com/users/14619",
"pm_score": 1,
"selected": false,
"text": "<p>My rule of thumb is if it's read-only, I'm willing to do it in JDBC, although I prefer to use an empty Hibernate project with SQLQuery to take advantage of Hibernate's type mapping. Once I have to do writes, I go with Hibernate because it's so much easier to set a few attributes and then call save than to set each column individually. And when you have to start optimizing to avoid updates on unchanged objects, you're way better off with an OR/M and its dirty checking. Dealing with foreign key relationships is another sign that you need to map it once and then use the getters. The same logic would apply to Toplink, although unless they've added something like HQL in the 3 years since I used it, Hibernate would be much better for this kind of transition from pure SQL. Keep in mind that you don't have to map every object/table, just the ones where there's a clear advantage. In my experience, most projects that don't use an existing OR/M end up building a new one, which is a bad idea.</p>\n"
},
{
"answer_id": 125054,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>The <strong>best</strong> way to learn ORM is on a small project. Start on this project.</p>\n\n<p>Once you get the hang of it, you'll use ORM for everything. </p>\n\n<p>There's nothing too small for ORM. After your first couple of projects, you'll find that you can't work any other way. The ORM mapping generally makes more sense than almost any other way of working.</p>\n"
},
{
"answer_id": 20153781,
"author": "Kalpesh Soni",
"author_id": 255139,
"author_profile": "https://Stackoverflow.com/users/255139",
"pm_score": 0,
"selected": false,
"text": "<p>Look at the various toplink guides here, they have intro, examples, scenarios etc</p>\n\n<p><a href=\"http://docs.oracle.com/cd/E14571_01/web.1111/b32441/toc.htm\" rel=\"nofollow\">http://docs.oracle.com/cd/E14571_01/web.1111/b32441/toc.htm</a></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17614/"
] |
Right now I'm making an extremely simple website- about 5 pages. Question is if it's overkill and worth the time to integrate some sort of database mapping solution or if it would be better to just use plain old JNDI. I'll have maybe a dozen things I need to read/write from the database. I guess I have a basic understanding of these technologies but it would still take a lot of referring to the documentation. Anyone else faced with the decision before?
EDIT: Sorry, I should've specified JNDI to lookup the DB connection and JDBC to perform the operations.
|
Short answer: It depends on the complexity you want to support.
Long answer:
First of all, ORM ( object relational mapping - database mapping as you call it - ) and JNDI ( Java Naming and Directory Interfaces ) are two different things.
The first as you already know, is used to map the Database tables to classes and objects. The second is to provide a lookup mechanism for resources, they may be DataSources, Ejb, Queues or others.
Maybe your mean "JDBC".
Now as for your question: If it is that simple may be it wouldn't be necessary to implement an ORM. The number tables would be around 5 - 10 at most, and the operations really simple, I guess.
Probably using plain JDBC would be enough.
If you use the DAO pattern you may change it later to support the ORM strategy if needed.
Like this:
Say you have the Employee table
You create the Employee.java with all the fields of the DB by hand ( it should not take too long ) and a EmployeeDaO.java with methods like:
```
+findById( id ): Employee
+insert( Employee )
+update( Employee )
+delete( Employee )
+findAll():List<Employee>
```
And the implementation is quite straight forward:
```
select * from employee where id = ?
insert into employee ( bla, bla, bla ) values ( ? , ? , ? )
update etc. etc
```
When ( and If ) your application becomes too complex you may change the DAO implementation . For instance in the "select" method you change the code to use the ORM object that performs the operation.
```
public Employee selectById( int id ) {
// Commenting out the previous implementation...
// String query = select * from employee where id = ?
// execute( query )
// Using the ORM solution
Session session = getSession();
Employee e = ( Employee ) session.get( Employee.clas, id );
return e;
}
```
This is just an example, in real life you may let the abstact factory create the ORM DAO, but that is offtopic. The point is you may start simple and by using the desing patterns you may change the implementation later if needed.
Of course if you want to learn the technology you may start rigth away with even 1 table.
The choice of one or another ( ORM solution that is ) depend basically on the technology you're using. For instance for JBoss or other opensource products Hibernate is great. It is opensource, there's a lot of resources where to learn from. But if you're using something that already has Toplink ( like the oracle application server ) or if the base is already built on Toplink you should stay with that framework.
By the way, since Oracle bought BEA, they said they're replacing Kodo ( weblogic peresistence framework ) with toplink in the now called "Oracle Weblogic Application Server".
I leave you some resources where you can get more info about this:
---
In this "Patterns of Enterprise Application Architecture" book, Martin Fowler, explains where to use one or another, here is the catalog. Take a look at Data Source Architectural Patterns vs. Object-Relational Behavioral Patterns:
[PEAA Catalog](http://martinfowler.com/eaaCatalog/index.html)
---
DAO ( Data Access Object ) is part of the core J2EE patterns catalog:
[The DAO pattern](http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html)
---
This is a starter tutorial for Hibernate:
[Hibernate](http://hibernate.org/152.html)
---
The official page of Toplink:
[Toplink](http://www.oracle.com/technology/products/ias/toplink/index.html)
---
Finally I "think" the good think of JPA is that you may change providers lately.
Start simple and then evolve.
I hope this helps.
|
122,582 |
<p>I'm using a lat/long SRID in my PostGIS database (-4326). I would like to find the nearest points to a given point in an efficient manner. I tried doing an</p>
<pre><code>ORDER BY ST_Distance(point, ST_GeomFromText(?,-4326))
</code></pre>
<p>which gives me ok results in the lower 48 states, but up in Alaska it gives me garbage. Is there a way to do real distance calculations in PostGIS, or am I going to have to give a reasonable sized buffer and then calculate the great circle distances and sort the results in the code afterwards?</p>
|
[
{
"answer_id": 123166,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": 2,
"selected": false,
"text": "<p>This is from SQL Server, and I use Haversine for a ridiculously fast distance that may suffer from your Alaska issue (can be off by a mile):</p>\n\n<pre><code>ALTER function [dbo].[getCoordinateDistance]\n (\n @Latitude1 decimal(16,12),\n @Longitude1 decimal(16,12),\n @Latitude2 decimal(16,12),\n @Longitude2 decimal(16,12)\n )\nreturns decimal(16,12)\nas\n/*\nfUNCTION: getCoordinateDistance\n\n Computes the Great Circle distance in kilometers\n between two points on the Earth using the\n Haversine formula distance calculation.\n\nInput Parameters:\n @Longitude1 - Longitude in degrees of point 1\n @Latitude1 - Latitude in degrees of point 1\n @Longitude2 - Longitude in degrees of point 2\n @Latitude2 - Latitude in degrees of point 2\n\n*/\nbegin\ndeclare @radius decimal(16,12)\n\ndeclare @lon1 decimal(16,12)\ndeclare @lon2 decimal(16,12)\ndeclare @lat1 decimal(16,12)\ndeclare @lat2 decimal(16,12)\n\ndeclare @a decimal(16,12)\ndeclare @distance decimal(16,12)\n\n-- Sets average radius of Earth in Kilometers\nset @radius = 6366.70701949371\n\n-- Convert degrees to radians\nset @lon1 = radians( @Longitude1 )\nset @lon2 = radians( @Longitude2 )\nset @lat1 = radians( @Latitude1 )\nset @lat2 = radians( @Latitude2 )\n\nset @a = sqrt(square(sin((@lat2-@lat1)/2.0E)) + \n (cos(@lat1) * cos(@lat2) * square(sin((@lon2-@lon1)/2.0E))) )\n\nset @distance =\n @radius * ( 2.0E *asin(case when 1.0E < @a then 1.0E else @a end ) )\n\nreturn @distance\n\nend\n</code></pre>\n\n<p>Vicenty is slow, but accurate to within 1 mm (and I only found a javascript imp of it):</p>\n\n<pre><code>/*\n * Calculate geodesic distance (in m) between two points specified by latitude/longitude (in numeric degrees)\n * using Vincenty inverse formula for ellipsoids\n */\nfunction distVincenty(lat1, lon1, lat2, lon2) {\n var a = 6378137, b = 6356752.3142, f = 1/298.257223563; // WGS-84 ellipsiod\n var L = (lon2-lon1).toRad();\n var U1 = Math.atan((1-f) * Math.tan(lat1.toRad()));\n var U2 = Math.atan((1-f) * Math.tan(lat2.toRad()));\n var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);\n var sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);\n\n var lambda = L, lambdaP = 2*Math.PI;\n var iterLimit = 20;\n while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0) {\n var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);\n var sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) + \n (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));\n if (sinSigma==0) return 0; // co-incident points\n var cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;\n var sigma = Math.atan2(sinSigma, cosSigma);\n var sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;\n var cosSqAlpha = 1 - sinAlpha*sinAlpha;\n var cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha;\n if (isNaN(cos2SigmaM)) cos2SigmaM = 0; // equatorial line: cosSqAlpha=0 (§6)\n var C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));\n lambdaP = lambda;\n lambda = L + (1-C) * f * sinAlpha *\n (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));\n }\n if (iterLimit==0) return NaN // formula failed to converge\n\n var uSq = cosSqAlpha * (a*a - b*b) / (b*b);\n var A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));\n var B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));\n var deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-\n B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));\n var s = b*A*(sigma-deltaSigma);\n\n s = s.toFixed(3); // round to 1mm precision\n return s;\n}\n</code></pre>\n"
},
{
"answer_id": 123689,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 4,
"selected": true,
"text": "<p>You are looking for ST_distance_sphere(point,point) or st_distance_spheroid(point,point).</p>\n\n<p>See:</p>\n\n<p><a href=\"http://postgis.refractions.net/documentation/manual-1.3/ch06.html#distance_sphere\" rel=\"noreferrer\">http://postgis.refractions.net/documentation/manual-1.3/ch06.html#distance_sphere</a>\n<a href=\"http://postgis.refractions.net/documentation/manual-1.3/ch06.html#distance_spheroid\" rel=\"noreferrer\">http://postgis.refractions.net/documentation/manual-1.3/ch06.html#distance_spheroid</a></p>\n\n<p>This is normally referred to a geodesic or geodetic distance... while the two terms have slightly different meanings, they tend to be used interchangably.</p>\n\n<p>Alternatively, you can project the data and use the standard st_distance function... this is only practical over short distances (using UTM or state plane) or if all distances are relative to a one or two points (equidistant projections).</p>\n"
},
{
"answer_id": 2219411,
"author": "TheSteve0",
"author_id": 266609,
"author_profile": "https://Stackoverflow.com/users/266609",
"pm_score": 2,
"selected": false,
"text": "<p>PostGIS 1.5 handles true globe distances using lat longs and meters. It is aware that lat/long is angular in nature and has a 360 degree line</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333/"
] |
I'm using a lat/long SRID in my PostGIS database (-4326). I would like to find the nearest points to a given point in an efficient manner. I tried doing an
```
ORDER BY ST_Distance(point, ST_GeomFromText(?,-4326))
```
which gives me ok results in the lower 48 states, but up in Alaska it gives me garbage. Is there a way to do real distance calculations in PostGIS, or am I going to have to give a reasonable sized buffer and then calculate the great circle distances and sort the results in the code afterwards?
|
You are looking for ST\_distance\_sphere(point,point) or st\_distance\_spheroid(point,point).
See:
<http://postgis.refractions.net/documentation/manual-1.3/ch06.html#distance_sphere>
<http://postgis.refractions.net/documentation/manual-1.3/ch06.html#distance_spheroid>
This is normally referred to a geodesic or geodetic distance... while the two terms have slightly different meanings, they tend to be used interchangably.
Alternatively, you can project the data and use the standard st\_distance function... this is only practical over short distances (using UTM or state plane) or if all distances are relative to a one or two points (equidistant projections).
|
122,589 |
<p>I have a ASP.NET application running on a remote web server and I just started getting this error. I can't seem to reproduce it in my development environment:</p>
<pre><code>Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'.
</code></pre>
<p>Could this be due to some misconfiguration of .NET Framework or IIS 6?</p>
<p>Update:
I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that implements a set of unique objects. It inherits from IEnumerable.) This line:</p>
<pre><code>Set<int> set = new Set<int>();
</code></pre>
<p>Is compiled into this line:</p>
<pre><code>Set<int> set = (Set<int>) new ICollection<CalendarModule>();
</code></pre>
<p>The Calendar class is a totally unrelated class!! Has anyone ever noticed .NET incorrectly compiling code like this before?</p>
|
[
{
"answer_id": 122604,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>Is your IIS setup to use .NET 2.0? If not, change it to 2.0. If you can't see 2.0 in the list then you'll need to run aspnet_regiis from the 2.0 framework directory.</p>\n"
},
{
"answer_id": 122605,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 1,
"selected": false,
"text": "<p>Are the .NET versions on both systems the same inc. the same service pack?</p>\n"
},
{
"answer_id": 619865,
"author": "Kevin Albrecht",
"author_id": 10475,
"author_profile": "https://Stackoverflow.com/users/10475",
"pm_score": 1,
"selected": true,
"text": "<p>This was caused by a bug in the aspnet merge tool which incorrectly merged optimized assemblies. It can be solved by either not merging the assemblies or not optimizing them.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10475/"
] |
I have a ASP.NET application running on a remote web server and I just started getting this error. I can't seem to reproduce it in my development environment:
```
Method not found: 'Void System.Collections.Generic.ICollection`1..ctor()'.
```
Could this be due to some misconfiguration of .NET Framework or IIS 6?
Update:
I disassembled the code in the DLL and it seems like the compiler is incorrectly optimizing the code. (Note that Set is a class that implements a set of unique objects. It inherits from IEnumerable.) This line:
```
Set<int> set = new Set<int>();
```
Is compiled into this line:
```
Set<int> set = (Set<int>) new ICollection<CalendarModule>();
```
The Calendar class is a totally unrelated class!! Has anyone ever noticed .NET incorrectly compiling code like this before?
|
This was caused by a bug in the aspnet merge tool which incorrectly merged optimized assemblies. It can be solved by either not merging the assemblies or not optimizing them.
|
122,607 |
<p>I need to consume an external web service from my VB6 program. I want to be able to deploy my program without the SOAP toolkit, if possible, but that's not a requirement. I do not have the web service source and I didn't create it. It is a vendor-provided service.</p>
<p>So outside of the SOAP toolkit, what is the best way to consume a web service from VB6?</p>
|
[
{
"answer_id": 122625,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 0,
"selected": false,
"text": "<p>The SOAP toolkit is arguably the best you could get. Trying to do the same thing without it would require considerable extra effort. You need to have quite serious reasons to do that.</p>\n\n<p>The format of the SOAP messages is not really easy to read or write manually and a third-party library is highly advised.</p>\n"
},
{
"answer_id": 122645,
"author": "Martin",
"author_id": 1529,
"author_profile": "https://Stackoverflow.com/users/1529",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming that you're running on Windows XP Professional or above, one interesting method is to use the SOAP moniker. Here's an example, lifted from some MSDN page. I don't know if this particular service works, but you get the idea...</p>\n\n<pre><code> set SoapObj = GetObject\n (\"soap:wsdl=http://www.xmethods.net/sd/TemperatureService.wsdl\")\n WScript.Echo \"Fairbanks Temperature = \" & SoapObj.getTemp(\"99707\")\n</code></pre>\n\n<p>This mechanism also works from VBScript. Which is nice.</p>\n"
},
{
"answer_id": 122683,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 2,
"selected": false,
"text": "<p>.NET has a good support for Web Services since day one, so you can develop your Web Service client logic in .NET as a .dll library/assembly and use it in VB6 app via COM Interop.</p>\n"
},
{
"answer_id": 123285,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 5,
"selected": true,
"text": "<p>I use this function to get data from a web service.</p>\n\n<pre><code>Private Function HttpGetRequest(url As String) As DOMDocument\n Dim req As XMLHTTP60\n Set req = New XMLHTTP60\n req.Open \"GET\", url, False\n req.send \"\"\n\n Dim resp As DOMDocument\n If req.responseText <> vbNullString Then\n Set resp = New DOMDocument60\n resp.loadXML req.responseText\n Else\n Set resp = req.responseXML\n End If\n Set HttpGetRequest = resp\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 124085,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.pocketsoap.com/\" rel=\"nofollow noreferrer\">Pocketsoap</a> works very well. To generate your objects use the <a href=\"http://www.pocketsoap.com/wsdl/\" rel=\"nofollow noreferrer\">WSDL generator</a>. Using this you don't have to parse anything yourself, plus everything is nice and strongly typed.</p>\n"
},
{
"answer_id": 227901,
"author": "Rob Windsor",
"author_id": 28785,
"author_profile": "https://Stackoverflow.com/users/28785",
"pm_score": 1,
"selected": false,
"text": "<p>Check out this article by Scott Swigart on the MSDN VB 6.0 Resource Center.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa730836.aspx\" rel=\"nofollow noreferrer\">Calling Web Services from Visual Basic 6, the Easy Way</a></p>\n"
},
{
"answer_id": 2556054,
"author": "Steve Jorgensen at Vigilan",
"author_id": 306338,
"author_profile": "https://Stackoverflow.com/users/306338",
"pm_score": 1,
"selected": false,
"text": "<p>I've had some measure of success so far using PocketSOAP to connect to the Salesforce API. I could not use the WSDL Wizard because it generates wrapper class filenames using the first 23 characters of the call names, and this results in duplicates. Nevertheless, PocketSOAP has been working well enough for me without the wizard, and it's much more straightforward than using XMLHTTP with DOMDocument.</p>\n\n<p>I also looked into making a wrapper in .NET or using one of the \"MS Office {MSO version} Web Services Toolkit\" libraries, but there were significant deployment hassles with those options. PocketSOAP is a simple COM DLL, not dependent on some particular version of MS Office, and is licensed under MPL.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7565/"
] |
I need to consume an external web service from my VB6 program. I want to be able to deploy my program without the SOAP toolkit, if possible, but that's not a requirement. I do not have the web service source and I didn't create it. It is a vendor-provided service.
So outside of the SOAP toolkit, what is the best way to consume a web service from VB6?
|
I use this function to get data from a web service.
```
Private Function HttpGetRequest(url As String) As DOMDocument
Dim req As XMLHTTP60
Set req = New XMLHTTP60
req.Open "GET", url, False
req.send ""
Dim resp As DOMDocument
If req.responseText <> vbNullString Then
Set resp = New DOMDocument60
resp.loadXML req.responseText
Else
Set resp = req.responseXML
End If
Set HttpGetRequest = resp
End Function
```
|
122,616 |
<p>Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I'd roll my own, but I would think this is a common problem with an equally common solution.</p>
|
[
{
"answer_id": 122721,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 9,
"selected": true,
"text": "<p>If you can modify the string:</p>\n\n<pre><code>// Note: This function returns a pointer to a substring of the original string.\n// If the given string was allocated dynamically, the caller must not overwrite\n// that pointer with the returned value, since the original pointer must be\n// deallocated using the same allocator with which it was allocated. The return\n// value must NOT be deallocated using free() etc.\nchar *trimwhitespace(char *str)\n{\n char *end;\n\n // Trim leading space\n while(isspace((unsigned char)*str)) str++;\n\n if(*str == 0) // All spaces?\n return str;\n\n // Trim trailing space\n end = str + strlen(str) - 1;\n while(end > str && isspace((unsigned char)*end)) end--;\n\n // Write new null terminator character\n end[1] = '\\0';\n\n return str;\n}\n</code></pre>\n\n<p>If you can't modify the string, then you can use basically the same method:</p>\n\n<pre><code>// Stores the trimmed input string into the given output buffer, which must be\n// large enough to store the result. If it is too small, the output is\n// truncated.\nsize_t trimwhitespace(char *out, size_t len, const char *str)\n{\n if(len == 0)\n return 0;\n\n const char *end;\n size_t out_size;\n\n // Trim leading space\n while(isspace((unsigned char)*str)) str++;\n\n if(*str == 0) // All spaces?\n {\n *out = 0;\n return 1;\n }\n\n // Trim trailing space\n end = str + strlen(str) - 1;\n while(end > str && isspace((unsigned char)*end)) end--;\n end++;\n\n // Set output size to minimum of trimmed string length and buffer size minus 1\n out_size = (end - str) < len-1 ? (end - str) : len-1;\n\n // Copy trimmed string and add null terminator\n memcpy(out, str, out_size);\n out[out_size] = 0;\n\n return out_size;\n}\n</code></pre>\n"
},
{
"answer_id": 122740,
"author": "Ben",
"author_id": 11522,
"author_profile": "https://Stackoverflow.com/users/11522",
"pm_score": 0,
"selected": false,
"text": "<p>Personally, I'd roll my own. You can use strtok, but you need to take care with doing so (particularly if you're removing leading characters) that you know what memory is what.</p>\n\n<p>Getting rid of trailing spaces is easy, and pretty safe, as you can just put a 0 in over the top of the last space, counting back from the end. Getting rid of leading spaces means moving things around. If you want to do it in place (probably sensible) you can just keep shifting everything back one character until there's no leading space. Or, to be more efficient, you could find the index of the first non-space character, and shift everything back by that number. Or, you could just use a pointer to the first non-space character (but then you need to be careful in the same way as you do with strtok).</p>\n"
},
{
"answer_id": 122793,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": -1,
"selected": false,
"text": "<p>Here is a function to do what you want. It should take care of degenerate cases where the string is all whitespace. You must pass in an output buffer and the length of the buffer, which means that you have to pass in a buffer that you allocate.</p>\n\n<pre><code>void str_trim(char *output, const char *text, int32 max_len)\n{\n int32 i, j, length;\n length = strlen(text);\n\n if (max_len < 0) {\n max_len = length + 1;\n }\n\n for (i=0; i<length; i++) {\n if ( (text[i] != ' ') && (text[i] != '\\t') && (text[i] != '\\n') && (text[i] != '\\r')) {\n break;\n }\n }\n\n if (i == length) {\n // handle lines that are all whitespace\n output[0] = 0;\n return;\n }\n\n for (j=length-1; j>=0; j--) {\n if ( (text[j] != ' ') && (text[j] != '\\t') && (text[j] != '\\n') && (text[j] != '\\r')) {\n break;\n }\n }\n\n length = j + 1 - i;\n strncpy(output, text + i, length);\n output[length] = 0;\n}\n</code></pre>\n\n<p>The if statements in the loops can probably be replaced with <strong>isspace(text[i])</strong> or <strong>isspace(text[j])</strong> to make the lines a little easier to read. I think that I had them set this way because there were some characters that I didn't want to test for, but it looks like I'm covering all whitespace now :-)</p>\n"
},
{
"answer_id": 122912,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure what you consider \"painless.\"</p>\n\n<p>C strings are pretty painful. We can find the first non-whitespace character position trivially:</p>\n\n<pre>\nwhile (isspace(* p)) p++;\n</pre>\n\n<p>We can find the last non-whitespace character position with two similar trivial moves:</p>\n\n<pre>\nwhile (* q) q++;\ndo { q--; } while (isspace(* q));\n</pre>\n\n<p>(I have spared you the pain of using the <code>*</code> and <code>++</code> operators at the same time.)</p>\n\n<p>The question now is what do you do with this? The datatype at hand isn't really a big robust abstract <code>String</code> that is easy to think about, but instead really barely any more than an array of storage bytes. Lacking a robust data type, it is impossible to write a function that will do the same as PHperytonby's <code>chomp</code> function. What would such a function in C return?</p>\n"
},
{
"answer_id": 122974,
"author": "indiv",
"author_id": 19719,
"author_profile": "https://Stackoverflow.com/users/19719",
"pm_score": 5,
"selected": false,
"text": "<p>Here's one that shifts the string into the first position of your buffer. You might want this behavior so that if you dynamically allocated the string, you can still free it on the same pointer that trim() returns:</p>\n\n<pre><code>char *trim(char *str)\n{\n size_t len = 0;\n char *frontp = str;\n char *endp = NULL;\n\n if( str == NULL ) { return NULL; }\n if( str[0] == '\\0' ) { return str; }\n\n len = strlen(str);\n endp = str + len;\n\n /* Move the front and back pointers to address the first non-whitespace\n * characters from each end.\n */\n while( isspace((unsigned char) *frontp) ) { ++frontp; }\n if( endp != frontp )\n {\n while( isspace((unsigned char) *(--endp)) && endp != frontp ) {}\n }\n\n if( frontp != str && endp == frontp )\n *str = '\\0';\n else if( str + len - 1 != endp )\n *(endp + 1) = '\\0';\n\n /* Shift the string so that it starts at str so that if it's dynamically\n * allocated, we can still free it on the returned pointer. Note the reuse\n * of endp to mean the front of the string buffer now.\n */\n endp = str;\n if( frontp != str )\n {\n while( *frontp ) { *endp++ = *frontp++; }\n *endp = '\\0';\n }\n\n return str;\n}\n</code></pre>\n\n<p>Test for correctness:</p>\n\n<pre><code>#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n\n/* Paste function from above here. */\n\nint main()\n{\n /* The test prints the following:\n [nothing to trim] -> [nothing to trim]\n [ trim the front] -> [trim the front]\n [trim the back ] -> [trim the back]\n [ trim front and back ] -> [trim front and back]\n [ trim one char front and back ] -> [trim one char front and back]\n [ trim one char front] -> [trim one char front]\n [trim one char back ] -> [trim one char back]\n [ ] -> []\n [ ] -> []\n [a] -> [a]\n [] -> []\n */\n\n char *sample_strings[] =\n {\n \"nothing to trim\",\n \" trim the front\",\n \"trim the back \",\n \" trim front and back \",\n \" trim one char front and back \",\n \" trim one char front\",\n \"trim one char back \",\n \" \",\n \" \",\n \"a\",\n \"\",\n NULL\n };\n char test_buffer[64];\n char comparison_buffer[64];\n size_t index, compare_pos;\n\n for( index = 0; sample_strings[index] != NULL; ++index )\n {\n // Fill buffer with known value to verify we do not write past the end of the string.\n memset( test_buffer, 0xCC, sizeof(test_buffer) );\n strcpy( test_buffer, sample_strings[index] );\n memcpy( comparison_buffer, test_buffer, sizeof(comparison_buffer));\n\n printf(\"[%s] -> [%s]\\n\", sample_strings[index],\n trim(test_buffer));\n\n for( compare_pos = strlen(comparison_buffer);\n compare_pos < sizeof(comparison_buffer);\n ++compare_pos )\n {\n if( test_buffer[compare_pos] != comparison_buffer[compare_pos] )\n {\n printf(\"Unexpected change to buffer @ index %u: %02x (expected %02x)\\n\",\n compare_pos, (unsigned char) test_buffer[compare_pos], (unsigned char) comparison_buffer[compare_pos]);\n }\n }\n }\n\n return 0;\n}\n</code></pre>\n\n<p>Source file was trim.c. Compiled with 'cc -Wall trim.c -o trim'.</p>\n"
},
{
"answer_id": 122986,
"author": "sfink",
"author_id": 14528,
"author_profile": "https://Stackoverflow.com/users/14528",
"pm_score": 0,
"selected": false,
"text": "<p>I'm only including code because the code posted so far seems suboptimal (and I don't have the rep to comment yet.)</p>\n\n<pre><code>void inplace_trim(char* s)\n{\n int start, end = strlen(s);\n for (start = 0; isspace(s[start]); ++start) {}\n if (s[start]) {\n while (end > 0 && isspace(s[end-1]))\n --end;\n memmove(s, &s[start], end - start);\n }\n s[end - start] = '\\0';\n}\n\nchar* copy_trim(const char* s)\n{\n int start, end;\n for (start = 0; isspace(s[start]); ++start) {}\n for (end = strlen(s); end > 0 && isspace(s[end-1]); --end) {}\n return strndup(s + start, end - start);\n}\n</code></pre>\n\n<p><code>strndup()</code> is a GNU extension. If you don't have it or something equivalent, roll your own. For example:</p>\n\n<pre><code>r = strdup(s + start);\nr[end-start] = '\\0';\n</code></pre>\n"
},
{
"answer_id": 123724,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 5,
"selected": false,
"text": "<p>My solution. String must be changeable. The advantage above some of the other solutions that it moves the non-space part to the beginning so you can keep using the old pointer, in case you have to free() it later.</p>\n\n<pre><code>void trim(char * s) {\n char * p = s;\n int l = strlen(p);\n\n while(isspace(p[l - 1])) p[--l] = 0;\n while(* p && isspace(* p)) ++p, --l;\n\n memmove(s, p, l + 1);\n} \n</code></pre>\n\n<p>This version creates a copy of the string with strndup() instead of editing it in place. strndup() requires _GNU_SOURCE, so maybe you need to make your own strndup() with malloc() and strncpy().</p>\n\n<pre><code>char * trim(char * s) {\n int l = strlen(s);\n\n while(isspace(s[l - 1])) --l;\n while(* s && isspace(* s)) ++s, --l;\n\n return strndup(s, l);\n}\n</code></pre>\n"
},
{
"answer_id": 125378,
"author": "James Antill",
"author_id": 10314,
"author_profile": "https://Stackoverflow.com/users/10314",
"pm_score": 2,
"selected": false,
"text": "<p>Use a <a href=\"http://www.and.org/vstr/comparison\" rel=\"nofollow noreferrer\">string library</a>, for instance:</p>\n\n<pre><code>Ustr *s1 = USTR1(\\7, \" 12345 \");\n\nustr_sc_trim_cstr(&s1, \" \");\nassert(ustr_cmp_cstr_eq(s1, \"12345\"));</code></pre>\n\n<p>...as you say this is a \"common\" problem, yes you need to include a #include or so and it's not included in libc but don't go inventing your own hack job storing random pointers and size_t's that way only leads to buffer overflows.</p>\n"
},
{
"answer_id": 1845096,
"author": "Balkrishna Talele",
"author_id": 175374,
"author_profile": "https://Stackoverflow.com/users/175374",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include \"stdafx.h\"\n#include \"malloc.h\"\n#include \"string.h\"\n\nint main(int argc, char* argv[])\n{\n\n char *ptr = (char*)malloc(sizeof(char)*30);\n strcpy(ptr,\" Hel lo wo rl d G eo rocks!!! by shahil sucks b i g tim e\");\n\n int i = 0, j = 0;\n\n while(ptr[j]!='\\0')\n {\n\n if(ptr[j] == ' ' )\n {\n j++;\n ptr[i] = ptr[j];\n }\n else\n {\n i++;\n j++;\n ptr[i] = ptr[j];\n }\n }\n\n\n printf(\"\\noutput-%s\\n\",ptr);\n return 0;\n}</code></pre>\n"
},
{
"answer_id": 2452438,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "<p>A bit late to the game, but I'll throw my routines into the fray. They're probably not the most absolute efficient, but I believe they're correct and they're simple (with <code>rtrim()</code> pushing the complexity envelope):</p>\n\n<pre><code>#include <ctype.h>\n#include <string.h>\n\n/*\n Public domain implementations of in-place string trim functions\n\n Michael Burr\n michael.burr@nth-element.com\n 2010\n*/\n\nchar* ltrim(char* s) \n{\n char* newstart = s;\n\n while (isspace( *newstart)) {\n ++newstart;\n }\n\n // newstart points to first non-whitespace char (which might be '\\0')\n memmove( s, newstart, strlen( newstart) + 1); // don't forget to move the '\\0' terminator\n\n return s;\n}\n\n\nchar* rtrim( char* s)\n{\n char* end = s + strlen( s);\n\n // find the last non-whitespace character\n while ((end != s) && isspace( *(end-1))) {\n --end;\n }\n\n // at this point either (end == s) and s is either empty or all whitespace\n // so it needs to be made empty, or\n // end points just past the last non-whitespace character (it might point\n // at the '\\0' terminator, in which case there's no problem writing\n // another there). \n *end = '\\0';\n\n return s;\n}\n\nchar* trim( char* s)\n{\n return rtrim( ltrim( s));\n}\n</code></pre>\n"
},
{
"answer_id": 3042515,
"author": "Shoots the Moon",
"author_id": 366892,
"author_profile": "https://Stackoverflow.com/users/366892",
"pm_score": 4,
"selected": false,
"text": "<p>Here's my C mini library for trimming left, right, both, all, in place and separate, and trimming a set of specified characters (or white space by default).</p>\n\n<h2><strong>contents of strlib.h:</strong></h2>\n\n<pre><code>#ifndef STRLIB_H_\n#define STRLIB_H_ 1\nenum strtrim_mode_t {\n STRLIB_MODE_ALL = 0, \n STRLIB_MODE_RIGHT = 0x01, \n STRLIB_MODE_LEFT = 0x02, \n STRLIB_MODE_BOTH = 0x03\n};\n\nchar *strcpytrim(char *d, // destination\n char *s, // source\n int mode,\n char *delim\n );\n\nchar *strtriml(char *d, char *s);\nchar *strtrimr(char *d, char *s);\nchar *strtrim(char *d, char *s); \nchar *strkill(char *d, char *s);\n\nchar *triml(char *s);\nchar *trimr(char *s);\nchar *trim(char *s);\nchar *kill(char *s);\n#endif\n</code></pre>\n\n<h2>contents of strlib.c:</h2>\n\n<pre><code>#include <strlib.h>\n\nchar *strcpytrim(char *d, // destination\n char *s, // source\n int mode,\n char *delim\n ) {\n char *o = d; // save orig\n char *e = 0; // end space ptr.\n char dtab[256] = {0};\n if (!s || !d) return 0;\n\n if (!delim) delim = \" \\t\\n\\f\";\n while (*delim) \n dtab[*delim++] = 1;\n\n while ( (*d = *s++) != 0 ) { \n if (!dtab[0xFF & (unsigned int)*d]) { // Not a match char\n e = 0; // Reset end pointer\n } else {\n if (!e) e = d; // Found first match.\n\n if ( mode == STRLIB_MODE_ALL || ((mode != STRLIB_MODE_RIGHT) && (d == o)) ) \n continue;\n }\n d++;\n }\n if (mode != STRLIB_MODE_LEFT && e) { // for everything but trim_left, delete trailing matches.\n *e = 0;\n }\n return o;\n}\n\n// perhaps these could be inlined in strlib.h\nchar *strtriml(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_LEFT, 0); }\nchar *strtrimr(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_RIGHT, 0); }\nchar *strtrim(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_BOTH, 0); }\nchar *strkill(char *d, char *s) { return strcpytrim(d, s, STRLIB_MODE_ALL, 0); }\n\nchar *triml(char *s) { return strcpytrim(s, s, STRLIB_MODE_LEFT, 0); }\nchar *trimr(char *s) { return strcpytrim(s, s, STRLIB_MODE_RIGHT, 0); }\nchar *trim(char *s) { return strcpytrim(s, s, STRLIB_MODE_BOTH, 0); }\nchar *kill(char *s) { return strcpytrim(s, s, STRLIB_MODE_ALL, 0); }\n</code></pre>\n\n<p>The one main routine does it all. \nIt trims in place if <em>src</em> == <em>dst</em>, otherwise,\nit works like the <code>strcpy</code> routines.\nIt trims a set of characters specified in the string <em>delim</em>, or white space if null.\nIt trims left, right, both, and all (like tr).\nThere is not much to it, and it iterates over the string only once. Some folks might complain that trim right starts on the left, however, no strlen is needed which starts on the left anyway. (One way or another you have to get to the end of the string for right trims, so you might as well do the work as you go.) There may be arguments to be made about pipelining and cache sizes and such -- who knows. Since the solution works from left to right and iterates only once, it can be expanded to work on streams as well. Limitations: it does <strong>not</strong> work on <strong>unicode</strong> strings.</p>\n"
},
{
"answer_id": 3975465,
"author": "Swiss",
"author_id": 84955,
"author_profile": "https://Stackoverflow.com/users/84955",
"pm_score": 3,
"selected": false,
"text": "<p>Here is my attempt at a simple, yet correct in-place trim function.</p>\n\n<pre><code>void trim(char *str)\n{\n int i;\n int begin = 0;\n int end = strlen(str) - 1;\n\n while (isspace((unsigned char) str[begin]))\n begin++;\n\n while ((end >= begin) && isspace((unsigned char) str[end]))\n end--;\n\n // Shift all characters back to the start of the string array.\n for (i = begin; i <= end; i++)\n str[i - begin] = str[i];\n\n str[i - begin] = '\\0'; // Null terminate string.\n}\n</code></pre>\n"
},
{
"answer_id": 4505533,
"author": "Rhys Ulerich",
"author_id": 103640,
"author_profile": "https://Stackoverflow.com/users/103640",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a solution similar to @adam-rosenfields in-place modification routine but without needlessly resorting to strlen(). Like @jkramer, the string is left-adjusted within the buffer so you can free the same pointer. Not optimal for large strings since it does not use memmove. Includes the ++/-- operators that @jfm3 mentions. <a href=\"http://fctx.wildbearsoftware.com\" rel=\"nofollow\">FCTX</a>-based unit tests included.</p>\n\n<pre><code>#include <ctype.h>\n\nvoid trim(char * const a)\n{\n char *p = a, *q = a;\n while (isspace(*q)) ++q;\n while (*q) *p++ = *q++;\n *p = '\\0';\n while (p > a && isspace(*--p)) *p = '\\0';\n}\n\n/* See http://fctx.wildbearsoftware.com/ */\n#include \"fct.h\"\n\nFCT_BGN()\n{\n FCT_QTEST_BGN(trim)\n {\n { char s[] = \"\"; trim(s); fct_chk_eq_str(\"\", s); } // Trivial\n { char s[] = \" \"; trim(s); fct_chk_eq_str(\"\", s); } // Trivial\n { char s[] = \"\\t\"; trim(s); fct_chk_eq_str(\"\", s); } // Trivial\n { char s[] = \"a\"; trim(s); fct_chk_eq_str(\"a\", s); } // NOP\n { char s[] = \"abc\"; trim(s); fct_chk_eq_str(\"abc\", s); } // NOP\n { char s[] = \" a\"; trim(s); fct_chk_eq_str(\"a\", s); } // Leading\n { char s[] = \" a c\"; trim(s); fct_chk_eq_str(\"a c\", s); } // Leading\n { char s[] = \"a \"; trim(s); fct_chk_eq_str(\"a\", s); } // Trailing\n { char s[] = \"a c \"; trim(s); fct_chk_eq_str(\"a c\", s); } // Trailing\n { char s[] = \" a \"; trim(s); fct_chk_eq_str(\"a\", s); } // Both\n { char s[] = \" a c \"; trim(s); fct_chk_eq_str(\"a c\", s); } // Both\n\n // Villemoes pointed out an edge case that corrupted memory. Thank you.\n // http://stackoverflow.com/questions/122616/#comment23332594_4505533\n {\n char s[] = \"a \"; // Buffer with whitespace before s + 2\n trim(s + 2); // Trim \" \" containing only whitespace\n fct_chk_eq_str(\"\", s + 2); // Ensure correct result from the trim\n fct_chk_eq_str(\"a \", s); // Ensure preceding buffer not mutated\n }\n\n // doukremt suggested I investigate this test case but\n // did not indicate the specific behavior that was objectionable.\n // http://stackoverflow.com/posts/comments/33571430\n {\n char s[] = \" foobar\"; // Shifted across whitespace\n trim(s); // Trim\n fct_chk_eq_str(\"foobar\", s); // Leading string is correct\n\n // Here is what the algorithm produces:\n char r[16] = { 'f', 'o', 'o', 'b', 'a', 'r', '\\0', ' ', \n ' ', 'f', 'o', 'o', 'b', 'a', 'r', '\\0'};\n fct_chk_eq_int(0, memcmp(s, r, sizeof(s)));\n }\n }\n FCT_QTEST_END();\n}\nFCT_END();\n</code></pre>\n"
},
{
"answer_id": 5916192,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 0,
"selected": false,
"text": "<p>Most of the answers so far do one of the following:</p>\n\n<ol>\n<li>Backtrack at the end of the string (i.e. find the end of the string and then seek backwards until a non-space character is found,) or</li>\n<li>Call <code>strlen()</code> first, making a second pass through the whole string.</li>\n</ol>\n\n<p>This version makes only one pass and does not backtrack. Hence it may perform better than the others, though only if it is common to have hundreds of trailing spaces (which is not unusual when dealing with the output of a SQL query.) </p>\n\n<pre><code>static char const WHITESPACE[] = \" \\t\\n\\r\";\n\nstatic void get_trim_bounds(char const *s,\n char const **firstWord,\n char const **trailingSpace)\n{\n char const *lastWord;\n *firstWord = lastWord = s + strspn(s, WHITESPACE);\n do\n {\n *trailingSpace = lastWord + strcspn(lastWord, WHITESPACE);\n lastWord = *trailingSpace + strspn(*trailingSpace, WHITESPACE);\n }\n while (*lastWord != '\\0');\n}\n\nchar *copy_trim(char const *s)\n{\n char const *firstWord, *trailingSpace;\n char *result;\n size_t newLength;\n\n get_trim_bounds(s, &firstWord, &trailingSpace);\n newLength = trailingSpace - firstWord;\n\n result = malloc(newLength + 1);\n memcpy(result, firstWord, newLength);\n result[newLength] = '\\0';\n return result;\n}\n\nvoid inplace_trim(char *s)\n{\n char const *firstWord, *trailingSpace;\n size_t newLength;\n\n get_trim_bounds(s, &firstWord, &trailingSpace);\n newLength = trailingSpace - firstWord;\n\n memmove(s, firstWord, newLength);\n s[newLength] = '\\0';\n}\n</code></pre>\n"
},
{
"answer_id": 11539150,
"author": "stars",
"author_id": 1534429,
"author_profile": "https://Stackoverflow.com/users/1534429",
"pm_score": -1,
"selected": false,
"text": "<pre><code>#include<stdio.h>\n#include<ctype.h>\n\nmain()\n{\n char sent[10]={' ',' ',' ','s','t','a','r','s',' ',' '};\n int i,j=0;\n char rec[10];\n\n for(i=0;i<=10;i++)\n {\n if(!isspace(sent[i]))\n {\n\n rec[j]=sent[i];\n j++;\n }\n }\n\nprintf(\"\\n%s\\n\",rec);\n\n}\n</code></pre>\n"
},
{
"answer_id": 14978802,
"author": "Michał Gawlas",
"author_id": 1678108,
"author_profile": "https://Stackoverflow.com/users/1678108",
"pm_score": 0,
"selected": false,
"text": "<p>This is the shortest possible implementation I can think of:</p>\n\n<pre><code>static const char *WhiteSpace=\" \\n\\r\\t\";\nchar* trim(char *t)\n{\n char *e=t+(t!=NULL?strlen(t):0); // *e initially points to end of string\n if (t==NULL) return;\n do --e; while (strchr(WhiteSpace, *e) && e>=t); // Find last char that is not \\r\\n\\t\n *(++e)=0; // Null-terminate\n e=t+strspn (t,WhiteSpace); // Find first char that is not \\t\n return e>t?memmove(t,e,strlen(e)+1):t; // memmove string contents and terminator\n}\n</code></pre>\n"
},
{
"answer_id": 16693536,
"author": "Telc",
"author_id": 869113,
"author_profile": "https://Stackoverflow.com/users/869113",
"pm_score": 0,
"selected": false,
"text": "<p>These functions will modify the original buffer, so if dynamically allocated, the original\npointer can be freed.</p>\n\n<pre><code>#include <string.h>\n\nvoid rstrip(char *string)\n{\n int l;\n if (!string)\n return;\n l = strlen(string) - 1;\n while (isspace(string[l]) && l >= 0)\n string[l--] = 0;\n}\n\nvoid lstrip(char *string)\n{\n int i, l;\n if (!string)\n return;\n l = strlen(string);\n while (isspace(string[(i = 0)]))\n while(i++ < l)\n string[i-1] = string[i];\n}\n\nvoid strip(char *string)\n{\n lstrip(string);\n rstrip(string);\n}\n</code></pre>\n"
},
{
"answer_id": 19441143,
"author": "Carthi",
"author_id": 1992435,
"author_profile": "https://Stackoverflow.com/users/1992435",
"pm_score": 0,
"selected": false,
"text": "<p>What do you think about using StrTrim function defined in header Shlwapi.h.? It is straight forward rather defining on your own. <br/>\nDetails can be found on: <br/>\n <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/bb773454(v=vs.85).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/windows/desktop/bb773454(v=vs.85).aspx</a> </p>\n\n<p>If you have<br>\n<code>char ausCaptain[]=\"GeorgeBailey \";</code><br>\n<code>StrTrim(ausCaptain,\" \");</code><br>\nThis will give <code>ausCaptain</code> as <code>\"GeorgeBailey\"</code> not <code>\"GeorgeBailey \"</code>.</p>\n"
},
{
"answer_id": 24168813,
"author": "Daniel",
"author_id": 1531346,
"author_profile": "https://Stackoverflow.com/users/1531346",
"pm_score": 2,
"selected": false,
"text": "<p>Another one, with one line doing the real job:</p>\n\n<pre><code>#include <stdio.h>\n\nint main()\n{\n const char *target = \" haha \";\n char buf[256];\n sscanf(target, \"%s\", buf); // Trimming on both sides occurs here\n printf(\"<%s>\\n\", buf);\n}\n</code></pre>\n"
},
{
"answer_id": 26063378,
"author": "Oleksiy",
"author_id": 1214101,
"author_profile": "https://Stackoverflow.com/users/1214101",
"pm_score": -1,
"selected": false,
"text": "<p>Here is what I disclosed regarding the question in Linux kernel code:</p>\n\n<pre><code>/**\n * skip_spaces - Removes leading whitespace from @s.\n * @s: The string to be stripped.\n *\n * Returns a pointer to the first non-whitespace character in @s.\n */\nchar *skip_spaces(const char *str)\n{\n while (isspace(*str))\n ++str;\n return (char *)str;\n}\n\n/**\n * strim - Removes leading and trailing whitespace from @s.\n * @s: The string to be stripped.\n *\n * Note that the first trailing whitespace is replaced with a %NUL-terminator\n * in the given string @s. Returns a pointer to the first non-whitespace\n * character in @s.\n */\nchar *strim(char *s)\n{\n size_t size;\n char *end;\n\n size = strlen(s);\n\n if (!size)\n return s;\n\n end = s + size - 1;\n while (end >= s && isspace(*end))\n end--;\n *(end + 1) = '\\0';\n\n return skip_spaces(s);\n}\n</code></pre>\n\n<p>It is supposed to be bug free due to the origin ;-)</p>\n\n<p>Mine one piece is closer to KISS principle I guess:</p>\n\n<pre><code>/**\n * trim spaces\n **/\nchar * trim_inplace(char * s, int len)\n{\n // trim leading\n while (len && isspace(s[0]))\n {\n s++; len--;\n }\n\n // trim trailing\n while (len && isspace(s[len - 1]))\n {\n s[len - 1] = 0; len--;\n }\n\n return s;\n}\n</code></pre>\n"
},
{
"answer_id": 26984026,
"author": "chux - Reinstate Monica",
"author_id": 2410359,
"author_profile": "https://Stackoverflow.com/users/2410359",
"pm_score": 3,
"selected": false,
"text": "<p>Late to the trim party</p>\n\n<p>Features:<br>\n 1. Trim the beginning quickly, as in a number of other answers.<br>\n 2. After going to the end, trimming the right with only 1 test per loop. Like @jfm3, but works for an all white-space string)<br>\n 3. To avoid undefined behavior when <code>char</code> is a signed <code>char</code>, cast <code>*s</code> to <code>unsigned char</code>. </p>\n\n<blockquote>\n <p><strong>Character handling </strong> \"In all cases the argument is an <code>int</code>, the value of which shall be representable as an <code>unsigned char</code> or shall equal the value of the macro <code>EOF</code>. If the argument has any other value, the behavior is undefined.\" C11 §7.4 1</p>\n</blockquote>\n\n<pre><code>#include <ctype.h>\n\n// Return a pointer to the trimmed string\nchar *string_trim_inplace(char *s) {\n while (isspace((unsigned char) *s)) s++;\n if (*s) {\n char *p = s;\n while (*p) p++;\n while (isspace((unsigned char) *(--p)));\n p[1] = '\\0';\n }\n\n // If desired, shift the trimmed string\n\n return s;\n}\n</code></pre>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/users/4593267/chqrlie\">@chqrlie</a> commented the above does not shift the trimmed string. To do so....</p>\n\n<pre><code>// Return a pointer to the (shifted) trimmed string\nchar *string_trim_inplace(char *s) {\n char *original = s;\n size_t len = 0;\n\n while (isspace((unsigned char) *s)) {\n s++;\n } \n if (*s) {\n char *p = s;\n while (*p) p++;\n while (isspace((unsigned char) *(--p)));\n p[1] = '\\0';\n // len = (size_t) (p - s); // older errant code\n len = (size_t) (p - s + 1); // Thanks to @theriver\n }\n\n return (s == original) ? s : memmove(original, s, len + 1);\n}\n</code></pre>\n"
},
{
"answer_id": 33599020,
"author": "wallek876",
"author_id": 4394382,
"author_profile": "https://Stackoverflow.com/users/4394382",
"pm_score": 1,
"selected": false,
"text": "<p>Just to keep this growing, one more option with a modifiable string:</p>\n\n<pre><code>void trimString(char *string)\n{\n size_t i = 0, j = strlen(string);\n while (j > 0 && isspace((unsigned char)string[j - 1])) string[--j] = '\\0';\n while (isspace((unsigned char)string[i])) i++;\n if (i > 0) memmove(string, string + i, j - i + 1);\n}\n</code></pre>\n"
},
{
"answer_id": 33757317,
"author": "Jason Stewart",
"author_id": 3277205,
"author_profile": "https://Stackoverflow.com/users/3277205",
"pm_score": 2,
"selected": false,
"text": "<p>I didn't like most of these answers because they did one or more of the following...</p>\n\n<ol>\n<li>Returned a different pointer inside the original pointer's string (kind of a pain to juggle two different pointers to the same thing).</li>\n<li>Made gratuitous use of things like <strong>strlen()</strong> that pre-iterate the entire string.</li>\n<li>Used non-portable OS-specific lib functions.</li>\n<li>Backscanned.</li>\n<li>Used comparison to <strong>' '</strong> instead of <strong>isspace()</strong> so that TAB / CR / LF are preserved.</li>\n<li>Wasted memory with large static buffers.</li>\n<li>Wasted cycles with high-cost functions like <strong>sscanf/sprintf</strong>.</li>\n</ol>\n\n<p>Here is my version:</p>\n\n<pre><code>void fnStrTrimInPlace(char *szWrite) {\n\n const char *szWriteOrig = szWrite;\n char *szLastSpace = szWrite, *szRead = szWrite;\n int bNotSpace;\n\n // SHIFT STRING, STARTING AT FIRST NON-SPACE CHAR, LEFTMOST\n while( *szRead != '\\0' ) {\n\n bNotSpace = !isspace((unsigned char)(*szRead));\n\n if( (szWrite != szWriteOrig) || bNotSpace ) {\n\n *szWrite = *szRead;\n szWrite++;\n\n // TRACK POINTER TO LAST NON-SPACE\n if( bNotSpace )\n szLastSpace = szWrite;\n }\n\n szRead++;\n }\n\n // TERMINATE AFTER LAST NON-SPACE (OR BEGINNING IF THERE WAS NO NON-SPACE)\n *szLastSpace = '\\0';\n}\n</code></pre>\n"
},
{
"answer_id": 34766453,
"author": "Marek R",
"author_id": 1387438,
"author_profile": "https://Stackoverflow.com/users/1387438",
"pm_score": -1,
"selected": false,
"text": "<p>C++ STL style</p>\n\n<pre><code>std::string Trimed(const std::string& s)\n{\n std::string::const_iterator begin = std::find_if(s.begin(),\n s.end(),\n [](char ch) { return !std::isspace(ch); });\n\n std::string::const_iterator end = std::find_if(s.rbegin(),\n s.rend(),\n [](char ch) { return !std::isspace(ch); }).base();\n return std::string(begin, end);\n}\n</code></pre>\n\n<p><a href=\"http://ideone.com/VwJaq9\" rel=\"nofollow\">http://ideone.com/VwJaq9</a></p>\n"
},
{
"answer_id": 35305045,
"author": "Mitch",
"author_id": 329999,
"author_profile": "https://Stackoverflow.com/users/329999",
"pm_score": -1,
"selected": false,
"text": "<pre><code>void trim(char* const str)\n{\n char* begin = str;\n char* end = str;\n while (isspace(*begin))\n {\n ++begin;\n }\n char* s = begin;\n while (*s != '\\0')\n {\n if (!isspace(*s++))\n {\n end = s;\n }\n }\n *end = '\\0';\n const int dist = end - begin;\n if (begin > str && dist > 0)\n {\n memmove(str, begin, dist + 1);\n }\n}\n</code></pre>\n\n<p>Modifies string in place, so you can still delete it. </p>\n\n<p>Doesn't use fancy pants library functions (unless you consider memmove fancy).</p>\n\n<p>Handles string overlap.</p>\n\n<p>Trims front and back (not middle, sorry).</p>\n\n<p>Fast if string is large (memmove often written in assembly).</p>\n\n<p>Only moves characters if required (I find this true in most use cases because strings rarely have leading spaces and often don't have tailing spaces)</p>\n\n<p>I would like to test this but I'm running late. Enjoy finding bugs... :-)</p>\n"
},
{
"answer_id": 35574577,
"author": "Деян Добромиров",
"author_id": 4170264,
"author_profile": "https://Stackoverflow.com/users/4170264",
"pm_score": 0,
"selected": false,
"text": "<p>To trim my strings from the both sides I use the oldie but the gooody ;)\nIt can trim anything with ascii less than a space, meaning that the control chars will be trimmed also !</p>\n\n<pre><code>char *trimAll(char *strData)\n{\n unsigned int L = strlen(strData);\n if(L > 0){ L--; }else{ return strData; }\n size_t S = 0, E = L;\n while((!(strData[S] > ' ') || !(strData[E] > ' ')) && (S >= 0) && (S <= L) && (E >= 0) && (E <= L))\n {\n if(strData[S] <= ' '){ S++; }\n if(strData[E] <= ' '){ E--; }\n }\n if(S == 0 && E == L){ return strData; } // Nothing to be done\n if((S >= 0) && (S <= L) && (E >= 0) && (E <= L)){\n L = E - S + 1;\n memmove(strData,&strData[S],L); strData[L] = '\\0';\n }else{ strData[0] = '\\0'; }\n return strData;\n}\n</code></pre>\n"
},
{
"answer_id": 35899634,
"author": "Vaner Magalhaes",
"author_id": 5731423,
"author_profile": "https://Stackoverflow.com/users/5731423",
"pm_score": -1,
"selected": false,
"text": "<pre><code>void trim(char* string) {\n int lenght = strlen(string);\n int i=0;\n\n while(string[0] ==' ') {\n for(i=0; i<lenght; i++) {\n string[i] = string[i+1];\n }\n lenght--;\n }\n\n\n for(i=lenght-1; i>0; i--) {\n if(string[i] == ' ') {\n string[i] = '\\0';\n } else {\n break;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 39931573,
"author": "sleepycal",
"author_id": 1267398,
"author_profile": "https://Stackoverflow.com/users/1267398",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using <code>glib</code>, then you can use <a href=\"https://developer.gnome.org/glib/stable/glib-String-Utility-Functions.html#g-strstrip\" rel=\"nofollow\">g_strstrip</a></p>\n"
},
{
"answer_id": 45582189,
"author": "Ekeyme Mo",
"author_id": 4988506,
"author_profile": "https://Stackoverflow.com/users/4988506",
"pm_score": 1,
"selected": false,
"text": "<p>I know there have many answers, but I post my answer here to see if my solution is good enough. </p>\n\n<pre><code>// Trims leading whitespace chars in left `str`, then copy at almost `n - 1` chars\n// into the `out` buffer in which copying might stop when the first '\\0' occurs, \n// and finally append '\\0' to the position of the last non-trailing whitespace char.\n// Reture the length the trimed string which '\\0' is not count in like strlen().\nsize_t trim(char *out, size_t n, const char *str)\n{\n // do nothing\n if(n == 0) return 0; \n\n // ptr stop at the first non-leading space char\n while(isspace(*str)) str++; \n\n if(*str == '\\0') {\n out[0] = '\\0';\n return 0;\n } \n\n size_t i = 0; \n\n // copy char to out until '\\0' or i == n - 1\n for(i = 0; i < n - 1 && *str != '\\0'; i++){\n out[i] = *str++;\n } \n\n // deal with the trailing space\n while(isspace(out[--i])); \n\n out[++i] = '\\0';\n return i;\n}\n</code></pre>\n"
},
{
"answer_id": 48563040,
"author": "saeed_falahat",
"author_id": 5958242,
"author_profile": "https://Stackoverflow.com/users/5958242",
"pm_score": 0,
"selected": false,
"text": "<p>Here i use the dynamic memory allocation to trim the input string to the function trimStr. First, we find how many non-empty characters exist in the input string. Then, we allocate a character array with that size and taking care of the null terminated character. When we use this function, we need to free the memory inside of main function. </p>\n\n<pre><code>#include<stdio.h>\n#include<stdlib.h>\n\nchar *trimStr(char *str){\nchar *tmp = str;\nprintf(\"input string %s\\n\",str);\nint nc = 0;\n\nwhile(*tmp!='\\0'){\n if (*tmp != ' '){\n nc++;\n }\n tmp++;\n}\nprintf(\"total nonempty characters are %d\\n\",nc);\nchar *trim = NULL;\n\ntrim = malloc(sizeof(char)*(nc+1));\nif (trim == NULL) return NULL;\ntmp = str;\nint ne = 0;\n\nwhile(*tmp!='\\0'){\n if (*tmp != ' '){\n trim[ne] = *tmp;\n ne++;\n }\n tmp++;\n}\ntrim[nc] = '\\0';\n\nprintf(\"trimmed string is %s\\n\",trim);\n\nreturn trim; \n }\n\n\nint main(void){\n\nchar str[] = \" s ta ck ove r fl o w \";\n\nchar *trim = trimStr(str);\n\nif (trim != NULL )free(trim);\n\nreturn 0;\n}\n</code></pre>\n"
},
{
"answer_id": 50087045,
"author": "Zibri",
"author_id": 236062,
"author_profile": "https://Stackoverflow.com/users/236062",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest way to skip leading spaces in a string is, imho,</p>\n\n<pre><code>#include <stdio.h>\n\nint main()\n{\nchar *foo=\" teststring \";\nchar *bar;\nsscanf(foo,\"%s\",bar);\nprintf(\"String is >%s<\\n\",bar);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 50881315,
"author": "Isaac To",
"author_id": 4635580,
"author_profile": "https://Stackoverflow.com/users/4635580",
"pm_score": 0,
"selected": false,
"text": "<p>Here is how I do it. It trims the string in place, so no worry about deallocating a returned string or losing the pointer to an allocated string. It may not be the shortest answer possible, but it should be clear to most readers.</p>\n\n<pre><code>#include <ctype.h>\n#include <string.h>\nvoid trim_str(char *s)\n{\n const size_t s_len = strlen(s);\n\n int i;\n for (i = 0; i < s_len; i++)\n {\n if (!isspace( (unsigned char) s[i] )) break;\n }\n\n if (i == s_len)\n {\n // s is an empty string or contains only space characters\n\n s[0] = '\\0';\n }\n else\n {\n // s contains non-space characters\n\n const char *non_space_beginning = s + i;\n\n char *non_space_ending = s + s_len - 1;\n while ( isspace( (unsigned char) *non_space_ending ) ) non_space_ending--;\n\n size_t trimmed_s_len = non_space_ending - non_space_beginning + 1;\n\n if (s != non_space_beginning)\n {\n // Non-space characters exist in the beginning of s\n\n memmove(s, non_space_beginning, trimmed_s_len);\n }\n\n s[trimmed_s_len] = '\\0';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 51215136,
"author": "David R Tribble",
"author_id": 170383,
"author_profile": "https://Stackoverflow.com/users/170383",
"pm_score": 2,
"selected": false,
"text": "<p><em>Very late to the party...</em></p>\n\n<p>Single-pass forward-scanning solution with no backtracking. Every character in the source string is tested exactly <s>once</s> twice. (So it should be faster than most of the other solutions here, especially if the source string has a lot of trailing spaces.)</p>\n\n<p>This includes two solutions, one to copy and trim a source string into another destination string, and the other to trim the source string in place. Both functions use the same code.</p>\n\n<p>The (modifiable) string is moved in-place, so the original pointer to it remains unchanged.</p>\n\n<pre><code>#include <stddef.h>\n#include <ctype.h>\n\nchar * trim2(char *d, const char *s)\n{\n // Sanity checks\n if (s == NULL || d == NULL)\n return NULL;\n\n // Skip leading spaces \n const unsigned char * p = (const unsigned char *)s;\n while (isspace(*p))\n p++;\n\n // Copy the string\n unsigned char * dst = (unsigned char *)d; // d and s can be the same\n unsigned char * end = dst;\n while (*p != '\\0')\n {\n if (!isspace(*dst++ = *p++))\n end = dst;\n }\n\n // Truncate trailing spaces\n *end = '\\0';\n return d;\n}\n\nchar * trim(char *s)\n{\n return trim2(s, s);\n}\n</code></pre>\n"
},
{
"answer_id": 51716928,
"author": "Mitch Laber",
"author_id": 9133063,
"author_profile": "https://Stackoverflow.com/users/9133063",
"pm_score": 0,
"selected": false,
"text": "<pre><code>char* strtrim(char* const str)\n{\n if (str != nullptr)\n {\n char const* begin{ str };\n while (std::isspace(*begin))\n {\n ++begin;\n }\n\n auto end{ begin };\n auto scout{ begin };\n while (*scout != '\\0')\n {\n if (!std::isspace(*scout++))\n {\n end = scout;\n }\n }\n\n auto /* std::ptrdiff_t */ const length{ end - begin };\n if (begin != str)\n {\n std::memmove(str, begin, length);\n }\n\n str[length] = '\\0';\n }\n\n return str;\n}\n</code></pre>\n"
},
{
"answer_id": 52674830,
"author": "poby",
"author_id": 1593044,
"author_profile": "https://Stackoverflow.com/users/1593044",
"pm_score": 1,
"selected": false,
"text": "<p>Ok this is my take on the question. I believe it's the most concise solution that modifies the string in place (<code>free</code> will work) and avoids any UB. For small strings, it's probably faster than a solution involving memmove.</p>\n\n<pre><code>void stripWS_LT(char *str)\n{\n char *a = str, *b = str;\n while (isspace((unsigned char)*a)) a++;\n while (*b = *a++) b++;\n while (b > str && isspace((unsigned char)*--b)) *b = 0;\n}\n</code></pre>\n"
},
{
"answer_id": 53989226,
"author": "rashok",
"author_id": 596370,
"author_profile": "https://Stackoverflow.com/users/596370",
"pm_score": 1,
"selected": false,
"text": "<pre><code>#include <ctype.h>\n#include <string.h>\n\nchar *trim_space(char *in)\n{\n char *out = NULL;\n int len;\n if (in) {\n len = strlen(in);\n while(len && isspace(in[len - 1])) --len;\n while(len && *in && isspace(*in)) ++in, --len;\n if (len) {\n out = strndup(in, len);\n }\n }\n return out;\n}\n</code></pre>\n\n<p><code>isspace</code> helps to trim all white spaces.</p>\n\n<ul>\n<li>Run a first loop to check from last byte for space character and reduce the length variable</li>\n<li>Run a second loop to check from first byte for space character and reduce the length variable and increment char pointer.</li>\n<li>Finally if length variable is more than 0, then use <code>strndup</code> to create new string buffer by excluding spaces.</li>\n</ul>\n"
},
{
"answer_id": 58016995,
"author": "Humpity",
"author_id": 2779074,
"author_profile": "https://Stackoverflow.com/users/2779074",
"pm_score": 1,
"selected": false,
"text": "<p>This one is short and simple, uses for-loops and doesn't overwrite the string boundaries.\nYou can replace the test with <code>isspace()</code> if needed.</p>\n\n<pre><code>void trim (char *s) // trim leading and trailing spaces+tabs\n{\n int i,j,k, len;\n\n j=k=0;\n len = strlen(s);\n // find start of string\n for (i=0; i<len; i++) if ((s[i]!=32) && (s[i]!=9)) { j=i; break; }\n // find end of string+1\n for (i=len-1; i>=j; i--) if ((s[i]!=32) && (s[i]!=9)) { k=i+1; break;} \n\n if (k<=j) {s[0]=0; return;} // all whitespace (j==k==0)\n\n len=k-j;\n for (i=0; i<len; i++) s[i] = s[j++]; // shift result to start of string\n s[i]=0; // end the string\n\n}//_trim\n</code></pre>\n"
},
{
"answer_id": 59202547,
"author": "Ace.C",
"author_id": 6191970,
"author_profile": "https://Stackoverflow.com/users/6191970",
"pm_score": 0,
"selected": false,
"text": "<p>As the other answers don't seem to mutate the string pointer directly, but rather rely on the return value, I thought I would provide this method which additionally does not use any libraries and so is appropriate for operating system style programming:</p>\n<pre><code>// only used for printf in main\n#include <stdio.h>\n\n// note the char ** means we can modify the address\nchar *trimws(char **strp) { \n char *str;\n // check if empty string\n if(!*str)\n return;\n // go to the end of the string\n for (str = *strp; *str; str++) \n ;\n // back up one from the null terminator\n str--; \n // set trailing ws to null\n for (; *str == ' '; str--) \n *str = 0;\n // increment past leading ws\n for (str = *strp; *str == ' '; str++) \n ;\n // set new begin address of string\n *strp = str; \n}\n\nint main(void) {\n char buf[256] = " whitespace ";\n // pointer must be modifiable lvalue so we make bufp\n char **bufp = &buf;\n // pass in the address\n trimws(&bufp);\n // prints : XXXwhitespaceXXX\n printf("XXX%sXXX\\n", bufp); \n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 67239486,
"author": "hesed",
"author_id": 10152015,
"author_profile": "https://Stackoverflow.com/users/10152015",
"pm_score": 0,
"selected": false,
"text": "<p>IMO, it can be done without <code>strlen</code> and <code>isspace</code>.</p>\n<pre><code>char *\ntrim (char * s, char c)\n{\n unsigned o = 0;\n char * sb = s;\n\n for (; *s == c; s++)\n o++;\n\n for (; *s != '\\0'; s++)\n continue;\n for (; s - o > sb && *--s == c;)\n continue;\n\n if (o > 0)\n memmove(sb, sb + o, s + 1 - o - sb);\n if (*s != '\\0')\n *(s + 1 - o) = '\\0';\n\n return sb;\n}\n</code></pre>\n"
},
{
"answer_id": 71442959,
"author": "James M. Lay",
"author_id": 1461154,
"author_profile": "https://Stackoverflow.com/users/1461154",
"pm_score": 1,
"selected": false,
"text": "<p>If, and ONLY IF there's only one contiguous block of text between whitespace, you can use a single call to <code>strtok(3)</code>, like so:</p>\n<pre><code>char *trimmed = strtok(input, "\\r\\t\\n ");\n</code></pre>\n<p>This works for strings like the following:</p>\n<pre><code>" +1.123.456.7890 "\n" 01-01-2020\\n"\n"\\t2.523"\n</code></pre>\n<p>This will not work for strings that contain whitespace between blocks of non-whitespace, like <code>" hi there "</code>. It's probably better to avoid this approach, but now it's here in your toolbox if you need it.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14463/"
] |
Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I'd roll my own, but I would think this is a common problem with an equally common solution.
|
If you can modify the string:
```
// Note: This function returns a pointer to a substring of the original string.
// If the given string was allocated dynamically, the caller must not overwrite
// that pointer with the returned value, since the original pointer must be
// deallocated using the same allocator with which it was allocated. The return
// value must NOT be deallocated using free() etc.
char *trimwhitespace(char *str)
{
char *end;
// Trim leading space
while(isspace((unsigned char)*str)) str++;
if(*str == 0) // All spaces?
return str;
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
// Write new null terminator character
end[1] = '\0';
return str;
}
```
If you can't modify the string, then you can use basically the same method:
```
// Stores the trimmed input string into the given output buffer, which must be
// large enough to store the result. If it is too small, the output is
// truncated.
size_t trimwhitespace(char *out, size_t len, const char *str)
{
if(len == 0)
return 0;
const char *end;
size_t out_size;
// Trim leading space
while(isspace((unsigned char)*str)) str++;
if(*str == 0) // All spaces?
{
*out = 0;
return 1;
}
// Trim trailing space
end = str + strlen(str) - 1;
while(end > str && isspace((unsigned char)*end)) end--;
end++;
// Set output size to minimum of trimmed string length and buffer size minus 1
out_size = (end - str) < len-1 ? (end - str) : len-1;
// Copy trimmed string and add null terminator
memcpy(out, str, out_size);
out[out_size] = 0;
return out_size;
}
```
|
122,639 |
<p>I have a temp table with the exact structure of a concrete table <code>T</code>. It was created like this: </p>
<pre><code>select top 0 * into #tmp from T
</code></pre>
<p>After processing and filling in content into <code>#tmp</code>, I want to copy the content back to <code>T</code> like this: </p>
<pre><code>insert into T select * from #tmp
</code></pre>
<p>This is okay as long as <code>T</code> doesn't have identity column, but in my case it does. Is there any way I can ignore the auto-increment identity column from <code>#tmp</code> when I copy to <code>T</code>? My motivation is to avoid having to spell out every column name in the Insert Into list. </p>
<p>EDIT: toggling identity_insert wouldn't work because the pkeys in <code>#tmp</code> may collide with those in <code>T</code> if rows were inserted into <code>T</code> outside of my script, that's if <code>#tmp</code> has auto-incremented the pkey to sync with T's in the first place. </p>
|
[
{
"answer_id": 122655,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 4,
"selected": false,
"text": "<p>SET IDENTITY_INSERT ON</p>\n\n<p>INSERT command</p>\n\n<p>SET IDENTITY_INSERT OFF</p>\n"
},
{
"answer_id": 122661,
"author": "Jasmine",
"author_id": 5255,
"author_profile": "https://Stackoverflow.com/users/5255",
"pm_score": 1,
"selected": false,
"text": "<pre><code>set identity_insert on\n</code></pre>\n\n<p>Use this.</p>\n"
},
{
"answer_id": 122699,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "<p>Not with <code>SELECT *</code> - if you selected every column but the identity, it will be fine. The only way I can see is that you could do this by dynamically building the <code>INSERT</code> statement.</p>\n"
},
{
"answer_id": 122715,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 1,
"selected": false,
"text": "<p>Just list the colums you want to re-insert, you should never use select * anyway. If you don't want to type them ,just drag them from the object browser (If you expand the table and drag the word, columns, you will get all of them, just delete the id column)</p>\n"
},
{
"answer_id": 122720,
"author": "DK.",
"author_id": 16886,
"author_profile": "https://Stackoverflow.com/users/16886",
"pm_score": 4,
"selected": true,
"text": "<p>As identity will be generated during insert anyway, could you simply remove this column from #tmp before inserting the data back to T?</p>\n\n<pre><code>alter table #tmp drop column id\n</code></pre>\n\n<p><strong>UPD:</strong> Here's an example I've tested in SQL Server 2008:</p>\n\n<pre><code>create table T(ID int identity(1,1) not null, Value nvarchar(50))\ninsert into T (Value) values (N'Hello T!')\nselect top 0 * into #tmp from T\nalter table #tmp drop column ID\ninsert into #tmp (Value) values (N'Hello #tmp')\ninsert into T select * from #tmp\ndrop table #tmp\nselect * from T\ndrop table T\n</code></pre>\n"
},
{
"answer_id": 122722,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<p>Might an \"update where T.ID = #tmp.ID\" work?</p>\n"
},
{
"answer_id": 122930,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <ol>\n <li>it gives me a chance to preview the data before I do the insert </li>\n <li>I have joins between temp tables as part of my calculation; temp tables allows me to focus on the exact set data that I am working with. I think that was it. Any suggestions/comments?</li>\n </ol>\n</blockquote>\n\n<p>For part 1, as mentioned by Kolten in one of the comments, encapsulating your statements in a transaction and adding a parameter to toggle between display and commit will meet your needs. For Part 2, I would needs to see what \"calculations\" you are attempting. Limiting your data to a temp table may be over complicating the situation. </p>\n"
},
{
"answer_id": 2464835,
"author": "Rob Packwood",
"author_id": 171485,
"author_profile": "https://Stackoverflow.com/users/171485",
"pm_score": 1,
"selected": false,
"text": "<p>INSERT INTO #Table\nSELECT MAX(Id) + ROW_NUMBER() OVER(ORDER BY Id)</p>\n"
},
{
"answer_id": 44634113,
"author": "sǝɯɐſ",
"author_id": 1579626,
"author_profile": "https://Stackoverflow.com/users/1579626",
"pm_score": 3,
"selected": false,
"text": "<p>See answers <a href=\"https://dba.stackexchange.com/a/936/116268\">here</a> and <a href=\"https://dba.stackexchange.com/a/925/116268\">here</a>:</p>\n\n<pre><code>select * into without_id from with_id\nunion all\nselect * from with_id where 1 = 0\n</code></pre>\n\n<p>Reason:</p>\n\n<blockquote>\n <p>When an existing identity column is selected into a new table, the new column inherits the IDENTITY property, unless one of the following conditions is true:</p>\n \n <ul>\n <li>The SELECT statement contains a join, GROUP BY clause, or aggregate function.</li>\n <li>Multiple SELECT statements are joined by using UNION.</li>\n <li>The identity column is listed more than one time in the select list.</li>\n <li>The identity column is part of an expression.</li>\n <li>The identity column is from a remote data source.</li>\n </ul>\n \n <p>If any one of these conditions is true, the column is created NOT NULL instead of inheriting the IDENTITY property. If an identity column is required in the new table but such a column is not available, or you want a seed or increment value that is different than the source identity column, define the column in the select list using the IDENTITY function. See \"Creating an identity column using the IDENTITY function\" in the Examples section below.</p>\n</blockquote>\n\n<p>All credit goes to <a href=\"https://dba.stackexchange.com/users/247/eric-humphrey-lotsahelp\">Eric Humphrey</a> and <a href=\"https://dba.stackexchange.com/users/136/bernd-k\">bernd_k</a></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10088/"
] |
I have a temp table with the exact structure of a concrete table `T`. It was created like this:
```
select top 0 * into #tmp from T
```
After processing and filling in content into `#tmp`, I want to copy the content back to `T` like this:
```
insert into T select * from #tmp
```
This is okay as long as `T` doesn't have identity column, but in my case it does. Is there any way I can ignore the auto-increment identity column from `#tmp` when I copy to `T`? My motivation is to avoid having to spell out every column name in the Insert Into list.
EDIT: toggling identity\_insert wouldn't work because the pkeys in `#tmp` may collide with those in `T` if rows were inserted into `T` outside of my script, that's if `#tmp` has auto-incremented the pkey to sync with T's in the first place.
|
As identity will be generated during insert anyway, could you simply remove this column from #tmp before inserting the data back to T?
```
alter table #tmp drop column id
```
**UPD:** Here's an example I've tested in SQL Server 2008:
```
create table T(ID int identity(1,1) not null, Value nvarchar(50))
insert into T (Value) values (N'Hello T!')
select top 0 * into #tmp from T
alter table #tmp drop column ID
insert into #tmp (Value) values (N'Hello #tmp')
insert into T select * from #tmp
drop table #tmp
select * from T
drop table T
```
|
122,688 |
<p>We use BigIP to load balance between our two IIS servers. We recently deployed a WCF service hosted on by IIS 6 onto these two Windows Server 2003R2 servers.</p>
<p>Each server is configured with two host headers: one for the load balancer address, and then a second host header that points only to that server. That way we can reference a specific server in the load balanced group for debugging.</p>
<p>So when we run We immediately got the error:</p>
<blockquote>
<p><strong>This collection already contains an address with scheme http. There can be at most one address per scheme in this collection.
Parameter name: item</strong></p>
</blockquote>
<p>I did some research and we can implement a filter to tell it to ignore the one of the hosts, but then we cannot access the server from that address. </p>
<pre><code><serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="http://domain.com:80"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
</code></pre>
<p>What is the best solution in this scenario which would allow us to hit a WCF service via <a href="http://domain.com/service.svc" rel="nofollow noreferrer">http://domain.com/service.svc</a> and <a href="http://server1.domain.com/service.svc" rel="nofollow noreferrer">http://server1.domain.com/service.svc</a>?</p>
<p>If we should create our own ServiceFactory as some sites suggest, does anyone have any sample code on this?</p>
<p>Any help is much appreciated.</p>
<p>EDIT: We will need to be able to access the WCF service from either of the two addresses, if at all possible.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 122754,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>The URL it uses is based on the bindings in IIS. Does the website have more than one binding? If it does, or is the WCF service used by multiple sites? If it is, then you are SOL AFAIK. We ran into this issue. Basically, there can be only one IIS binding for HTTP, otherwise it bombs.</p>\n\n<p>Also, here's info on <a href=\"http://www.robzelt.com/blog/2007/01/24/WCF+This+Collection+Already+Contains+An+Address+With+Scheme+Http.aspx\" rel=\"nofollow noreferrer\">implementing a ServiceHostFactory</a>. That WILL work if it's possible that your WCF service only be accessible through 1 address (unfortunately for us, this was not possible).</p>\n"
},
{
"answer_id": 171747,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 0,
"selected": false,
"text": "<p>When you need to test a specific machine, you could \"bypass\" the load balancing and ensure the correct host-header is sent to keeep WCF happy by editing the \"hosts\" file on the machine you're testing from so, for example:</p>\n\n<p>10.0.0.11 through 10.0.0.16 are the six hosts that are in the cluster \"cluster.mycompany.local\", with a load balanced IP address of 10.0.0.10. When testing you could add a line to the machines hosts file that says \"10.0.0.13 cluster.mycompany.local\" to be able to hit the third machine in the cluster directly.</p>\n"
},
{
"answer_id": 267115,
"author": "CPU_BUSY",
"author_id": 27688,
"author_profile": "https://Stackoverflow.com/users/27688",
"pm_score": 2,
"selected": true,
"text": "<p>On your bigIP Create 2 new virtual servers\n<a href=\"http://server1.domain.com/\" rel=\"nofollow noreferrer\">http://server1.domain.com/</a>\n<a href=\"http://server2.domain.com/\" rel=\"nofollow noreferrer\">http://server2.domain.com/</a></p>\n\n<p>create a pool for each VS with only the specific server in it - so there will be no actual load balancing and access it that way. If you are short on external IP'S you can still use the same IP as your production domain name and just use an irule to direct traffic to the appropriate pool</p>\n\n<p>Hope this helps</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13368/"
] |
We use BigIP to load balance between our two IIS servers. We recently deployed a WCF service hosted on by IIS 6 onto these two Windows Server 2003R2 servers.
Each server is configured with two host headers: one for the load balancer address, and then a second host header that points only to that server. That way we can reference a specific server in the load balanced group for debugging.
So when we run We immediately got the error:
>
> **This collection already contains an address with scheme http. There can be at most one address per scheme in this collection.
> Parameter name: item**
>
>
>
I did some research and we can implement a filter to tell it to ignore the one of the hosts, but then we cannot access the server from that address.
```
<serviceHostingEnvironment>
<baseAddressPrefixFilters>
<add prefix="http://domain.com:80"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
```
What is the best solution in this scenario which would allow us to hit a WCF service via <http://domain.com/service.svc> and <http://server1.domain.com/service.svc>?
If we should create our own ServiceFactory as some sites suggest, does anyone have any sample code on this?
Any help is much appreciated.
EDIT: We will need to be able to access the WCF service from either of the two addresses, if at all possible.
Thank you.
|
On your bigIP Create 2 new virtual servers
<http://server1.domain.com/>
<http://server2.domain.com/>
create a pool for each VS with only the specific server in it - so there will be no actual load balancing and access it that way. If you are short on external IP'S you can still use the same IP as your production domain name and just use an irule to direct traffic to the appropriate pool
Hope this helps
|
122,690 |
<p>I've been too lax with performing DB backups on our internal servers. </p>
<p>Is there a simple command line program that I can use to backup certain databases in SQL Server 2005? Or is there a simple VBScript? </p>
|
[
{
"answer_id": 122705,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 3,
"selected": false,
"text": "<p>Schedule the following to backup all Databases:</p>\n\n<pre><code>Use Master\n\nDeclare @ToExecute VarChar(8000)\n\nSelect @ToExecute = Coalesce(@ToExecute + 'Backup Database ' + [Name] + ' To Disk = ''D:\\Backups\\Databases\\' + [Name] + '.bak'' With Format;' + char(13),'')\nFrom\nMaster..Sysdatabases\nWhere\n[Name] Not In ('tempdb')\nand databasepropertyex ([Name],'Status') = 'online'\n\nExecute(@ToExecute)\n</code></pre>\n\n<p>There are also more details on my blog: how to <a href=\"http://gatekiller.co.uk/Post/Automate_SQL_Server_Express_Backups\" rel=\"noreferrer\">Automate SQL Server Express Backups</a>.</p>\n"
},
{
"answer_id": 122729,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": -1,
"selected": false,
"text": "<p>If you can find the DB files... \"cp DBFiles backup/\"</p>\n\n<p><em>Almost for sure <strong>not advisable</strong> in most cases</em>, but it's simple as all getup.</p>\n"
},
{
"answer_id": 122737,
"author": "Craig Trader",
"author_id": 12895,
"author_profile": "https://Stackoverflow.com/users/12895",
"pm_score": 8,
"selected": true,
"text": "<p>To backup a single database from the command line, use <a href=\"https://msdn.microsoft.com/en-us/library/ms162806.aspx\" rel=\"noreferrer\">osql</a> or <a href=\"https://msdn.microsoft.com/en-us/library/ms162773.aspx\" rel=\"noreferrer\">sqlcmd</a>.</p>\n\n<pre><code>\"C:\\Program Files\\Microsoft SQL Server\\90\\Tools\\Binn\\osql.exe\" \n -E -Q \"BACKUP DATABASE mydatabase TO DISK='C:\\tmp\\db.bak' WITH FORMAT\"\n</code></pre>\n\n<p>You'll also want to read the documentation on <a href=\"https://msdn.microsoft.com/en-us/library/ms186865.aspx\" rel=\"noreferrer\">BACKUP</a> and <a href=\"https://msdn.microsoft.com/en-us/library/ms190372.aspx\" rel=\"noreferrer\">RESTORE</a> and <a href=\"https://msdn.microsoft.com/en-us/library/ms187048.aspx\" rel=\"noreferrer\">general procedures</a>.</p>\n"
},
{
"answer_id": 586690,
"author": "Martin Meixger",
"author_id": 64466,
"author_profile": "https://Stackoverflow.com/users/64466",
"pm_score": 3,
"selected": false,
"text": "<p>I use <a href=\"http://www.codeplex.com/ExpressMaint\" rel=\"nofollow noreferrer\">ExpressMaint</a>.</p>\n\n<p>To backup all user databases I do for example:</p>\n\n<pre><code>C:\\>ExpressMaint.exe -S (local)\\sqlexpress -D ALL_USER -T DB -BU HOURS -BV 1 -B c:\\backupdir\\ -DS\n</code></pre>\n"
},
{
"answer_id": 11002314,
"author": "Ira C",
"author_id": 1451928,
"author_profile": "https://Stackoverflow.com/users/1451928",
"pm_score": 2,
"selected": false,
"text": "<p>I'm using tsql on a Linux/UNIX infrastructure to access MSSQL databases. Here's a simple shell script to dump a table to a file:</p>\n\n<pre><code>#!/usr/bin/ksh\n#\n#.....\n(\ntsql -S {database} -U {user} -P {password} <<EOF\nselect * from {table}\ngo\nquit\nEOF\n) >{output_file.dump}\n</code></pre>\n"
},
{
"answer_id": 16754365,
"author": "John W.",
"author_id": 1893068,
"author_profile": "https://Stackoverflow.com/users/1893068",
"pm_score": 3,
"selected": false,
"text": "<p>I found this on a Microsoft Support page <a href=\"http://support.microsoft.com/kb/2019698\" rel=\"noreferrer\">http://support.microsoft.com/kb/2019698</a>. </p>\n\n<p>It works great! And since it came from Microsoft, I feel like it's pretty legit.</p>\n\n<p>Basically there are two steps.</p>\n\n<ol>\n<li>Create a stored procedure in your master db. See msft link or if it's broken try here: <a href=\"http://pastebin.com/svRLkqnq\" rel=\"noreferrer\">http://pastebin.com/svRLkqnq</a></li>\n<li><p>Schedule the backup from your task scheduler. You might want to put into a .bat or .cmd file first and then schedule that file.</p>\n\n<pre><code>sqlcmd -S YOUR_SERVER_NAME\\SQLEXPRESS -E -Q \"EXEC sp_BackupDatabases @backupLocation='C:\\SQL_Backup\\', @backupType='F'\" 1>c:\\SQL_Backup\\backup.log \n</code></pre></li>\n</ol>\n\n<p>Obviously replace YOUR_SERVER_NAME with your computer name or optionally try .\\SQLEXPRESS and make sure the backup folder exists. In this case it's trying to put it into c:\\SQL_Backup</p>\n"
},
{
"answer_id": 24409144,
"author": "George Vrynios",
"author_id": 1832537,
"author_profile": "https://Stackoverflow.com/users/1832537",
"pm_score": 2,
"selected": false,
"text": "<p>Eventual if you don't have a trusted connection as the –E switch declares </p>\n\n<p>Use following command line</p>\n\n<p><code>\"[program dir]\\[sql server version]\\Tools\\Binn\\osql.exe\" -Q \"BACKUP DATABASE mydatabase TO DISK='C:\\tmp\\db.bak'\" -S [server] –U [login id] -P [password]</code></p>\n\n<p>Where</p>\n\n<p>[program dir] is the directory where the osql.exe exists</p>\n\n<pre>On 32bit OS c:\\Program Files\\Microsoft SQL Server\\</pre>\n\n<pre>On 64bit OS c:\\Program Files (x86)\\Microsoft SQL Server\\</pre>\n\n<p>[sql server version] your sql server version 110 or 100 or 90 or 80 begin with the largest number</p>\n\n<p>[server] your servername or server ip</p>\n\n<p>[login id] your ms-sql server user login name</p>\n\n<p>[password] the required login password</p>\n"
},
{
"answer_id": 47576493,
"author": "P.Thompson",
"author_id": 8400383,
"author_profile": "https://Stackoverflow.com/users/8400383",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the backup application by ApexSQL. Although it’s a GUI application, it has all its features supported in CLI. It is possible to either perform one-time backup operations, or to create a job that would back up specified databases on the regular basis. You can check the switch rules and exampled in the articles:</p>\n\n<ul>\n<li><a href=\"https://knowledgebase.apexsql.com/apexsql-backup-cli-support/\" rel=\"noreferrer\">ApexSQL Backup CLI support</a></li>\n<li><a href=\"https://knowledgebase.apexsql.com/apexsql-backup-cli-examples/\" rel=\"noreferrer\">ApexSQL Backup CLI examples</a></li>\n</ul>\n"
},
{
"answer_id": 52283550,
"author": "ezrarieben",
"author_id": 2048290,
"author_profile": "https://Stackoverflow.com/users/2048290",
"pm_score": 0,
"selected": false,
"text": "<p>You could use a VB Script I wrote exactly for this purpose:\n<a href=\"https://github.com/ezrarieben/mssql-backup-vbs/\" rel=\"nofollow noreferrer\">https://github.com/ezrarieben/mssql-backup-vbs/</a></p>\n\n<p>Schedule a task in the \"Task Scheduler\" to execute the script as you like and it'll backup the entire DB to a BAK file and save it wherever you specify.</p>\n"
},
{
"answer_id": 55609181,
"author": "Sagar Mahajan",
"author_id": 7901091,
"author_profile": "https://Stackoverflow.com/users/7901091",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SET NOCOUNT ON;\ndeclare @PATH VARCHAR(200)='D:\\MyBackupFolder\\'\n -- path where you want to take backups\nIF OBJECT_ID('TEMPDB..#back') IS NOT NULL\n\nDROP TABLE #back\n\nCREATE TABLE #back\n(\nRN INT IDENTITY (1,1),\nDatabaseName NVARCHAR(200)\n\n)\n\nINSERT INTO #back \nSELECT 'MyDatabase1'\nUNION SELECT 'MyDatabase2'\nUNION SELECT 'MyDatabase3'\nUNION SELECT 'MyDatabase4'\n\n-- your databases List\n\nDECLARE @COUNT INT =0 , @RN INT =1, @SCRIPT NVARCHAR(MAX)='', @DBNAME VARCHAR(200)\n\nPRINT '---------------------FULL BACKUP SCRIPT-------------------------'+CHAR(10)\nSET @COUNT = (SELECT COUNT(*) FROM #back)\nPRINT 'USE MASTER'+CHAR(10)\nWHILE(@COUNT > = @RN)\nBEGIN\n\nSET @DBNAME =(SELECT DatabaseName FROM #back WHERE RN=@RN)\nSET @SCRIPT ='BACKUP DATABASE ' +'['+@DBNAME+']'+CHAR(10)+'TO DISK =N'''+@PATH+@DBNAME+ N'_Backup_'\n+ REPLACE ( REPLACE ( REPLACE ( REPLACE ( CAST ( CAST ( GETDATE () AS DATETIME2 ) AS VARCHAR ( 100 )), '-' , '_' ), ' ' , '_' ), '.' , '_' ), ':' , '' )+'.bak'''+CHAR(10)+'WITH COMPRESSION, STATS = 10'+CHAR(10)+'GO'+CHAR(10)\nPRINT @SCRIPT\nSET @RN=@RN+1\nEND\n\n PRINT '---------------------DIFF BACKUP SCRIPT-------------------------'+CHAR(10)\n\n SET @COUNT =0 SET @RN =1 SET @SCRIPT ='' SET @DBNAME =''\n SET @COUNT = (SELECT COUNT(*) FROM #back)\nPRINT 'USE MASTER'+CHAR(10)\nWHILE(@COUNT > = @RN)\nBEGIN\nSET @DBNAME =(SELECT DatabaseName FROM #back WHERE RN=@RN)\nSET @SCRIPT ='BACKUP DATABASE ' +'['+@DBNAME+']'+CHAR(10)+'TO DISK =N'''+@PATH+@DBNAME+ N'_Backup_'\n+ REPLACE ( REPLACE ( REPLACE ( REPLACE ( CAST ( CAST ( GETDATE () AS DATETIME2 ) AS VARCHAR ( 100 )), '-' , '_' ), ' ' , '_' ), '.' , '_' ), ':' , '' )+'.diff'''+CHAR(10)+'WITH DIFFERENTIAL, COMPRESSION, STATS = 10'+CHAR(10)+'GO'+CHAR(10)\nPRINT @SCRIPT\nSET @RN=@RN+1\nEND\n</code></pre>\n"
},
{
"answer_id": 61644743,
"author": "CraigD",
"author_id": 11311561,
"author_profile": "https://Stackoverflow.com/users/11311561",
"pm_score": 2,
"selected": false,
"text": "<p>Microsoft's answer to backing up all user databases on SQL Express is <a href=\"https://support.microsoft.com/en-us/help/2019698/how-to-schedule-and-automate-backups-of-sql-server-databases-in-sql-se\" rel=\"nofollow noreferrer\">here</a>:</p>\n<p>The process is: copy, paste, and execute their code (see below. I've commented some oddly non-commented lines at the top) as a query on your database server. That means you should first install the SQL Server Management Studio (or otherwise connect to your database server with SSMS). This code execution will create a stored procedure on your database server.</p>\n<p>Create a batch file to execute the stored procedure, then use Task Scheduler to schedule a periodic (e.g. nightly) run of this batch file. My code (that works) is a slightly modified version of their first example:</p>\n<pre><code>sqlcmd -S .\\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases @backupLocation='E:\\SQLBackups\\', @backupType='F'" \n</code></pre>\n<p>This worked for me, and I like it. Each time you run it, new backup files are created. You'll need to devise a method of deleting old backup files on a routine basis. I already have a routine that does that sort of thing, so I'll keep a couple of days' worth of backups on disk (long enough for them to get backed up by my normal backup routine), then I'll delete them. In other words, I'll always have a few days' worth of backups on hand without having to restore from my backup system.</p>\n<p>I'll paste Microsoft's stored procedure creation script below:</p>\n<pre><code>--// Copyright © Microsoft Corporation. All Rights Reserved.\n--// This code released under the terms of the\n--// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)\n\nUSE [master] \nGO \n\n/****** Object: StoredProcedure [dbo].[sp_BackupDatabases] ******/ \n\nSET ANSI_NULLS ON \nGO \n\nSET QUOTED_IDENTIFIER ON \nGO \n\n \n-- ============================================= \n-- Author: Microsoft \n-- Create date: 2010-02-06\n-- Description: Backup Databases for SQLExpress\n-- Parameter1: databaseName \n-- Parameter2: backupType F=full, D=differential, L=log\n-- Parameter3: backup file location\n-- =============================================\n\nCREATE PROCEDURE [dbo].[sp_BackupDatabases] \n @databaseName sysname = null,\n @backupType CHAR(1),\n @backupLocation nvarchar(200) \nAS \n\n SET NOCOUNT ON; \n\n DECLARE @DBs TABLE\n (\n ID int IDENTITY PRIMARY KEY,\n DBNAME nvarchar(500)\n )\n \n -- Pick out only databases which are online in case ALL databases are chosen to be backed up\n\n -- If specific database is chosen to be backed up only pick that out from @DBs\n\n INSERT INTO @DBs (DBNAME)\n SELECT Name FROM master.sys.databases\n where state=0\n AND name=@DatabaseName\n OR @DatabaseName IS NULL\n ORDER BY Name\n\n \n -- Filter out databases which do not need to backed up\n \n IF @backupType='F'\n BEGIN\n DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')\n END\n ELSE IF @backupType='D'\n BEGIN\n DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')\n END\n ELSE IF @backupType='L'\n BEGIN\n DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')\n END\n ELSE\n BEGIN\n RETURN\n END\n \n\n -- Declare variables\n\n DECLARE @BackupName varchar(100)\n DECLARE @BackupFile varchar(100)\n DECLARE @DBNAME varchar(300)\n DECLARE @sqlCommand NVARCHAR(1000) \n DECLARE @dateTime NVARCHAR(20)\n DECLARE @Loop int \n \n -- Loop through the databases one by one\n\n SELECT @Loop = min(ID) FROM @DBs\n WHILE @Loop IS NOT NULL\n BEGIN\n \n-- Database Names have to be in [dbname] format since some have - or _ in their name\n\n SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'\n\n\n-- Set the current date and time n yyyyhhmmss format\n\n SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' + REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','') \n \n\n-- Create backup filename in path\\filename.extension format for full,diff and log backups\n\n IF @backupType = 'F'\n SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'\n ELSE IF @backupType = 'D'\n SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'\n ELSE IF @backupType = 'L'\n SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'\n \n\n-- Provide the backup a name for storing in the media\n\n IF @backupType = 'F'\n SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime\n\n IF @backupType = 'D'\n SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime\n\n IF @backupType = 'L'\n SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime\n\n\n-- Generate the dynamic SQL command to be executed\n\n IF @backupType = 'F' \n BEGIN\n SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'\n END\n\n IF @backupType = 'D'\n BEGIN\n SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT' \n END\n\n IF @backupType = 'L' \n BEGIN\n SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT' \n END\n \n\n-- Execute the generated SQL command\n\n EXEC(@sqlCommand)\n\n \n-- Goto the next database\n\nSELECT @Loop = min(ID) FROM @DBs where ID>@Loop\n \n\nEND\n</code></pre>\n"
},
{
"answer_id": 67097327,
"author": "Ashutosh Ranjan",
"author_id": 2727802,
"author_profile": "https://Stackoverflow.com/users/2727802",
"pm_score": 0,
"selected": false,
"text": "<p>This can be helpful when you are dealing with dockerised mssql container in your day to day work and want to take a quick dump of the data from table. I have specially found it useful when you are re-building the db container quite frequently and don't want to loose the test data after the re-build.</p>\n<pre><code>Export data using bcp utility\n/opt/mssql-tools/bin/bcp <Table_Name> out /tmp/MyData.bcp -d <database_name> -c -U <user_name> -P "<password>" -S <server_name>\n\nImport data using bcp utility\n\n/opt/mssql-tools/bin/bcp <Table_Name> IN /tmp/MyData.bcp -d <database_name> -c -U <user_name> -P "<password>" -S <server_name>\n</code></pre>\n"
},
{
"answer_id": 69494573,
"author": "Bhadresh Patel",
"author_id": 3134543,
"author_profile": "https://Stackoverflow.com/users/3134543",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Here is an example one, it will take backup database, compress using 7zip and delete backup file so issue related to storage also solved. In this example I use 7zip, which is free</strong></p>\n<pre><code>@echo off\n\nCLS\n\necho Running dump ...\n\nsqlcmd -S SERVER\\SQLEXPRESS -U username -P password -Q "BACKUP DATABASE master TO DISK='D:\\DailyDBBackup\\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%.bak'"\n\necho Zipping ...\n\n"C:\\Program Files\\7-Zip\\7z.exe" a -tzip "D:\\DailyDBBackup\\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%_%time:~0,2%%time:~3,2%%time:~6,2%.bak.zip" "D:\\DailyDBBackup\\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%.bak"\n\necho Deleting the SQL file ...\n\ndel "D:\\DailyDBBackup\\DB_master_%date:~-10,2%%date:~-7,2%%date:~-4,4%.bak"\n\necho Done!\n</code></pre>\n<p>Save this as sqlbackup.bat and schedule it to be run everyday.</p>\n<p>If you just want to take backup only then you can create script without zipping and deleting.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] |
I've been too lax with performing DB backups on our internal servers.
Is there a simple command line program that I can use to backup certain databases in SQL Server 2005? Or is there a simple VBScript?
|
To backup a single database from the command line, use [osql](https://msdn.microsoft.com/en-us/library/ms162806.aspx) or [sqlcmd](https://msdn.microsoft.com/en-us/library/ms162773.aspx).
```
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\osql.exe"
-E -Q "BACKUP DATABASE mydatabase TO DISK='C:\tmp\db.bak' WITH FORMAT"
```
You'll also want to read the documentation on [BACKUP](https://msdn.microsoft.com/en-us/library/ms186865.aspx) and [RESTORE](https://msdn.microsoft.com/en-us/library/ms190372.aspx) and [general procedures](https://msdn.microsoft.com/en-us/library/ms187048.aspx).
|
122,695 |
<p>For example, I have an ASP.NET form that is called by another aspx:</p>
<pre><code>string url = "http://somewhere.com?P1=" + Request["param"];
Response.Write(url);
</code></pre>
<p>I want to do something like this:</p>
<pre><code>string url = "http://somewhere.com?P1=" + Request["param"];
string str = GetResponse(url);
if (str...) {}
</code></pre>
<p>I need to get whatever Response.Write is getting as a result or going to url, manipulate that response, and send something else back.</p>
<p>Any help or a point in the right direction would be greatly appreciated.</p>
|
[
{
"answer_id": 122707,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 3,
"selected": false,
"text": "<pre><code>WebClient client = new WebClient();\nstring response = client.DownloadString(url);\n</code></pre>\n"
},
{
"answer_id": 122712,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>You will need to use the HttpWebRequest and HttpWebResponse objects. You could also use the WebClient object</p>\n"
},
{
"answer_id": 122719,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 3,
"selected": true,
"text": "<p>Webclient.DownloadString() is probably want you want.</p>\n"
},
{
"answer_id": 122723,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 0,
"selected": false,
"text": "<p>An HttpResponse is something that is sent back to the client in response to an HttpRequest. If you want process something on the server, then you can probably do it with either a web service call or a page method. However, I'm not totally sure I understand what you're trying to do in the first place.</p>\n"
},
{
"answer_id": 122858,
"author": "David",
"author_id": 20682,
"author_profile": "https://Stackoverflow.com/users/20682",
"pm_score": 0,
"selected": false,
"text": "<p>WebClient.DownloadString totally did the trick. I got myself too wrapped up in this one.. I was looking at HttpModule and HttpHandler, when I had used WebClient.DownloadFile in the past.</p>\n\n<p>Thank you very much to all who've replied. </p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20682/"
] |
For example, I have an ASP.NET form that is called by another aspx:
```
string url = "http://somewhere.com?P1=" + Request["param"];
Response.Write(url);
```
I want to do something like this:
```
string url = "http://somewhere.com?P1=" + Request["param"];
string str = GetResponse(url);
if (str...) {}
```
I need to get whatever Response.Write is getting as a result or going to url, manipulate that response, and send something else back.
Any help or a point in the right direction would be greatly appreciated.
|
Webclient.DownloadString() is probably want you want.
|
122,714 |
<p>When I try the following lookup in my code:</p>
<pre><code>Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
return (DataSource) envCtx.lookup("jdbc/mydb");
</code></pre>
<p>I get the following exception:</p>
<pre><code>java.sql.SQLException: QueryResults: Unable to initialize naming context:
Name java:comp is not bound in this Context at
com.onsitemanager.database.ThreadLocalConnection.getConnection
(ThreadLocalConnection.java:130) at
...
</code></pre>
<p>I installed embedded JBoss following the JBoss <a href="http://wiki.jboss.org/wiki/Tomcat5.5.x?action=e&windowstate=normal&mode=view" rel="nofollow noreferrer">wiki instructions</a>. And I configured Tomcat using the "Scanning every WAR by default" deployment as specified in the <a href="http://wiki.jboss.org/wiki/EmbeddedAndTomcat" rel="nofollow noreferrer">configuration wiki page</a>.</p>
<p>Quoting the config page:</p>
<blockquote>
<p>JNDI</p>
<p>Embedded JBoss components like connection pooling, EJB, JPA, and transactions make
extensive use of JNDI to publish services. Embedded JBoss overrides Tomcat's JNDI
implementation by layering itself on top of Tomcat's JNDI instantiation. There are a few > reasons for this:</p>
<ol>
<li>To avoid having to declare each and every one of these services within server.xml</li>
<li>To allow seemeless integration of the java:comp namespace between web apps and
EJBs.</li>
<li>Tomcat's JNDI implementation has a few critical bugs in it that hamper some JBoss
components ability to work</li>
<li>We want to provide the option for you of remoting EJBs and other services that can > be remotely looked up</li>
</ol>
</blockquote>
<p>Anyone have any thoughts on how I can configure the JBoss naming service which according to the above quote is overriding Tomcat's JNDI implementation so that I can do a lookup on java:comp/env? </p>
<p>FYI - My environment Tomcat 5.5.9, Seam 2.0.2sp, Embedded JBoss (Beta 3), </p>
<p>Note: I do have a -ds.xml file for my database connection properly setup and accessible on the class path per the instructions.</p>
<p>Also note: I have posted this question in embedded Jboss forum and seam user forum. </p>
|
[
{
"answer_id": 122820,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 1,
"selected": false,
"text": "<p>java:comp/env is known as the Enterprise Naming Context (ENC) and is not globally visible. See <a href=\"http://www.informit.com/articles/article.aspx?p=384904\" rel=\"nofollow noreferrer\">here</a> for more information. You will need to locate the global JNDI name which your datasource is regsitered at.</p>\n\n<p>The easiest way to do this is to navigate to JBoss' web-based JMX console and look for a 'JNDIView' (not exactly sure of the name - currently at home) mbean. This mbean should have a list method which you can invoke, which will display the context path for all of the JNDI-bound objects.</p>\n"
},
{
"answer_id": 123259,
"author": "Joe Dean",
"author_id": 5917,
"author_profile": "https://Stackoverflow.com/users/5917",
"pm_score": 3,
"selected": true,
"text": "<p>Thanks for the response toolkit.... yes, I can access my datasource by going directly to java:jdbc/mydb, but I'm using an existing code base that connects via the ENC. Here's some interesting info that I've found out ....</p>\n\n<ol>\n<li><p>The above code works with <strong>JBoss 4.2.2.GA</strong> and here's the JNDI ctx parameters being used:<br/>\njava.naming.factory.initial=org.jnp.interfaces.NamingContextFactory\njava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces:\norg.jboss.naming:org.jnp.interfaces</p></li>\n<li><p>The above code works with <strong>Tomcat 5.5.x</strong> and here's the JNDI ctx parameters being used:<br/>\njava.naming.factory.initial=org.apache.naming.java.javaURLContextFactory\njava.naming.factory.url.pkgs=org.apache.naming</p></li>\n<li><p>The above code fails with <strong>Embedded JBoss (Beta 3)</strong> in Tomcat 5.5.x with the above error message. <br/>\njava.naming.factory.initial=org.apache.naming.java.javaURLContextFactory\njava.naming.factory.url.pkgs=org.apache.namingThe above code fails with the above error using JBoss Embedded in tomcat 5.5.x</p></li>\n</ol>\n\n<p>Anyone have any thoughts I what I need to do with configuring embedded JBoss JNDI configuration?</p>\n"
},
{
"answer_id": 6264195,
"author": "Kirijav",
"author_id": 787306,
"author_profile": "https://Stackoverflow.com/users/787306",
"pm_score": 1,
"selected": false,
"text": "<p>I had some similar issue with Jboss Embedded and i finally fix playing in the file:\ntest-Datasource-ds.xml</p>\n\n<p>adding </p>\n\n<pre><code><mbean code=\"org.jboss.naming.NamingAlias\" name=\"jboss.jmx:alias=testDatasource\">\n <attribute name=\"FromName\">jdbc/Example DataSource</attribute>\n <attribute name=\"ToName\">java:/testDatasource</attribute>\n</mbean>\n</code></pre>\n\n<p>The problem was jboss add the prefix java:/ for all data source declared. So finally i had a datasource named testDatasource, overrided with that directive to jdbc/Example DataSource</p>\n\n<p>Hope it works</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5917/"
] |
When I try the following lookup in my code:
```
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
return (DataSource) envCtx.lookup("jdbc/mydb");
```
I get the following exception:
```
java.sql.SQLException: QueryResults: Unable to initialize naming context:
Name java:comp is not bound in this Context at
com.onsitemanager.database.ThreadLocalConnection.getConnection
(ThreadLocalConnection.java:130) at
...
```
I installed embedded JBoss following the JBoss [wiki instructions](http://wiki.jboss.org/wiki/Tomcat5.5.x?action=e&windowstate=normal&mode=view). And I configured Tomcat using the "Scanning every WAR by default" deployment as specified in the [configuration wiki page](http://wiki.jboss.org/wiki/EmbeddedAndTomcat).
Quoting the config page:
>
> JNDI
>
>
> Embedded JBoss components like connection pooling, EJB, JPA, and transactions make
> extensive use of JNDI to publish services. Embedded JBoss overrides Tomcat's JNDI
> implementation by layering itself on top of Tomcat's JNDI instantiation. There are a few > reasons for this:
>
>
> 1. To avoid having to declare each and every one of these services within server.xml
> 2. To allow seemeless integration of the java:comp namespace between web apps and
> EJBs.
> 3. Tomcat's JNDI implementation has a few critical bugs in it that hamper some JBoss
> components ability to work
> 4. We want to provide the option for you of remoting EJBs and other services that can > be remotely looked up
>
>
>
Anyone have any thoughts on how I can configure the JBoss naming service which according to the above quote is overriding Tomcat's JNDI implementation so that I can do a lookup on java:comp/env?
FYI - My environment Tomcat 5.5.9, Seam 2.0.2sp, Embedded JBoss (Beta 3),
Note: I do have a -ds.xml file for my database connection properly setup and accessible on the class path per the instructions.
Also note: I have posted this question in embedded Jboss forum and seam user forum.
|
Thanks for the response toolkit.... yes, I can access my datasource by going directly to java:jdbc/mydb, but I'm using an existing code base that connects via the ENC. Here's some interesting info that I've found out ....
1. The above code works with **JBoss 4.2.2.GA** and here's the JNDI ctx parameters being used:
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces:
org.jboss.naming:org.jnp.interfaces
2. The above code works with **Tomcat 5.5.x** and here's the JNDI ctx parameters being used:
java.naming.factory.initial=org.apache.naming.java.javaURLContextFactory
java.naming.factory.url.pkgs=org.apache.naming
3. The above code fails with **Embedded JBoss (Beta 3)** in Tomcat 5.5.x with the above error message.
java.naming.factory.initial=org.apache.naming.java.javaURLContextFactory
java.naming.factory.url.pkgs=org.apache.namingThe above code fails with the above error using JBoss Embedded in tomcat 5.5.x
Anyone have any thoughts I what I need to do with configuring embedded JBoss JNDI configuration?
|
122,728 |
<p>I have a dilemma, I'm using Java and Oracle and trying to keep queries on PL/SQL side. Everything is OK, until I have these complex queries which may and may not have conditions. <br></p>
<p>It's not hard in Java to put together <code>WHERE</code> clause with conditions, but it's not nice.
And on PL/SQL side I also found out that the only possibility for <code>dynamic queries</code> is string manipulations like</p>
<pre><code>IF inputname IS NOT NULL THEN
query := query ||' and NAME=' || inputname;
END IF;
</code></pre>
<p>Now I'm thinking, I'm leaving query in PL/SQL and sending <code>WHERE</code> clause with function parameter.
Any good recommendations or examples please?</p>
|
[
{
"answer_id": 122759,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://openhms.sourceforge.net/sqlbuilder/\" rel=\"nofollow noreferrer\">SQLBuilder</a> might be useful to you from the Java side. It allows you to write compile-time checked Java code that dynamically builds sql:</p>\n\n<pre><code>String selectQuery =\n (new SelectQuery())\n .addColumns(t1Col1, t1Col2, t2Col1)\n .addJoin(SelectQuery.JoinType.INNER_JOIN, joinOfT1AndT2)\n .addOrderings(t1Col1)\n .validate().toString();\n</code></pre>\n"
},
{
"answer_id": 122774,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "<p>In PL/SQL use:</p>\n\n<pre><code>EXECUTE IMMEDIATE lString;\n</code></pre>\n\n<p>This lets you build the lString (a VARCHAR2) into most bits of SQL that you'll want to use. e.g.</p>\n\n<pre><code> EXECUTE IMMEDIATE 'SELECT value\n FROM TABLE\n WHERE '||pWhereClause\n INTO lValue;\n</code></pre>\n\n<p>You can also return multiple rows and perform DDL statements in EXECUTE IMMEDIATE.</p>\n"
},
{
"answer_id": 122804,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 1,
"selected": false,
"text": "<p>PL/SQL is not pleasant for creating dynamic SQL as you have discovered, its string manipulation is painful. You can send the where clause from the client, but you must make sure to check for SQL injection, i.e. make sure the phrase starts with \"where\", has no semi-colon or only at the end (if it could occur in the middle you need to look from string delimiter and only allow it within them), etc. Another option would be a stored procedure that takes a predefined parameter list of field filters, applying a \"like\" for each column against the parameter field.</p>\n"
},
{
"answer_id": 123014,
"author": "marko",
"author_id": 13114,
"author_profile": "https://Stackoverflow.com/users/13114",
"pm_score": 0,
"selected": false,
"text": "<p>Yea, EXECUTE IMMEDIATE is my friend also. Thanks for suggestions. I think this time I try to send just WHERE clause with parameter</p>\n"
},
{
"answer_id": 123135,
"author": "Telcontar",
"author_id": 518,
"author_profile": "https://Stackoverflow.com/users/518",
"pm_score": 0,
"selected": false,
"text": "<p>I think its better to have the whole logic of the query creation in one place, Java or Oracle. I asume that you know how to do it in Java. In Oracle if the query only retrieves a row you can use the EXECUTE IMMEDIATE ... INTO clause. </p>\n\n<p>If the query return multiple rows and has single parameters (no use the IN operator ) you can use the REF CURSOR strategy to loop the query results or return the cursor itself to the Java program (you must import Oracle java clases if you use it). <a href=\"http://www.oradev.com/ref_cursor.jsp\" rel=\"nofollow noreferrer\">First Ref Cursor answer in Google</a></p>\n\n<p>If you must use the IN parameter ( or in another rare cases) you must parse the query with the DBMS_SQL package, which is TOO verbose and a little tricky to use, but it's VERY flexible. <a href=\"http://www.psoug.org/reference/dbms_sql.html\" rel=\"nofollow noreferrer\">DBMS_SQL doc</a> (watch the flow diagram BEFORE read the methods)</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13114/"
] |
I have a dilemma, I'm using Java and Oracle and trying to keep queries on PL/SQL side. Everything is OK, until I have these complex queries which may and may not have conditions.
It's not hard in Java to put together `WHERE` clause with conditions, but it's not nice.
And on PL/SQL side I also found out that the only possibility for `dynamic queries` is string manipulations like
```
IF inputname IS NOT NULL THEN
query := query ||' and NAME=' || inputname;
END IF;
```
Now I'm thinking, I'm leaving query in PL/SQL and sending `WHERE` clause with function parameter.
Any good recommendations or examples please?
|
[SQLBuilder](http://openhms.sourceforge.net/sqlbuilder/) might be useful to you from the Java side. It allows you to write compile-time checked Java code that dynamically builds sql:
```
String selectQuery =
(new SelectQuery())
.addColumns(t1Col1, t1Col2, t2Col1)
.addJoin(SelectQuery.JoinType.INNER_JOIN, joinOfT1AndT2)
.addOrderings(t1Col1)
.validate().toString();
```
|
122,736 |
<p>I have a stored procedure that consists of a single select query used to insert into another table based on some minor math that is done to the arguments in the procedure. Can I generate the plan used for this query by referencing the procedure somehow, or do I have to copy and paste the query and create bind variables for the input parameters?</p>
|
[
{
"answer_id": 122790,
"author": "Jasmine",
"author_id": 5255,
"author_profile": "https://Stackoverflow.com/users/5255",
"pm_score": 1,
"selected": false,
"text": "<p>From what I understand, this was done on purpose. The idea is that individual queries within the procedure are considered separately by the optimizer, so EXPLAIN PLAN doesn't make sense against a stored proc, which could contain multiple queries/statements.</p>\n\n<p>The current answer is NO, you can't run it against a proc, and you must run it against the individual statements themselves. Tricky when you have variables and calculations, but that's the way it is.</p>\n"
},
{
"answer_id": 122807,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 1,
"selected": false,
"text": "<p>Many tools, such as Toad or SQL Developer, will prompt you for the bind variable values when you execute an explain plan. You would have to do so manually in SQL*Plus or other tools.</p>\n\n<p>You could also turn on SQL tracing and execute the stored procedure, then retrieve the explain plan from the trace file.</p>\n\n<p>Be careful that you do not just retrieve the explain plan for the SELECT statement. The presence of the INSERT clause can change the optimizer goal from first rows to all rows.</p>\n"
},
{
"answer_id": 122817,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 4,
"selected": true,
"text": "<p>Use <a href=\"http://68.142.116.68/docs/cd/B19306_01/server.102/b14211/sqltrace.htm#i4640\" rel=\"nofollow noreferrer\">SQL Trace and TKPROF</a>. For example, open SQL*Plus, and then issue the following code:-</p>\n\n<pre><code>alter session set tracefile_identifier = 'something-unique'\nalter session set sql_trace = true;\nalter session set events '10046 trace name context forever, level 8';\n\nselect 'right-before-my-sp' from dual;\nexec your_stored_procedure\n\nalter session set sql_trace = false;\n</code></pre>\n\n<p>Once this has been done, go look in your database's UDUMP directory for a TRC file with \"something-unique\" in the filename. Format this TRC file with TKPROF, and then open the formatted file and search for the string \"right-before-my-sp\". The SQL command issued by your stored procedure should be shortly after this section, and immediately under that SQL statement will be the plan for the SQL statement.</p>\n\n<p><strong>Edit:</strong> For the purposes of full disclosure, I should thank all those who gave me answers on <a href=\"https://stackoverflow.com/questions/104066/how-do-i-troubleshoot-performance-problems-with-an-oracle-sql-statement\">this thread</a> last week that helped me learn how to do this.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] |
I have a stored procedure that consists of a single select query used to insert into another table based on some minor math that is done to the arguments in the procedure. Can I generate the plan used for this query by referencing the procedure somehow, or do I have to copy and paste the query and create bind variables for the input parameters?
|
Use [SQL Trace and TKPROF](http://68.142.116.68/docs/cd/B19306_01/server.102/b14211/sqltrace.htm#i4640). For example, open SQL\*Plus, and then issue the following code:-
```
alter session set tracefile_identifier = 'something-unique'
alter session set sql_trace = true;
alter session set events '10046 trace name context forever, level 8';
select 'right-before-my-sp' from dual;
exec your_stored_procedure
alter session set sql_trace = false;
```
Once this has been done, go look in your database's UDUMP directory for a TRC file with "something-unique" in the filename. Format this TRC file with TKPROF, and then open the formatted file and search for the string "right-before-my-sp". The SQL command issued by your stored procedure should be shortly after this section, and immediately under that SQL statement will be the plan for the SQL statement.
**Edit:** For the purposes of full disclosure, I should thank all those who gave me answers on [this thread](https://stackoverflow.com/questions/104066/how-do-i-troubleshoot-performance-problems-with-an-oracle-sql-statement) last week that helped me learn how to do this.
|
122,741 |
<p>OK, I have been working on a random image selector and queue system (so you don't see the same images too often).</p>
<p>All was going swimmingly (as far as my crappy code does) <strong>until</strong> I got to the random bit. I wanted to test it, but how do you test for it? There is no <code>Debug.Assert(i.IsRandom)</code> (sadly) :D</p>
<p>So, I got my brain on it after watering it with some tea and came up with the following, I was just wondering if I could have your thoughts?</p>
<ul>
<li>Basically I knew the <strong>random</strong> bit was the problem, so I ripped that out to a delegate (which would then be passed to the objects constructor).</li>
<li>I then created a class that pretty much performs the same logic as the <em>live</em> code, but remembers the value selected in a private variable.</li>
<li>I then threw that delegate to the live class and tested against that:</li>
</ul>
<p>i.e.</p>
<pre><code>Debug.Assert(myObj.RndVal == RndIntTester.ValuePassed);
</code></pre>
<p>But I couldn't help but think, <strong>was I wasting my time?</strong> I ran that through lots of iterations to see if it fell over at any time etc.</p>
<p>Do you think I was wasting my time with this? Or could I have got away with:</p>
<p><img src="https://imgs.xkcd.com/comics/random_number.png" alt="Awesome Random Number Generator" /></p>
<p><a href="https://stackoverflow.com/questions/122741/testing-for-random-value-thoughts-on-this-approach#122765">GateKiller's answer</a> reminded me of this:</p>
<p><img src="https://www.random.org/analysis/dilbert.jpg" alt="Dilbert Random" /></p>
<h2>Update to Clarify</h2>
<ul>
<li><strong>I should add that I basically never want to see the same result more than X number of times from a pool of Y size.</strong></li>
<li>The addition of the test container basically allowed me to see if any of the previously selected images were "randomly" selected.</li>
<li>I guess technically the thing here being tested in not the RNG (since I never wrote that code) but the fact that am I expecting <em>random</em> results from a limited pool, and I want to track them.</li>
</ul>
|
[
{
"answer_id": 122765,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>Random is Random. Even if the same picture shows up 4 times in a row, it could still be considered random.</p>\n"
},
{
"answer_id": 122770,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "<p>It's impossible to test if a value is truly random or not. The best you can do is perform the test some large number of times and test that you got an appropriate distribution, but if the results are truly random, even this has a (very small) chance of failing.</p>\n\n<p>If you're doing white box testing, and you know your random seed, then you can actually compute the expected result, but you may need a separate test to test the randomness of your RNG.</p>\n"
},
{
"answer_id": 122779,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 0,
"selected": false,
"text": "<p>My opinion is that anything random cannot be properly tested. </p>\n\n<p>Sure you can attempt to test it, but there are so many combinations to try that you are better off just relying on the RNG and spot checking a large handful of cases.</p>\n"
},
{
"answer_id": 122810,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 0,
"selected": false,
"text": "<p>Well, the problem is that random numbers by definition <em>can</em> get repeated (because they are... wait for it: random). Maybe what you want to do is save the latest random number and compare the calculated one to that, and if equal just calculate another... but now your numbers are <em>less random</em> (I know there's not such a thing as \"more or less\" randomness, but let me use the term just this time), because they are guaranteed not to repeat.</p>\n\n<p>Anyway, you should never give random numbers so much thought. :)</p>\n"
},
{
"answer_id": 122824,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 0,
"selected": false,
"text": "<p>As others have pointed out, it is impossible to really test for randomness. You can (and should) have the randomness contained to one particular method, and then write unit tests for every other method. That way, you can test all of the other functionality, assuming that you can get a random number out of that one last part.</p>\n"
},
{
"answer_id": 122854,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": "<p>If you have a fixed set of items, and you don't want them to repeat too often, shuffle the collection randomly. Then you will be sure that you never see the same image twice in a row, feel like you're listening to Top 20 radio, etc. You'll make a full pass through the collection before repeating.</p>\n\n<pre><code>Item[] foo = …\nfor (int idx = foo.size(); idx > 1; --idx) {\n /* Pick random number from half-open interval [0, idx) */\n int rnd = random(idx); \n Item tmp = foo[idx - 1];\n foo[idx - 1] = foo[rnd];\n foo[rnd] = tmp;\n}\n</code></pre>\n\n<p>If you have too many items to collect and shuffle all at once (10s of thousands of images in a repository), you can add some divide-and-conquer to the same approach. Shuffle groups of images, then shuffle each group.</p>\n\n<p>A slightly different approach that sounds like it might apply to your revised problem statement is to have your \"image selector\" implementation keep its recent selection history in a queue of at most <code>Y</code> length. Before returning an image, it tests to see if its in the queue <code>X</code> times already, and if so, it randomly selects another, until it find one that passes.</p>\n\n<p>If you are really asking about testing the quality of the random number generator, I'll have to open the statistics book.</p>\n"
},
{
"answer_id": 122878,
"author": "vicky",
"author_id": 17987,
"author_profile": "https://Stackoverflow.com/users/17987",
"pm_score": 0,
"selected": false,
"text": "<p>store the random values and before you use the next generated random number, check against the stored value.</p>\n"
},
{
"answer_id": 122898,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>The generation of random numbers is\n too important to be left to chance. -- Robert R. Coveyou</p>\n</blockquote>\n\n<p>To solve the psychological problem:</p>\n\n<p>A decent way to prevent apparent repetitions is to select a few items at random from the full set, discarding duplicates. Play those, then select another few. How many is \"a few\" depends on how fast you're playing them and how big the full set is, but for example avoiding a repeat inside the larger of \"20\", and \"5 minutes\" might be OK. Do user testing - as the programmer you'll be so sick of slideshows you're not a good test subject.</p>\n\n<p>To test randomising code, I would say:</p>\n\n<p>Step 1: specify how the code MUST map the raw random numbers to choices in your domain, and make sure that your code correctly uses the output of the random number generator. Test this by Mocking the generator (or seeding it with a known test value if it's a PRNG).</p>\n\n<p>Step 2: make sure the generator is sufficiently random for your purposes. If you used a library function, you do this by reading the documentation. If you wrote your own, why?</p>\n\n<p>Step 3 (advanced statisticians only): run some statistical tests for randomness on the output of the generator. Make sure you know what the probability is of a false failure on the test.</p>\n"
},
{
"answer_id": 122921,
"author": "mes5k",
"author_id": 1359466,
"author_profile": "https://Stackoverflow.com/users/1359466",
"pm_score": 0,
"selected": false,
"text": "<p>Any good pseudo-random number generator will let you seed the generator. If you seed the generator with same number, then the stream of random numbers generated will be the same. So why not seed your random number generator and then create your unit tests based on that particular stream of numbers?</p>\n"
},
{
"answer_id": 122983,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 4,
"selected": true,
"text": "<p>Test from the requirement : \"so you don't see the same images too often\"</p>\n\n<p>Ask for 100 images. Did you see an image too often?</p>\n"
},
{
"answer_id": 123059,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 3,
"selected": false,
"text": "<p>There is a handy list of <a href=\"http://en.wikipedia.org/wiki/Statistical_randomness\" rel=\"noreferrer\">statistical randomness</a> tests and <a href=\"http://en.wikipedia.org/wiki/Randomness_tests\" rel=\"noreferrer\">related research</a> on Wikipedia. Note that you won't know for certain that a source is truly random with most of these, you'll just have ruled out some ways in which it may be easily predictable.</p>\n"
},
{
"answer_id": 123097,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>To get a series of non-repeating random numbers:</p>\n\n<ol>\n<li>Create a list of random numbers.</li>\n<li>Add a sequence number to each random number</li>\n<li>Sort the sequenced list by the original random number</li>\n<li>Use your sequence number as a new random number.</li>\n</ol>\n"
},
{
"answer_id": 123107,
"author": "Illandril",
"author_id": 17887,
"author_profile": "https://Stackoverflow.com/users/17887",
"pm_score": 0,
"selected": false,
"text": "<p>Don't test the randomness, test to see if the results your getting are desirable (or, rather, try to get undesirable results a few times before accepting that your results are probably going to be desirable).\nIt will be impossible to ensure that you'll never get an undesirable result if you're testing a random output, but you can at least increase the chances that you'll notice it happening.</p>\n\n<p>I would either take N pools of Y size, checking for any results that appear more than X number of times, or take one pool of N*Y size, checking every group of Y size for any result that appears more than X times (1 to Y, 2 to Y + 1, 3 to Y + 2, etc). What N is would depend on how reliable you want the test to be.</p>\n"
},
{
"answer_id": 123112,
"author": "Joe Pineda",
"author_id": 21258,
"author_profile": "https://Stackoverflow.com/users/21258",
"pm_score": 1,
"selected": false,
"text": "<p>What the <em>Random</em> and similar functions give you is but pseudo-random numbers, a series of numbers produced through a function. Usually, you give that function it's first input parameter (a.k.a. the \"seed\") which is used to produce the first \"random\" number. After that, each last value is used as the input parameter for the next iteration of the cycle. You can check the Wikipedia article on \"Pseudorandom number generator\", the explanation there is very good.</p>\n\n<p>All of these algorithms have something in common: <strong>the series repeats itself after a number of iterations</strong>. Remember, these aren't truly random numbers, only series of numbers that <em>seem</em> random. To select one generator over another, you need to ask yourself: What do you want it for?</p>\n\n<p>How do you test randomness? Indeed you can. There are plenty of tests for that. The first and most simple is, of course, run your pseudo-random number generator an enormous number of times, and compile the number of times each result appears. In the end, each result should've appeared a number of times very close to (number of iterations)/(number of possible results). The greater the standard deviation of this, the worse your generator is.</p>\n\n<p>The second is: how much random numbers are you using at the time? 2, 3? Take them in pairs (or tripplets) and repeat the previous experiment: after a very long number of iterations, each expected result should have appeared at least once, and again the number of times each result has appeared shouldn't be too far away from the expected. There are some generators which work just fine for taking one or 2 at a time, but fail spectacularly when you're taking 3 or more (RANDU anyone?).</p>\n\n<p>There are other, more complex tests: some involve plotting the results in a logarithmic scale, or onto a plane with a circle in the middle and then counting how much of the plots fell within, others... I believe those 2 above should suffice most of the times (unless you're a finicky mathematician).</p>\n"
},
{
"answer_id": 123210,
"author": "jschultz",
"author_id": 16490,
"author_profile": "https://Stackoverflow.com/users/16490",
"pm_score": 0,
"selected": false,
"text": "<p>Random numbers are generated from a distribution. In this case, every value should have the same propability of appearing. If you calculate an infinite amount of randoms, you get the exact distribution. </p>\n\n<p>In practice, call the function many times and check the results. If you expect to have N images, calculate 100*N randoms, then count how many of each expected number were found. Most should appear 70-130 times. Re-run the test with different random-seed to see if the results are different. </p>\n\n<p>If you find the generator you use now is not good enough, you can easily find something. Google for \"Mersenne Twister\" - that is much more random than you ever need.</p>\n\n<p>To avoid images re-appearing, you need something less random. A simple approach would be to check for the unallowed values, if its one of those, re-calculate.</p>\n"
},
{
"answer_id": 123251,
"author": "C. Dragon 76",
"author_id": 5682,
"author_profile": "https://Stackoverflow.com/users/5682",
"pm_score": 0,
"selected": false,
"text": "<p>Although you cannot test for randomness, you can test that for correlation, or distribution, of a sequence of numbers.</p>\n\n<p>Hard to test goal: Each time we need an image, select 1 of 4 images at random.</p>\n\n<p>Easy to test goal: For every 100 images we select, each of the 4 images must appear at least 20 times.</p>\n"
},
{
"answer_id": 123451,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with Adam Rosenfield. For the situation you're talking about, the only thing you can usefully test for is distribution across the range.</p>\n\n<p>The situation I usually encounter is that I'm generating pseudorandom numbers with my favourite language's PRNG, and then manipulating them into the desired range. To check whether my manipulations have affected the distribution, I generate a bunch of numbers, manipulate them, and then check the distribution of the results.</p>\n\n<p>To get a good test, you should generate at least a couple orders of magnitude more numbers than your range holds. The more values you use, the better the test. Obviously if you have a really large range, this won't work since you'll have to generate far too many numbers. But in your situation it should work fine.</p>\n\n<p>Here's an example in Perl that illustrates what I mean:</p>\n\n<pre><code>for (my $i=0; $i<=100000; $i++) {\n my $r = rand; # Get the random number\n $r = int($r * 1000); # Move it into the desired range\n $dist{$r} ++; # Count the occurrences of each number\n}\n\nprint \"Min occurrences: \", (sort { $a <=> $b } values %dist)[1], \"\\n\";\nprint \"Max occurrences: \", (sort { $b <=> $a } values %dist)[1], \"\\n\";\n</code></pre>\n\n<p>If the spread between the min and max occurrences is small, then your distribution is good. If it's wide, then your distribution may be bad. You can also use this approach to check whether your range was covered and whether any values were missed.</p>\n\n<p>Again, the more numbers you generate, the more valid the results. I tend to start small and work up to whatever my machine will handle in a reasonable amount of time, e.g. five minutes.</p>\n"
},
{
"answer_id": 123822,
"author": "not-bob",
"author_id": 14770,
"author_profile": "https://Stackoverflow.com/users/14770",
"pm_score": 0,
"selected": false,
"text": "<p>Supposing you are testing a range for randomness within integers, one way to verify this is to create a gajillion (well, maybe 10,000 or so) 'random' numbers and plot their occurrence on a histogram.</p>\n\n<pre><code> ****** ****** ****\n***********************************************\n*************************************************\n*************************************************\n*************************************************\n*************************************************\n*************************************************\n*************************************************\n*************************************************\n*************************************************\n 1 2 3 4 5\n12345678901234567890123456789012345678901234567890\n</code></pre>\n\n<p>The above shows a 'relatively' normal distribution.</p>\n\n<p>if it looked more skewed, such as this:</p>\n\n<pre><code> ****** ****** ****\n ************ ************ ************\n ************ ************ ***************\n ************ ************ ****************\n ************ ************ *****************\n ************ ************ *****************\n *************************** ******************\n **************************** ******************\n******************************* ******************\n**************************************************\n 1 2 3 4 5\n12345678901234567890123456789012345678901234567890\n</code></pre>\n\n<p>Then you can see there is less randomness. As others have mentioned, there is the issue of repetition to contend with as well.</p>\n\n<p>If you were to write a binary file of say 10,000 random numbers from your generator using, say a random number from 1 to 1024 and try to compress that file using some compression (zip, gzip, etc.) then you could compare the two file sizes. If there is 'lots' of compression, then it's not particularly random. If there isn't much of a change in size, then it's 'pretty random'.</p>\n\n<p><strong>Why this works</strong></p>\n\n<p>The compression algorithms look for patterns (repetition and otherwise) and reduces that in some way. One way to look a these compression algorithms is a measure of the amount of information in a file. A highly compressed file has little information (e.g. randomness) and a little-compressed file has much information (randomness)</p>\n"
},
{
"answer_id": 125762,
"author": "pjf",
"author_id": 19422,
"author_profile": "https://Stackoverflow.com/users/19422",
"pm_score": 2,
"selected": false,
"text": "<p>There are whole books one can write about randomness and evaluating if something <em>appears</em> to be random, but I'll save you the pages of mathematics. In short, you can use a <a href=\"http://en.wikipedia.org/wiki/Pearson%27s_chi-square_test\" rel=\"nofollow noreferrer\">chi-square test</a> as a way of determining how well an apparently \"random\" distribution fits what you expect.</p>\n\n<p>If you're using Perl, you can use the <a href=\"http://search.cpan.org/perldo?Statistics::ChiSquare\" rel=\"nofollow noreferrer\">Statistics::ChiSquare</a> module to do the hard work for you.</p>\n\n<p>However if you want to make sure that your images are evenly <em>distributed</em>, then you probably won't want them to be truly random. Instead, I'd suggest you take your entire list of images, shuffle that list, and then remove an item from it whenever you need a \"random\" image. When the list is empty, you re-build it, re-shuffle, and repeat.</p>\n\n<p>This technique means that given a set of images, each individual image can't appear more than once every iteration through your list. Your images can't help but be evenly distributed.</p>\n\n<p>All the best,</p>\n\n<p>Paul</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
OK, I have been working on a random image selector and queue system (so you don't see the same images too often).
All was going swimmingly (as far as my crappy code does) **until** I got to the random bit. I wanted to test it, but how do you test for it? There is no `Debug.Assert(i.IsRandom)` (sadly) :D
So, I got my brain on it after watering it with some tea and came up with the following, I was just wondering if I could have your thoughts?
* Basically I knew the **random** bit was the problem, so I ripped that out to a delegate (which would then be passed to the objects constructor).
* I then created a class that pretty much performs the same logic as the *live* code, but remembers the value selected in a private variable.
* I then threw that delegate to the live class and tested against that:
i.e.
```
Debug.Assert(myObj.RndVal == RndIntTester.ValuePassed);
```
But I couldn't help but think, **was I wasting my time?** I ran that through lots of iterations to see if it fell over at any time etc.
Do you think I was wasting my time with this? Or could I have got away with:

[GateKiller's answer](https://stackoverflow.com/questions/122741/testing-for-random-value-thoughts-on-this-approach#122765) reminded me of this:

Update to Clarify
-----------------
* **I should add that I basically never want to see the same result more than X number of times from a pool of Y size.**
* The addition of the test container basically allowed me to see if any of the previously selected images were "randomly" selected.
* I guess technically the thing here being tested in not the RNG (since I never wrote that code) but the fact that am I expecting *random* results from a limited pool, and I want to track them.
|
Test from the requirement : "so you don't see the same images too often"
Ask for 100 images. Did you see an image too often?
|
122,752 |
<p>I've seen <a href="https://stackoverflow.com/questions/55622/best-tools-for-working-with-docbook-xml-documents">Best tools for working with DocBook XML documents</a>, but my question is slightly different. Which is the currently recommended formatting toolchain - as opposed to editing tool - for XML DocBook?</p>
<p>In Eric Raymond's <a href="https://rads.stackoverflow.com/amzn/click/com/0131429019" rel="nofollow noreferrer" rel="nofollow noreferrer">'The Art of Unix Programming'</a> from 2003 (an excellent book!), the suggestion is XML-FO (XML Formatting Objects), but I've since seen suggestions here that indicated that XML-FO is no longer under development (though I can no longer find that question on StackOverflow, so maybe it was erroneous).</p>
<p>Assume I'm primarily interested in Unix/Linux (including MacOS X), but I wouldn't automatically ignore Windows-only solutions.</p>
<p>Is <a href="http://xmlgraphics.apache.org/fop/" rel="nofollow noreferrer">Apache's FOP</a> the best way to go? Are there any alternatives?</p>
|
[
{
"answer_id": 122791,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 2,
"selected": false,
"text": "<p>A popular approach is to use <a href=\"http://docbook.sourceforge.net/\" rel=\"nofollow noreferrer\">DocBook XSL Stylesheets</a>.</p>\n"
},
{
"answer_id": 122922,
"author": "Gustavo Carreno",
"author_id": 8167,
"author_profile": "https://Stackoverflow.com/users/8167",
"pm_score": 5,
"selected": true,
"text": "<p>I've been doing some manual writing with DocBook, under cygwin, to produce One Page HTML, Many Pages HTML, CHM and PDF.</p>\n\n<p>I installed the following:</p>\n\n<ol>\n<li>The <a href=\"http://www.docbook.org\" rel=\"nofollow noreferrer\">docbook</a> stylesheets (xsl) repository.</li>\n<li>xmllint, to test if the xml is correct.</li>\n<li>xsltproc, to process the xml with the stylesheets.</li>\n<li><a href=\"http://xmlgraphics.apache.org/fop/download.html\" rel=\"nofollow noreferrer\">Apache's fop</a>, to produce PDF's.I make sure to add the installed folder to the PATH.</li>\n<li>Microsoft's <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=00535334-c8a6-452f-9aa0-d597d16580cc&displaylang=en\" rel=\"nofollow noreferrer\">HTML Help Workshop</a>, to produce CHM's. I make sure to add the installed folder to the PATH.</li>\n</ol>\n\n<p><strong>Edit</strong>: In the below code I'm using more than the 2 files. If someone wants a cleaned up version of the scripts and the folder structure, please contact me: guscarreno (squiggly/at) googlemail (period/dot) com</p>\n\n<p>I then use a configure.in: </p>\n\n<pre><code>AC_INIT(Makefile.in)\n\nFOP=fop.sh\nHHC=hhc\nXSLTPROC=xsltproc\n\nAC_ARG_WITH(fop, [ --with-fop Where to find Apache FOP],\n[\n if test \"x$withval\" != \"xno\"; then\n FOP=\"$withval\"\n fi\n]\n)\nAC_PATH_PROG(FOP, $FOP)\n\nAC_ARG_WITH(hhc, [ --with-hhc Where to find Microsoft Help Compiler],\n[\n if test \"x$withval\" != \"xno\"; then\n HHC=\"$withval\"\n fi\n]\n)\nAC_PATH_PROG(HHC, $HHC)\n\nAC_ARG_WITH(xsltproc, [ --with-xsltproc Where to find xsltproc],\n[\n if test \"x$withval\" != \"xno\"; then\n XSLTPROC=\"$withval\"\n fi\n]\n)\nAC_PATH_PROG(XSLTPROC, $XSLTPROC)\n\nAC_SUBST(FOP)\nAC_SUBST(HHC)\nAC_SUBST(XSLTPROC)\n\nHERE=`pwd`\nAC_SUBST(HERE)\nAC_OUTPUT(Makefile)\n\ncat > config.nice <<EOT\n#!/bin/sh\n./configure \\\n --with-fop='$FOP' \\\n --with-hhc='$HHC' \\\n --with-xsltproc='$XSLTPROC' \\\n\nEOT\nchmod +x config.nice\n</code></pre>\n\n<p>and a Makefile.in: </p>\n\n<pre><code>FOP=@FOP@\nHHC=@HHC@\nXSLTPROC=@XSLTPROC@\nHERE=@HERE@\n\n# Subdirs that contain docs\nDOCS=appendixes chapters reference \n\nXML_CATALOG_FILES=./build/docbook-xsl-1.71.0/catalog.xml\nexport XML_CATALOG_FILES\n\nall: entities.ent manual.xml html\n\nclean:\n@echo -e \"\\n=== Cleaning\\n\"\n@-rm -f html/*.html html/HTML.manifest pdf/* chm/*.html chm/*.hhp chm/*.hhc chm/*.chm entities.ent .ent\n@echo -e \"Done.\\n\"\n\ndist-clean:\n@echo -e \"\\n=== Restoring defaults\\n\"\n@-rm -rf .ent autom4te.cache config.* configure Makefile html/*.html html/HTML.manifest pdf/* chm/*.html chm/*.hhp chm/*.hhc chm/*.chm build/docbook-xsl-1.71.0\n@echo -e \"Done.\\n\"\n\nentities.ent: ./build/mkentities.sh $(DOCS)\n@echo -e \"\\n=== Creating entities\\n\"\n@./build/mkentities.sh $(DOCS) > .ent\n@if [ ! -f entities.ent ] || [ ! cmp entities.ent .ent ]; then mv .ent entities.ent ; fi\n@echo -e \"Done.\\n\"\n\n# Build the docs in chm format\n\nchm: chm/htmlhelp.hpp\n@echo -e \"\\n=== Creating CHM\\n\"\n@echo logo.png >> chm/htmlhelp.hhp\n@echo arrow.gif >> chm/htmlhelp.hhp\n@-cd chm && \"$(HHC)\" htmlhelp.hhp\n@echo -e \"Done.\\n\"\n\nchm/htmlhelp.hpp: entities.ent build/docbook-xsl manual.xml build/chm.xsl\n@echo -e \"\\n=== Creating input for CHM\\n\"\n@\"$(XSLTPROC)\" --output ./chm/index.html ./build/chm.xsl manual.xml\n\n# Build the docs in HTML format\n\nhtml: html/index.html\n\nhtml/index.html: entities.ent build/docbook-xsl manual.xml build/html.xsl\n@echo -e \"\\n=== Creating HTML\\n\"\n@\"$(XSLTPROC)\" --output ./html/index.html ./build/html.xsl manual.xml\n@echo -e \"Done.\\n\"\n\n# Build the docs in PDF format\n\npdf: pdf/manual.fo\n@echo -e \"\\n=== Creating PDF\\n\"\n@\"$(FOP)\" ./pdf/manual.fo ./pdf/manual.pdf\n@echo -e \"Done.\\n\"\n\npdf/manual.fo: entities.ent build/docbook-xsl manual.xml build/pdf.xsl\n@echo -e \"\\n=== Creating input for PDF\\n\"\n@\"$(XSLTPROC)\" --output ./pdf/manual.fo ./build/pdf.xsl manual.xml\n\ncheck: manual.xml\n@echo -e \"\\n=== Checking correctness of manual\\n\"\n@xmllint --valid --noout --postvalid manual.xml\n@echo -e \"Done.\\n\"\n\n# need to touch the dir because the timestamp in the tarball\n# is older than that of the tarball :)\nbuild/docbook-xsl: build/docbook-xsl-1.71.0.tar.gz\n@echo -e \"\\n=== Un-taring docbook-xsl\\n\"\n@cd build && tar xzf docbook-xsl-1.71.0.tar.gz && touch docbook-xsl-1.71.0\n</code></pre>\n\n<p>to automate the production of the above mentioned file outputs.</p>\n\n<p>I prefer to use a nix approach to the scripting just because the toolset is more easy to find and use, not to mention easier to chain.</p>\n"
},
{
"answer_id": 123379,
"author": "Palmin",
"author_id": 5949,
"author_profile": "https://Stackoverflow.com/users/5949",
"pm_score": 2,
"selected": false,
"text": "<p>Regarding the question about Apache's FOP: when we established our toolchain (similar to what Gustavo has suggested) we had very good results using the <a href=\"http://www.renderx.com/tools/xep.html\" rel=\"nofollow noreferrer\">RenderX XEP engine</a>. XEPs output looks a little bit more polished, and as far as I recall, FOP had some problems with tables (this was a few years ago though, this might have changed).</p>\n"
},
{
"answer_id": 266134,
"author": "Dick",
"author_id": 34785,
"author_profile": "https://Stackoverflow.com/users/34785",
"pm_score": 2,
"selected": false,
"text": "<p>The DocBook stylesheets, plus FOP, work well, but I finally decided to spring for RenderX, which covers the standard more thoroughly and has some nice extensions that the DocBook stylesheets take advantage of.</p>\n\n<p>Bob Stayton's book, <a href=\"http://www.sagehill.net/index.html\" rel=\"nofollow noreferrer\">DocBook XSL: The Complete Guide</a>, describes several alternate tool chains, including ones that work on Linux or Windows (almost surely MacOS, too, though I have not personally used a Mac).</p>\n"
},
{
"answer_id": 875036,
"author": "Oliver Drotbohm",
"author_id": 18122,
"author_profile": "https://Stackoverflow.com/users/18122",
"pm_score": 3,
"selected": false,
"text": "<p>We use <a href=\"http://www.xmlmind.com/xmleditor/\" rel=\"noreferrer\">XMLmind XmlEdit</a> for editing and Maven's <a href=\"http://docs.codehaus.org/display/MAVENUSER/Docbkx+Maven+Plugin\" rel=\"noreferrer\">docbkx</a> plugin to create output during our builds. For a set of good templates take a look at the ones <a href=\"http://www.hibernate.org\" rel=\"noreferrer\">Hibernate</a> or <a href=\"http://www.springframework.org\" rel=\"noreferrer\">Spring</a> provide.</p>\n"
},
{
"answer_id": 879318,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 3,
"selected": false,
"text": "<p>For HTML output, I use the <a href=\"http://docbook.sourceforge.net/\" rel=\"noreferrer\">Docbook XSL stylesheets</a> with the XSLT processor xsltproc.</p>\n\n<p>For PDF output, I use <a href=\"http://dblatex.sourceforge.net/\" rel=\"noreferrer\">dblatex</a>, which translates to LaTeX and then use pdflatex to compile it to PDF. (I used Jade, the DSSSL stylesheets and jadetex before.)</p>\n"
},
{
"answer_id": 2165076,
"author": "Verhagen",
"author_id": 261378,
"author_profile": "https://Stackoverflow.com/users/261378",
"pm_score": 3,
"selected": false,
"text": "<p>We use</p>\n\n<ul>\n<li><a href=\"http://www.serna-xmleditor.com/\" rel=\"nofollow noreferrer\">Serna XML Editor</a></li>\n<li>Eclipse (plain xml editing, mostly used by the technical people)</li>\n<li>own specific Eclipse plug-in (just for our release-notes)</li>\n<li>Maven docbkx plug-in</li>\n<li>Maven jar with specific corporate style sheet, based on the standard docbook style-sheets</li>\n<li>Maven plug-in for converting csv to DocBook table</li>\n<li>Maven plug-in for extracting BugZilla data and creating a DocBook section from it</li>\n<li>Hudson (to generate the PDF document(s))</li>\n<li>Nexus to deploy the created PDF documents</li>\n</ul>\n\n<p>Some ideas we have:</p>\n\n<p>Deploy with each product version not only the PDF, but also the original complete DocBook document (as we partly write the document and partly generate them). Saving the full DocBook document makes them independent for changes in the system setup in the future. Meaning, if the system changes, from which the content was extracted (or replaced by diff. systems) we would not be able to generate the exact content any more. Which could cause an issue, if we needed to re-release (with different style-sheet) the whole product ranche of manuals. Same as with the jars; these compiled Java classes are also placed in Nexus (you do not want to store them in your SCM); this we would also do with the generated DocBook document.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>Fresh created a <em>Maven HTML Cleaner Plug-in</em>, which makes it possible to <a href=\"http://docbook-utils.sourceforge.net/maven-html-cleaner-plugin_1.0/docbook/article-quick-start-docbook.html\" rel=\"nofollow noreferrer\">add DocBook content to a Maven Project Site</a> (Beta version available). Feedback is welcome through the <a href=\"https://sourceforge.net/projects/docbook-utils/forums/forum/1123044\" rel=\"nofollow noreferrer\">Open Discussion</a> Forum.</p>\n"
},
{
"answer_id": 2403356,
"author": "Liz Fraley",
"author_id": 289015,
"author_profile": "https://Stackoverflow.com/users/289015",
"pm_score": 2,
"selected": false,
"text": "<p>With FOP you get the features that someone decided they wanted bad enough to implement. I'd say that no one who's serious about publishing uses it in production. You're far better off with RenderX or Antenna House or <a href=\"http://single-sourcing.com/products/arbortext/publishing.html?utm_source=stackoverflow&utm_medium=comment&utm_term=fop&utm_content=ati&utm_campaign=us\" rel=\"nofollow noreferrer\">Arbortext</a>. (I've used them all over the last decade's worth of implementation projects.) It depends on your business requirements, how much you want to automate, and what your team's skills, time, and resources are like as well. It's not just a technology question.</p>\n"
},
{
"answer_id": 3030289,
"author": "uman",
"author_id": 319190,
"author_profile": "https://Stackoverflow.com/users/319190",
"pm_score": 2,
"selected": false,
"text": "<p>If you're on Red Hat, Ubuntu, or Windows, you could take a look at Publican, which is supposed to be a fairly complete command line toolchain. Red Hat uses it extensively.</p>\n\n<ul>\n<li>Wiki here: <a href=\"https://fedorahosted.org/publican/\" rel=\"nofollow noreferrer\">https://fedorahosted.org/publican/</a></li>\n<li>Doc here: <a href=\"http://jfearn.fedorapeople.org/Publican/\" rel=\"nofollow noreferrer\">http://jfearn.fedorapeople.org/Publican/</a></li>\n<li>Source tarballs and exes here: <a href=\"https://fedorahosted.org/releases/p/u/publican/\" rel=\"nofollow noreferrer\">https://fedorahosted.org/releases/p/u/publican/</a></li>\n</ul>\n"
},
{
"answer_id": 5465213,
"author": "Dave Thompson",
"author_id": 680984,
"author_profile": "https://Stackoverflow.com/users/680984",
"pm_score": 2,
"selected": false,
"text": "<p>I release/am working on an open-source project called bookshop which is a RubyGem that installs a complete Docbook-XSL pipeline/toolchain. It includes everything needed to create and edit Docbook source files and output differing formats (currently pdf and epub, and growing quickly).</p>\n\n<p>My goal is to make it possible to go from Zero-to-Exporting(pdf's or whatever) from your Docbook source in under 10 minutes.</p>\n\n<p>The Summary:</p>\n\n<p>bookShop is an OSS ruby-based framework for docbook toolchain happiness and sustainable productivity. The framework is optimized to help developers quickly ramp-up, allowing them to more rapidly jump in and develop their DocBook-to-Output flows, by favoring convention over configuration, setting them up with best practices, standards and tools from the get-go.</p>\n\n<p>Here's the gem location: <a href=\"https://rubygems.org/gems/bookshop\" rel=\"nofollow\">https://rubygems.org/gems/bookshop</a></p>\n\n<p>And the source code: <a href=\"https://github.com/blueheadpublishing/bookshop\" rel=\"nofollow\">https://github.com/blueheadpublishing/bookshop</a></p>\n"
},
{
"answer_id": 10746691,
"author": "Ishan De Silva",
"author_id": 813976,
"author_profile": "https://Stackoverflow.com/users/813976",
"pm_score": 2,
"selected": false,
"text": "<p>The article called <a href=\"http://en.tldp.org/HOWTO/DocBook-Demystification-HOWTO/x128.html\" rel=\"nofollow\">The DocBook toolchain</a> might be useful as well. It is a section of a <a href=\"http://en.tldp.org/HOWTO/DocBook-Demystification-HOWTO/index.html\" rel=\"nofollow\">HOWTO</a> on DocBook written by Eric Raymond.</p>\n"
},
{
"answer_id": 13019236,
"author": "Ismael Olea",
"author_id": 902251,
"author_profile": "https://Stackoverflow.com/users/902251",
"pm_score": 2,
"selected": false,
"text": "<p>I've been using two CLI utils for simplifying my docbook toolchain: xmlto and publican.</p>\n\n<p>Publican looks elegant to me but enough fitted for the Fedora & Redhat publication needs.</p>\n\n<ul>\n<li><a href=\"https://fedorahosted.org/xmlto/\" rel=\"nofollow\">https://fedorahosted.org/xmlto/</a></li>\n<li><a href=\"https://fedorahosted.org/publican/\" rel=\"nofollow\">https://fedorahosted.org/publican/</a></li>\n</ul>\n"
},
{
"answer_id": 18566432,
"author": "Ajay",
"author_id": 1944101,
"author_profile": "https://Stackoverflow.com/users/1944101",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer using Windows for most of my content creation (Notepad++ editor). Publican in Linux is a good tool chain to create a good documentation structure and process outputs. I use Dropbox (there are other document sharing services as well, which should work well on both platforms) on my Windows machine as well as Virtual Linux machine. \nWith this setup I've been able to achieve a combination that works great for me.\nOnce edit work is completed in Windows (which immediately syncs to Linux machine), I switch to Linux to run publican build and create HTML and PDF outputs, which again are updated in my Windows folder by Dropbox.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15168/"
] |
I've seen [Best tools for working with DocBook XML documents](https://stackoverflow.com/questions/55622/best-tools-for-working-with-docbook-xml-documents), but my question is slightly different. Which is the currently recommended formatting toolchain - as opposed to editing tool - for XML DocBook?
In Eric Raymond's ['The Art of Unix Programming'](https://rads.stackoverflow.com/amzn/click/com/0131429019) from 2003 (an excellent book!), the suggestion is XML-FO (XML Formatting Objects), but I've since seen suggestions here that indicated that XML-FO is no longer under development (though I can no longer find that question on StackOverflow, so maybe it was erroneous).
Assume I'm primarily interested in Unix/Linux (including MacOS X), but I wouldn't automatically ignore Windows-only solutions.
Is [Apache's FOP](http://xmlgraphics.apache.org/fop/) the best way to go? Are there any alternatives?
|
I've been doing some manual writing with DocBook, under cygwin, to produce One Page HTML, Many Pages HTML, CHM and PDF.
I installed the following:
1. The [docbook](http://www.docbook.org) stylesheets (xsl) repository.
2. xmllint, to test if the xml is correct.
3. xsltproc, to process the xml with the stylesheets.
4. [Apache's fop](http://xmlgraphics.apache.org/fop/download.html), to produce PDF's.I make sure to add the installed folder to the PATH.
5. Microsoft's [HTML Help Workshop](http://www.microsoft.com/downloads/details.aspx?FamilyID=00535334-c8a6-452f-9aa0-d597d16580cc&displaylang=en), to produce CHM's. I make sure to add the installed folder to the PATH.
**Edit**: In the below code I'm using more than the 2 files. If someone wants a cleaned up version of the scripts and the folder structure, please contact me: guscarreno (squiggly/at) googlemail (period/dot) com
I then use a configure.in:
```
AC_INIT(Makefile.in)
FOP=fop.sh
HHC=hhc
XSLTPROC=xsltproc
AC_ARG_WITH(fop, [ --with-fop Where to find Apache FOP],
[
if test "x$withval" != "xno"; then
FOP="$withval"
fi
]
)
AC_PATH_PROG(FOP, $FOP)
AC_ARG_WITH(hhc, [ --with-hhc Where to find Microsoft Help Compiler],
[
if test "x$withval" != "xno"; then
HHC="$withval"
fi
]
)
AC_PATH_PROG(HHC, $HHC)
AC_ARG_WITH(xsltproc, [ --with-xsltproc Where to find xsltproc],
[
if test "x$withval" != "xno"; then
XSLTPROC="$withval"
fi
]
)
AC_PATH_PROG(XSLTPROC, $XSLTPROC)
AC_SUBST(FOP)
AC_SUBST(HHC)
AC_SUBST(XSLTPROC)
HERE=`pwd`
AC_SUBST(HERE)
AC_OUTPUT(Makefile)
cat > config.nice <<EOT
#!/bin/sh
./configure \
--with-fop='$FOP' \
--with-hhc='$HHC' \
--with-xsltproc='$XSLTPROC' \
EOT
chmod +x config.nice
```
and a Makefile.in:
```
FOP=@FOP@
HHC=@HHC@
XSLTPROC=@XSLTPROC@
HERE=@HERE@
# Subdirs that contain docs
DOCS=appendixes chapters reference
XML_CATALOG_FILES=./build/docbook-xsl-1.71.0/catalog.xml
export XML_CATALOG_FILES
all: entities.ent manual.xml html
clean:
@echo -e "\n=== Cleaning\n"
@-rm -f html/*.html html/HTML.manifest pdf/* chm/*.html chm/*.hhp chm/*.hhc chm/*.chm entities.ent .ent
@echo -e "Done.\n"
dist-clean:
@echo -e "\n=== Restoring defaults\n"
@-rm -rf .ent autom4te.cache config.* configure Makefile html/*.html html/HTML.manifest pdf/* chm/*.html chm/*.hhp chm/*.hhc chm/*.chm build/docbook-xsl-1.71.0
@echo -e "Done.\n"
entities.ent: ./build/mkentities.sh $(DOCS)
@echo -e "\n=== Creating entities\n"
@./build/mkentities.sh $(DOCS) > .ent
@if [ ! -f entities.ent ] || [ ! cmp entities.ent .ent ]; then mv .ent entities.ent ; fi
@echo -e "Done.\n"
# Build the docs in chm format
chm: chm/htmlhelp.hpp
@echo -e "\n=== Creating CHM\n"
@echo logo.png >> chm/htmlhelp.hhp
@echo arrow.gif >> chm/htmlhelp.hhp
@-cd chm && "$(HHC)" htmlhelp.hhp
@echo -e "Done.\n"
chm/htmlhelp.hpp: entities.ent build/docbook-xsl manual.xml build/chm.xsl
@echo -e "\n=== Creating input for CHM\n"
@"$(XSLTPROC)" --output ./chm/index.html ./build/chm.xsl manual.xml
# Build the docs in HTML format
html: html/index.html
html/index.html: entities.ent build/docbook-xsl manual.xml build/html.xsl
@echo -e "\n=== Creating HTML\n"
@"$(XSLTPROC)" --output ./html/index.html ./build/html.xsl manual.xml
@echo -e "Done.\n"
# Build the docs in PDF format
pdf: pdf/manual.fo
@echo -e "\n=== Creating PDF\n"
@"$(FOP)" ./pdf/manual.fo ./pdf/manual.pdf
@echo -e "Done.\n"
pdf/manual.fo: entities.ent build/docbook-xsl manual.xml build/pdf.xsl
@echo -e "\n=== Creating input for PDF\n"
@"$(XSLTPROC)" --output ./pdf/manual.fo ./build/pdf.xsl manual.xml
check: manual.xml
@echo -e "\n=== Checking correctness of manual\n"
@xmllint --valid --noout --postvalid manual.xml
@echo -e "Done.\n"
# need to touch the dir because the timestamp in the tarball
# is older than that of the tarball :)
build/docbook-xsl: build/docbook-xsl-1.71.0.tar.gz
@echo -e "\n=== Un-taring docbook-xsl\n"
@cd build && tar xzf docbook-xsl-1.71.0.tar.gz && touch docbook-xsl-1.71.0
```
to automate the production of the above mentioned file outputs.
I prefer to use a nix approach to the scripting just because the toolset is more easy to find and use, not to mention easier to chain.
|
122,763 |
<p>I have a dict, that looks like this:</p>
<pre><code>{
'foo': {
'opt1': 1,
'opt2': 2,
},
'foo/bar': {
'opt3': 3,
'opt4': 4,
},
'foo/bar/baz': {
'opt5': 5,
'opt6': 6,
}
}
</code></pre>
<p>And I need to get it to look like:</p>
<pre><code>{
'foo': {
'opt1': 1,
'opt2': 2,
'bar': {
'opt3': 3,
'opt4': 4,
'baz': {
'opt5': 5,
'opt6': 6,
}
}
}
}
</code></pre>
<p>I should point out that there can and will be multiple top-level keys ('foo' in this case). I could probably throw something together to get what i need, but I was hoping that there is a solution that's more efficient.</p>
|
[
{
"answer_id": 122785,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 4,
"selected": true,
"text": "<p>Like this:</p>\n\n<pre><code>def nest(d):\n rv = {}\n for key, value in d.iteritems():\n node = rv\n for part in key.split('/'):\n node = node.setdefault(part, {})\n node.update(value)\n return rv\n</code></pre>\n"
},
{
"answer_id": 122812,
"author": "Mike Elkins",
"author_id": 19193,
"author_profile": "https://Stackoverflow.com/users/19193",
"pm_score": 1,
"selected": false,
"text": "<pre><code>def layer(dict):\n for k,v in dict:\n if '/' in k:\n del dict[k]\n subdict = dict.get(k[:k.find('/')],{})\n subdict[k[k.find('/')+1:]] = v\n layer(subdict)\n</code></pre>\n"
},
{
"answer_id": 47448562,
"author": "Manoj Jadhav",
"author_id": 6165783,
"author_profile": "https://Stackoverflow.com/users/6165783",
"pm_score": 0,
"selected": false,
"text": "<p>Got this lib to print your dict in a better way. <code>pprint</code>.\n <code>https://docs.python.org/3.2/library/pprint.html</code></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18866/"
] |
I have a dict, that looks like this:
```
{
'foo': {
'opt1': 1,
'opt2': 2,
},
'foo/bar': {
'opt3': 3,
'opt4': 4,
},
'foo/bar/baz': {
'opt5': 5,
'opt6': 6,
}
}
```
And I need to get it to look like:
```
{
'foo': {
'opt1': 1,
'opt2': 2,
'bar': {
'opt3': 3,
'opt4': 4,
'baz': {
'opt5': 5,
'opt6': 6,
}
}
}
}
```
I should point out that there can and will be multiple top-level keys ('foo' in this case). I could probably throw something together to get what i need, but I was hoping that there is a solution that's more efficient.
|
Like this:
```
def nest(d):
rv = {}
for key, value in d.iteritems():
node = rv
for part in key.split('/'):
node = node.setdefault(part, {})
node.update(value)
return rv
```
|
122,772 |
<p>When I try to display the contents of a LOB (large object) column in SQL*Plus, it is truncated. How do I display the whole thing?</p>
|
[
{
"answer_id": 122776,
"author": "Anonymoose",
"author_id": 2391,
"author_profile": "https://Stackoverflow.com/users/2391",
"pm_score": 7,
"selected": true,
"text": "<pre><code>SQL> set long 30000\nSQL> show long\nlong 30000\n</code></pre>\n"
},
{
"answer_id": 7272671,
"author": "Kevin O'Donnell",
"author_id": 203789,
"author_profile": "https://Stackoverflow.com/users/203789",
"pm_score": 4,
"selected": false,
"text": "<p>You may also need:</p>\n\n<pre><code>SQL> set longchunksize 30000\n</code></pre>\n\n<p>Otherwise the LOB/CLOB will wrap.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2391/"
] |
When I try to display the contents of a LOB (large object) column in SQL\*Plus, it is truncated. How do I display the whole thing?
|
```
SQL> set long 30000
SQL> show long
long 30000
```
|
122,778 |
<p>Under VS's external tools settings there is a "Use Output Window" check box that captures the tools command line output and dumps it to a VS tab.</p>
<p>The question is: <em>can I get the same processing for my program when I hit F5?</em></p>
<p><strong>Edit:</strong> FWIW I'm in C# but if that makes a difference to your answer then it's unlikely that your answer is what I'm looking for.</p>
<p>What I want would take the output stream of the program and transfer it to the output tab in VS using the same devices that output redirection ('|' and '>') uses in the cmd prompt.</p>
|
[
{
"answer_id": 122988,
"author": "ScaleOvenStove",
"author_id": 12268,
"author_profile": "https://Stackoverflow.com/users/12268",
"pm_score": 0,
"selected": false,
"text": "<p>System.Diagnostics.Debug.Writeline() or Trace.Writeline()</p>\n"
},
{
"answer_id": 122991,
"author": "cori",
"author_id": 8151,
"author_profile": "https://Stackoverflow.com/users/8151",
"pm_score": 0,
"selected": false,
"text": "<p>You can use Systems.Diagnostics.Trace class to write your output to the Output window instead of (or in addition to) the console. It take a little configuration, but it works. Is that along the line of what you want?</p>\n\n<p>You can also add your own tab per <a href=\"http://www.knowdotnet.com/articles/outputwindow.html\" rel=\"nofollow noreferrer\">this article</a>, but I've never tried it.</p>\n"
},
{
"answer_id": 123067,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 2,
"selected": true,
"text": "<p>I'm going to make a few assumptions here. First, I presume that you are talking about printf output from an application (whether it be from a console app or from a windows GUI app). My second assumption is the C language.</p>\n\n<p><em>To my knowledge, you cannot direct printf output to the output window in dev studio, not directly anyway.</em> <sub>[emphasis added by OP]</sub></p>\n\n<p>There might be a way but I'm not aware of it. One thing that you could do though would be to direct printf function calls to your own routine which will</p>\n\n<ol>\n<li>call printf and print the string</li>\n<li>call OuputDebugString() to print the string to the output window</li>\n</ol>\n\n<p>You could do several things to accomplish this goal. First would be to write your own printf function and then call printf and the OuputDebugString()</p>\n\n<pre><code>void my_printf(const char *format, ...)\n{\n char buf[2048];\n\n // get the arg list and format it into a string\n va_start(arglist, format);\n vsprintf_s(buf, 2048, format, arglist);\n va_end(arglist); \n\n vprintf_s(buf); // prints to the standard output stream\n OutputDebugString(buf); // prints to the output window\n}\n</code></pre>\n\n<p>The code above is mostly untested, but it should get the concepts across.</p>\n\n<p>If you are not doing this in C/C++, then this method won't work for you. :-) </p>\n"
},
{
"answer_id": 125492,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to capture the output in a text file and use that.</p>\n\n<p>I don't have a VS handy, so this is from memory:</p>\n\n<ol>\n<li>Create a C++ project</li>\n<li>Open the project settings, debugging tab</li>\n<li>Enable managed debugging</li>\n<li>Edit command line to add \"<code>> output.txt</code>\"</li>\n<li>Run your program under the debugger</li>\n</ol>\n\n<p>If things work the way I remember, this will redirect STDOUT to a file, even though you're not actually running under CMD.EXE. </p>\n\n<p>(The debugger has its own implementation of redirection syntax, which is not 100% the same as cmd, but it's pretty good.)</p>\n\n<p>Now, if you open this file in VS, you can still see the output from within VS, although not in exactly the same window you were hoping for.</p>\n"
},
{
"answer_id": 125509,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe this will work for you: set a breakpoint on the close <code>}</code> in <code>Main</code>, and then look at the console window before it closes. You can even copy the text out of it if you need to.</p>\n\n<p>On every machine that I use for development, I configure my console window in a certain way, which happens to make this approach work better:</p>\n\n<ol>\n<li>Run cmd.exe</li>\n<li>ALT-SPACE, D</li>\n<li>In Options, enable QuickEdit mode.</li>\n<li>In Layout, set Buffer Height to 9999</li>\n<li>Click OK</li>\n<li>Exit the CMD window.</li>\n</ol>\n"
},
{
"answer_id": 5577787,
"author": "Carl R",
"author_id": 480986,
"author_profile": "https://Stackoverflow.com/users/480986",
"pm_score": 2,
"selected": false,
"text": "<p>The console can redirect it's output to any textwriter. If you implement a textwriter that writes to Diagnostics.Debug, you are all set.</p>\n\n<p>Here's a textwriter that writes to the debugger.</p>\n\n<pre><code>using System.Diagnostics;\nusing System.IO;\nusing System.Text;\n\nnamespace TestConsole\n{\n public class DebugTextWriter : TextWriter\n {\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n }\n\n //Required\n public override void Write(char value)\n {\n Debug.Write(value);\n }\n\n //Added for efficiency\n public override void Write(string value)\n {\n Debug.Write(value);\n }\n\n //Added for efficiency\n public override void WriteLine(string value)\n {\n Debug.WriteLine(value);\n }\n }\n}\n</code></pre>\n\n<p>Since it uses Diagnostics.Debug it will adhere to your compiler settings to wether it should write any output or not. This output can also be seen in Sysinternals DebugView.</p>\n\n<p>Here's how you use it:</p>\n\n<pre><code>using System;\n\nnamespace TestConsole\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.SetOut(new DebugTextWriter());\n Console.WriteLine(\"This text goes to the Visual Studio output window.\");\n }\n }\n}\n</code></pre>\n\n<p>If you want to see the output in Sysinternals DebugView when you are compiling in Release mode, you can use a TextWriter that writes to the OutputDebugString API. It could look like this:</p>\n\n<pre><code>using System.IO;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace TestConsole\n{\n public class OutputDebugStringTextWriter : TextWriter\n {\n [DllImport(\"kernel32.dll\")]\n static extern void OutputDebugString(string lpOutputString);\n\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n }\n\n //Required\n public override void Write(char value)\n {\n OutputDebugString(value.ToString());\n }\n\n //Added for efficiency\n public override void Write(string value)\n {\n OutputDebugString(value);\n }\n\n //Added for efficiency\n public override void WriteLine(string value)\n {\n OutputDebugString(value);\n }\n }\n}\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
Under VS's external tools settings there is a "Use Output Window" check box that captures the tools command line output and dumps it to a VS tab.
The question is: *can I get the same processing for my program when I hit F5?*
**Edit:** FWIW I'm in C# but if that makes a difference to your answer then it's unlikely that your answer is what I'm looking for.
What I want would take the output stream of the program and transfer it to the output tab in VS using the same devices that output redirection ('|' and '>') uses in the cmd prompt.
|
I'm going to make a few assumptions here. First, I presume that you are talking about printf output from an application (whether it be from a console app or from a windows GUI app). My second assumption is the C language.
*To my knowledge, you cannot direct printf output to the output window in dev studio, not directly anyway.* [emphasis added by OP]
There might be a way but I'm not aware of it. One thing that you could do though would be to direct printf function calls to your own routine which will
1. call printf and print the string
2. call OuputDebugString() to print the string to the output window
You could do several things to accomplish this goal. First would be to write your own printf function and then call printf and the OuputDebugString()
```
void my_printf(const char *format, ...)
{
char buf[2048];
// get the arg list and format it into a string
va_start(arglist, format);
vsprintf_s(buf, 2048, format, arglist);
va_end(arglist);
vprintf_s(buf); // prints to the standard output stream
OutputDebugString(buf); // prints to the output window
}
```
The code above is mostly untested, but it should get the concepts across.
If you are not doing this in C/C++, then this method won't work for you. :-)
|
122,781 |
<p>I have a page in my desktop app, and I've implemented simple grab-and-pan. It works great.</p>
<p>When you are panning in this way and you are release, the page stops dead where you dropped it.</p>
<p>I'd like it to continue slightly with some momentum, and stop eventually. Rather like the 'throw' in the iPhone UI, I guess.</p>
<p>I'm not really chasing perfection, just a very crude simple sense of being able to 'throw' that page.</p>
|
[
{
"answer_id": 122988,
"author": "ScaleOvenStove",
"author_id": 12268,
"author_profile": "https://Stackoverflow.com/users/12268",
"pm_score": 0,
"selected": false,
"text": "<p>System.Diagnostics.Debug.Writeline() or Trace.Writeline()</p>\n"
},
{
"answer_id": 122991,
"author": "cori",
"author_id": 8151,
"author_profile": "https://Stackoverflow.com/users/8151",
"pm_score": 0,
"selected": false,
"text": "<p>You can use Systems.Diagnostics.Trace class to write your output to the Output window instead of (or in addition to) the console. It take a little configuration, but it works. Is that along the line of what you want?</p>\n\n<p>You can also add your own tab per <a href=\"http://www.knowdotnet.com/articles/outputwindow.html\" rel=\"nofollow noreferrer\">this article</a>, but I've never tried it.</p>\n"
},
{
"answer_id": 123067,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 2,
"selected": true,
"text": "<p>I'm going to make a few assumptions here. First, I presume that you are talking about printf output from an application (whether it be from a console app or from a windows GUI app). My second assumption is the C language.</p>\n\n<p><em>To my knowledge, you cannot direct printf output to the output window in dev studio, not directly anyway.</em> <sub>[emphasis added by OP]</sub></p>\n\n<p>There might be a way but I'm not aware of it. One thing that you could do though would be to direct printf function calls to your own routine which will</p>\n\n<ol>\n<li>call printf and print the string</li>\n<li>call OuputDebugString() to print the string to the output window</li>\n</ol>\n\n<p>You could do several things to accomplish this goal. First would be to write your own printf function and then call printf and the OuputDebugString()</p>\n\n<pre><code>void my_printf(const char *format, ...)\n{\n char buf[2048];\n\n // get the arg list and format it into a string\n va_start(arglist, format);\n vsprintf_s(buf, 2048, format, arglist);\n va_end(arglist); \n\n vprintf_s(buf); // prints to the standard output stream\n OutputDebugString(buf); // prints to the output window\n}\n</code></pre>\n\n<p>The code above is mostly untested, but it should get the concepts across.</p>\n\n<p>If you are not doing this in C/C++, then this method won't work for you. :-) </p>\n"
},
{
"answer_id": 125492,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to capture the output in a text file and use that.</p>\n\n<p>I don't have a VS handy, so this is from memory:</p>\n\n<ol>\n<li>Create a C++ project</li>\n<li>Open the project settings, debugging tab</li>\n<li>Enable managed debugging</li>\n<li>Edit command line to add \"<code>> output.txt</code>\"</li>\n<li>Run your program under the debugger</li>\n</ol>\n\n<p>If things work the way I remember, this will redirect STDOUT to a file, even though you're not actually running under CMD.EXE. </p>\n\n<p>(The debugger has its own implementation of redirection syntax, which is not 100% the same as cmd, but it's pretty good.)</p>\n\n<p>Now, if you open this file in VS, you can still see the output from within VS, although not in exactly the same window you were hoping for.</p>\n"
},
{
"answer_id": 125509,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe this will work for you: set a breakpoint on the close <code>}</code> in <code>Main</code>, and then look at the console window before it closes. You can even copy the text out of it if you need to.</p>\n\n<p>On every machine that I use for development, I configure my console window in a certain way, which happens to make this approach work better:</p>\n\n<ol>\n<li>Run cmd.exe</li>\n<li>ALT-SPACE, D</li>\n<li>In Options, enable QuickEdit mode.</li>\n<li>In Layout, set Buffer Height to 9999</li>\n<li>Click OK</li>\n<li>Exit the CMD window.</li>\n</ol>\n"
},
{
"answer_id": 5577787,
"author": "Carl R",
"author_id": 480986,
"author_profile": "https://Stackoverflow.com/users/480986",
"pm_score": 2,
"selected": false,
"text": "<p>The console can redirect it's output to any textwriter. If you implement a textwriter that writes to Diagnostics.Debug, you are all set.</p>\n\n<p>Here's a textwriter that writes to the debugger.</p>\n\n<pre><code>using System.Diagnostics;\nusing System.IO;\nusing System.Text;\n\nnamespace TestConsole\n{\n public class DebugTextWriter : TextWriter\n {\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n }\n\n //Required\n public override void Write(char value)\n {\n Debug.Write(value);\n }\n\n //Added for efficiency\n public override void Write(string value)\n {\n Debug.Write(value);\n }\n\n //Added for efficiency\n public override void WriteLine(string value)\n {\n Debug.WriteLine(value);\n }\n }\n}\n</code></pre>\n\n<p>Since it uses Diagnostics.Debug it will adhere to your compiler settings to wether it should write any output or not. This output can also be seen in Sysinternals DebugView.</p>\n\n<p>Here's how you use it:</p>\n\n<pre><code>using System;\n\nnamespace TestConsole\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.SetOut(new DebugTextWriter());\n Console.WriteLine(\"This text goes to the Visual Studio output window.\");\n }\n }\n}\n</code></pre>\n\n<p>If you want to see the output in Sysinternals DebugView when you are compiling in Release mode, you can use a TextWriter that writes to the OutputDebugString API. It could look like this:</p>\n\n<pre><code>using System.IO;\nusing System.Runtime.InteropServices;\nusing System.Text;\n\nnamespace TestConsole\n{\n public class OutputDebugStringTextWriter : TextWriter\n {\n [DllImport(\"kernel32.dll\")]\n static extern void OutputDebugString(string lpOutputString);\n\n public override Encoding Encoding\n {\n get { return Encoding.UTF8; }\n }\n\n //Required\n public override void Write(char value)\n {\n OutputDebugString(value.ToString());\n }\n\n //Added for efficiency\n public override void Write(string value)\n {\n OutputDebugString(value);\n }\n\n //Added for efficiency\n public override void WriteLine(string value)\n {\n OutputDebugString(value);\n }\n }\n}\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15721/"
] |
I have a page in my desktop app, and I've implemented simple grab-and-pan. It works great.
When you are panning in this way and you are release, the page stops dead where you dropped it.
I'd like it to continue slightly with some momentum, and stop eventually. Rather like the 'throw' in the iPhone UI, I guess.
I'm not really chasing perfection, just a very crude simple sense of being able to 'throw' that page.
|
I'm going to make a few assumptions here. First, I presume that you are talking about printf output from an application (whether it be from a console app or from a windows GUI app). My second assumption is the C language.
*To my knowledge, you cannot direct printf output to the output window in dev studio, not directly anyway.* [emphasis added by OP]
There might be a way but I'm not aware of it. One thing that you could do though would be to direct printf function calls to your own routine which will
1. call printf and print the string
2. call OuputDebugString() to print the string to the output window
You could do several things to accomplish this goal. First would be to write your own printf function and then call printf and the OuputDebugString()
```
void my_printf(const char *format, ...)
{
char buf[2048];
// get the arg list and format it into a string
va_start(arglist, format);
vsprintf_s(buf, 2048, format, arglist);
va_end(arglist);
vprintf_s(buf); // prints to the standard output stream
OutputDebugString(buf); // prints to the output window
}
```
The code above is mostly untested, but it should get the concepts across.
If you are not doing this in C/C++, then this method won't work for you. :-)
|
122,782 |
<p>I'm looking to have two versions of BOOST compiled into a project at the same time. Ideally they should be usable along these lines:</p>
<pre><code>boost_1_36_0::boost::shared_ptr<SomeClass> someClass = new SomeClass();
boost_1_35_0::boost::regex expression("[0-9]", boost_1_35_0::boost::regex_constants::basic);
</code></pre>
|
[
{
"answer_id": 122801,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 0,
"selected": false,
"text": "<p>You'll have a world of trouble linking because the mangled names will be different. And yes, I see you knew that, but it seems like it will be trouble all around.</p>\n"
},
{
"answer_id": 122843,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>@Josh:\nWhile I agree with the shivering, I still believe this is the better course of action. Otherwise, linking troubles are a certainty. I've had the situation before where I had to hack the compiled libraries using <code>objcopy</code> to avoid definition conflicts. It was a nightmare for platform interoperability reasons because the name mangling works very differently even in different versions of the same compilers (in my case, GCC).</p>\n"
},
{
"answer_id": 123233,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 5,
"selected": true,
"text": "<p>I read (well scanned) through the <a href=\"http://thread.gmane.org/gmane.comp.lib.boost.devel/180008\" rel=\"noreferrer\">development list discussion</a>. There's no easy solution. To sum up:</p>\n\n<ol>\n<li><p>Wrapping header files in a namespace declaration </p>\n\n<pre><code>namespace boost_1_36_0 {\n #include <boost_1_36_0/boost/regex.hpp>\n}\nnamespace boost_1_35_0 {\n #include <boost_1_35_0/boost/shared_ptr.hpp>\n}\n</code></pre>\n\n<ul>\n<li>Requires modifying source files</li>\n<li>Doesn't allow for both versions to be included in the same translation unit, due to the fact that macros do not respect namespaces. </li>\n</ul></li>\n<li><p>Defining boost before including headers </p>\n\n<pre><code>#define boost boost_1_36_0\n #include <boost_1_36_0/boost/regex.hpp>\n#undef boost\n#define boost boost_1_35_0\n #include <boost_1_35_0/boost/shared_ptr.hpp>\n#undef boost\n</code></pre>\n\n<ul>\n<li>Source files can simply be compiled with <code>-Dboost=boost_1_36_0</code></li>\n<li>Still doesn't address macro conflicts in a single translation unit.</li>\n<li><p>Some internal header file inclusions may be messed up, since this sort of thing does happen.</p>\n\n<pre><code>#if defined(SOME_CONDITION)\n# define HEADER <boost/some/header.hpp>\n#else\n# define HEADER <boost/some/other/header.hpp>\n#endif\n</code></pre>\n\n<p>But it may be easy enough to work around those cases.</p></li>\n</ul></li>\n<li>Modifying the entire boost library to replace <code>namespace boost {..}</code> with <code>namespace boost_1_36_0 {...}</code> and then providing a namespace alias. Replace all <code>BOOST_XYZ</code> macros and their uses with <code>BOOST_1_36_0_XYZ</code> macros.\n\n<ul>\n<li>This would likely work if you were willing to put into the effort.</li>\n</ul></li>\n</ol>\n"
},
{
"answer_id": 21413269,
"author": "0xC0DEGURU",
"author_id": 1353723,
"author_profile": "https://Stackoverflow.com/users/1353723",
"pm_score": 2,
"selected": false,
"text": "<p>Using <a href=\"http://www.boost.org/doc/libs/1_55_0b1/tools/bcp/doc/html/index.html\" rel=\"nofollow\">bcp</a> can install boost library to a specific location and can replace all 'namespace boost' in their code to a custom alias. Assuming our alias is 'boost_1_36_0' all 'namespace boost' code blocks will start with 'boost_1_36_0'. Something like </p>\n\n<pre><code>bcp --namespace=boost_1_36_0 --namespace-alias shared_ptr regex /path/to/install\n</code></pre>\n\n<p>, but check the documentation in the link yourself because I'm not sure if it is legal syntaxis.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8701/"
] |
I'm looking to have two versions of BOOST compiled into a project at the same time. Ideally they should be usable along these lines:
```
boost_1_36_0::boost::shared_ptr<SomeClass> someClass = new SomeClass();
boost_1_35_0::boost::regex expression("[0-9]", boost_1_35_0::boost::regex_constants::basic);
```
|
I read (well scanned) through the [development list discussion](http://thread.gmane.org/gmane.comp.lib.boost.devel/180008). There's no easy solution. To sum up:
1. Wrapping header files in a namespace declaration
```
namespace boost_1_36_0 {
#include <boost_1_36_0/boost/regex.hpp>
}
namespace boost_1_35_0 {
#include <boost_1_35_0/boost/shared_ptr.hpp>
}
```
* Requires modifying source files
* Doesn't allow for both versions to be included in the same translation unit, due to the fact that macros do not respect namespaces.
2. Defining boost before including headers
```
#define boost boost_1_36_0
#include <boost_1_36_0/boost/regex.hpp>
#undef boost
#define boost boost_1_35_0
#include <boost_1_35_0/boost/shared_ptr.hpp>
#undef boost
```
* Source files can simply be compiled with `-Dboost=boost_1_36_0`
* Still doesn't address macro conflicts in a single translation unit.
* Some internal header file inclusions may be messed up, since this sort of thing does happen.
```
#if defined(SOME_CONDITION)
# define HEADER <boost/some/header.hpp>
#else
# define HEADER <boost/some/other/header.hpp>
#endif
```
But it may be easy enough to work around those cases.
3. Modifying the entire boost library to replace `namespace boost {..}` with `namespace boost_1_36_0 {...}` and then providing a namespace alias. Replace all `BOOST_XYZ` macros and their uses with `BOOST_1_36_0_XYZ` macros.
* This would likely work if you were willing to put into the effort.
|
122,799 |
<p>There is no summary available of the big O notation for operations on the most common data structures including arrays, linked lists, hash tables etc.</p>
|
[
{
"answer_id": 122894,
"author": "Jose Vega",
"author_id": 17162,
"author_profile": "https://Stackoverflow.com/users/17162",
"pm_score": 4,
"selected": false,
"text": "<p>I guess I will start you off with the time complexity of a linked list:<br></p>\n\n<p>Indexing---->O(n)<br>\nInserting / Deleting at end---->O(1) or O(n)<br>\nInserting / Deleting in middle--->O(1) with iterator O(n) with out<br></p>\n\n<p>The time complexity for the Inserting at the end depends if you have the location of the last node, if you do, it would be O(1) other wise you will have to search through the linked list and the time complexity would jump to O(n).</p>\n"
},
{
"answer_id": 123853,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 1,
"selected": false,
"text": "<p>Amortized Big-O for hashtables:</p>\n\n<ul>\n<li>Insert - O(1)</li>\n<li>Retrieve - O(1)</li>\n<li>Delete - O(1)</li>\n</ul>\n\n<p>Note that there is a constant factor for the hashing algorithm, and the amortization means that actual measured performance may vary dramatically.</p>\n"
},
{
"answer_id": 123879,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "<p>Red-Black trees:</p>\n\n<ul>\n<li>Insert - O(log n)</li>\n<li>Retrieve - O(log n)</li>\n<li>Delete - O(log n)</li>\n</ul>\n"
},
{
"answer_id": 130304,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 2,
"selected": false,
"text": "<p>Keep in mind that unless you're writing your own data structure (e.g. linked list in C), it can depend dramatically on the implementation of data structures in your language/framework of choice. As an example, take a look at the <a href=\"http://ridiculousfish.com/blog/?p=27\" rel=\"noreferrer\">benchmarks of Apple's CFArray over at Ridiculous Fish</a>. In this case, the data type, a CFArray from Apple's CoreFoundation framework, actually changes data structures depending on how many objects are actually in the array - changing from linear time to constant time at around 30,000 objects.</p>\n\n<p>This is actually one of the beautiful things about object-oriented programming - you don't need to know <em>how</em> it works, just <em>that</em> it works, and the 'how it works' can change depending on requirements.</p>\n"
},
{
"answer_id": 17410009,
"author": "Mobiletainment",
"author_id": 1265240,
"author_profile": "https://Stackoverflow.com/users/1265240",
"pm_score": 6,
"selected": false,
"text": "<p>Information on this topic is now available on Wikipedia at: <a href=\"http://en.wikipedia.org/wiki/Search_data_structure\" rel=\"noreferrer\">Search data structure</a></p>\n\n<pre><code>+----------------------+----------+------------+----------+--------------+\n| | Insert | Delete | Search | Space Usage |\n+----------------------+----------+------------+----------+--------------+\n| Unsorted array | O(1) | O(1) | O(n) | O(n) |\n| Value-indexed array | O(1) | O(1) | O(1) | O(n) |\n| Sorted array | O(n) | O(n) | O(log n) | O(n) |\n| Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) |\n| Sorted linked list | O(n)* | O(1)* | O(n) | O(n) |\n| Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) |\n| Heap | O(log n) | O(log n)** | O(n) | O(n) |\n| Hash table | O(1) | O(1) | O(1) | O(n) |\n+----------------------+----------+------------+----------+--------------+\n\n * The cost to add or delete an element into a known location in the list \n (i.e. if you have an iterator to the location) is O(1). If you don't \n know the location, then you need to traverse the list to the location\n of deletion/insertion, which takes O(n) time. \n\n** The deletion cost is O(log n) for the minimum or maximum, O(n) for an\n arbitrary element.\n</code></pre>\n"
},
{
"answer_id": 52363824,
"author": "Pritam Banerjee",
"author_id": 1475228,
"author_profile": "https://Stackoverflow.com/users/1475228",
"pm_score": 3,
"selected": false,
"text": "<p>Nothing as useful as this: <a href=\"http://bigocheatsheet.com/\" rel=\"noreferrer\">Common Data Structure Operations</a>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Gv0Xc.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Gv0Xc.jpg\" alt=\"enter image description here\"></a></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340748/"
] |
There is no summary available of the big O notation for operations on the most common data structures including arrays, linked lists, hash tables etc.
|
Information on this topic is now available on Wikipedia at: [Search data structure](http://en.wikipedia.org/wiki/Search_data_structure)
```
+----------------------+----------+------------+----------+--------------+
| | Insert | Delete | Search | Space Usage |
+----------------------+----------+------------+----------+--------------+
| Unsorted array | O(1) | O(1) | O(n) | O(n) |
| Value-indexed array | O(1) | O(1) | O(1) | O(n) |
| Sorted array | O(n) | O(n) | O(log n) | O(n) |
| Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) |
| Sorted linked list | O(n)* | O(1)* | O(n) | O(n) |
| Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) |
| Heap | O(log n) | O(log n)** | O(n) | O(n) |
| Hash table | O(1) | O(1) | O(1) | O(n) |
+----------------------+----------+------------+----------+--------------+
* The cost to add or delete an element into a known location in the list
(i.e. if you have an iterator to the location) is O(1). If you don't
know the location, then you need to traverse the list to the location
of deletion/insertion, which takes O(n) time.
** The deletion cost is O(log n) for the minimum or maximum, O(n) for an
arbitrary element.
```
|
122,815 |
<p>I'm looking for a groovy equivalent on .NET
<a href="http://boo.codehaus.org/" rel="nofollow noreferrer">http://boo.codehaus.org/</a></p>
<p>So far Boo looks interesting, but it is statically typed, yet does include some of the metaprogramming features I'd be looking for.</p>
<p>Can anyone comment on the experience of using Boo and is it worth looking into for more than hobby purposes at a 1.0 Version? </p>
<p><em>Edit</em>: Changed BOO to Boo</p>
|
[
{
"answer_id": 122894,
"author": "Jose Vega",
"author_id": 17162,
"author_profile": "https://Stackoverflow.com/users/17162",
"pm_score": 4,
"selected": false,
"text": "<p>I guess I will start you off with the time complexity of a linked list:<br></p>\n\n<p>Indexing---->O(n)<br>\nInserting / Deleting at end---->O(1) or O(n)<br>\nInserting / Deleting in middle--->O(1) with iterator O(n) with out<br></p>\n\n<p>The time complexity for the Inserting at the end depends if you have the location of the last node, if you do, it would be O(1) other wise you will have to search through the linked list and the time complexity would jump to O(n).</p>\n"
},
{
"answer_id": 123853,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 1,
"selected": false,
"text": "<p>Amortized Big-O for hashtables:</p>\n\n<ul>\n<li>Insert - O(1)</li>\n<li>Retrieve - O(1)</li>\n<li>Delete - O(1)</li>\n</ul>\n\n<p>Note that there is a constant factor for the hashing algorithm, and the amortization means that actual measured performance may vary dramatically.</p>\n"
},
{
"answer_id": 123879,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 2,
"selected": false,
"text": "<p>Red-Black trees:</p>\n\n<ul>\n<li>Insert - O(log n)</li>\n<li>Retrieve - O(log n)</li>\n<li>Delete - O(log n)</li>\n</ul>\n"
},
{
"answer_id": 130304,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 2,
"selected": false,
"text": "<p>Keep in mind that unless you're writing your own data structure (e.g. linked list in C), it can depend dramatically on the implementation of data structures in your language/framework of choice. As an example, take a look at the <a href=\"http://ridiculousfish.com/blog/?p=27\" rel=\"noreferrer\">benchmarks of Apple's CFArray over at Ridiculous Fish</a>. In this case, the data type, a CFArray from Apple's CoreFoundation framework, actually changes data structures depending on how many objects are actually in the array - changing from linear time to constant time at around 30,000 objects.</p>\n\n<p>This is actually one of the beautiful things about object-oriented programming - you don't need to know <em>how</em> it works, just <em>that</em> it works, and the 'how it works' can change depending on requirements.</p>\n"
},
{
"answer_id": 17410009,
"author": "Mobiletainment",
"author_id": 1265240,
"author_profile": "https://Stackoverflow.com/users/1265240",
"pm_score": 6,
"selected": false,
"text": "<p>Information on this topic is now available on Wikipedia at: <a href=\"http://en.wikipedia.org/wiki/Search_data_structure\" rel=\"noreferrer\">Search data structure</a></p>\n\n<pre><code>+----------------------+----------+------------+----------+--------------+\n| | Insert | Delete | Search | Space Usage |\n+----------------------+----------+------------+----------+--------------+\n| Unsorted array | O(1) | O(1) | O(n) | O(n) |\n| Value-indexed array | O(1) | O(1) | O(1) | O(n) |\n| Sorted array | O(n) | O(n) | O(log n) | O(n) |\n| Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) |\n| Sorted linked list | O(n)* | O(1)* | O(n) | O(n) |\n| Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) |\n| Heap | O(log n) | O(log n)** | O(n) | O(n) |\n| Hash table | O(1) | O(1) | O(1) | O(n) |\n+----------------------+----------+------------+----------+--------------+\n\n * The cost to add or delete an element into a known location in the list \n (i.e. if you have an iterator to the location) is O(1). If you don't \n know the location, then you need to traverse the list to the location\n of deletion/insertion, which takes O(n) time. \n\n** The deletion cost is O(log n) for the minimum or maximum, O(n) for an\n arbitrary element.\n</code></pre>\n"
},
{
"answer_id": 52363824,
"author": "Pritam Banerjee",
"author_id": 1475228,
"author_profile": "https://Stackoverflow.com/users/1475228",
"pm_score": 3,
"selected": false,
"text": "<p>Nothing as useful as this: <a href=\"http://bigocheatsheet.com/\" rel=\"noreferrer\">Common Data Structure Operations</a>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Gv0Xc.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Gv0Xc.jpg\" alt=\"enter image description here\"></a></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129162/"
] |
I'm looking for a groovy equivalent on .NET
<http://boo.codehaus.org/>
So far Boo looks interesting, but it is statically typed, yet does include some of the metaprogramming features I'd be looking for.
Can anyone comment on the experience of using Boo and is it worth looking into for more than hobby purposes at a 1.0 Version?
*Edit*: Changed BOO to Boo
|
Information on this topic is now available on Wikipedia at: [Search data structure](http://en.wikipedia.org/wiki/Search_data_structure)
```
+----------------------+----------+------------+----------+--------------+
| | Insert | Delete | Search | Space Usage |
+----------------------+----------+------------+----------+--------------+
| Unsorted array | O(1) | O(1) | O(n) | O(n) |
| Value-indexed array | O(1) | O(1) | O(1) | O(n) |
| Sorted array | O(n) | O(n) | O(log n) | O(n) |
| Unsorted linked list | O(1)* | O(1)* | O(n) | O(n) |
| Sorted linked list | O(n)* | O(1)* | O(n) | O(n) |
| Balanced binary tree | O(log n) | O(log n) | O(log n) | O(n) |
| Heap | O(log n) | O(log n)** | O(n) | O(n) |
| Hash table | O(1) | O(1) | O(1) | O(n) |
+----------------------+----------+------------+----------+--------------+
* The cost to add or delete an element into a known location in the list
(i.e. if you have an iterator to the location) is O(1). If you don't
know the location, then you need to traverse the list to the location
of deletion/insertion, which takes O(n) time.
** The deletion cost is O(log n) for the minimum or maximum, O(n) for an
arbitrary element.
```
|
122,821 |
<p>I've got a Sharepoint WebPart which loads a custom User Control. The user control contains a Repeater which in turn contains several LinkButtons. </p>
<p>In the RenderContent call in the Webpart I've got some code to add event handlers:</p>
<pre><code> ArrayList nextPages = new ArrayList();
//populate nextPages ....
AfterPageRepeater.DataSource = nextPages;
AfterPageRepeater.DataBind();
foreach (Control oRepeaterControl in AfterPageRepeater.Controls)
{
if (oRepeaterControl is RepeaterItem)
{
if (oRepeaterControl.HasControls())
{
foreach (Control oControl in oRepeaterControl.Controls)
{
if (oControl is LinkButton)
{
((LinkButton)oControl).Click += new EventHandler(PageNavigateButton_Click);
}
}
}
}
}
</code></pre>
<p>The function PageNavigateButton_Click is never called however. I can see it being added as an event handler in the debugger however.</p>
<p>Any ideas? I'm stumped how to do this. </p>
|
[
{
"answer_id": 122842,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>You need to make sure that the link button is re-added to the control tree and/or that the event is rewired up to the control before the event fires. </p>\n\n<p><a href=\"https://web.archive.org/web/20211031102347/https://aspnet.4guysfromrolla.com/articles/092904-1.aspx\" rel=\"nofollow noreferrer\">Article @ 4guysfromrolla</a></p>\n"
},
{
"answer_id": 122850,
"author": "Matt Blaine",
"author_id": 16272,
"author_profile": "https://Stackoverflow.com/users/16272",
"pm_score": 1,
"selected": false,
"text": "<p>I've never done a SharePoint WebPart, so I don't know if this will apply. But if it were a plain-old apsx page, I'd say that by the time it's rendering, it's too late. Try adding the event handlers in the control's Init or PreInit events.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Wait, I think Dilli-O might be right. See the <em>Adding Button Controls to a Repeater</em> section at the end of <a href=\"http://www.ondotnet.com/pub/a/dotnet/2003/03/03/repeater.html\" rel=\"nofollow noreferrer\">http://www.ondotnet.com/pub/a/dotnet/2003/03/03/repeater.html</a>. It's in VB.NET, but you can easily do the same thing in C#.</p>\n"
},
{
"answer_id": 122859,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried assigning the CommandName and CommandArgument properties to each button as you iterate through? The Repeater control supports the ItemCommand event, which is an event that will be raised when a control with the CommandName property is hit.</p>\n\n<p>From there it is easy enough to process because the CommandName and CommandArgument values are passed into the event and are readily accessible.</p>\n"
},
{
"answer_id": 122948,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "<p>By the time RenderContent() is called, all the registered event handlers have been called by the framework. You need to add the event handlers in an earlier method, like OnLoad():</p>\n\n<pre><code>protected override void OnLoad(EventArge e)\n { base.OnLoad(e);\n EnsureChildControls();\n\n var linkButtons = from c in AfterPageRepeater.Controls\n .OfType<RepeaterItem>()\n where c.HasControls()\n select c into ris\n from lb in ris.OfType<LinkButton>()\n select lb;\n\n foreach(var linkButton in linkButtons)\n { linkButton.Click += PageNavigateButton_Click\n } \n }\n</code></pre>\n"
},
{
"answer_id": 124353,
"author": "Preston Guillot",
"author_id": 21418,
"author_profile": "https://Stackoverflow.com/users/21418",
"pm_score": 1,
"selected": false,
"text": "<p>As others have pointed out, you're adding the event handler too late in the page life cycle. For SharePoint WebParts you'd typically want to override the class' OnInit/CreateChildControls methods to handle the activity.</p>\n"
},
{
"answer_id": 1335623,
"author": "Colin",
"author_id": 119660,
"author_profile": "https://Stackoverflow.com/users/119660",
"pm_score": 1,
"selected": false,
"text": "<p>YOu need your webpart to implement the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx\" rel=\"nofollow noreferrer\">INamingContainer</a> marker interface, it is used by the framework to allow postbacks to return to the correct control...\nAlso the controls in your webpart all need to have an ID.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21299/"
] |
I've got a Sharepoint WebPart which loads a custom User Control. The user control contains a Repeater which in turn contains several LinkButtons.
In the RenderContent call in the Webpart I've got some code to add event handlers:
```
ArrayList nextPages = new ArrayList();
//populate nextPages ....
AfterPageRepeater.DataSource = nextPages;
AfterPageRepeater.DataBind();
foreach (Control oRepeaterControl in AfterPageRepeater.Controls)
{
if (oRepeaterControl is RepeaterItem)
{
if (oRepeaterControl.HasControls())
{
foreach (Control oControl in oRepeaterControl.Controls)
{
if (oControl is LinkButton)
{
((LinkButton)oControl).Click += new EventHandler(PageNavigateButton_Click);
}
}
}
}
}
```
The function PageNavigateButton\_Click is never called however. I can see it being added as an event handler in the debugger however.
Any ideas? I'm stumped how to do this.
|
By the time RenderContent() is called, all the registered event handlers have been called by the framework. You need to add the event handlers in an earlier method, like OnLoad():
```
protected override void OnLoad(EventArge e)
{ base.OnLoad(e);
EnsureChildControls();
var linkButtons = from c in AfterPageRepeater.Controls
.OfType<RepeaterItem>()
where c.HasControls()
select c into ris
from lb in ris.OfType<LinkButton>()
select lb;
foreach(var linkButton in linkButtons)
{ linkButton.Click += PageNavigateButton_Click
}
}
```
|
122,834 |
<p>Suppose there are two scripts Requester.php and Provider.php, and Requester requires processing from Provider and makes an http request to it (Provider.php?data="data"). In this situation, Provider quickly finds the answer, but to maintain the system must perform various updates throughout the database. Is there a way to immediately return the value to Requester, and then continue processing in Provider. </p>
<p>Psuedo Code</p>
<pre><code>Provider.php
{
$answer = getAnswer($_GET['data']);
echo $answer;
//SIGNAL TO REQUESTER THAT WE ARE FINISHED
processDBUpdates();
return;
}
</code></pre>
|
[
{
"answer_id": 122897,
"author": "Peter Olsson",
"author_id": 2703,
"author_profile": "https://Stackoverflow.com/users/2703",
"pm_score": 2,
"selected": false,
"text": "<p>You can flush the output buffer with the flush() command.<br>\nRead the comments in the <a href=\"http://se.php.net/manual/en/function.flush.php\" rel=\"nofollow noreferrer\">PHP manual</a> for more info</p>\n"
},
{
"answer_id": 122966,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 0,
"selected": false,
"text": "<p>Split the Provider in two: <code>ProviderCore</code> and <code>ProviderInterface</code>. In <code>ProviderInterface</code> just do the \"quick and easy\" part, also save a flag in database that the recent request hasn't been processed yet. Run <code>ProviderCore</code> as a cron job that searches for that flag and completes processing. If there's nothing to do, <code>ProviderCore</code> will terminate and retry in (say) 2 minutes.</p>\n"
},
{
"answer_id": 122981,
"author": "DreamWerx",
"author_id": 15487,
"author_profile": "https://Stackoverflow.com/users/15487",
"pm_score": 1,
"selected": false,
"text": "<p>I think you'll need on the provider to send the data (be sure to flush), and then on the Requester, use fopen/fread to read an expected amount of data, so you can drop the connection to the Provider and continue. If you don't specify an amount of data to expect, I would think the requester would sit there waiting for the Provider to close the connection, which probably doesn't happen until the end of it's run (ie. all the secondary work intensive tasks are complete). You'll need to try out a few POC's..</p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 122985,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 2,
"selected": false,
"text": "<p>I use <a href=\"https://stackoverflow.com/questions/45953/php-execute-a-background-process#45966\">this code</a> for running a process in the background (works on Linux).</p>\n\n<p>The process runs with its output redirected to a file.</p>\n\n<p>That way, if I need to display status on the process, it's just a matter of writing a small amount of code to read and display the contents of the output file.</p>\n\n<p>I like this approach because it means you can completely close the browser and easily come back later to check on the status.</p>\n"
},
{
"answer_id": 122997,
"author": "William OConnor - csevb10",
"author_id": 10084,
"author_profile": "https://Stackoverflow.com/users/10084",
"pm_score": 2,
"selected": true,
"text": "<p>You basically want to signal the end of 1 process (return to the original <code>Requester.php</code>) and spawn a new process (finish <code>Provider.php</code>). There is probably a more elegant way to pull this off, but I've managed this a couple different ways. All of them basically result in exec-ing a command in order to shell off the second process.</p>\n\n<p>adding the following <code>> /dev/null 2>&1 &</code> to the end of your command will allow it to run in the background without inhibiting the actual execution of your current script</p>\n\n<p>Something like the following may work for you:</p>\n\n<pre><code>exec(\"wget -O - \\\"$url\\\" > /dev/null 2>&1 &\"); \n</code></pre>\n\n<p>-- though you could do it as a command line PHP process as well.</p>\n\n<p>You could also save the information that needs to be processed and handle the remaining processing on a cron job that re-creates the same sort of functionality without the need to exec.</p>\n"
},
{
"answer_id": 1077690,
"author": "Extrakun",
"author_id": 128585,
"author_profile": "https://Stackoverflow.com/users/128585",
"pm_score": 0,
"selected": false,
"text": "<p>I'm going out on a limb here, but perhaps you should try cURL or use a socket to update the requester?</p>\n"
},
{
"answer_id": 24540176,
"author": "John Foley",
"author_id": 1775336,
"author_profile": "https://Stackoverflow.com/users/1775336",
"pm_score": 0,
"selected": false,
"text": "<p>You could start another php process in Provider.php using pcntl_fork()</p>\n\n<pre><code>Provider.php \n{\n // Fork process\n $pid = pcntl_fork();\n\n // You are now running both a daemon process and the parent process\n // through the rest of the code below\n\n if ($pid > 0) {\n // PARENT Process\n $answer = getAnswer($_GET['data']);\n echo $answer; \n //SIGNAL TO REQUESTER THAT WE ARE FINISHED\n return;\n }\n\n if ($pid == 0) {\n // DAEMON Process\n processDBUpdates();\n return;\n }\n\n // If you get here the daemon process failed to start\n handleDaemonErrorCondition();\n return;\n\n}\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8880/"
] |
Suppose there are two scripts Requester.php and Provider.php, and Requester requires processing from Provider and makes an http request to it (Provider.php?data="data"). In this situation, Provider quickly finds the answer, but to maintain the system must perform various updates throughout the database. Is there a way to immediately return the value to Requester, and then continue processing in Provider.
Psuedo Code
```
Provider.php
{
$answer = getAnswer($_GET['data']);
echo $answer;
//SIGNAL TO REQUESTER THAT WE ARE FINISHED
processDBUpdates();
return;
}
```
|
You basically want to signal the end of 1 process (return to the original `Requester.php`) and spawn a new process (finish `Provider.php`). There is probably a more elegant way to pull this off, but I've managed this a couple different ways. All of them basically result in exec-ing a command in order to shell off the second process.
adding the following `> /dev/null 2>&1 &` to the end of your command will allow it to run in the background without inhibiting the actual execution of your current script
Something like the following may work for you:
```
exec("wget -O - \"$url\" > /dev/null 2>&1 &");
```
-- though you could do it as a command line PHP process as well.
You could also save the information that needs to be processed and handle the remaining processing on a cron job that re-creates the same sort of functionality without the need to exec.
|
122,853 |
<p>I want to get the size of an http:/.../file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header?</p>
|
[
{
"answer_id": 122874,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>Can this be done with HTTP headers?</p>\n</blockquote>\n\n<p>Yes, this is the way to go. <em>If</em> the information is provided, it's in the header as the <code>Content-Length</code>. Note, however, that this is not necessarily the case.</p>\n\n<p>Downloading only the header can be done using a <code>HEAD</code> request instead of <code>GET</code>. Maybe the following code helps:</p>\n\n<pre><code>HttpWebRequest req = (HttpWebRequest)WebRequest.Create(\"http://example.com/\");\nreq.Method = \"HEAD\";\nlong len;\nusing(HttpWebResponse resp = (HttpWebResponse)(req.GetResponse()))\n{\n len = resp.ContentLength;\n}\n</code></pre>\n\n<p>Notice the property for the content length on the <code>HttpWebResponse</code> object – no need to parse the <code>Content-Length</code> header manually.</p>\n"
},
{
"answer_id": 122984,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 8,
"selected": true,
"text": "<p>Yes, assuming the HTTP server you're talking to supports/allows this:</p>\n\n<pre><code>public long GetFileSize(string url)\n{\n long result = -1;\n\n System.Net.WebRequest req = System.Net.WebRequest.Create(url);\n req.Method = \"HEAD\";\n using (System.Net.WebResponse resp = req.GetResponse())\n {\n if (long.TryParse(resp.Headers.Get(\"Content-Length\"), out long ContentLength))\n {\n result = ContentLength;\n }\n }\n\n return result;\n}\n</code></pre>\n\n<p>If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information.</p>\n"
},
{
"answer_id": 46999741,
"author": "Umut D.",
"author_id": 2914860,
"author_profile": "https://Stackoverflow.com/users/2914860",
"pm_score": 1,
"selected": false,
"text": "<pre><code>WebClient webClient = new WebClient();\nwebClient.OpenRead(\"http://stackoverflow.com/robots.txt\");\nlong totalSizeBytes= Convert.ToInt64(webClient.ResponseHeaders[\"Content-Length\"]);\nConsole.WriteLine((totalSizeBytes));\n</code></pre>\n"
},
{
"answer_id": 51393151,
"author": "Daria",
"author_id": 4526973,
"author_profile": "https://Stackoverflow.com/users/4526973",
"pm_score": 2,
"selected": false,
"text": "<p>Note that not every server accepts <code>HTTP HEAD</code> requests. One alternative approach to get the file size is to make an <code>HTTP GET</code> call to the server requesting only a portion of the file to keep the response small and retrieve the file size from the metadata that is returned as part of the response content header.</p>\n\n<p>The standard <code>System.Net.Http.HttpClient</code> can be used to accomplish this. The partial content is requested by setting a byte range on the request message header as:</p>\n\n<pre><code> request.Headers.Range = new RangeHeaderValue(startByte, endByte)\n</code></pre>\n\n<p>The server responds with a message containing the requested range as well as the entire file size. This information is returned in the response content header (<code>response.Content.Header</code>) with the key \"Content-Range\". </p>\n\n<p>Here's an example of the content range in the response message content header:</p>\n\n<pre><code> {\n \"Key\": \"Content-Range\",\n \"Value\": [\n \"bytes 0-15/2328372\"\n ]\n }\n</code></pre>\n\n<p>In this example the header value implies the response contains bytes 0 to 15 (i.e., 16 bytes total) and the file is 2,328,372 bytes in its entirety.</p>\n\n<p>Here's a sample implementation of this method:</p>\n\n<pre><code>public static class HttpClientExtensions\n{\n public static async Task<long> GetContentSizeAsync(this System.Net.Http.HttpClient client, string url)\n {\n using (var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url))\n {\n // In order to keep the response as small as possible, set the requested byte range to [0,0] (i.e., only the first byte)\n request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(from: 0, to: 0);\n\n using (var response = await client.SendAsync(request))\n {\n response.EnsureSuccessStatusCode();\n\n if (response.StatusCode != System.Net.HttpStatusCode.PartialContent) \n throw new System.Net.WebException($\"expected partial content response ({System.Net.HttpStatusCode.PartialContent}), instead received: {response.StatusCode}\");\n\n var contentRange = response.Content.Headers.GetValues(@\"Content-Range\").Single();\n var lengthString = System.Text.RegularExpressions.Regex.Match(contentRange, @\"(?<=^bytes\\s[0-9]+\\-[0-9]+/)[0-9]+$\").Value;\n return long.Parse(lengthString);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 71395577,
"author": "Ilya",
"author_id": 15122582,
"author_profile": "https://Stackoverflow.com/users/15122582",
"pm_score": 0,
"selected": false,
"text": "<pre><code> HttpClient client = new HttpClient(\n new HttpClientHandler() {\n Proxy = null, UseProxy = false\n } // removes the delay getting a response from the server, if you not use Proxy\n );\n\n public async Task<long?> GetContentSizeAsync(string url) {\n using (HttpResponseMessage responce = await client.GetAsync(url))\n return responce.Content.Headers.ContentLength;\n }\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to get the size of an http:/.../file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header?
|
Yes, assuming the HTTP server you're talking to supports/allows this:
```
public long GetFileSize(string url)
{
long result = -1;
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.Method = "HEAD";
using (System.Net.WebResponse resp = req.GetResponse())
{
if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength))
{
result = ContentLength;
}
}
return result;
}
```
If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information.
|
122,855 |
<p>Anyone know if it is possible to write an app that uses the Java Sound API on a system that doesn't actually have a hardware sound device?</p>
<p>I have some code I've written based on the API that manipulates some audio and plays the result but I am now trying to run this in a server environment, where the audio will be recorded to a file instead of played to line out.</p>
<p>The server I'm running on has no sound card, and I seem to be running into roadblocks with Java Sound not being able to allocate any lines if there is not a Mixer that supports it. (And with no hardware devices I'm getting no Mixers.)</p>
<p>Any info would be much appreciated -</p>
<p>thanks.</p>
|
[
{
"answer_id": 122874,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>Can this be done with HTTP headers?</p>\n</blockquote>\n\n<p>Yes, this is the way to go. <em>If</em> the information is provided, it's in the header as the <code>Content-Length</code>. Note, however, that this is not necessarily the case.</p>\n\n<p>Downloading only the header can be done using a <code>HEAD</code> request instead of <code>GET</code>. Maybe the following code helps:</p>\n\n<pre><code>HttpWebRequest req = (HttpWebRequest)WebRequest.Create(\"http://example.com/\");\nreq.Method = \"HEAD\";\nlong len;\nusing(HttpWebResponse resp = (HttpWebResponse)(req.GetResponse()))\n{\n len = resp.ContentLength;\n}\n</code></pre>\n\n<p>Notice the property for the content length on the <code>HttpWebResponse</code> object – no need to parse the <code>Content-Length</code> header manually.</p>\n"
},
{
"answer_id": 122984,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 8,
"selected": true,
"text": "<p>Yes, assuming the HTTP server you're talking to supports/allows this:</p>\n\n<pre><code>public long GetFileSize(string url)\n{\n long result = -1;\n\n System.Net.WebRequest req = System.Net.WebRequest.Create(url);\n req.Method = \"HEAD\";\n using (System.Net.WebResponse resp = req.GetResponse())\n {\n if (long.TryParse(resp.Headers.Get(\"Content-Length\"), out long ContentLength))\n {\n result = ContentLength;\n }\n }\n\n return result;\n}\n</code></pre>\n\n<p>If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information.</p>\n"
},
{
"answer_id": 46999741,
"author": "Umut D.",
"author_id": 2914860,
"author_profile": "https://Stackoverflow.com/users/2914860",
"pm_score": 1,
"selected": false,
"text": "<pre><code>WebClient webClient = new WebClient();\nwebClient.OpenRead(\"http://stackoverflow.com/robots.txt\");\nlong totalSizeBytes= Convert.ToInt64(webClient.ResponseHeaders[\"Content-Length\"]);\nConsole.WriteLine((totalSizeBytes));\n</code></pre>\n"
},
{
"answer_id": 51393151,
"author": "Daria",
"author_id": 4526973,
"author_profile": "https://Stackoverflow.com/users/4526973",
"pm_score": 2,
"selected": false,
"text": "<p>Note that not every server accepts <code>HTTP HEAD</code> requests. One alternative approach to get the file size is to make an <code>HTTP GET</code> call to the server requesting only a portion of the file to keep the response small and retrieve the file size from the metadata that is returned as part of the response content header.</p>\n\n<p>The standard <code>System.Net.Http.HttpClient</code> can be used to accomplish this. The partial content is requested by setting a byte range on the request message header as:</p>\n\n<pre><code> request.Headers.Range = new RangeHeaderValue(startByte, endByte)\n</code></pre>\n\n<p>The server responds with a message containing the requested range as well as the entire file size. This information is returned in the response content header (<code>response.Content.Header</code>) with the key \"Content-Range\". </p>\n\n<p>Here's an example of the content range in the response message content header:</p>\n\n<pre><code> {\n \"Key\": \"Content-Range\",\n \"Value\": [\n \"bytes 0-15/2328372\"\n ]\n }\n</code></pre>\n\n<p>In this example the header value implies the response contains bytes 0 to 15 (i.e., 16 bytes total) and the file is 2,328,372 bytes in its entirety.</p>\n\n<p>Here's a sample implementation of this method:</p>\n\n<pre><code>public static class HttpClientExtensions\n{\n public static async Task<long> GetContentSizeAsync(this System.Net.Http.HttpClient client, string url)\n {\n using (var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url))\n {\n // In order to keep the response as small as possible, set the requested byte range to [0,0] (i.e., only the first byte)\n request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(from: 0, to: 0);\n\n using (var response = await client.SendAsync(request))\n {\n response.EnsureSuccessStatusCode();\n\n if (response.StatusCode != System.Net.HttpStatusCode.PartialContent) \n throw new System.Net.WebException($\"expected partial content response ({System.Net.HttpStatusCode.PartialContent}), instead received: {response.StatusCode}\");\n\n var contentRange = response.Content.Headers.GetValues(@\"Content-Range\").Single();\n var lengthString = System.Text.RegularExpressions.Regex.Match(contentRange, @\"(?<=^bytes\\s[0-9]+\\-[0-9]+/)[0-9]+$\").Value;\n return long.Parse(lengthString);\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 71395577,
"author": "Ilya",
"author_id": 15122582,
"author_profile": "https://Stackoverflow.com/users/15122582",
"pm_score": 0,
"selected": false,
"text": "<pre><code> HttpClient client = new HttpClient(\n new HttpClientHandler() {\n Proxy = null, UseProxy = false\n } // removes the delay getting a response from the server, if you not use Proxy\n );\n\n public async Task<long?> GetContentSizeAsync(string url) {\n using (HttpResponseMessage responce = await client.GetAsync(url))\n return responce.Content.Headers.ContentLength;\n }\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8063/"
] |
Anyone know if it is possible to write an app that uses the Java Sound API on a system that doesn't actually have a hardware sound device?
I have some code I've written based on the API that manipulates some audio and plays the result but I am now trying to run this in a server environment, where the audio will be recorded to a file instead of played to line out.
The server I'm running on has no sound card, and I seem to be running into roadblocks with Java Sound not being able to allocate any lines if there is not a Mixer that supports it. (And with no hardware devices I'm getting no Mixers.)
Any info would be much appreciated -
thanks.
|
Yes, assuming the HTTP server you're talking to supports/allows this:
```
public long GetFileSize(string url)
{
long result = -1;
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.Method = "HEAD";
using (System.Net.WebResponse resp = req.GetResponse())
{
if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength))
{
result = ContentLength;
}
}
return result;
}
```
If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information.
|
122,857 |
<p>As a follow up to <a href="https://stackoverflow.com/questions/104224/how-do-you-troubleshoot-wpf-ui-problems">my previous question</a>, I am wondering how to use transparent windows correctly. If I have set my window to use transparency, the UI will occasionally appear to stop responding. What is actually happening is that the UI simply is not updating as it should. Animations do not occur, pages do not appear to navigate; however, if you watch the debugger clicking on buttons, links, etc.. do actually work. Minimizing and restoring the window "catches up" the UI again and the user can continue working until the behavior comes back.</p>
<p>If I remove the transparent borders, the behavior does not occur. Am I doing something wrong or is there some other setting, code, etc... that I need to implement to work with transparent borders properly?</p>
<p>Here is my window declaration for the code that fails.</p>
<pre><code><Window x:Class="MyProject.MainContainer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF APplication" Height="600" Width="800"
xmlns:egc="ControlLibrary" Background="{x:Null}"
BorderThickness="0"
AllowsTransparency="True"
MinHeight="300" MinWidth="400" WindowStyle="None" >
</code></pre>
<p>And the code that does not exhibit the behavior</p>
<pre><code><Window x:Class="MyProject.MainContainer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Application" Height="600" Width="800"
xmlns:egc="ControlLibrary" Background="{x:Null}"
BorderThickness="0"
AllowsTransparency="False"
MinHeight="300" MinWidth="400" WindowStyle="None" >
</code></pre>
|
[
{
"answer_id": 123026,
"author": "Abe Heidebrecht",
"author_id": 9268,
"author_profile": "https://Stackoverflow.com/users/9268",
"pm_score": 2,
"selected": false,
"text": "<p>Are you using .NET 3.0, or .NET 3.5 on Windows XP SP2? If so, this is a known problem with the transparent window API that has been fixed in .NET 3.5 and SP3 of XP (and I think SP1 of Vista). Basically when you set the AllowsTransparency to True, the WPF pipeline has to render in software only mode. This will cause a significant degradation in performance on most systems. </p>\n\n<p>Unfortunately, the only thing you can do to fix this is to upgrade to .NET 3.0 SP1 (included in .NET 3.5), and install the appropriate service pack for Windows. Note that the transparent windows are still slower, but not nearly as bad. You can find a more in-depth discussion <a href=\"http://blogs.msdn.com/dwayneneed/archive/2008/09/08/transparent-windows-in-wpf.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 123046,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 0,
"selected": false,
"text": "<p>I am running on Windows XP Pro SP3 and using .NET 3.5 SP1. I have also verified that the project is targeting version 3.5 of the framework.</p>\n"
},
{
"answer_id": 124366,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 2,
"selected": true,
"text": "<p>I think that I've finally found a workaround. From everything I've read this problem should not be occurring with XP SP3 & .NET 3.5 SP1, but it is.</p>\n\n<p>The example from <a href=\"http://jerryclin.wordpress.com/2007/11/13/creating-non-rectangular-windows-with-interop/\" rel=\"nofollow noreferrer\">this blog post</a> shows how to use the Win32 API functions to create an irregular shaped window, which is what I\"m doing. After reworking my main window to use these techniques, things seem to be working as expected and the behavior has not returned.</p>\n\n<p>It is also of note that the reason the author recommends this method is due to performance issues with WPF and transparent windows. While I believe it may be better in .NET 3.5 SP1 that it was, this was not that hard to implement and should perform better.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312/"
] |
As a follow up to [my previous question](https://stackoverflow.com/questions/104224/how-do-you-troubleshoot-wpf-ui-problems), I am wondering how to use transparent windows correctly. If I have set my window to use transparency, the UI will occasionally appear to stop responding. What is actually happening is that the UI simply is not updating as it should. Animations do not occur, pages do not appear to navigate; however, if you watch the debugger clicking on buttons, links, etc.. do actually work. Minimizing and restoring the window "catches up" the UI again and the user can continue working until the behavior comes back.
If I remove the transparent borders, the behavior does not occur. Am I doing something wrong or is there some other setting, code, etc... that I need to implement to work with transparent borders properly?
Here is my window declaration for the code that fails.
```
<Window x:Class="MyProject.MainContainer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF APplication" Height="600" Width="800"
xmlns:egc="ControlLibrary" Background="{x:Null}"
BorderThickness="0"
AllowsTransparency="True"
MinHeight="300" MinWidth="400" WindowStyle="None" >
```
And the code that does not exhibit the behavior
```
<Window x:Class="MyProject.MainContainer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Application" Height="600" Width="800"
xmlns:egc="ControlLibrary" Background="{x:Null}"
BorderThickness="0"
AllowsTransparency="False"
MinHeight="300" MinWidth="400" WindowStyle="None" >
```
|
I think that I've finally found a workaround. From everything I've read this problem should not be occurring with XP SP3 & .NET 3.5 SP1, but it is.
The example from [this blog post](http://jerryclin.wordpress.com/2007/11/13/creating-non-rectangular-windows-with-interop/) shows how to use the Win32 API functions to create an irregular shaped window, which is what I"m doing. After reworking my main window to use these techniques, things seem to be working as expected and the behavior has not returned.
It is also of note that the reason the author recommends this method is due to performance issues with WPF and transparent windows. While I believe it may be better in .NET 3.5 SP1 that it was, this was not that hard to implement and should perform better.
|
122,865 |
<p>I have a <code>div</code> and an <code>iframe</code> on the page
the <code>div</code> has</p>
<pre><code>z-index: 0;
</code></pre>
<p>the <code>iframe</code> has its content with a popup having a <code>z-index</code> of 1000</p>
<pre><code>z-index: 1000;
</code></pre>
<p>However, the <code>div</code> still overshadows the popup in IE (but works fine in Firefox).</p>
<p>Does anyone know what I can do?</p>
|
[
{
"answer_id": 123037,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": 1,
"selected": false,
"text": "<p>Which version of IE?</p>\n\n<p>I'm no javascript guru, but I think hiding the div when the popup pops might accomplish what you need.</p>\n\n<p>I've had to work with divs and iframes when creating a javascript menu that should show overtop dropdown boxes and listboxes -- other menu implementations just hide these items whose default behavior in IE6 is to show on top of any DIV, no matter the z-index.</p>\n"
},
{
"answer_id": 123079,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://www.quirksmode.org/bugreports/archives/2006/01/Explorer_z_index_bug.html\" rel=\"noreferrer\">Explorer Z-index bug</a></p>\n\n<p>In general, <a href=\"http://www.quirksmode.org/\" rel=\"noreferrer\">http://www.quirksmode.org/</a> is an excellent reference for this sort of thing.</p>\n"
},
{
"answer_id": 123084,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 1,
"selected": false,
"text": "<p>I face the same problem. The problem in my case is that the content in the iframe is not controlled by IE directly, but by Acrobat as it is a pdf file. You can try to show the iframe without the content, in which case the popup displays normally. For some reason IE is not able to control the z-index for external helpers.</p>\n\n<p>It was tested with IE7</p>\n"
},
{
"answer_id": 123176,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Without seeing a code snippet, it's hard to determine what the issue is. You may want to try appending an iframe under your popup that is the same size as your popup. With IE7 if you render the iframed popup after the other iframe has already loaded you should be able to cover up elements that are beneath. I believe some JS calendars and some lightbox/thickbox code does this if you are looking for examples.</p>\n"
},
{
"answer_id": 123199,
"author": "Rich Adams",
"author_id": 10018,
"author_profile": "https://Stackoverflow.com/users/10018",
"pm_score": 1,
"selected": false,
"text": "<p>Without seeing your code, it's difficult to determine the problem. But it's worth noting that z-index only works when the element has been positioned (e.g. <code>position: absolute;</code>), so perhaps that could be an issue?</p>\n\n<p>There's a <a href=\"http://developer.mozilla.org/en/Understanding_CSS_z-index\" rel=\"nofollow noreferrer\">good article on CSS Z-index</a> from the Mozilla Developer Center.</p>\n"
},
{
"answer_id": 123221,
"author": "WalterJ89",
"author_id": 14627,
"author_profile": "https://Stackoverflow.com/users/14627",
"pm_score": 0,
"selected": false,
"text": "<p>never set your z-index to anything bellow 1 enless you want to hide it. I'm not sure about 7.0 but older versions of IE I've had issues with doing that. IE doesn't like z-index that much. Also check your positioning. Positioning may be your issue. sorry, i don't have enough info to help you further. </p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] |
I have a `div` and an `iframe` on the page
the `div` has
```
z-index: 0;
```
the `iframe` has its content with a popup having a `z-index` of 1000
```
z-index: 1000;
```
However, the `div` still overshadows the popup in IE (but works fine in Firefox).
Does anyone know what I can do?
|
[Explorer Z-index bug](http://www.quirksmode.org/bugreports/archives/2006/01/Explorer_z_index_bug.html)
In general, <http://www.quirksmode.org/> is an excellent reference for this sort of thing.
|
122,877 |
<p>So I've got some C code:</p>
<pre><code>#include <stdio.h>
#include <string.h>
/* putting one of the "char*"s here causes a segfault */
void main() {
char* path = "/temp";
char* temp;
strcpy(temp, path);
}
</code></pre>
<p>This compiles, runs, and behaves as it looks. However, if one or both of the character pointers is declared as global variable, strcpy results in a segmentation fault. Why does this happen? Evidently there's an error in my understanding of scope.</p>
|
[
{
"answer_id": 122885,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 3,
"selected": false,
"text": "<p>You forgot to allocate and initialize temp:</p>\n\n<pre><code>temp = (char *)malloc(TEMP_SIZE);\n</code></pre>\n\n<p>Just make sure TEMP_SIZE is big enough. You can also calculate this at run-time, then make sure the size is enough (should be at least strlen(path))</p>\n"
},
{
"answer_id": 122903,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "<p>The important part to note:<br>\n<b>destination string dest must be large enough to receive the copy.</b><br>\nIn your situation temp has no memory allocated to copy into.</p>\n\n<p>Copied from the man page of strcpy:</p>\n\n<pre><code>DESCRIPTION\n The strcpy() function copies the string pointed to by src (including\n the terminating '\\0' character) to the array pointed to by dest. The\n strings may not overlap, and the destination string dest must be large\n enough to receive the copy.\n</code></pre>\n"
},
{
"answer_id": 122910,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 3,
"selected": false,
"text": "<p>The temp variable doesn't point to any storage (memory) and it is uninitialized. </p>\n\n<p>if temp is declared as <code>char temp[32];</code> then the code would work no matter where it is declared. However, there are other problems with declaring temp with a fixed size like that, but that is a question for another day.</p>\n\n<p>Now, why does it crash when declared globally and not locally. Luck...</p>\n\n<p>When declared locally, the value of temp is coming from what ever value might be on the stack at that time. It is luck that it points to an address that doesn't cause a crash. However, it is trashing memory used by someone else.</p>\n\n<p>When declared globally, on most processors these variables will be stored in data segments that will use demand zero pages. Thus <code>char *temp</code> appears as if it was declared <code>char *temp=0</code>.</p>\n"
},
{
"answer_id": 122911,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "<p>You're invoking undefined behavior, since you're not initializing the <code>temp</code> variable. It points to a random location in memory, so your program <em>may</em> work, but most likely it will segfault. You need to have your destination string be an array, or have it point to dynamic memory:</p>\n\n<pre><code>// Make temp a static array of 256 chars\nchar temp[256];\nstrncpy(temp, 256, path);\n\n// Or, use dynamic memory\nchar *temp = (char *)malloc(256);\nstrncpy(temp, 256, path);\n</code></pre>\n\n<p>Also, use <code>strncpy()</code> instead of <code>strcpy()</code> to avoid buffer overruns.</p>\n"
},
{
"answer_id": 122936,
"author": "Sridhar Iyer",
"author_id": 13820,
"author_profile": "https://Stackoverflow.com/users/13820",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned above, you forgot to allocate space for temp.\nI prefer <code>strdup</code> to <code>malloc+strcpy</code>. It does what you want to do.</p>\n"
},
{
"answer_id": 122939,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "<p>No - this doesn't work regardless of the variables - it just looks like it did because you got (un)lucky. You need to allocate space to store the contents of the string, rather than leave the variable uninitialised.</p>\n\n<p>Uninitialised variables on the stack are going to be pointing at pretty much random locations of memory. If these addresses happen to be valid, your code will trample all over whatever was there, but you won't get an error (but may get nasty memory corruption related bugs elsewhere in your code).</p>\n\n<p>Globals consistently fail because they usually get set to specific patterns that point to unmapped memory. Attempting to dereference these gives you an segfault immediately (which is better - leaving it to later makes the bug very hard to track down).</p>\n"
},
{
"answer_id": 122940,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 5,
"selected": true,
"text": "<p>As other posters mentioned, the root of the problem is that temp is uninitialized. When declared as an automatic variable on the stack it will contain whatever garbage happens to be in that memory location. Apparently for the compiler+CPU+OS you are running, the garbage at that location is a valid pointer. The strcpy \"succeeds\" in that it does not segfault, but really it copied a string to some arbitrary location elsewhere in memory. This kind of memory corruption problem strikes fear into the hearts of C programmers everywhere as it is extraordinarily difficult to debug.</p>\n\n<p>When you move the temp variable declaration to global scope, it is placed in the BSS section and automatically zeroed. Attempts to dereference *temp then result in a segfault.</p>\n\n<p>When you move *path to global scope, then *temp moves up one location on the stack. The garbage at that location is apparently not a valid pointer, and so dereferencing *temp results in a segfault.</p>\n"
},
{
"answer_id": 123027,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 2,
"selected": false,
"text": "<p>I'd like to rewrite first Adam's fragment as</p>\n\n<pre><code>// Make temp a static array of 256 chars\nchar temp[256];\nstrncpy(temp, sizeof(temp), path);\ntemp[sizeof(temp)-1] = '\\0';\n</code></pre>\n\n<p>That way you:</p>\n\n<pre><code>1. don't have magic numbers laced through the code, and\n2. you guarantee that your string is null terminated.\n</code></pre>\n\n<p>The second point is at the loss of the last char of your source string if it is >=256 characters long.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12926/"
] |
So I've got some C code:
```
#include <stdio.h>
#include <string.h>
/* putting one of the "char*"s here causes a segfault */
void main() {
char* path = "/temp";
char* temp;
strcpy(temp, path);
}
```
This compiles, runs, and behaves as it looks. However, if one or both of the character pointers is declared as global variable, strcpy results in a segmentation fault. Why does this happen? Evidently there's an error in my understanding of scope.
|
As other posters mentioned, the root of the problem is that temp is uninitialized. When declared as an automatic variable on the stack it will contain whatever garbage happens to be in that memory location. Apparently for the compiler+CPU+OS you are running, the garbage at that location is a valid pointer. The strcpy "succeeds" in that it does not segfault, but really it copied a string to some arbitrary location elsewhere in memory. This kind of memory corruption problem strikes fear into the hearts of C programmers everywhere as it is extraordinarily difficult to debug.
When you move the temp variable declaration to global scope, it is placed in the BSS section and automatically zeroed. Attempts to dereference \*temp then result in a segfault.
When you move \*path to global scope, then \*temp moves up one location on the stack. The garbage at that location is apparently not a valid pointer, and so dereferencing \*temp results in a segfault.
|
122,882 |
<p>What is the proper technique to have <strong>ThreadA</strong> signal <strong>ThreadB</strong> of some event, without having <strong>ThreadB</strong> sit blocked waiting for an event to happen?</p>
<p>i have a background thread that will be filling a shared List<T>. i'm trying to find a way to asynchronously signal the "main" thread that there is data available to be picked up.</p>
<hr>
<p>i considered setting an event with an EventWaitHandle object, but i can't have my main thread sitting at an Event.WaitOne().</p>
<hr>
<p>i considered having a delegate callback, but
a) i don't want the main thread doing work in the delegate: the thread needs to get back to work adding more stuff - i don't want it waiting while the delegate executes, and
b) the delegate needs to be marshalled onto the main thread, but i'm not running a UI, i have no Control to .Invoke the delegate against.</p>
<hr>
<p>i considered have a delegate callback that simply starts a zero interval System.Windows.Forms.Timer (with thread access to the timer synchronized). This way the thread only needs to be stuck as it calls</p>
<p><code>Timer.Enabled = true;</code></p>
<p>but that seems like a hack.</p>
<p>In the olden days my object would have created a hidden window and had the thread post messages to that hidden windows' HWND. i considered creating a hidden control, but i gather that you cannot .Invoke on a control with no handle created. Plus, i have no UI: my object could have been created on a web-server, service, or console, i don't want there to be a graphical control appearing - nor do i want to compile a dependency on System.Windows.Forms.</p>
<hr>
<p>i considered having my object expose an ISynchronizeInvoke interface, but then i would need to implement .Invoke(), and that's my problem.</p>
<hr>
<p>What is the proper technique to have thread A signal thread B of some event, without having thread B sit blocked waiting for an event to happen?</p>
|
[
{
"answer_id": 122953,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>If you use a backgroundworker to start the second thread and use the ProgressChanged event to notify the other thread that data is ready. Other events are available as well. <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.progresschanged.aspx\" rel=\"nofollow noreferrer\">THis MSDN article should get you started</a>.</p>\n"
},
{
"answer_id": 122977,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 1,
"selected": false,
"text": "<p>There are many ways to do this, depending upon exactly what you want to do. A <a href=\"http://www.albahari.com/threading/part2.aspx#_ProducerConsumerQWaitHandle\" rel=\"nofollow noreferrer\">producer/consumer queue</a> is probably what you want. For an excellent in-depth look into threads, see the chapter on <a href=\"http://www.albahari.com/threading/\" rel=\"nofollow noreferrer\">Threading</a> (available online) from the excellent book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596527578\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">C# 3.0 in a Nutshell</a>.</p>\n"
},
{
"answer_id": 123205,
"author": "Leandro Oliveira",
"author_id": 16610,
"author_profile": "https://Stackoverflow.com/users/16610",
"pm_score": 1,
"selected": false,
"text": "<p>You can use an AutoResetEvent (or ManualResetEvent). If you use AutoResetEvent.WaitOne(0, false), it will not block. For example:</p>\n\n<pre><code>AutoResetEvent ev = new AutoResetEvent(false);\n...\nif(ev.WaitOne(0, false)) {\n // event happened\n}\nelse {\n // do other stuff\n}\n</code></pre>\n"
},
{
"answer_id": 123569,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 0,
"selected": false,
"text": "<p>If your \"main\" thread is the Windows message pump (GUI) thread, then you can poll using a Forms.Timer - tune the timer interval according to how quickly you need to have your GUI thread 'notice' the data from the worker thread. </p>\n\n<p>Remember to synchronize access to the shared <code>List<></code> if you are going to use <code>foreach</code>, to avoid <code>CollectionModified</code> exceptions.</p>\n\n<p>I use this technique for all the market-data-driven GUI updates in a real-time trading application, and it works very well.</p>\n"
},
{
"answer_id": 123693,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 2,
"selected": false,
"text": "<p>I'm combining a few responses here. </p>\n\n<p>The ideal situation uses a thread-safe flag such as an <code>AutoResetEvent</code>. You don't have to block indefinitely when you call <code>WaitOne()</code>, in fact it has an overload that allows you to specify a timeout. This overload returns <code>false</code> if the flag was not set during the interval.</p>\n\n<p>A <code>Queue</code> is a more ideal structure for a producer/consumer relationship, but you can mimic it if your requirements are forcing you to use a <code>List</code>. The major difference is you're going to have to ensure your consumer locks access to the collection while it's extracting items; the safest thing is to probably use the <code>CopyTo</code> method to copy all elements to an array, then release the lock. Of course, ensure your producer won't try to update the <code>List</code> while the lock is held.</p>\n\n<p>Here's a simple C# console application that demonstrates how this might be implemented. If you play around with the timing intervals you can cause various things to happen; in this particular configuration I was trying to have the producer generate multiple items before the consumer checks for items.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Threading;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n private static object LockObject = new Object();\n\n private static AutoResetEvent _flag;\n private static Queue<int> _list;\n\n static void Main(string[] args)\n {\n _list = new Queue<int>();\n _flag = new AutoResetEvent(false);\n\n ThreadPool.QueueUserWorkItem(ProducerThread);\n\n int itemCount = 0;\n\n while (itemCount < 10)\n {\n if (_flag.WaitOne(0))\n {\n // there was an item\n lock (LockObject)\n {\n Console.WriteLine(\"Items in queue:\");\n while (_list.Count > 0)\n {\n Console.WriteLine(\"Found item {0}.\", _list.Dequeue());\n itemCount++;\n }\n }\n }\n else\n {\n Console.WriteLine(\"No items in queue.\");\n Thread.Sleep(125);\n }\n }\n }\n\n private static void ProducerThread(object state)\n {\n Random rng = new Random();\n\n Thread.Sleep(250);\n\n for (int i = 0; i < 10; i++)\n {\n lock (LockObject)\n {\n _list.Enqueue(rng.Next(0, 100));\n _flag.Set();\n Thread.Sleep(rng.Next(0, 250));\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>If you don't want to block the producer at all, it's a little more tricky. In this case, I'd suggest making the producer its own class with both a private and a public buffer and a public <code>AutoResetEvent</code>. The producer will by default store items in the private buffer, then try to write them to the public buffer. When the consumer is working with the public buffer, it resets the flag on the producer object. Before the producer tries to move items from the private buffer to the public buffer, it checks this flag and only copies items when the consumer isn't working on it.</p>\n"
},
{
"answer_id": 123694,
"author": "herbrandson",
"author_id": 13181,
"author_profile": "https://Stackoverflow.com/users/13181",
"pm_score": 5,
"selected": true,
"text": "<p>Here's a code sample for the System.ComponentModel.BackgroundWorker class.</p>\n\n<pre><code> private static BackgroundWorker worker = new BackgroundWorker();\n static void Main(string[] args)\n {\n worker.DoWork += worker_DoWork;\n worker.RunWorkerCompleted += worker_RunWorkerCompleted;\n worker.ProgressChanged += worker_ProgressChanged;\n worker.WorkerReportsProgress = true;\n\n Console.WriteLine(\"Starting application.\");\n worker.RunWorkerAsync();\n\n Console.ReadKey();\n }\n\n static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n {\n Console.WriteLine(\"Progress.\");\n }\n\n static void worker_DoWork(object sender, DoWorkEventArgs e)\n {\n Console.WriteLine(\"Starting doing some work now.\");\n\n for (int i = 0; i < 5; i++)\n {\n Thread.Sleep(1000);\n worker.ReportProgress(i);\n }\n }\n\n static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n {\n Console.WriteLine(\"Done now.\");\n }\n</code></pre>\n"
},
{
"answer_id": 124083,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 1,
"selected": false,
"text": "<p>The BackgroundWorker class is answer in this case. It is the only threading construct that is able to asynchronously send messages to the <em>thread</em> that created the BackgroundWorker object. Internally <code>BackgroundWorker</code> uses the <code>AsyncOperation</code> class by calling the <code>asyncOperation.Post()</code> method.</p>\n\n<pre><code>this.asyncOperation = AsyncOperationManager.CreateOperation(null);\nthis.asyncOperation.Post(delegateMethod, arg);\n</code></pre>\n\n<p>A few other classes in the .NET framework also use AsyncOperation:</p>\n\n<ul>\n<li>BackgroundWorker</li>\n<li>SoundPlayer.LoadAsync()</li>\n<li>SmtpClient.SendAsync()</li>\n<li>Ping.SendAsync()</li>\n<li>WebClient.DownloadDataAsync()</li>\n<li>WebClient.DownloadFile()</li>\n<li>WebClient.DownloadFileAsync()</li>\n<li>WebClient...</li>\n<li>PictureBox.LoadAsync()</li>\n</ul>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
What is the proper technique to have **ThreadA** signal **ThreadB** of some event, without having **ThreadB** sit blocked waiting for an event to happen?
i have a background thread that will be filling a shared List<T>. i'm trying to find a way to asynchronously signal the "main" thread that there is data available to be picked up.
---
i considered setting an event with an EventWaitHandle object, but i can't have my main thread sitting at an Event.WaitOne().
---
i considered having a delegate callback, but
a) i don't want the main thread doing work in the delegate: the thread needs to get back to work adding more stuff - i don't want it waiting while the delegate executes, and
b) the delegate needs to be marshalled onto the main thread, but i'm not running a UI, i have no Control to .Invoke the delegate against.
---
i considered have a delegate callback that simply starts a zero interval System.Windows.Forms.Timer (with thread access to the timer synchronized). This way the thread only needs to be stuck as it calls
`Timer.Enabled = true;`
but that seems like a hack.
In the olden days my object would have created a hidden window and had the thread post messages to that hidden windows' HWND. i considered creating a hidden control, but i gather that you cannot .Invoke on a control with no handle created. Plus, i have no UI: my object could have been created on a web-server, service, or console, i don't want there to be a graphical control appearing - nor do i want to compile a dependency on System.Windows.Forms.
---
i considered having my object expose an ISynchronizeInvoke interface, but then i would need to implement .Invoke(), and that's my problem.
---
What is the proper technique to have thread A signal thread B of some event, without having thread B sit blocked waiting for an event to happen?
|
Here's a code sample for the System.ComponentModel.BackgroundWorker class.
```
private static BackgroundWorker worker = new BackgroundWorker();
static void Main(string[] args)
{
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.ProgressChanged += worker_ProgressChanged;
worker.WorkerReportsProgress = true;
Console.WriteLine("Starting application.");
worker.RunWorkerAsync();
Console.ReadKey();
}
static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Progress.");
}
static void worker_DoWork(object sender, DoWorkEventArgs e)
{
Console.WriteLine("Starting doing some work now.");
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
worker.ReportProgress(i);
}
}
static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("Done now.");
}
```
|
122,883 |
<p>Could someone please demystify interfaces for me or point me to some good examples? I keep seeing interfaces popup here and there, but I haven't ever really been exposed to good explanations of interfaces or when to use them.</p>
<p>I am talking about interfaces in a context of interfaces vs. abstract classes.</p>
|
[
{
"answer_id": 122926,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "<p>Interfaces are a way to enforce that an object implements a certain amount of functionality, without having to use inheritance (which leads to strongly coupled code, instead of loosely coupled which can be achieved through using interfaces).</p>\n\n<p>Interfaces describe the functionality, not the implementation.</p>\n"
},
{
"answer_id": 122941,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 5,
"selected": false,
"text": "<p>The easiest answer is that interfaces define a what your class can do. It's a \"contract\" that says that your class will be able to do that action.</p>\n\n<pre><code>Public Interface IRollOver\n Sub RollOver()\nEnd Interface\n\nPublic Class Dog Implements IRollOver\n Public Sub RollOver() Implements IRollOver.RollOver\n Console.WriteLine(\"Rolling Over!\")\n End Sub\nEnd Class\n\nPublic Sub Main()\n Dim d as New Dog()\n Dim ro as IRollOver = TryCast(d, IRollOver)\n If ro isNot Nothing Then\n ro.RollOver()\n End If\nEnd Sub\n</code></pre>\n\n<p>Basically, you are guaranteeing that the Dog class always has the ability to roll over as long as it continues to implement that Interface. Should cats ever gain the ability to RollOver(), they too could implement that interface, and you can treat both Dogs and Cats homogeneously when asking them to RollOver().</p>\n"
},
{
"answer_id": 122971,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "<p>Interfaces allow you to program against a \"description\" instead of a type, which allows you to more-loosely associate elements of your software. </p>\n\n<p>Think of it this way: You want to share data with someone in the cube next to you, so you pull out your flash stick and copy/paste. You walk next door and the guy says \"is that USB?\" and you say yes - all set. It doesn't matter the size of the flash stick, nor the maker - all that matters is that it's USB.</p>\n\n<p>In the same way, interfaces allow you to generisize your development. Using another analogy - imagine you wanted to create an application that virtually painted cars. You might have a signature like this:</p>\n\n<pre><code>public void Paint(Car car, System.Drawing.Color color)...\n</code></pre>\n\n<p>This would work until your client said \"now I want to paint trucks\" so you could do this:</p>\n\n<pre><code>public void Paint (Vehicle vehicle, System.Drawing.Color color)...\n</code></pre>\n\n<p>this would broaden your app... until your client said \"now I want to paint houses!\" What you could have done from the very beginning is created an interface:</p>\n\n<pre><code>public interface IPaintable{\n void Paint(System.Drawing.Color color);\n}\n</code></pre>\n\n<p>...and passed that to your routine:</p>\n\n<pre><code>public void Paint(IPaintable item, System.Drawing.Color color){\n item.Paint(color);\n}\n</code></pre>\n\n<p>Hopefully this makes sense - it's a pretty simplistic explanation but hopefully gets to the heart of it.</p>\n"
},
{
"answer_id": 122987,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 1,
"selected": false,
"text": "<p>Simply put: An interface is a class that methods defined but no implementation in them. In contrast an abstract class has some of the methods implemented but not all. </p>\n"
},
{
"answer_id": 122992,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 4,
"selected": false,
"text": "<p>When you drive a friend's car, you more or less know how to do that. This is because conventional cars all have a very similar interface: steering wheel, pedals, and so forth. Think of this interface as a contract between car manufacturers and drivers. As a driver (the user/client of the interface in software terms), you don't need to learn the particulars of different cars to be able to drive them: e.g., all you need to know is that turning the steering wheel makes the car turn. As a car manufacturer (the provider of an implementation of the interface in software terms) you have a clear idea what your new car should have and how it should behave so that drivers can use them without much extra training. This contract is what people in software design refer to as decoupling (the user from the provider) -- the client code is in terms of using an interface rather than a particular implementation thereof and hence doesn't need to know the details of the objects implementing the interface.</p>\n"
},
{
"answer_id": 123004,
"author": "JoshReedSchramm",
"author_id": 7018,
"author_profile": "https://Stackoverflow.com/users/7018",
"pm_score": 6,
"selected": false,
"text": "<p>Interfaces establish a contract between a class and the code that calls it. They also allow you to have similar classes that implement the same interface but do different actions or events and not have to know which you are actually working with. This might make more sense as an example so let me try one here. </p>\n\n<p>Say you have a couple classes called Dog, Cat, and Mouse. Each of these classes is a Pet and in theory you could inherit them all from another class called Pet but here's the problem. Pets in and of themselves don't do anything. You can't go to the store and buy a pet. You can go and buy a dog or a cat but a pet is an abstract concept and not concrete. </p>\n\n<p>So You know pets can do certain things. They can sleep, or eat, etc. So you define an interface called IPet and it looks something like this (C# syntax)</p>\n\n<pre><code>public interface IPet\n{\n void Eat(object food);\n void Sleep(int duration);\n}\n</code></pre>\n\n<p>Each of your Dog, Cat, and Mouse classes implement IPet. </p>\n\n<pre><code>public class Dog : IPet\n</code></pre>\n\n<p>So now each of those classes has to have it's own implementation of Eat and Sleep. Yay you have a contract... Now what's the point. </p>\n\n<p>Next let's say you want to make a new object called PetStore. And this isn't a very good PetStore so they basically just sell you a random pet (yes i know this is a contrived example). </p>\n\n<pre><code>public class PetStore\n{\n public static IPet GetRandomPet()\n { \n //Code to return a random Dog, Cat, or Mouse\n } \n}\n\nIPet myNewRandomPet = PetStore.GetRandomPet();\nmyNewRandomPet.Sleep(10);\n</code></pre>\n\n<p>The problem is you don't know what type of pet it will be. Thanks to the interface though you know whatever it is it will Eat and Sleep. </p>\n\n<p>So this answer may not have been helpful at all but the general idea is that interfaces let you do neat stuff like Dependency Injection and Inversion of Control where you can get an object, have a well defined list of stuff that object can do without ever REALLY knowing what the concrete type of that object is. </p>\n"
},
{
"answer_id": 123013,
"author": "Kevin Pang",
"author_id": 1574,
"author_profile": "https://Stackoverflow.com/users/1574",
"pm_score": 1,
"selected": false,
"text": "<p>Think of an interface as a contract. When a class implements an interface, it is essentially agreeing to honor the terms of that contract. As a consumer, you only care that the objects you have can perform their contractual duties. Their inner workings and details aren't important.</p>\n"
},
{
"answer_id": 123015,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 2,
"selected": false,
"text": "<p>Interfaces let you code against objects in a generic way. For instance, say you have a method that sends out reports. Now say you have a new requirement that comes in where you need to write a new report. It would be nice if you could reuse the method you already had written right? Interfaces makes that easy:</p>\n\n<pre><code>interface IReport\n{\n string RenderReport();\n}\n\nclass MyNewReport : IReport\n{\n public string RenderReport()\n {\n return \"Hello World Report!\";\n\n }\n}\n\nclass AnotherReport : IReport\n{\n public string RenderReport()\n {\n return \"Another Report!\";\n\n }\n}\n\n//This class can process any report that implements IReport!\nclass ReportEmailer()\n{\n public void EmailReport(IReport report)\n {\n Email(report.RenderReport());\n }\n}\n\nclass MyApp()\n{\n void Main()\n {\n //create specific \"MyNewReport\" report using interface\n IReport newReport = new MyNewReport();\n\n //create specific \"AnotherReport\" report using interface\n IReport anotherReport = new AnotherReport();\n\n ReportEmailer reportEmailer = new ReportEmailer();\n\n //emailer expects interface\n reportEmailer.EmailReport(newReport);\n reportEmailer.EmailReport(anotherReport);\n\n\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 123019,
"author": "fooledbyprimes",
"author_id": 20714,
"author_profile": "https://Stackoverflow.com/users/20714",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a db related example I often use. Let us say you have an object and a container object like an list. Let us assume that sometime you might want to store the objects in a particular sequence. Assume that the sequence is not related to the position in the array but instead that the objects are a subset of a larger set of objects and the sequence position is related to the database sql filtering. </p>\n\n<p>To keep track of your customized sequence positions you could make your object implement a custom interface. The custom interface could mediate the organizational effort required to maintain such sequences. </p>\n\n<p>For example, the sequence you are interested in has nothing to do with primary keys in the records. With the object implementing the interface you could say myObject.next() or myObject.prev().</p>\n"
},
{
"answer_id": 123029,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 3,
"selected": false,
"text": "<p>This is a rather \"long\" subject, but let me try to put it simple.</p>\n\n<p>An interface is -as \"they name it\"- a Contract. But forget about that word. </p>\n\n<p>The best way to understand them is through some sort of pseudo-code example. That's how I understood them long time ago. </p>\n\n<p>Suppose you have an app that processes Messages. A Message contains some stuff, like a subject, a text, etc.</p>\n\n<p>So you write your MessageController to read a database, and extract messages. It's very nice until you suddenly hear that Faxes will be also implemented soon. So you will now have to read \"Faxes\" and process them as messages!</p>\n\n<p>This could easily turn into a Spagetti code. So what you do instead of having a MessageController than controls \"Messages\" only, you make it able to work with an <strong>interface</strong> called IMessage (the I is just common usage, but not required).</p>\n\n<p>Your IMessage interface, contains some basic data you <em>need</em> to make sure that you're able to process the Message as such. </p>\n\n<p>So when you create your EMail, Fax, PhoneCall classes, you make them <strong>Implement</strong> the <strong>Interface</strong> called <em>IMessage</em>. </p>\n\n<p>So in your MessageController, you can have a method called like this: </p>\n\n<pre><code>private void ProcessMessage(IMessage oneMessage)\n{\n DoSomething();\n}\n</code></pre>\n\n<p>If you had not used Interfaces, you'd have to have: </p>\n\n<pre><code>private void ProcessEmail(Email someEmail);\nprivate void ProcessFax(Fax someFax);\netc.\n</code></pre>\n\n<p>So, by using a <strong>common</strong> interface, you just made sure that the ProcessMessage method will be able to work with it, no matter if it was a Fax, an Email a PhoneCall, etc. </p>\n\n<p><em>Why or how</em>?</p>\n\n<p>Because the interface is a <em>contract</em> that specifies some things you <strong>must</strong> adhere (or implement) in order to be able to use it. Think of it as a <em>badge</em>. If your object \"Fax\" doesn't have the IMessage interface, then your ProcessMessage method wouldn't be able to work with that, it will give you an invalid type, because you're passing a Fax to a method that expects an IMessage object.</p>\n\n<p>Do you see the point? </p>\n\n<p>Think of the interface as a \"subset\" of methods and properties that you will have available, <strong>despite</strong> the real object type. If the original object (Fax, Email, PhoneCall, etc) implements that interface, you can safety pass it across methods that need that Interface. </p>\n\n<p>There's more magic hidden in there, you can CAST the interfaces back to their original objects:</p>\n\n<p>Fax myFax = (Fax)SomeIMessageThatIReceive;</p>\n\n<p>The ArrayList() in .NET 1.1 had a nice interface called IList. If you had an IList (very \"generic\") you could transform it into an ArrayList:</p>\n\n<pre><code>ArrayList ar = (ArrayList)SomeIList;\n</code></pre>\n\n<p>And there are thousands of samples out there in the wild. </p>\n\n<p>Interfaces like ISortable, IComparable, etc., define the methods and properties you <strong>must</strong> implement in your class in order to achieve that functionality.</p>\n\n<p>To expand our sample, you could have a List<> of Emails, Fax, PhoneCall, all in the same List, if the Type is IMessage, but you couldn't have them all together if the objects were simply Email, Fax, etc.</p>\n\n<p>If you wanted to sort (or enumerate for example) your objects, you'd need them to implement the corresponding interface. In the .NET sample, if you have a list of \"Fax\" objects and want to be able to <em>sort</em> them by using MyList.Sort(), you <strong>need</strong> to make your fax class like this:</p>\n\n<pre><code>public class Fax : ISorteable \n{\n //implement the ISorteable stuff here.\n}\n</code></pre>\n\n<p>I hope this gives you a hint. Other users will possibly post other good examples. Good luck! and Embrace the power of INterfaces.</p>\n\n<p><strong>warning</strong>: Not everything is good about interfaces, there are <em>some</em> issues with them, OOP purists will start a war on this. I shall remain aside. One drawback of an Interfce (in .NET 2.0 at least) is that you cannot have PRIVATE members, or protected, it <em>must</em> be public. This makes some sense, but sometimes you wish you could simply declare stuff as private or protected. </p>\n"
},
{
"answer_id": 123030,
"author": "JasonTrue",
"author_id": 13433,
"author_profile": "https://Stackoverflow.com/users/13433",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming you're referring to interfaces in statically-typed object-oriented languages, the primary use is in asserting that your class follows a particular contract or protocol.</p>\n\n<p>Say you have:</p>\n\n<pre><code>public interface ICommand\n{\n void Execute();\n}\npublic class PrintSomething : ICommand\n{\n OutputStream Stream { get; set; }\n String Content {get; set;}\n void Execute()\n { \n Stream.Write(content);\n }\n}\n</code></pre>\n\n<p>Now you have a substitutable command structure. Any instance of a class that implements IExecute can be stored in a list of some sort, say something that implements IEnumerable and you can loop through that and execute each one, knowing that each object will Just Do The Right Thing. You can create a composite command by implementing CompositeCommand which will have its own list of commands to run, or a LoopingCommand to run a set of commands repeatedly, then you'll have most of a simple interpreter.</p>\n\n<p>When you can reduce a set of objects to a behavior that they all have in common, you might have cause to extract an interface. Also, sometimes you can use interfaces to prevent objects from accidentally intruding on the concerns of that class; for example, you may implement an interface that only allows clients to retrieve, rather than change data in your object, and have most objects receive only a reference to the retrieval interface.</p>\n\n<p>Interfaces work best when your interfaces are relatively simple and make few assumptions.</p>\n\n<p>Look up the Liskov subsitution principle to make more sense of this.</p>\n\n<p>Some statically-typed languages like C++ don't support interfaces as a first-class concept, so you create interfaces using pure abstract classes.</p>\n\n<p><strong>Update</strong>\nSince you seem to be asking about abstract classes vs. interfaces, here's my preferred oversimplification:</p>\n\n<ul>\n<li>Interfaces define capabilities and features.</li>\n<li>Abstract classes define core functionality.</li>\n</ul>\n\n<p>Typically, I do an extract interface refactoring before I build an abstract class. I'm more likely to build an abstract class if I think there should be a creational contract (specifically, that a specific type of constructor should always be supported by subclasses). However, I rarely use \"pure\" abstract classes in C#/java. I'm far more likely to implement a class with at least one method containing meaningful behavior, and use abstract methods to support template methods called by that method. Then the abstract class is a base implementation of a behavior, which all concrete subclasses can take advantage of without having to reimplement.</p>\n"
},
{
"answer_id": 123041,
"author": "cblades",
"author_id": 21305,
"author_profile": "https://Stackoverflow.com/users/21305",
"pm_score": 0,
"selected": false,
"text": "<p>Interfaces require any class that implements them to contain the methods defined in the interface.</p>\n\n<p>The purpose is so that, without having to see the code in a class, you can know if it can be used for a certain task. For example, the Integer class in Java implements the comparable interface, so, if you only saw the method header (public class String implements Comparable), you would know that it contains a compareTo() method.</p>\n"
},
{
"answer_id": 123053,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 2,
"selected": false,
"text": "<p>OK, so it's about abstract classes vs. interfaces...</p>\n\n<p>Conceptually, abstract classes are there to be used as base classes. Quite often they themselves already provide some basic functionality, and the subclasses have to provide their own implementation of the abstract methods (those are the methods which aren't implemented in the abstract base class).</p>\n\n<p>Interfaces are mostly used for decoupling the client code from the details of a particular implementation. Also, sometimes the ability to switch the implementation without changing the client code makes the client code more generic.</p>\n\n<p>On the technical level, it's harder to draw the line between abstract classes and interfaces, because in some languages (e.g., C++), there's no syntactic difference, or because you could also use abstract classes for the purposes of decoupling or generalization. Using an abstract class as an interface is possible because every base class, by definition, defines an interface that all of its subclasses should honor (i.e., it should be possible to use a subclass instead of a base class).</p>\n"
},
{
"answer_id": 123060,
"author": "Internet Friend",
"author_id": 18037,
"author_profile": "https://Stackoverflow.com/users/18037",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to the function interfaces have within programming languages, they also are a powerful semantic tool when expressing design ideas to other <em>people</em>.</p>\n\n<p>A code base with well-designed interfaces is suddenly a lot easier to discuss. \"Yes, you need a CredentialsManager to register new remote servers.\" \"Pass a PropertyMap to ThingFactory to get a working instance.\"</p>\n\n<p>Ability to address a complex thing with a single word is pretty useful.</p>\n"
},
{
"answer_id": 123109,
"author": "Sam Schutte",
"author_id": 146,
"author_profile": "https://Stackoverflow.com/users/146",
"pm_score": 2,
"selected": false,
"text": "<p>Interfaces are also key to polymorphism, one of the \"THREE PILLARS OF OOD\".</p>\n\n<p>Some people touched on it above, polymorphism just means a given class can take on different \"forms\". Meaning, if we have two classes, \"Dog\" and \"Cat\" and both implement the interface \"INeedFreshFoodAndWater\" (hehe) - your code can do something like this (pseudocode):</p>\n\n<pre><code>INeedFreshFoodAndWater[] array = new INeedFreshFoodAndWater[];\narray.Add(new Dog());\narray.Add(new Cat());\n\nforeach(INeedFreshFoodAndWater item in array)\n{\n item.Feed();\n item.Water();\n}\n</code></pre>\n\n<p>This is powerful because it allows you to treat different classes of objects abstractly, and allows you to do things like make your objects more loosely coupled, etc.</p>\n"
},
{
"answer_id": 123203,
"author": "David",
"author_id": 21328,
"author_profile": "https://Stackoverflow.com/users/21328",
"pm_score": 1,
"selected": false,
"text": "<p>Simple answer: An interface is a bunch of method signatures (+ return type). When an object says it <em>implements</em> an interface, you know it exposes that set of methods.</p>\n"
},
{
"answer_id": 123244,
"author": "Eric Asberry",
"author_id": 20437,
"author_profile": "https://Stackoverflow.com/users/20437",
"pm_score": 1,
"selected": false,
"text": "<p>One good reason for using an interface vs. an abstract class in Java is that a subclass cannot extend multiple base classes, but it CAN implement multiple interfaces. </p>\n"
},
{
"answer_id": 123284,
"author": "user21334",
"author_id": 21334,
"author_profile": "https://Stackoverflow.com/users/21334",
"pm_score": 1,
"selected": false,
"text": "<p>Java does not allow multiple inheritance (for very good reasons, look up dreadful diamond) but what if you want to have your class supply several sets of behavior? Say you want anyone who uses it to know it can be serialized, and also that it can paint itself on the screen. the answer is to implement two different interfaces.</p>\n\n<p>Because interfaces contain no implementation of their own and no instance members it is safe to implement several of them in the same class with no ambiguities.</p>\n\n<p>The down side is that you will have to have the implementation in each class separately. So if your hierarchy is simple and there are parts of the implementation that should be the same for all the inheriting classes use an abstract class. </p>\n"
},
{
"answer_id": 123342,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 1,
"selected": false,
"text": "<p>Like others have said here, interfaces define a contract (how the classes who use the interface will \"look\") and abstract classes define shared functionality.</p>\n\n<p>Let's see if the code helps:</p>\n\n<pre><code>public interface IReport\n{\n void RenderReport(); // This just defines the method prototype\n}\n\npublic abstract class Reporter\n{\n protected void DoSomething()\n {\n // This method is the same for every class that inherits from this class\n }\n}\n\npublic class ReportViolators : Reporter, IReport\n{\n public void RenderReport()\n {\n // Some kind of implementation specific to this class\n }\n}\n\npublic class ClientApp\n{\n var violatorsReport = new ReportViolators();\n\n // The interface method\n violatorsReport.RenderReport();\n\n // The abstract class method\n violatorsReport.DoSomething();\n}\n</code></pre>\n"
},
{
"answer_id": 123874,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 1,
"selected": false,
"text": "<p>Interfaces are a way to implement conventions in a way that is still strongly typed and polymorphic.</p>\n\n<p>A good real world example would be IDisposable in .NET. A class that implements the IDisposable interface forces that class to implement the Dispose() method. If the class doesn't implement Dispose() you'll get a compiler error when trying to build. Additionally, this code pattern:</p>\n\n<pre><code>using (DisposableClass myClass = new DisposableClass())\n {\n // code goes here\n }\n</code></pre>\n\n<p>Will cause myClass.Dispose() to be executed automatically when execution exits the inner block.</p>\n\n<p>However, and this is important, there is no enforcement as to what your Dispose() method should do. You could have your Dispose() method pick random recipes from a file and email them to a distribution list, the compiler doesn't care. The intent of the IDisposable pattern is to make cleaning up resources easier. If instances of a class will hold onto file handles then IDisposable makes it very easy to centralize the deallocation and cleanup code in one spot and to promote a style of use which ensures that deallocation always occurs.</p>\n\n<p>And that's the key to interfaces. They are a way to streamline programming conventions and design patterns. Which, when used correctly, promotes simpler, self-documenting code which is easier to use, easier to maintain, and more correct.</p>\n"
},
{
"answer_id": 124545,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 4,
"selected": false,
"text": "<p>Interfaces are a mechanism to reduce coupling between different, possibly disparate parts of a system.</p>\n\n<p>From a <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\" rel=\"nofollow noreferrer\">.NET</a> perspective</p>\n\n<ul>\n<li>The interface definition is a list of operations and/or properties.</li>\n<li>Interface methods are always public.</li>\n<li>The interface itself doesn't have to be public.</li>\n</ul>\n\n<p>When you create a class that <em>implements</em> the interface, you must provide either an explicit or implicit implementation of all methods and properties defined by the interface.</p>\n\n<p>Further, .NET has only single inheritance, and interfaces are a necessity for an object to expose methods to other objects that aren't aware of, or lie outside of its class hierarchy. This is also known as exposing behaviors.</p>\n\n<h3>An example that's a little more concrete:</h3>\n\n<p>Consider is we have many DTO's (data transfer objects) that have properties for who updated last, and when that was. The problem is that not all the DTO's have this property because it's not always relevant.</p>\n\n<p>At the same time we desire a generic mechanism to guarantee these properties are set if available when submitted to the workflow, but the workflow object should be loosely coupled from the submitted objects. i.e. the submit workflow method shouldn't really know about all the subtleties of each object, and all objects in the workflow aren't necessarily DTO objects.</p>\n\n<pre><code>// First pass - not maintainable\nvoid SubmitToWorkflow(object o, User u)\n{\n if (o is StreetMap)\n {\n var map = (StreetMap)o;\n map.LastUpdated = DateTime.UtcNow;\n map.UpdatedByUser = u.UserID;\n }\n else if (o is Person)\n {\n var person = (Person)o;\n person.LastUpdated = DateTime.Now; // Whoops .. should be UtcNow\n person.UpdatedByUser = u.UserID;\n }\n // Whoa - very unmaintainable.\n</code></pre>\n\n<p>In the code above, <code>SubmitToWorkflow()</code> must know about each and every object. Additionally, the code is a mess with one massive if/else/switch, violates the <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">don't repeat yourself</a> (DRY) principle, and requires developers to remember copy/paste changes every time a new object is added to the system.</p>\n\n<pre><code>// Second pass - brittle\nvoid SubmitToWorkflow(object o, User u)\n{\n if (o is DTOBase)\n {\n DTOBase dto = (DTOBase)o;\n dto.LastUpdated = DateTime.UtcNow;\n dto.UpdatedByUser = u.UserID;\n }\n</code></pre>\n\n<p>It is slightly better, but it is still brittle. If we want to submit other types of objects, we need still need more case statements. etc.</p>\n\n<pre><code>// Third pass pass - also brittle\nvoid SubmitToWorkflow(DTOBase dto, User u)\n{\n dto.LastUpdated = DateTime.UtcNow;\n dto.UpdatedByUser = u.UserID;\n</code></pre>\n\n<p>It is still brittle, and both methods impose the constraint that all the DTOs have to implement this property which we indicated wasn't universally applicable. Some developers might be tempted to write do-nothing methods, but that smells bad. We don't want classes pretending they support update tracking but don't.</p>\n\n<h3>Interfaces, how can they help?</h3>\n\n<p>If we define a very simple interface:</p>\n\n<pre><code>public interface IUpdateTracked\n{\n DateTime LastUpdated { get; set; }\n int UpdatedByUser { get; set; }\n}\n</code></pre>\n\n<p>Any class that needs this automatic update tracking can implement the interface.</p>\n\n<pre><code>public class SomeDTO : IUpdateTracked\n{\n // IUpdateTracked implementation as well as other methods for SomeDTO\n}\n</code></pre>\n\n<p>The workflow method can be made to be a lot more generic, smaller, and more maintainable, and it will continue to work no matter how many classes implement the interface (DTOs or otherwise) because it only deals with the interface.</p>\n\n<pre><code>void SubmitToWorkflow(object o, User u)\n{\n IUpdateTracked updateTracked = o as IUpdateTracked;\n if (updateTracked != null)\n {\n updateTracked.LastUpdated = DateTime.UtcNow;\n updateTracked.UpdatedByUser = u.UserID;\n }\n // ...\n</code></pre>\n\n<ul>\n<li>We can note the variation <code>void SubmitToWorkflow(IUpdateTracked updateTracked, User u)</code> would guarantee type safety, however it doesn't seem as relevant in these circumstances.</li>\n</ul>\n\n<p>In some production code we use, we have code generation to create these DTO classes from the database definition. The only thing the developer does is have to create the field name correctly and decorate the class with the interface. As long as the properties are called LastUpdated and UpdatedByUser, it just works.</p>\n\n<p>Maybe you're asking <em>What happens if my database is legacy and that's not possible?</em> You just have to do a little more typing; another great feature of interfaces is they can allow you to create a bridge between the classes.</p>\n\n<p>In the code below we have a fictitious <code>LegacyDTO</code>, a pre-existing object having similarly-named fields. It's implementing the IUpdateTracked interface to bridge the existing, but differently named properties.</p>\n\n<pre><code>// Using an interface to bridge properties\npublic class LegacyDTO : IUpdateTracked\n{\n public int LegacyUserID { get; set; }\n public DateTime LastSaved { get; set; }\n\n public int UpdatedByUser\n {\n get { return LegacyUserID; }\n set { LegacyUserID = value; }\n }\n public DateTime LastUpdated\n {\n get { return LastSaved; }\n set { LastSaved = value; }\n }\n}\n</code></pre>\n\n<p>You might thing <em>Cool, but isn't it confusing having multiple properties?</em> or <em>What happens if there are already those properties, but they mean something else?</em> .NET gives you the ability to explicitly implement the interface.</p>\n\n<p>What this means is that the IUpdateTracked properties will only be visible when we're using a reference to IUpdateTracked. Note how there is no public modifier on the declaration, and the declaration includes the interface name.</p>\n\n<pre><code>// Explicit implementation of an interface\npublic class YetAnotherObject : IUpdatable\n{\n int IUpdatable.UpdatedByUser\n { ... }\n DateTime IUpdatable.LastUpdated\n { ... }\n</code></pre>\n\n<p>Having so much flexibility to define how the class implements the interface gives the developer a lot of freedom to decouple the object from methods that consume it. Interfaces are a great way to break coupling.</p>\n\n<p>There is a lot more to interfaces than just this. This is just a simplified real-life example that utilizes one aspect of interface based programming.</p>\n\n<p>As I mentioned earlier, and by other responders, you can create methods that take and/or return interface references rather than a specific class reference. If I needed to find duplicates in a list, I could write a method that takes and returns an <code>IList</code> (an interface defining operations that work on lists) and I'm not constrained to a concrete collection class.</p>\n\n<pre><code>// Decouples the caller and the code as both\n// operate only on IList, and are free to swap\n// out the concrete collection.\npublic IList<T> FindDuplicates( IList<T> list )\n{\n var duplicates = new List<T>()\n // TODO - write some code to detect duplicate items\n return duplicates;\n}\n</code></pre>\n\n<h3>Versioning caveat</h3>\n\n<p>If it's a public interface, you're declaring <em>I guarantee interface x looks like this!</em> And once you have shipped code and published the interface, you should never change it. As soon as consumer code starts to rely on that interface, you don't want to break their code in the field.</p>\n\n<p>See <a href=\"http://haacked.com/archive/2008/02/20/versioning-issues-with-abstract-base-classes-and-interfaces.aspx\" rel=\"nofollow noreferrer\">this Haacked post</a> for a good discussion.</p>\n\n<h3>Interfaces versus abstract (base) classes</h3>\n\n<p>Abstract classes can provide implementation whereas Interfaces cannot. Abstract classes are in some ways more flexible in the versioning aspect if you follow some guidelines like the NVPI (Non-Virtual Public Interface) pattern.</p>\n\n<p>It's worth reiterating that in .NET, a class can only inherit from a single class, but a class can implement as many interfaces as it likes.</p>\n\n<h2>Dependency Injection</h2>\n\n<p>The quick summary of interfaces and dependency injection (DI) is that the use of interfaces enables developers to write code that is programmed against an interface to provide services. In practice you can end up with a lot of small interfaces and small classes, and one idea is that small classes that do one thing and only one thing are much easier to code and maintain.</p>\n\n<pre><code>class AnnualRaiseAdjuster\n : ISalaryAdjuster\n{\n AnnualRaiseAdjuster(IPayGradeDetermination payGradeDetermination) { ... }\n\n void AdjustSalary(Staff s)\n {\n var payGrade = payGradeDetermination.Determine(s);\n s.Salary = s.Salary * 1.01 + payGrade.Bonus;\n }\n}\n</code></pre>\n\n<p>In brief, the benefit shown in the above snippet is that the pay grade determination is just injected into the annual raise adjuster. How pay grade is determined doesn't actually matter to this class. When testing, the developer can mock pay grade determination results to ensure the salary adjuster functions as desired. The tests are also fast because the test is only testing the class, and not everything else.</p>\n\n<p>This isn't a DI primer though as there are whole books devoted to the subject; the above example is very simplified.</p>\n"
},
{
"answer_id": 3646867,
"author": "terjetyl",
"author_id": 29519,
"author_profile": "https://Stackoverflow.com/users/29519",
"pm_score": 1,
"selected": false,
"text": "<p>I have had the same problem as you and I find the \"contract\" explanation a bit confusing.</p>\n\n<p>If you specify that a method takes an IEnumerable interface as an in-parameter you could say that this is a contract specifying that the parameter must be of a type that inherits from the IEnumerable interface and hence supports all methods specified in the IEnumerable interface. The same would be true though if we used an abstract class or a normal class. Any object that inherits from those classes would be ok to pass in as a parameter. You would in any case be able to say that the inherited object supports all public methods in the base class whether the base class is a normal class, an abstract class or an interface. </p>\n\n<p>An abstract class with all abstract methods is basically the same as an interface so you could say an interface is simply a class without implemented methods. You could actually drop interfaces from the language and just use abstract class with only abstract methods instead. I think the reason we separate them is for semantic reasons but for coding reasons I don't see the reason and find it just confusing. </p>\n\n<p>Another suggestion could be to rename the interface to interface class as the interface is just another variation of a class.</p>\n\n<p>In certain languages there are subtle differences that allows a class to inherit only 1 class but multiple interfaces while in others you could have many of both, but that is another issue and not directly related I think</p>\n"
},
{
"answer_id": 11818132,
"author": "Eric J.",
"author_id": 141172,
"author_profile": "https://Stackoverflow.com/users/141172",
"pm_score": 0,
"selected": false,
"text": "<p>In your simple case, you could achieve something similar to what you get with interfaces by using a common base class that implements <code>show()</code> (or perhaps defines it as abstract). Let me change your generic names to something more concrete, <em>Eagle</em> and <em>Hawk</em> instead of <em>MyClass1</em> and <em>MyClass2</em>. In that case you could write code like</p>\n\n<pre><code>Bird bird = GetMeAnInstanceOfABird(someCriteriaForSelectingASpecificKindOfBird);\nbird.Fly(Direction.South, Speed.CruisingSpeed);\n</code></pre>\n\n<p>That lets you write code that can handle anything that <em>is a</em> <em>Bird</em>. You could then write code that causes the <em>Bird</em> to do its thing (fly, eat, lay eggs, and so forth) that acts on an instance it treats as a <em>Bird</em>. That code would work whether <em>Bird</em> is really an <em>Eagle</em>, <em>Hawk</em>, or anything else that derives from <em>Bird</em>.</p>\n\n<p>That paradigm starts to get messy, though, when you don't have a true <em>is a</em> relationship. Say you want to write code that flies things around in the sky. If you write that code to accept a <em>Bird</em> base class, it suddenly becomes hard to evolve that code to work on a <em>JumboJet</em> instance, because while a <em>Bird</em> and a <em>JumboJet</em> can certainly both fly, a <em>JumboJet</em> is most certainly not a <em>Bird</em>.</p>\n\n<p>Enter the interface.</p>\n\n<p>What <em>Bird</em> (and <em>Eagle</em>, and <em>Hawk</em>) <em>do</em> have in common is that they can all fly. If you write the above code instead to act on an interface, <em>IFly</em>, that code can be applied to anything that provides an implementation to that interface.</p>\n"
},
{
"answer_id": 11831062,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest way to understand interfaces is to start by considering what class inheritance means. It includes two aspects:</p>\n\n<ol><li>Members of a derived class can use public or protected members of a base class as their own.\n<li>Members of a derived class can be used by code which expects a member of the base class (meaning they are substitutable).\n</ol>\n\n<p>Both of these features are useful, but because it is difficult to allow a class to use members of more than one class as its own, many languages and frameworks only allow classes to inherit from a single base class. On the other hand, there is no particular difficulty with having a class be substitutable for multiple other unrelated things.</p>\n\n<p>Further, because the first benefit of inheritance can be largely achieved via encapsulation, the relative benefit from allowing multiple-inheritance of the first type is somewhat limited. On the other hand, being able to substitute an object for multiple unrelated types of things is a useful ability which cannot be readily achieved without language support.</p>\n\n<p>Interfaces provide a means by which a language/framework can allow programs to benefit from the second aspect of inheritance for multiple base types, without requiring it to also provide the first.</p>\n"
},
{
"answer_id": 13000272,
"author": "Arcturus",
"author_id": 1202971,
"author_profile": "https://Stackoverflow.com/users/1202971",
"pm_score": 2,
"selected": false,
"text": "<p>Most of the interfaces you come across are a collection of method and property signatures. Any one who implements an interface must provide definitions to what ever is in the interface. </p>\n"
},
{
"answer_id": 24603321,
"author": "Rezo Megrelidze",
"author_id": 2204040,
"author_profile": "https://Stackoverflow.com/users/2204040",
"pm_score": 1,
"selected": false,
"text": "<p>Interface is like a fully abstract class. That is, an abstract class with only abstract members. You can also implement multiple interfaces, it's like inheriting from multiple fully abstract classes. Anyway.. this explanation only helps if you understand what an abstract class is. </p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16820/"
] |
Could someone please demystify interfaces for me or point me to some good examples? I keep seeing interfaces popup here and there, but I haven't ever really been exposed to good explanations of interfaces or when to use them.
I am talking about interfaces in a context of interfaces vs. abstract classes.
|
Interfaces allow you to program against a "description" instead of a type, which allows you to more-loosely associate elements of your software.
Think of it this way: You want to share data with someone in the cube next to you, so you pull out your flash stick and copy/paste. You walk next door and the guy says "is that USB?" and you say yes - all set. It doesn't matter the size of the flash stick, nor the maker - all that matters is that it's USB.
In the same way, interfaces allow you to generisize your development. Using another analogy - imagine you wanted to create an application that virtually painted cars. You might have a signature like this:
```
public void Paint(Car car, System.Drawing.Color color)...
```
This would work until your client said "now I want to paint trucks" so you could do this:
```
public void Paint (Vehicle vehicle, System.Drawing.Color color)...
```
this would broaden your app... until your client said "now I want to paint houses!" What you could have done from the very beginning is created an interface:
```
public interface IPaintable{
void Paint(System.Drawing.Color color);
}
```
...and passed that to your routine:
```
public void Paint(IPaintable item, System.Drawing.Color color){
item.Paint(color);
}
```
Hopefully this makes sense - it's a pretty simplistic explanation but hopefully gets to the heart of it.
|
122,909 |
<p>I have a file. I want to get its contents into a blob column in my oracle database or into a blob variable in my PL/SQL program. What is the best way to do that?</p>
|
[
{
"answer_id": 123017,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "<p>Depends a bit on your environment. In Java you could do it something like this...</p>\n\n<pre><code>// Need as OracleConnection in mConnection\n\n// Set an EMPTY_BLOB()\nString update = \"UPDATE tablename\"+\n \" SET blob_column = EMPTY_BLOB()\"+\n \" WHERE ID = \"+id;\nCallableStatement stmt = mConnection.prepareCall(update);\nstmt.executeUpdate();\n\n// Lock the row FOR UPDATE\nString select = \"BEGIN \" +\n \" SELECT \" + blob_column\n \" INTO ? \" +\n \" FROM \" + tablename +\n \" WHERE ID = '\" + id + \"'\" +\n \" FOR UPDATE; \" +\n \"END;\";\n\nstmt = mConnection.prepareCall(select);\nstmt.registerOutParameter(1, java.sql.Types.BLOB);\nstmt.executeUpdate();\n\nBLOB blob = (BLOB) stmt.getBlob(1);\nOutputStream bos = blob.setBinaryStream(0L);\nFileInputStream fis = new FileInputStream(file);\n// Code needed here to copy one stream to the other\nfis.close();\nbos.close();\nstmt.close();\n\nmConnection.commit();\n</code></pre>\n\n<p>But it really depends what environment / tools you're using. More info needed.</p>\n"
},
{
"answer_id": 123051,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 5,
"selected": true,
"text": "<p>To do it entirely in PL/SQL, the file would need to be on the server, located in a directory which you'd need to define in the database. Create the following objects:</p>\n\n<pre><code>CREATE OR REPLACE DIRECTORY\n BLOB_DIR\n AS\n '/oracle/base/lobs'\n/\n\n\n\nCREATE OR REPLACE PROCEDURE BLOB_LOAD\nAS\n\n lBlob BLOB;\n lFile BFILE := BFILENAME('BLOB_DIR', 'filename');\n\nBEGIN\n\n INSERT INTO table (id, your_blob)\n VALUES (xxx, empty_blob())\n RETURNING your_blob INTO lBlob;\n\n DBMS_LOB.OPEN(lFile, DBMS_LOB.LOB_READONLY);\n\n DBMS_LOB.OPEN(lBlob, DBMS_LOB.LOB_READWRITE);\n\n DBMS_LOB.LOADFROMFILE(DEST_LOB => lBlob,\n SRC_LOB => lFile,\n AMOUNT => DBMS_LOB.GETLENGTH(lFile));\n\n DBMS_LOB.CLOSE(lFile);\n DBMS_LOB.CLOSE(lBlob);\n\n COMMIT;\n\nEND;\n/\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13693/"
] |
I have a file. I want to get its contents into a blob column in my oracle database or into a blob variable in my PL/SQL program. What is the best way to do that?
|
To do it entirely in PL/SQL, the file would need to be on the server, located in a directory which you'd need to define in the database. Create the following objects:
```
CREATE OR REPLACE DIRECTORY
BLOB_DIR
AS
'/oracle/base/lobs'
/
CREATE OR REPLACE PROCEDURE BLOB_LOAD
AS
lBlob BLOB;
lFile BFILE := BFILENAME('BLOB_DIR', 'filename');
BEGIN
INSERT INTO table (id, your_blob)
VALUES (xxx, empty_blob())
RETURNING your_blob INTO lBlob;
DBMS_LOB.OPEN(lFile, DBMS_LOB.LOB_READONLY);
DBMS_LOB.OPEN(lBlob, DBMS_LOB.LOB_READWRITE);
DBMS_LOB.LOADFROMFILE(DEST_LOB => lBlob,
SRC_LOB => lFile,
AMOUNT => DBMS_LOB.GETLENGTH(lFile));
DBMS_LOB.CLOSE(lFile);
DBMS_LOB.CLOSE(lBlob);
COMMIT;
END;
/
```
|
122,914 |
<p>Does anyone know any implementation of a templated cache of objects?</p>
<ul>
<li>You use a key to find object (the same as in std::map<>)</li>
<li>You specify a maximum number of objects that can be in the cache at the same time</li>
<li>There are facilities to create an object not found in the cache</li>
<li>There are facilities to know when an object is discarded from the cache</li>
</ul>
<p>For example : </p>
<pre><code>typedef cache<int, MyObj*> MyCache;
MyCache oCache;
oCache.SetSize(1);
oCache.Insert(make_pair(1, new MyObj());
oCache.Touch(1);
MyObj* oldObj = oCache.Delete(1);
...
</code></pre>
<p>It can be as simple as a LRU or MRU cache.</p>
<p>Any suggestions are welcomed!</p>
<p>Nic</p>
|
[
{
"answer_id": 123715,
"author": "jpinto3912",
"author_id": 11567,
"author_profile": "https://Stackoverflow.com/users/11567",
"pm_score": -1,
"selected": false,
"text": "<p>In an application I can hardly imagine it would speed/boost up performance to store objects that apparently can be re-created (hip: since they can be automatically discarded, when the cache tops).\nA sw cache would require memory-fetching through associativism code, surely slower then memory allocation and constructor running (mostly memory initializations).</p>\n\n<p>With the exception of manual user configuration to avoid the paging mechanism (precisely to boost performance, btw), most OS \"caches\" memory for you on disk... it's \"paging\", a form of \"high-cost caching\", because nothing gets thrown away, and it's done by specific HW, a sub-processing unit called Memory Management Unit...</p>\n\n<p>A caching-code, in the big picture, would be slowing processes while being redundant.</p>\n"
},
{
"answer_id": 35187400,
"author": "Straw1239",
"author_id": 3482801,
"author_profile": "https://Stackoverflow.com/users/3482801",
"pm_score": 1,
"selected": false,
"text": "<p>Ive put together a relatively simple LRU cache built from a map and a linked list:</p>\n\n<pre><code>template<typename K, typename V, typename Map = std::unordered_map<K, typename std::list<K>::iterator>>\nclass LRUCache\n{\n size_t maxSize;\n Map data;\n std::list<K> usageOrder;\n std::function<void(std::pair<K, V>)> onEject = [](std::pair<K, V> x){};\n\n void moveToFront(typename std::list<K>::iterator itr)\n {\n if(itr != usageOrder.begin())\n usageOrder.splice(usageOrder.begin(), usageOrder, itr);\n }\n\n\n void trimToSize()\n {\n while(data.size() > maxSize)\n {\n auto itr = data.find(usageOrder.back());\n\n onEject(std::pair<K, V>(itr->first, *(itr->second)));\n data.erase(usageOrder.back());\n usageOrder.erase(--usageOrder.end());\n }\n }\n\npublic:\n typedef std::pair<const K, V> value_type;\n typedef K key_type;\n typedef V mapped_type;\n\n\n LRUCache(size_t maxEntries) : maxSize(maxEntries)\n {\n data.reserve(maxEntries);\n }\n\n size_t size() const\n {\n return data.size();\n }\n\n void insert(const value_type& v)\n {\n usageOrder.push_front(v.first);\n data.insert(typename Map::value_type(v.first, usageOrder.begin()));\n\n trimToSize();\n }\n\n bool contains(const K& k) const\n {\n return data.count(k) != 0;\n }\n\n V& at(const K& k)\n {\n auto itr = data.at(k);\n moveToFront(itr);\n return *itr;\n }\n\n\n void setMaxEntries(size_t maxEntries)\n {\n maxSize = maxEntries;\n trimToSize();\n }\n\n void touch(const K& k)\n {\n at(k);\n }\n\n template<typename Compute>\n V& getOrCompute(const K& k)\n {\n if(!data.contains(k)) insert(value_type(k, Compute()));\n return(at(k));\n }\n\n void setOnEject(decltype(onEject) f)\n {\n onEject = f;\n }\n};\n</code></pre>\n\n<p>Which I believe meets your criteria. Anything need to be added, or changed?</p>\n"
},
{
"answer_id": 36476108,
"author": "david.jugon",
"author_id": 1126053,
"author_profile": "https://Stackoverflow.com/users/1126053",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"http://www.boost.org/doc/libs/1_60_0/libs/multi_index/doc/index.html\" rel=\"nofollow\">Boost.MultiIndex</a> library.\nIt is easy to implement a <a href=\"http://www.boost.org/doc/libs/1_60_0/libs/multi_index/doc/examples.html#example9\" rel=\"nofollow\">MRU cache</a>.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18800/"
] |
Does anyone know any implementation of a templated cache of objects?
* You use a key to find object (the same as in std::map<>)
* You specify a maximum number of objects that can be in the cache at the same time
* There are facilities to create an object not found in the cache
* There are facilities to know when an object is discarded from the cache
For example :
```
typedef cache<int, MyObj*> MyCache;
MyCache oCache;
oCache.SetSize(1);
oCache.Insert(make_pair(1, new MyObj());
oCache.Touch(1);
MyObj* oldObj = oCache.Delete(1);
...
```
It can be as simple as a LRU or MRU cache.
Any suggestions are welcomed!
Nic
|
You can use the [Boost.MultiIndex](http://www.boost.org/doc/libs/1_60_0/libs/multi_index/doc/index.html) library.
It is easy to implement a [MRU cache](http://www.boost.org/doc/libs/1_60_0/libs/multi_index/doc/examples.html#example9).
|
122,919 |
<p>I have this bit of javascript written with jQuery 1.2.5. It's contained inside the main function() of a plugin that I wrote. The plugin is a horizontal gallery scroller very similar to jCarousel. It does alot of auto calculating of widths and determines how many to scroll based on that and the size of the images, which is what all the calculations are that are going on.</p>
<p>What my question is, how do I prevent this from firing off before a previous execution is finished. For instance, if I get a little click happy and just frantically mash down on <code>.digi_next</code>. Things don't go so well in the UI when that happens and I'd like to fix it :) I thought the answer might lie in <code>queue</code>, but all my attempts at using it haven't turned out anything worthwhile.</p>
<pre><code> var self = this;
$(".digi_next", this.container).click(function(){
var curLeft = $(".digi_container", self.container).css("left").split("px")[0];
var newLeft = (curLeft*1) - (self.containerPad + self.containerWidth) * self.show_photos;
if (newLeft < ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1) {
newLeft = ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1;
}
$(".digi_container", self.container).animate({
left: newLeft + "px"
}, self.rotateSpeed);
});
</code></pre>
|
[
{
"answer_id": 122995,
"author": "Davide Vosti",
"author_id": 1812,
"author_profile": "https://Stackoverflow.com/users/1812",
"pm_score": 1,
"selected": false,
"text": "<p>Since JavaScript functions calls are asyncronus, you can pass as a in parameter a callback function that's called when the previous call ends (same for errors).</p>\n\n<p>You can pass the function you wrote in this post as the callback for the function that fire before.</p>\n\n<p>Hope this helps.</p>\n\n<p>Regards</p>\n"
},
{
"answer_id": 123091,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 4,
"selected": true,
"text": "<p>Just use a global busy flag. When you enter your click handler, check it, and only proceed if it's false. Immediately set it to true, and then set it back to false when the animation ends. JavaScript is single-threaded, so there is no race condition to worry about.</p>\n\n<pre><code>var busy = false;\n$(\"...\").onclick(function() {\n if (busy) return false;\n busy = true;\n $(\"...\").animate(..., ..., ..., function() {\n busy= false;\n });\n return false;\n});\n</code></pre>\n"
},
{
"answer_id": 123257,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at <a href=\"http://ui.jquery.com/\" rel=\"noreferrer\">jQuery UI</a>. Specifically <a href=\"http://docs.jquery.com/UI/Effects/Slide\" rel=\"noreferrer\">the effects-part</a> of the plug in. I use the slide-effect on <a href=\"http://roosteronacid.com/\" rel=\"noreferrer\">my personal website</a> (click on the arrows at the sides of the boxes).</p>\n\n<p>I prevent users triggering the effect more than once - before the effect has ended - with the <a href=\"http://docs.jquery.com/Events/one#typedatafn\" rel=\"noreferrer\"><strong>one</strong> event-handler</a> and a callback function.</p>\n\n<p><a href=\"http://roosteronacid.com/index.js\" rel=\"noreferrer\">Here's the source-code</a></p>\n"
},
{
"answer_id": 123348,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": 2,
"selected": false,
"text": "<p>As an alternative to the afformentioned global flag, you could assign the value to the DOM element, that way enabling multiple elements on the page to have the same behaviour:</p>\n\n<pre><code>$(\"...\").onclick(function(el) {\n var self = el;\n if (self.busy) return false;\n self.busy = true;\n $(\"...\").animate(..., ..., ..., function() {\n self.busy= false;\n });\n return false;\n});\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
I have this bit of javascript written with jQuery 1.2.5. It's contained inside the main function() of a plugin that I wrote. The plugin is a horizontal gallery scroller very similar to jCarousel. It does alot of auto calculating of widths and determines how many to scroll based on that and the size of the images, which is what all the calculations are that are going on.
What my question is, how do I prevent this from firing off before a previous execution is finished. For instance, if I get a little click happy and just frantically mash down on `.digi_next`. Things don't go so well in the UI when that happens and I'd like to fix it :) I thought the answer might lie in `queue`, but all my attempts at using it haven't turned out anything worthwhile.
```
var self = this;
$(".digi_next", this.container).click(function(){
var curLeft = $(".digi_container", self.container).css("left").split("px")[0];
var newLeft = (curLeft*1) - (self.containerPad + self.containerWidth) * self.show_photos;
if (newLeft < ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1) {
newLeft = ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1;
}
$(".digi_container", self.container).animate({
left: newLeft + "px"
}, self.rotateSpeed);
});
```
|
Just use a global busy flag. When you enter your click handler, check it, and only proceed if it's false. Immediately set it to true, and then set it back to false when the animation ends. JavaScript is single-threaded, so there is no race condition to worry about.
```
var busy = false;
$("...").onclick(function() {
if (busy) return false;
busy = true;
$("...").animate(..., ..., ..., function() {
busy= false;
});
return false;
});
```
|
122,920 |
<p>I'd like to line up items approximately like this:</p>
<pre><code>item1 item2 i3 longitemname
i4 longitemname2 anotheritem i5
</code></pre>
<p>Basically items of varying length arranged in a table like structure. The tricky part is the container for these can vary in size and I'd like to fit as many as I can in each row - in other words, I won't know beforehand how many items fit in a line, and if the page is resized the items should re-flow themselves to accommodate. E.g. initially 10 items could fit on each line, but on resize it could be reduced to 5.</p>
<p>I don't think I can use an html table since I don't know the number of columns (since I don't know how many will fit on a line). I can use css to float them, but since they're of varying size they won't line up.</p>
<p>So far the only thing I can think of is to use javascript to get the size of largest item, set the size of all items to that size, and float everything left.</p>
<p>Any better suggestions?</p>
|
[
{
"answer_id": 122952,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 0,
"selected": false,
"text": "<p>You could use block level elements floated left, but you will need some javascript to check the sizes, find the largest one, and set them all to that width.</p>\n\n<p>EDIT: Just read the second half of your post, and saw that you suggested just this fix. Count this post as +1 for your current idea :)</p>\n"
},
{
"answer_id": 123280,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You would actually need to calculate the maxWidth and the maxHeight and then go through with a resize function in Javascript after the page loads. I had to do this for a prior project and one of the browsers (FF?) will snag/offset the ones underneath if the height of the divs vary. </p>\n"
},
{
"answer_id": 123326,
"author": "EvilSyn",
"author_id": 6350,
"author_profile": "https://Stackoverflow.com/users/6350",
"pm_score": 0,
"selected": false,
"text": "<p>Well, could you just create a floated div for each 'item', and loop through its properties and use linebreaks? Then when you finish looping over the properties, close the div and start a new one? That way they will be like columns and just float next to each other. If the window is small, they'll drop down to the next 'line' and when resized, will float back up to the right (which is really the left :-)</p>\n"
},
{
"answer_id": 123405,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 0,
"selected": false,
"text": "<p>You could float a couple of unordered lists, like this:</p>\n\n<pre><code><ul style=\"float: left;\">\n <li>Short</li>\n <li>Loooong</li>\n <li>Even longer</li>\n</ul>\n<ul style=\"float: left;\">\n <li>Loooong</li>\n <li>Short</li>\n <li>...</li>\n</ul>\n<ul style=\"float: left;\">\n <li>Semi long</li>\n <li>...</li>\n <li>Short</li>\n</ul>\n</code></pre>\n\n<p>It would require you to do some calculations on how many list-items in how many lists should be shoved into the DOM, but this way - when you re-size the container which holds the lists - the lists will float to fit into that container.</p>\n"
},
{
"answer_id": 123416,
"author": "Parand",
"author_id": 13055,
"author_profile": "https://Stackoverflow.com/users/13055",
"pm_score": 3,
"selected": true,
"text": "<p>This can be done using floated div's, calculating the max width, and setting all widths to the max. Here's jquery code to do it:</p>\n\n<p>html:</p>\n\n<pre><code><div class=\"item\">something</div>\n<div class=\"item\">something else</div>\n</code></pre>\n\n<p>css:</p>\n\n<pre><code>div.item { float: left; }\n</code></pre>\n\n<p>jquery:</p>\n\n<pre><code>var max_width=0;\n$('div.item').each( function() { if ($(this).width() > max_width) { max_width=$(this).width(); } } ).width(max_width);\n</code></pre>\n\n<p>Not too ugly but not too pretty either, I'm still open to better suggestions...</p>\n"
},
{
"answer_id": 123474,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": 1,
"selected": false,
"text": "<p>What happens when you get one item thats rediculously large and makes the rest look small? I would consider two solutions:</p>\n\n<ol>\n<li>What you've already come up with involving a float:left; rule and jQuery, but with a max max_width as well or</li>\n<li>Just decide on a preset width for all items before hand, based on what values you expect to be in there</li>\n</ol>\n\n<p>Then add an overflow:hidden; rule so items that are longer don't scew the table-look. You could even change the jQuery function to trim items that are longer, adding an elipsis (...) to the end.</p>\n"
},
{
"answer_id": 123483,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 0,
"selected": false,
"text": "<p>You could use the following with each column the same width.</p>\n\n<p>You'll have a fixed column width, but the list will reflow itself automatically.\nI added a little bit of extra HTML but now it works in FF en IE.</p>\n\n<p>html:</p>\n\n<pre><code><ul class=\"ColumnBasedList\">\n <li><span>Item1 2</span></li>\n <li><span>Item2 3</span></li>\n <li><span>Item3 5</span></li>\n <li><span>Item4 6</span></li>\n <li><span>Item5 7</span></li>\n <li><span>Item6 8</span></li>\n</ul>\n</code></pre>\n\n<p>css:</p>\n\n<pre><code>.ColumnBasedList\n{\n width: 80%;\n margin: 0;\n padding: 0;\n}\n\n.ColumnBasedList li\n{\n list-style-type: none;\n display:inline;\n}\n\n.ColumnBasedList li span\n{\n display: -moz-inline-block;\n display: inline-block;\n width: 20em;\n margin: 0.3em;\n}\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
I'd like to line up items approximately like this:
```
item1 item2 i3 longitemname
i4 longitemname2 anotheritem i5
```
Basically items of varying length arranged in a table like structure. The tricky part is the container for these can vary in size and I'd like to fit as many as I can in each row - in other words, I won't know beforehand how many items fit in a line, and if the page is resized the items should re-flow themselves to accommodate. E.g. initially 10 items could fit on each line, but on resize it could be reduced to 5.
I don't think I can use an html table since I don't know the number of columns (since I don't know how many will fit on a line). I can use css to float them, but since they're of varying size they won't line up.
So far the only thing I can think of is to use javascript to get the size of largest item, set the size of all items to that size, and float everything left.
Any better suggestions?
|
This can be done using floated div's, calculating the max width, and setting all widths to the max. Here's jquery code to do it:
html:
```
<div class="item">something</div>
<div class="item">something else</div>
```
css:
```
div.item { float: left; }
```
jquery:
```
var max_width=0;
$('div.item').each( function() { if ($(this).width() > max_width) { max_width=$(this).width(); } } ).width(max_width);
```
Not too ugly but not too pretty either, I'm still open to better suggestions...
|
122,942 |
<p>I have a table <code>UserAliases</code> (<code>UserId, Alias</code>) with multiple aliases per user. I need to query it and return all aliases for a given user, the trick is to return them all in one column.</p>
<p>Example:</p>
<pre><code>UserId/Alias
1/MrX
1/MrY
1/MrA
2/Abc
2/Xyz
</code></pre>
<p>I want the query result in the following format:</p>
<pre><code>UserId/Alias
1/ MrX, MrY, MrA
2/ Abc, Xyz
</code></pre>
<p>Thank you.</p>
<p>I'm using SQL Server 2005.</p>
<p>p.s. actual T-SQL query would be appreciated :)</p>
|
[
{
"answer_id": 122956,
"author": "gehsekky",
"author_id": 21310,
"author_profile": "https://Stackoverflow.com/users/21310",
"pm_score": 0,
"selected": false,
"text": "<p>group_concat() sounds like what you're looking for.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat</a></p>\n\n<p>since you're on mssql, i just googled \"group_concat mssql\" and found a bunch of hits to recreate group_concat functionality. here's one of the hits i found:</p>\n\n<p><a href=\"http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html\" rel=\"nofollow noreferrer\">http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html</a></p>\n"
},
{
"answer_id": 122964,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 0,
"selected": false,
"text": "<p>You can either loop through the rows with a cursor and append to a field in a temp table, or you could use the COALESCE function to concatenate the fields.</p>\n"
},
{
"answer_id": 122980,
"author": "CodeRedick",
"author_id": 17145,
"author_profile": "https://Stackoverflow.com/users/17145",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry, read the question wrong the first time. You can do something like this:</p>\n\n<pre><code>declare @result varchar(max)\n\n--must \"initialize\" result for this to work\nselect @result = ''\n\nselect @result = @result + alias\nFROM aliases\nWHERE username='Bob'\n</code></pre>\n"
},
{
"answer_id": 123025,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 7,
"selected": true,
"text": "<p>You can use a function with COALESCE.</p>\n\n<pre><code>CREATE FUNCTION [dbo].[GetAliasesById]\n(\n @userID int\n)\nRETURNS varchar(max)\nAS\nBEGIN\n declare @output varchar(max)\n select @output = COALESCE(@output + ', ', '') + alias\n from UserAliases\n where userid = @userID\n\n return @output\nEND\n\nGO\n\nSELECT UserID, dbo.GetAliasesByID(UserID)\nFROM UserAliases\nGROUP BY UserID\n\nGO\n</code></pre>\n"
},
{
"answer_id": 177153,
"author": "leoinfo",
"author_id": 6948,
"author_profile": "https://Stackoverflow.com/users/6948",
"pm_score": 4,
"selected": false,
"text": "<p>Well... I see that an answer was already accepted... but I think you should see another solutions anyway:</p>\n\n<pre><code>/* EXAMPLE */\nDECLARE @UserAliases TABLE(UserId INT , Alias VARCHAR(10))\nINSERT INTO @UserAliases (UserId,Alias) SELECT 1,'MrX'\n UNION ALL SELECT 1,'MrY' UNION ALL SELECT 1,'MrA'\n UNION ALL SELECT 2,'Abc' UNION ALL SELECT 2,'Xyz'\n\n/* QUERY */\n;WITH tmp AS ( SELECT DISTINCT UserId FROM @UserAliases )\nSELECT \n LEFT(tmp.UserId, 10) +\n '/ ' +\n STUFF(\n ( SELECT ', '+Alias \n FROM @UserAliases \n WHERE UserId = tmp.UserId \n FOR XML PATH('') \n ) \n , 1, 2, ''\n ) AS [UserId/Alias]\nFROM tmp\n\n/* -- OUTPUT\n UserId/Alias\n 1/ MrX, MrY, MrA\n 2/ Abc, Xyz \n*/\n</code></pre>\n"
},
{
"answer_id": 891516,
"author": "Tushar Maru",
"author_id": 103344,
"author_profile": "https://Stackoverflow.com/users/103344",
"pm_score": 1,
"selected": false,
"text": "<pre><code>DECLARE @Str varchar(500)\n\nSELECT @Str=COALESCE(@Str,'') + CAST(ID as varchar(10)) + ','\nFROM dbo.fcUser\n\nSELECT @Str\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] |
I have a table `UserAliases` (`UserId, Alias`) with multiple aliases per user. I need to query it and return all aliases for a given user, the trick is to return them all in one column.
Example:
```
UserId/Alias
1/MrX
1/MrY
1/MrA
2/Abc
2/Xyz
```
I want the query result in the following format:
```
UserId/Alias
1/ MrX, MrY, MrA
2/ Abc, Xyz
```
Thank you.
I'm using SQL Server 2005.
p.s. actual T-SQL query would be appreciated :)
|
You can use a function with COALESCE.
```
CREATE FUNCTION [dbo].[GetAliasesById]
(
@userID int
)
RETURNS varchar(max)
AS
BEGIN
declare @output varchar(max)
select @output = COALESCE(@output + ', ', '') + alias
from UserAliases
where userid = @userID
return @output
END
GO
SELECT UserID, dbo.GetAliasesByID(UserID)
FROM UserAliases
GROUP BY UserID
GO
```
|
122,951 |
<p>I received the following exception when I was using the Regex class with the regular expression: (?'named a'asdf)</p>
<pre><code>System.ArgumentException: parsing \"(?'named a'asdf)\" - Invalid group name: Group names must begin with a word character.
</code></pre>
<p>What is the problem with my regular expression?</p>
|
[
{
"answer_id": 122973,
"author": "Simon Johnson",
"author_id": 854,
"author_profile": "https://Stackoverflow.com/users/854",
"pm_score": -1,
"selected": false,
"text": "<p>The problem is your quotes around the name of the named capture group. Try the string: (?<Named>asdf)</p>\n"
},
{
"answer_id": 123010,
"author": "vengafoo",
"author_id": 12834,
"author_profile": "https://Stackoverflow.com/users/12834",
"pm_score": 4,
"selected": true,
"text": "<p>The problem is the space in the name of the capture. Remove the space and it works fine.</p>\n\n<p>From the MSDN documentation:\n\"The string used for name must not contain any punctuation and cannot begin with a number. You can use single quotes instead of angle brackets; for example, (?'name').\"</p>\n\n<p>It does not matter if you use angle brackets <> or single quotes '' to indicate a group name.</p>\n"
},
{
"answer_id": 145351,
"author": "hurst",
"author_id": 10991,
"author_profile": "https://Stackoverflow.com/users/10991",
"pm_score": 2,
"selected": false,
"text": "<p>The reference for the MSDN documentation mentioned by vengafoo is here:\n<a href=\"http://msdn.microsoft.com/en-us/library/bs2twtah.aspx\" rel=\"nofollow noreferrer\">Regular Expression Grouping Constructs</a></p>\n\n<blockquote>\n <p><strong><code>(?<name> subexpression)</code></strong><br>\n Captures the matched subexpression into a group name or number name. The string used\n for name must not contain any punctuation and cannot begin with a\n number. <strong>You can use single quotes instead of angle brackets; for example, (?'name').</strong></p>\n</blockquote>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12834/"
] |
I received the following exception when I was using the Regex class with the regular expression: (?'named a'asdf)
```
System.ArgumentException: parsing \"(?'named a'asdf)\" - Invalid group name: Group names must begin with a word character.
```
What is the problem with my regular expression?
|
The problem is the space in the name of the capture. Remove the space and it works fine.
From the MSDN documentation:
"The string used for name must not contain any punctuation and cannot begin with a number. You can use single quotes instead of angle brackets; for example, (?'name')."
It does not matter if you use angle brackets <> or single quotes '' to indicate a group name.
|
122,990 |
<p>I have several sources of tables with personal data, like this:</p>
<pre><code>SOURCE 1
ID, FIRST_NAME, LAST_NAME, FIELD1, ...
1, jhon, gates ...
SOURCE 2
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
1, jon, gate ...
SOURCE 3
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
2, jhon, ballmer ...
</code></pre>
<p>So, assuming that records with ID 1, from sources 1 and 2, are the same person, my problem <strong>is how to determine if a record in every source, represents the same person</strong>. Additionally, sure not every records exists in all sources. All the names, are written in spanish, mainly.</p>
<p>In this case, the exact matching needs to be relaxed because we assume <em>the data sources has not been rigurously checked</em> against the official bureau of identification of the country. Also we need to assume <em>typos are common</em>, because the nature of the processes to collect the data. What is more, the amount of records is around 2 or 3 millions in every source...</p>
<p>Our team had thought in something like this: first, force exact matching in selected fields like ID NUMBER, and NAMES to know how hard the problem can be. Second, relaxing the matching criteria, and count how much records more can be matched, but is here where the problem arises: <strong>how to do to relax the matching criteria without generating too noise neither restricting too much?</strong></p>
<p>What tool can be more effective to handle this?, for example, do you know about some especific extension in some database engine to support this matching?
Do you know about clever algorithms like <a href="http://en.wikipedia.org/wiki/Soundex" rel="nofollow noreferrer">soundex</a> to handle this approximate matching, but for spanish texts?</p>
<p>Any help would be appreciated!</p>
<p>Thanks.</p>
|
[
{
"answer_id": 123001,
"author": "ScaleOvenStove",
"author_id": 12268,
"author_profile": "https://Stackoverflow.com/users/12268",
"pm_score": 2,
"selected": false,
"text": "<p>SSIS , try using the Fuzzy Lookup transformation</p>\n"
},
{
"answer_id": 123050,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 2,
"selected": false,
"text": "<p>This sounds like a <a href=\"http://en.wikipedia.org/wiki/Customer_Data_Integration\" rel=\"nofollow noreferrer\">Customer Data Integration</a> problem. Search on that term and you might find some more information. Also, have a poke around inside <a href=\"http://www.tdwi.org/\" rel=\"nofollow noreferrer\">The Data Warehousing Institude</a>, and you might find some answers there as well.</p>\n\n<p><strong>Edit:</strong> In addition, <a href=\"http://www.javalobby.org/java/forums/t16936.html\" rel=\"nofollow noreferrer\">here's</a> an article that might interest you on spanish phonetic matching.</p>\n"
},
{
"answer_id": 123076,
"author": "Ryan Rinaldi",
"author_id": 2278,
"author_profile": "https://Stackoverflow.com/users/2278",
"pm_score": 2,
"selected": false,
"text": "<p>I've had to do something similar before and what I did was use a <a href=\"http://en.wikipedia.org/wiki/Double_Metaphone\" rel=\"nofollow noreferrer\">double metaphone</a> phonetic search on the names. </p>\n\n<p>Before I compared the names though, I tried to normalize away any name/nickname differences by looking up the name in a nick name table I created. (I populated the table with census data I found online) So people called Bob became Robert, Alex became Alexander, Bill became William, etc. </p>\n\n<p><strong>Edit</strong>: Double Metaphone was specifically designed to be better than Soundex and work in languages other than English.</p>\n"
},
{
"answer_id": 123608,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 3,
"selected": true,
"text": "<p>The crux of the problem is to compute one or more measures of distance between each pair of entries and then consider them to be the same when one of the distances is less than a certain acceptable threshold. The key is to setup the analysis and then vary the acceptable distance until you reach what you consider to be the best trade-off between false-positives and false-negatives.</p>\n\n<p>One distance measurement could be phonetic. Another you might consider is the <a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow noreferrer\">Levenshtein or edit distance</a> between the entires, which would attempt to measure typos.</p>\n\n<p>If you have a reasonable idea of how many persons you should have, then your goal is to find the sweet spot where you are getting about the right number of persons. Make your matching too fuzzy and you'll have too few. Make it to restrictive and you'll have too many.</p>\n\n<p>If you know roughly how many entries a person should have, then you can use that as the metric to see when you are getting close. Or you can divide the number of records into the average number of records for each person and get a rough number of persons that you're shooting for.</p>\n\n<p>If you don't have any numbers to use, then you're left picking out groups of records from your analysis and checking by hand whether they look like the same person or not. So it's guess and check.</p>\n\n<p>I hope that helps.</p>\n"
},
{
"answer_id": 135289,
"author": "Alex. S.",
"author_id": 18300,
"author_profile": "https://Stackoverflow.com/users/18300",
"pm_score": 1,
"selected": false,
"text": "<p>Just to add some details to solve this issue, I'd found this modules for Postgresql 8.3</p>\n\n<ul>\n<li><a href=\"http://www.postgresql.org/docs/8.3/static/fuzzystrmatch.html\" rel=\"nofollow noreferrer\">Fuzzy String Match</a></li>\n<li><a href=\"http://www.postgresql.org/docs/8.3/static/pgtrgm.html\" rel=\"nofollow noreferrer\">Trigrams</a></li>\n</ul>\n"
},
{
"answer_id": 139295,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 0,
"selected": false,
"text": "<p>You might try to cannonicalise the names by comparing them with a dicionary.<br>\nThis would allow you to spot some common typos and correct them. </p>\n"
},
{
"answer_id": 280506,
"author": "Yuval F",
"author_id": 1702,
"author_profile": "https://Stackoverflow.com/users/1702",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds to me you have a <a href=\"http://www.answers.com/topic/record-linkage\" rel=\"nofollow noreferrer\">record linkage</a> problem. You can use the references in the link.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/122990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18300/"
] |
I have several sources of tables with personal data, like this:
```
SOURCE 1
ID, FIRST_NAME, LAST_NAME, FIELD1, ...
1, jhon, gates ...
SOURCE 2
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
1, jon, gate ...
SOURCE 3
ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ...
2, jhon, ballmer ...
```
So, assuming that records with ID 1, from sources 1 and 2, are the same person, my problem **is how to determine if a record in every source, represents the same person**. Additionally, sure not every records exists in all sources. All the names, are written in spanish, mainly.
In this case, the exact matching needs to be relaxed because we assume *the data sources has not been rigurously checked* against the official bureau of identification of the country. Also we need to assume *typos are common*, because the nature of the processes to collect the data. What is more, the amount of records is around 2 or 3 millions in every source...
Our team had thought in something like this: first, force exact matching in selected fields like ID NUMBER, and NAMES to know how hard the problem can be. Second, relaxing the matching criteria, and count how much records more can be matched, but is here where the problem arises: **how to do to relax the matching criteria without generating too noise neither restricting too much?**
What tool can be more effective to handle this?, for example, do you know about some especific extension in some database engine to support this matching?
Do you know about clever algorithms like [soundex](http://en.wikipedia.org/wiki/Soundex) to handle this approximate matching, but for spanish texts?
Any help would be appreciated!
Thanks.
|
The crux of the problem is to compute one or more measures of distance between each pair of entries and then consider them to be the same when one of the distances is less than a certain acceptable threshold. The key is to setup the analysis and then vary the acceptable distance until you reach what you consider to be the best trade-off between false-positives and false-negatives.
One distance measurement could be phonetic. Another you might consider is the [Levenshtein or edit distance](http://en.wikipedia.org/wiki/Levenshtein_distance) between the entires, which would attempt to measure typos.
If you have a reasonable idea of how many persons you should have, then your goal is to find the sweet spot where you are getting about the right number of persons. Make your matching too fuzzy and you'll have too few. Make it to restrictive and you'll have too many.
If you know roughly how many entries a person should have, then you can use that as the metric to see when you are getting close. Or you can divide the number of records into the average number of records for each person and get a rough number of persons that you're shooting for.
If you don't have any numbers to use, then you're left picking out groups of records from your analysis and checking by hand whether they look like the same person or not. So it's guess and check.
I hope that helps.
|
123,002 |
<p>So I've got maybe 10 objects each of which has 1-3 dependencies (which I think is ok as far as loose coupling is concerned) but also some settings that can be used to define behavior (timeout, window size, etc).</p>
<p>Now before I started using an Inversion of Control container I would have created a factory and maybe even a simple ObjectSettings object for each of the objects that requires more than 1 setting to keep the size of the constructor to the recommended "less than 4" parameter size. I am now using an inversion of control container and I just don't see all that much of a point to it. Sure I might get a constructor with 7 parameters, but who cares? It's all being filled out by the IoC anyways.</p>
<p>Am I missing something here or is this basically correct?</p>
|
[
{
"answer_id": 123055,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 1,
"selected": false,
"text": "<p>G'day George,</p>\n\n<p>First off, what are the dependencies between the objects?</p>\n\n<p>Lots of \"isa\" relationships? Lots of \"hasa\" relationships?</p>\n\n<p>Lots of fan-in? Or fan-out?</p>\n\n<p>George's response: \"has-a mostly, been trying to follow the composition over inheritance advice...why would it matter though?\"</p>\n\n<p>As it's mostly \"hasa\" you should be all right.</p>\n\n<p>Better make sure that your construction (and destruction) of the components is done correctly though to prevent memory leaks.</p>\n\n<p>And, if this is in C++, make sure you use virtual destructors?</p>\n"
},
{
"answer_id": 123117,
"author": "JC.",
"author_id": 3615,
"author_profile": "https://Stackoverflow.com/users/3615",
"pm_score": 2,
"selected": false,
"text": "<p>The need for many dependencies (maybe over 8) could be indicative of a design flaw but in general I think there is no problem as long as the design is cohesive.</p>\n\n<p>Also, consider using a service locator or static gateway for infrastructure concerns such as logging and authorization rather than cluttering up the constructor arguments.</p>\n\n<p>EDIT: 8 probably is too many but I figured there'd be the odd case for it. After looking at Lee's post I agree, 1-4 is usually good.</p>\n"
},
{
"answer_id": 123121,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 1,
"selected": false,
"text": "<p>This is a tough one, and why I favor a hybrid approach where appropriate properties are mutable and only immutable properties and required dependencies without a useful default are part of the constructor. Some classes are constructed with the essentials, then tuned if necessary via setters.</p>\n"
},
{
"answer_id": 142182,
"author": "Lee",
"author_id": 13943,
"author_profile": "https://Stackoverflow.com/users/13943",
"pm_score": 4,
"selected": true,
"text": "<p>The relationship between class complexity and the size of the IoC constructor had not occurred to me before reading this question, but my analysis below suggests that having many arguments in the IoC constructor is a <a href=\"https://stackoverflow.com/questions/114342/what-are-code-smells-what-is-the-best-way-to-correct-them\">code smell</a> to be aware of when using IoC. Having a goal to stick to a short constructor argument list will help you keep the classes themselves simple. Following the <a href=\"https://stackoverflow.com/questions/15412/is-single-responsibility-principle-a-rule-of-oop\">single responsibility principle</a> will guide you towards this goal.</p>\n\n<p>I work on a system that currently has 122 classes that are instantiated using the Spring.NET framework. All relationships between these classes are set up in their constructors. Admittedly, the system has its fair share of less than perfect code where I have broken a few rules. (But, hey, our failures are opportunities to learn!)</p>\n\n<p>The constructors of those classes have varying numbers of arguments, which I show in the table below.</p>\n\n<pre><code>Number of constructor arguments Number of classes\n 0 57\n 1 19\n 2 25\n 3 9\n 4 3\n 5 1\n 6 3\n 7 2\n 8 2\n</code></pre>\n\n<p>The classes with zero arguments are either concrete strategy classes, or classes that respond to events by sending data to external systems.</p>\n\n<p>Those with 5 or 6 arguments are all somewhat inelegant and could use some refactoring to simplify them.</p>\n\n<p>The four classes with 7 or 8 arguments are excellent examples of <a href=\"http://en.wikipedia.org/wiki/God_object\" rel=\"nofollow noreferrer\">God objects</a>. They ought to be broken up, and each is already on my list of trouble-spots within the system.</p>\n\n<p>The remaining classes (1 to 4 arguments) are (mostly) simply designed, easy to understand, and conform to the <a href=\"https://stackoverflow.com/questions/15412/is-single-responsibility-principle-a-rule-of-oop\">single responsibility principle</a>.</p>\n"
},
{
"answer_id": 404047,
"author": "Shiva",
"author_id": 50395,
"author_profile": "https://Stackoverflow.com/users/50395",
"pm_score": 0,
"selected": false,
"text": "<p>It all depends upon what kind of container that you have used to do the IOC and what approaches the container takes whether it uses annotations or configuration file to saturate the object to be instiantiated. Furthermore, if your constructor parameters are just plain primitive data types then it is not really a big deal; however if you have non-primitive types then in my opinion, you can use the Property based DI rather than consutructor based DI.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
So I've got maybe 10 objects each of which has 1-3 dependencies (which I think is ok as far as loose coupling is concerned) but also some settings that can be used to define behavior (timeout, window size, etc).
Now before I started using an Inversion of Control container I would have created a factory and maybe even a simple ObjectSettings object for each of the objects that requires more than 1 setting to keep the size of the constructor to the recommended "less than 4" parameter size. I am now using an inversion of control container and I just don't see all that much of a point to it. Sure I might get a constructor with 7 parameters, but who cares? It's all being filled out by the IoC anyways.
Am I missing something here or is this basically correct?
|
The relationship between class complexity and the size of the IoC constructor had not occurred to me before reading this question, but my analysis below suggests that having many arguments in the IoC constructor is a [code smell](https://stackoverflow.com/questions/114342/what-are-code-smells-what-is-the-best-way-to-correct-them) to be aware of when using IoC. Having a goal to stick to a short constructor argument list will help you keep the classes themselves simple. Following the [single responsibility principle](https://stackoverflow.com/questions/15412/is-single-responsibility-principle-a-rule-of-oop) will guide you towards this goal.
I work on a system that currently has 122 classes that are instantiated using the Spring.NET framework. All relationships between these classes are set up in their constructors. Admittedly, the system has its fair share of less than perfect code where I have broken a few rules. (But, hey, our failures are opportunities to learn!)
The constructors of those classes have varying numbers of arguments, which I show in the table below.
```
Number of constructor arguments Number of classes
0 57
1 19
2 25
3 9
4 3
5 1
6 3
7 2
8 2
```
The classes with zero arguments are either concrete strategy classes, or classes that respond to events by sending data to external systems.
Those with 5 or 6 arguments are all somewhat inelegant and could use some refactoring to simplify them.
The four classes with 7 or 8 arguments are excellent examples of [God objects](http://en.wikipedia.org/wiki/God_object). They ought to be broken up, and each is already on my list of trouble-spots within the system.
The remaining classes (1 to 4 arguments) are (mostly) simply designed, easy to understand, and conform to the [single responsibility principle](https://stackoverflow.com/questions/15412/is-single-responsibility-principle-a-rule-of-oop).
|
123,003 |
<p>I need to determine the ID of a form field from within an action handler. The field is a part of a included facelets component and so the form will vary.</p>
<p><strong>included.xhtml</strong> </p>
<pre><code><ui:component>
<h:inputText id="contained_field"/>
<h:commandButton actionListener="#{backingBean.update}" value="Submit"/>
</ui:component>
</code></pre>
<p><strong>example_containing.xhtml</strong></p>
<pre><code><h:form id="containing_form">
<ui:include src="/included.xhtml"/>
</h:form>
</code></pre>
<p>How may I determine the ID of the form in the <code>update</code> method at runtime? Or better yet, the ID of the input field directly.</p>
|
[
{
"answer_id": 123208,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 4,
"selected": true,
"text": "<p>Bind the button to your backing bean, then use getParent() until you find the nearest form.</p>\n"
},
{
"answer_id": 157512,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Programmatically I would use jsight's method. You can know the id of your elements (unless you let JSF create them, I don't know the means for numbering in the ids) by looking at it. h:form is a naming container so as long as you don't have it wrapped in another naming container it will be containingForm:containedfield The ':' is the naming separator by default is JSF and the ids are created like this, roughly anyway, (parentNamingContainerId:)*componentId</p>\n"
},
{
"answer_id": 266221,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Since update method is of type actionListener, you can access your UI component as follows</p>\n\n<pre><code>public void update(javax.faces.event.ActionEvent ac) {\n javax.faces.component.UIComponent myCommand = ac.getComponent( );\n String id = myCommand.getId(); // get the id of the firing component\n\n ..... your code .........\n\n}\n</code></pre>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
I need to determine the ID of a form field from within an action handler. The field is a part of a included facelets component and so the form will vary.
**included.xhtml**
```
<ui:component>
<h:inputText id="contained_field"/>
<h:commandButton actionListener="#{backingBean.update}" value="Submit"/>
</ui:component>
```
**example\_containing.xhtml**
```
<h:form id="containing_form">
<ui:include src="/included.xhtml"/>
</h:form>
```
How may I determine the ID of the form in the `update` method at runtime? Or better yet, the ID of the input field directly.
|
Bind the button to your backing bean, then use getParent() until you find the nearest form.
|
123,007 |
<p>I can't quite figure this out. Microsoft Access 2000, on the report total section I have totals for three columns that are just numbers. These <code>=Sum[(ThisColumn1)], 2, 3</code>, etc and those grand totls all work fine. </p>
<p>I want to have another column that says <code>=Sum([ThisColumn1])+Sum([ThisColumn2]) + Sum([ThisColumn3])</code> but can't figure those one out. Just get a blank so I am sure there is an error.</p>
|
[
{
"answer_id": 123022,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 3,
"selected": true,
"text": "<p>Give the 3 Grand Totals meaningful Control Names and then for the Grand Grand Total use:</p>\n\n<pre><code>=[GrandTotal1] + [GrandTotal2] + [GrandTotal3]\n</code></pre>\n\n<p>Your Grand Total formulas should be something like:</p>\n\n<pre><code>=Sum(Nz([ThisColumn1], 0))\n</code></pre>\n"
},
{
"answer_id": 123032,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "<p>Create a new query, and the sql should look like this:</p>\n\n<pre><code>SELECT SUM(Column1 + Column2 + Column3),\n SUM(Column1),\n SUM(Column2),\n SUM(Column3),\n FROM Your_Table;\n</code></pre>\n"
},
{
"answer_id": 162903,
"author": "Shane Miskin",
"author_id": 16415,
"author_profile": "https://Stackoverflow.com/users/16415",
"pm_score": 1,
"selected": false,
"text": "<p>NULL values propagate through an expression which means that if any of your three subtotals are blank, the final total will also be blank. For example:</p>\n\n<p>NULL + 10 = NULL</p>\n\n<p>Access has a built in function that you can use to convert NULL values to zero. </p>\n\n<p>NZ( FieldName, ValueIfNull )</p>\n\n<p>You can use NZ in reports, queries, forms and VBA.</p>\n\n<p>So the example above could read like this:</p>\n\n<p>=NZ([GrandTotal1],0) + NZ([GrandTotal2],0) + NZ([GrandTotal3],0)</p>\n\n<p><a href=\"http://office.microsoft.com/en-us/access/HA012288901033.aspx\" rel=\"nofollow noreferrer\">http://office.microsoft.com/en-us/access/HA012288901033.aspx</a></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I can't quite figure this out. Microsoft Access 2000, on the report total section I have totals for three columns that are just numbers. These `=Sum[(ThisColumn1)], 2, 3`, etc and those grand totls all work fine.
I want to have another column that says `=Sum([ThisColumn1])+Sum([ThisColumn2]) + Sum([ThisColumn3])` but can't figure those one out. Just get a blank so I am sure there is an error.
|
Give the 3 Grand Totals meaningful Control Names and then for the Grand Grand Total use:
```
=[GrandTotal1] + [GrandTotal2] + [GrandTotal3]
```
Your Grand Total formulas should be something like:
```
=Sum(Nz([ThisColumn1], 0))
```
|
123,075 |
<p>How to do paging in Pervasive SQL (version 9.1)? I need to do something similar like:</p>
<pre><code>//MySQL
SELECT foo FROM table LIMIT 10, 10
</code></pre>
<p>But I can't find a way to define offset.</p>
|
[
{
"answer_id": 123168,
"author": "Jasmine",
"author_id": 5255,
"author_profile": "https://Stackoverflow.com/users/5255",
"pm_score": 0,
"selected": false,
"text": "<p>I face this problem in MS Sql too... no Limit or rownumber functions. What I do is insert the keys for my final query result (or sometimes the entire list of fields) into a temp table with an identity column... then I delete from the temp table everything outside the range I want... then use a join against the keys and the original table, to bring back the items I want. This works if you have a nice unique key - if you don't, well... that's a design problem in itself.</p>\n\n<p>Alternative with slightly better performance is to skip the deleting step and just use the row numbers in your final join. Another performance improvement is to use the TOP operator so that at the very least, you don't have to grab the stuff past the end of what you want.</p>\n\n<p>So... in pseudo-code... to grab items 80-89...</p>\n\n<pre><code>create table #keys (rownum int identity(1,1), key varchar(10))\n\ninsert #keys (key)\nselect TOP 89 key from myTable ORDER BY whatever\n\ndelete #keys where rownumber < 80\n\nselect <columns> from #keys join myTable on #keys.key = myTable.key\n</code></pre>\n"
},
{
"answer_id": 190005,
"author": "jjacka",
"author_id": 26515,
"author_profile": "https://Stackoverflow.com/users/26515",
"pm_score": 1,
"selected": false,
"text": "<p>Our paging required that we be able to pass in the current page number and page size (along with some additional filter parameters) as variables. Since a select top @page_size doesn't work in MS SQL, we came up with creating an temporary or variable table to assign each rows primary key an identity that can later be filtered on for the desired page number and size. </p>\n\n<p>** Note that if you have a GUID primary key or a compound key, you just have to change the object id on the temporary table to a uniqueidentifier or add the additional key columns to the table.</p>\n\n<p>The down side to this is that it still has to insert all of the results into the temporary table, but at least it is only the keys. This works in MS SQL, but should be able to work for any DB with minimal tweaks.</p>\n\n<blockquote>\n <p>declare @page_number int, @page_size\n int -- add any additional search\n parameters here<br/></p>\n \n <p>--create the temporary table with the identity column and the id <br/>\n --of the record that you'll be selecting. This is an in memory<br/>\n --table, so if the number of rows you'll be inserting is greater<br/>\n --than 10,000, then you should use a temporary table in tempdb<br/>\n --instead. To do this, use <br/>\n --CREATE TABLE #temp_table (row_num int IDENTITY(1,1), objectid int)<br/>\n --and change all the references to @temp_table to #temp_table<br/>\n DECLARE @temp_table TABLE (row_num int\n IDENTITY(1,1), objectid int)</p>\n \n <p>--insert into the temporary table with the ids of the records<br/>\n --we want to return. It's critical to make sure the order by<br/>\n --reflects the order of the records to return so that the row_num <br/>\n --values are set in the correct order and we are selecting the<br/> \n --correct records based on the page<br/> INSERT INTO @temp_table\n (objectid)</p>\n \n <p>/* Example: Select that inserts\n records into the temporary table<br/>\n SELECT personid <br/> FROM person WITH\n (NOLOCK) <br/> inner join degree WITH\n (NOLOCK) on degree.personid =\n person.personid<br/> WHERE\n person.lastname = @last_name<br/>\n ORDER BY person.lastname asc,\n person.firsname asc<br/>\n */</p>\n \n <p>--get the total number of rows that we matched<br/> DECLARE @total_rows\n int<br/> SET @total_rows =\n @@ROWCOUNT<br/>\n --calculate the total number of pages based on the number of<br/>\n --rows that matched and the page size passed in as a parameter<br/> DECLARE\n @total_pages int <br/>\n --add the @page_size - 1 to the total number of rows to <br/>\n --calculate the total number of pages. This is because sql <br/>\n --alwasy rounds down for division of integers<br/> SET @total_pages =\n (@total_rows + @page_size - 1) /\n @page_size </p>\n \n <p>--return the result set we are interested in by joining<br/>\n --back to the @temp_table and filtering by row_num<br/> /* Example:\n Selecting the data to return. If the\n insert was done<br/> properly, then\n you should always be joining the table\n that contains<br/> the rows to return\n to the objectid column on the\n @temp_table</p>\n \n <p>SELECT person.*<br/> FROM person WITH\n (NOLOCK) INNER JOIN @temp_table\n tt<br/> ON person.personid =\n tt.objectid<br/>\n */<br/>\n --return only the rows in the page that we are interested in<br/>\n --and order by the row_num column of the @temp_table to make sure<br/> \n --we are selecting the correct records<br/> WHERE tt.row_num <\n (@page_size * @page_number) + 1 <br/>\n AND tt.row_num > (@page_size *\n @page_number) - @page_size<br/> ORDER\n BY tt.row_num</p>\n</blockquote>\n"
},
{
"answer_id": 197046,
"author": "Vertigo",
"author_id": 5468,
"author_profile": "https://Stackoverflow.com/users/5468",
"pm_score": 1,
"selected": true,
"text": "<p>I ended up doing the paging in code. I just skip the first records in loop. </p>\n\n<p>I thought I made up an easy way for doing the paging, but it seems that pervasive sql doesn't allow order clauses in subqueries. But this should work on other DBs (I tested it on firebird)</p>\n\n<pre><code>select *\nfrom (select top [rows] * from\n(select top [rows * pagenumber] * from mytable order by id)\norder by id desc)\norder by id\n</code></pre>\n"
},
{
"answer_id": 2811818,
"author": "Vijay Bobba",
"author_id": 338408,
"author_profile": "https://Stackoverflow.com/users/338408",
"pm_score": 2,
"selected": false,
"text": "<p>Tested query in PSQL:</p>\n\n<pre><code>select top n * \nfrom tablename \nwhere id not in(\nselect top k id\nfrom tablename \n) \n</code></pre>\n\n<p>for all n = no.of records u need to fetch at a time.\nand k = multiples of n(eg. n=5; k=0,5,10,15,....)</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5468/"
] |
How to do paging in Pervasive SQL (version 9.1)? I need to do something similar like:
```
//MySQL
SELECT foo FROM table LIMIT 10, 10
```
But I can't find a way to define offset.
|
I ended up doing the paging in code. I just skip the first records in loop.
I thought I made up an easy way for doing the paging, but it seems that pervasive sql doesn't allow order clauses in subqueries. But this should work on other DBs (I tested it on firebird)
```
select *
from (select top [rows] * from
(select top [rows * pagenumber] * from mytable order by id)
order by id desc)
order by id
```
|
123,078 |
<p>On destruction of a restful resource, I want to guarantee a few things before I allow a destroy operation to continue? Basically, I want the ability to stop the destroy operation if I note that doing so would place the database in a invalid state? There are no validation callbacks on a destroy operation, so how does one "validate" whether a destroy operation should be accepted?</p>
|
[
{
"answer_id": 123190,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 7,
"selected": true,
"text": "<p>You can raise an exception which you then catch. Rails wraps deletes in a transaction, which helps matters.</p>\n\n<p>For example:</p>\n\n<pre><code>class Booking < ActiveRecord::Base\n has_many :booking_payments\n ....\n def destroy\n raise \"Cannot delete booking with payments\" unless booking_payments.count == 0\n # ... ok, go ahead and destroy\n super\n end\nend\n</code></pre>\n\n<p>Alternatively you can use the before_destroy callback. This callback is normally used to destroy dependent records, but you can throw an exception or add an error instead.</p>\n\n<pre><code>def before_destroy\n return true if booking_payments.count == 0\n errors.add :base, \"Cannot delete booking with payments\"\n # or errors.add_to_base in Rails 2\n false\n # Rails 5\n throw(:abort)\nend\n</code></pre>\n\n<p><code>myBooking.destroy</code> will now return false, and <code>myBooking.errors</code> will be populated on return.</p>\n"
},
{
"answer_id": 123219,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use the before_destroy callback to raise an exception.</p>\n"
},
{
"answer_id": 124267,
"author": "go minimal",
"author_id": 1396,
"author_profile": "https://Stackoverflow.com/users/1396",
"pm_score": 3,
"selected": false,
"text": "<p>The ActiveRecord associations has_many and has_one allows for a dependent option that will make sure related table rows are deleted on delete, but this is usually to keep your database clean rather than preventing it from being invalid.</p>\n"
},
{
"answer_id": 125518,
"author": "Toby Hede",
"author_id": 14971,
"author_profile": "https://Stackoverflow.com/users/14971",
"pm_score": 3,
"selected": false,
"text": "<p>You can wrap the destroy action in an \"if\" statement in the controller:</p>\n\n<pre><code>def destroy # in controller context\n if (model.valid_destroy?)\n model.destroy # if in model context, use `super`\n end\nend\n</code></pre>\n\n<p>Where <em>valid_destroy?</em> is a method on your model class that returns true if the conditions for destroying a record are met.</p>\n\n<p>Having a method like this will also let you prevent the display of the delete option to the user - which will improve the user experience as the user won't be able to perform an illegal operation. </p>\n"
},
{
"answer_id": 6874233,
"author": "workdreamer",
"author_id": 855668,
"author_profile": "https://Stackoverflow.com/users/855668",
"pm_score": 6,
"selected": false,
"text": "<p>just a note:</p>\n\n<p>For rails 3</p>\n\n<pre><code>class Booking < ActiveRecord::Base\n\nbefore_destroy :booking_with_payments?\n\nprivate\n\ndef booking_with_payments?\n errors.add(:base, \"Cannot delete booking with payments\") unless booking_payments.count == 0\n\n errors.blank? #return false, to not destroy the element, otherwise, it will delete.\nend\n</code></pre>\n"
},
{
"answer_id": 17155048,
"author": "Hugo Forte",
"author_id": 231759,
"author_profile": "https://Stackoverflow.com/users/231759",
"pm_score": 2,
"selected": false,
"text": "<p>I ended up using code from here to create a can_destroy override on activerecord:\n<a href=\"https://gist.github.com/andhapp/1761098\" rel=\"nofollow\">https://gist.github.com/andhapp/1761098</a></p>\n\n<pre><code>class ActiveRecord::Base\n def can_destroy?\n self.class.reflect_on_all_associations.all? do |assoc|\n assoc.options[:dependent] != :restrict || (assoc.macro == :has_one && self.send(assoc.name).nil?) || (assoc.macro == :has_many && self.send(assoc.name).empty?)\n end\n end\nend\n</code></pre>\n\n<p>This has the added benefit of making it trivial to hide/show a delete button on the ui</p>\n"
},
{
"answer_id": 21056053,
"author": "Mateo Vidal",
"author_id": 2077627,
"author_profile": "https://Stackoverflow.com/users/2077627",
"pm_score": 2,
"selected": false,
"text": "<p>I have these classes or models</p>\n\n<pre><code>class Enterprise < AR::Base\n has_many :products\n before_destroy :enterprise_with_products?\n\n private\n\n def empresas_with_portafolios?\n self.portafolios.empty? \n end\nend\n\nclass Product < AR::Base\n belongs_to :enterprises\nend\n</code></pre>\n\n<p>Now when you delete an enterprise this process validates if there are products associated with enterprises\nNote: You have to write this in the top of the class in order to validate it first.</p>\n"
},
{
"answer_id": 37880585,
"author": "Raphael Monteiro",
"author_id": 4235629,
"author_profile": "https://Stackoverflow.com/users/4235629",
"pm_score": 4,
"selected": false,
"text": "<p>It is what I did with Rails 5:</p>\n\n<pre><code>before_destroy do\n cannot_delete_with_qrcodes\n throw(:abort) if errors.present?\nend\n\ndef cannot_delete_with_qrcodes\n errors.add(:base, 'Cannot delete shop with qrcodes') if qrcodes.any?\nend\n</code></pre>\n"
},
{
"answer_id": 47968834,
"author": "swordray",
"author_id": 3422600,
"author_profile": "https://Stackoverflow.com/users/3422600",
"pm_score": 1,
"selected": false,
"text": "<p>Use ActiveRecord context validation in Rails 5.</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>class ApplicationRecord < ActiveRecord::Base\n before_destroy do\n throw :abort if invalid?(:destroy)\n end\nend\n</code></pre>\n\n<pre class=\"lang-rb prettyprint-override\"><code>class Ticket < ApplicationRecord\n validate :validate_expires_on, on: :destroy\n\n def validate_expires_on\n errors.add :expires_on if expires_on > Time.now\n end\nend\n</code></pre>\n"
},
{
"answer_id": 49560873,
"author": "ragurney",
"author_id": 5677587,
"author_profile": "https://Stackoverflow.com/users/5677587",
"pm_score": 1,
"selected": false,
"text": "<p>I was hoping this would be supported so I opened a rails issue to get it added: </p>\n\n<p><a href=\"https://github.com/rails/rails/issues/32376\" rel=\"nofollow noreferrer\">https://github.com/rails/rails/issues/32376</a></p>\n"
},
{
"answer_id": 59034233,
"author": "thisismydesign",
"author_id": 2771889,
"author_profile": "https://Stackoverflow.com/users/2771889",
"pm_score": 4,
"selected": false,
"text": "<p>State of affairs as of Rails 6:</p>\n\n<p>This works:</p>\n\n<pre><code>before_destroy :ensure_something, prepend: true do\n throw(:abort) if errors.present?\nend\n\nprivate\n\ndef ensure_something\n errors.add(:field, \"This isn't a good idea..\") if something_bad\nend\n</code></pre>\n\n<p><code>validate :validate_test, on: :destroy</code> doesn't work: <a href=\"https://github.com/rails/rails/issues/32376\" rel=\"noreferrer\">https://github.com/rails/rails/issues/32376</a></p>\n\n<p>Since Rails 5 <code>throw(:abort)</code> is required to cancel execution: <a href=\"https://makandracards.com/makandra/20301-cancelling-the-activerecord-callback-chain\" rel=\"noreferrer\">https://makandracards.com/makandra/20301-cancelling-the-activerecord-callback-chain</a></p>\n\n<p><code>prepend: true</code> is required so that <code>dependent: :destroy</code> doesn't run before the validations are executed: <a href=\"https://github.com/rails/rails/issues/3458\" rel=\"noreferrer\">https://github.com/rails/rails/issues/3458</a></p>\n\n<p>You can fish this together from other answers and comments, but I found none of them to be complete.</p>\n\n<p><em>As a sidenote, many used a <code>has_many</code> relation as an example where they want to make sure not to delete any records if it would create orphaned records. This can be solved much more easily:</em></p>\n\n<p><code>has_many :entities, dependent: :restrict_with_error</code></p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21317/"
] |
On destruction of a restful resource, I want to guarantee a few things before I allow a destroy operation to continue? Basically, I want the ability to stop the destroy operation if I note that doing so would place the database in a invalid state? There are no validation callbacks on a destroy operation, so how does one "validate" whether a destroy operation should be accepted?
|
You can raise an exception which you then catch. Rails wraps deletes in a transaction, which helps matters.
For example:
```
class Booking < ActiveRecord::Base
has_many :booking_payments
....
def destroy
raise "Cannot delete booking with payments" unless booking_payments.count == 0
# ... ok, go ahead and destroy
super
end
end
```
Alternatively you can use the before\_destroy callback. This callback is normally used to destroy dependent records, but you can throw an exception or add an error instead.
```
def before_destroy
return true if booking_payments.count == 0
errors.add :base, "Cannot delete booking with payments"
# or errors.add_to_base in Rails 2
false
# Rails 5
throw(:abort)
end
```
`myBooking.destroy` will now return false, and `myBooking.errors` will be populated on return.
|
123,088 |
<p><strong>C#6 Update</strong></p>
<p>In <a href="https://msdn.microsoft.com/en-us/magazine/dn802602.aspx" rel="nofollow noreferrer">C#6 <code>?.</code> is now a language feature</a>:</p>
<pre><code>// C#1-5
propertyValue1 = myObject != null ? myObject.StringProperty : null;
// C#6
propertyValue1 = myObject?.StringProperty;
</code></pre>
<p>The question below still applies to older versions, but if developing a new application using the new <code>?.</code> operator is far better practice.</p>
<p><strong>Original Question:</strong></p>
<p>I regularly want to access properties on possibly null objects:</p>
<pre><code>string propertyValue1 = null;
if( myObject1 != null )
propertyValue1 = myObject1.StringProperty;
int propertyValue2 = 0;
if( myObject2 != null )
propertyValue2 = myObject2.IntProperty;
</code></pre>
<p>And so on...</p>
<p>I use this so often that I have a snippet for it.</p>
<p>You can shorten this to some extent with an inline if:</p>
<pre><code>propertyValue1 = myObject != null ? myObject.StringProperty : null;
</code></pre>
<p>However this is a little clunky, especially if setting lots of properties or if more than one level can be null, for instance:</p>
<pre><code>propertyValue1 = myObject != null ?
(myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null;
</code></pre>
<p>What I really want is <code>??</code> style syntax, which works great for directly null types:</p>
<pre><code>int? i = SomeFunctionWhichMightReturnNull();
propertyValue2 = i ?? 0;
</code></pre>
<p>So I came up with the following:</p>
<pre><code>public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action, TResult valueIfNull )
where T : class
{
if ( input != null ) return action( input );
else return valueIfNull;
}
//lets us have a null default if the type is nullable
public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action )
where T : class
where TResult : class
{ return input.IfNotNull( action, null ); }
</code></pre>
<p>This lets me us this syntax:</p>
<pre><code>propertyValue1 = myObject1.IfNotNull( x => x.StringProperty );
propertyValue2 = myObject2.IfNotNull( x => x.IntProperty, 0);
//or one with multiple levels
propertyValue1 = myObject.IfNotNull(
o => o.ObjectProp.IfNotNull( p => p.StringProperty ) );
</code></pre>
<p>This simplifies these calls, but I'm not sure about checking this sort of extension method in - it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, although I could put it in a specifically referenced namespace.</p>
<p>This example is a rather simple one, a slightly more complex one would be comparing two nullable object properties:</p>
<pre><code>if( ( obj1 == null && obj2 == null ) ||
( obj1 != null && obj2 != null && obj1.Property == obj2.Property ) )
...
//becomes
if( obj1.NullCompare( obj2, (x,y) => x.Property == y.Property )
...
</code></pre>
<p>What are the pitfalls of using extensions in this way? Are other coders likely to be confused? Is this just abuse of extensions?</p>
<hr>
<p>I guess what I really want here is a compiler/language extension:</p>
<pre><code>propertyValue1 = myObject != null ? myObject.StringProperty : null;
//becomes
propertyValue1 = myObject?StringProperty;
</code></pre>
<p>This would make the complex case far easier:</p>
<pre><code>propertyValue1 = myObject != null ?
(myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null
//becomes
propertyValue1 = myObject?ObjectProp?StringProperty;
</code></pre>
<p>This would only work for value types, but you could return nullable equivalents:</p>
<pre><code>int? propertyValue2 = myObject?ObjectProp?IntProperty;
//or
int propertyValue3 = myObject?ObjectProp?IntProperty ?? 0;
</code></pre>
|
[
{
"answer_id": 123140,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 0,
"selected": false,
"text": "<p>Personally, even after all your explanation, I can't remember how the heck this works:</p>\n\n<pre><code>if( obj1.NullCompare( obj2, (x,y) => x.Property == y.Property ) \n</code></pre>\n\n<p>This could be because I have no C# experience; however, I could read and understand everything else in your code. I prefer to keep code language agnostic (esp. for trivial things) so that tomorrow, another developer could change it to a whole new language without too much information about the existing language.</p>\n"
},
{
"answer_id": 123229,
"author": "ljorquera",
"author_id": 9132,
"author_profile": "https://Stackoverflow.com/users/9132",
"pm_score": 4,
"selected": false,
"text": "<p>If you find yourself having to check very often if a reference to an object is null, may be you should be using the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"nofollow noreferrer\">Null Object Pattern</a>. In this pattern, instead of using null to deal with the case where you don't have an object, you implement a new class with the same interface but with methods and properties that return adequate default values.</p>\n"
},
{
"answer_id": 123496,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, </p>\n</blockquote>\n\n<p>Note that you are not actually extending anything (except theoretically).</p>\n\n<pre><code>propertyValue2 = myObject2.IfNotNull( x => x.IntProperty, 0);\n</code></pre>\n\n<p>will generate IL code exactly as if it were written:</p>\n\n<pre><code>ExtentionClass::IfNotNull(myObject2, x => x.IntProperty, 0);\n</code></pre>\n\n<p>There is no \"overhead\" added to the objects to support this.</p>\n"
},
{
"answer_id": 123568,
"author": "Robert Jeppesen",
"author_id": 9436,
"author_profile": "https://Stackoverflow.com/users/9436",
"pm_score": 3,
"selected": false,
"text": "<p>How is </p>\n\n<pre><code>propertyValue1 = myObject.IfNotNull(o => o.ObjectProp.IfNotNull( p => p.StringProperty ) );\n</code></pre>\n\n<p>easier to read and write than </p>\n\n<pre><code>if(myObject != null && myObject.ObjectProp != null)\n propertyValue1 = myObject.ObjectProp.StringProperty;\n</code></pre>\n\n<p>Jafar Husain posted a sample of using Expression Trees to check for null in a chain, <a href=\"http://themechanicalbride.blogspot.com/2007/03/runtime-macros-in-c-30.html\" rel=\"noreferrer\">Runtime macros in C# 3</a>. </p>\n\n<p>This obviously has performance implications though. Now if only we had a way to do this at compile time. </p>\n"
},
{
"answer_id": 123576,
"author": "Stefan Rusek",
"author_id": 19704,
"author_profile": "https://Stackoverflow.com/users/19704",
"pm_score": 3,
"selected": false,
"text": "<p>I just have to say that I love this hack!</p>\n\n<p>I hadn't realized that extension methods don't imply a null check, but it totally makes sense. As James pointed out, The extension method call itself is not any more expensive than a normal method, however if you are doing a ton of this, then it does make sense to follow the Null Object Pattern, that ljorquera suggested. Or to use a null object and ?? together.</p>\n\n<pre><code>class Class1\n{\n public static readonly Class1 Empty = new Class1();\n.\n.\nx = (obj1 ?? Class1.Empty).X;\n</code></pre>\n"
},
{
"answer_id": 123635,
"author": "mancaus",
"author_id": 13797,
"author_profile": "https://Stackoverflow.com/users/13797",
"pm_score": 1,
"selected": false,
"text": "<p>To reader not in the know it looks like you're calling a method on a null reference. If you want this, I'd suggest putting it in a utility class rather than using an extension method:</p>\n\n<pre><code>\npropertyValue1 = Util.IfNotNull(myObject1, x => x.StringProperty );\npropertyValue2 = Util.IfNotNull(myObject2, x => x.IntProperty, 0);\n</code></pre>\n\n<p>The \"Util.\" grates, but is IMO the lesser syntactic evil.</p>\n\n<p>Also, if you developing this as part of a team, then gently ask what others think and do. Consistency across a codebase for frequently used patterns is important. </p>\n"
},
{
"answer_id": 124577,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "<p>While extension methods generally cause misunderstandings when called from null instances, I think the intent is <em>pretty straightforward</em> in this case.</p>\n\n<pre><code>string x = null;\nint len = x.IfNotNull(y => y.Length, 0);\n</code></pre>\n\n<p>I would want to be sure this static method works on Value Types that can be null, such as int?</p>\n\n<p>Edit: compiler says that neither of these are valid:</p>\n\n<pre><code> public void Test()\n {\n int? x = null;\n int a = x.IfNotNull(z => z.Value + 1, 3);\n int b = x.IfNotNull(z => z.Value + 1);\n }\n</code></pre>\n\n<p>Other than that, go for it.</p>\n"
},
{
"answer_id": 144982,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "<p>Here's another solution, for chained members, including extension methods:</p>\n\n<pre><code>public static U PropagateNulls<T,U> ( this T obj\n ,Expression<Func<T,U>> expr) \n{ if (obj==null) return default(U);\n\n //uses a stack to reverse Member1(Member2(obj)) to obj.Member1.Member2 \n var members = new Stack<MemberInfo>();\n\n bool searchingForMembers = true;\n Expression currentExpression = expr.Body;\n\n while (searchingForMembers) switch (currentExpression.NodeType)\n { case ExpressionType.Parameter: searchingForMembers = false; break;\n\n case ExpressionType.MemberAccess: \n { var ma= (MemberExpression) currentExpression;\n members.Push(ma.Member);\n currentExpression = ma.Expression; \n } break; \n\n case ExpressionType.Call:\n { var mc = (MethodCallExpression) currentExpression;\n members.Push(mc.Method);\n\n //only supports 1-arg static methods and 0-arg instance methods\n if ( (mc.Method.IsStatic && mc.Arguments.Count == 1) \n || (mc.Arguments.Count == 0))\n { currentExpression = mc.Method.IsStatic ? mc.Arguments[0]\n : mc.Object; \n break;\n }\n\n throw new NotSupportedException(mc.Method+\" is not supported\");\n } \n\n default: throw new NotSupportedException\n (currentExpression.GetType()+\" not supported\");\n }\n\n object currValue = obj;\n while(members.Count > 0)\n { var m = members.Pop();\n\n switch(m.MemberType)\n { case MemberTypes.Field:\n currValue = ((FieldInfo) m).GetValue(currValue); \n break;\n\n case MemberTypes.Method:\n var method = (MethodBase) m;\n currValue = method.IsStatic\n ? method.Invoke(null,new[]{currValue})\n : method.Invoke(currValue,null); \n break;\n\n case MemberTypes.Property:\n var method = ((PropertyInfo) m).GetGetMethod(true);\n currValue = method.Invoke(currValue,null);\n break;\n\n } \n\n if (currValue==null) return default(U); \n }\n\n return (U) currValue; \n}\n</code></pre>\n\n<p>Then you can do this where any can be null, or none:</p>\n\n<pre><code>foo.PropagateNulls(x => x.ExtensionMethod().Property.Field.Method());\n</code></pre>\n"
},
{
"answer_id": 191596,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 5,
"selected": true,
"text": "<p>We independently came up with the exact same extension method name and implementation: <a href=\"http://code.logos.com/blog/2008/01/nullpropagating_extension_meth.html\" rel=\"noreferrer\">Null-propagating extension method</a>. So we don't think it's confusing or an abuse of extension methods.</p>\n\n<p>I would write your \"multiple levels\" example with chaining as follows:</p>\n\n<pre><code>propertyValue1 = myObject.IfNotNull(o => o.ObjectProp).IfNotNull(p => p.StringProperty);\n</code></pre>\n\n<p>There's a <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=192177\" rel=\"noreferrer\">now-closed bug on Microsoft Connect</a> that proposed \"?.\" as a new C# operator that would perform this null propagation. Mads Torgersen (from the C# language team) briefly explained why they won't implement it.</p>\n"
},
{
"answer_id": 921448,
"author": "epitka",
"author_id": 103682,
"author_profile": "https://Stackoverflow.com/users/103682",
"pm_score": 0,
"selected": false,
"text": "<p>Here is another solution using myObject.NullSafe(x=>x.SomeProperty.NullSafe(x=>x.SomeMethod)), explained at \n<a href=\"http://www.epitka.blogspot.com/\" rel=\"nofollow noreferrer\">http://www.epitka.blogspot.com/</a></p>\n"
},
{
"answer_id": 27822535,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 1,
"selected": false,
"text": "<p>Not an answer to the exact question asked, but there is <em>Null-Conditional Operator</em> <a href=\"http://msdn.microsoft.com/en-us/magazine/dn802602.aspx\" rel=\"nofollow\">in C# 6.0</a>. I can argue it will be a poor choice to use the option in OP since C# 6.0 :)</p>\n\n<p>So your expression is simpler,</p>\n\n<pre><code>string propertyValue = myObject?.StringProperty;\n</code></pre>\n\n<p>In case <code>myObject</code> is null it returns null. In case the property is a value type you have to use equivalent nullable type, like,</p>\n\n<pre><code>int? propertyValue = myObject?.IntProperty;\n</code></pre>\n\n<p>Or otherwise you can coalesce with null coalescing operator to give a default value in case of null. For eg,</p>\n\n<pre><code>int propertyValue = myObject?.IntProperty ?? 0;\n</code></pre>\n\n<p><code>?.</code> is not the only syntax available. For indexed properties you can use <code>?[..]</code>. For eg,</p>\n\n<pre><code>string propertyValue = myObject?[index]; //returns null in case myObject is null\n</code></pre>\n\n<p>One surprising behaviour of the <code>?.</code> operator is that it can intelligently bypass subsequent <code>.Member</code> calls if object happens to be null. One such example is given in the link:</p>\n\n<pre><code>var result = value?.Substring(0, Math.Min(value.Length, length)).PadRight(length);\n</code></pre>\n\n<p>In this case <code>result</code> is null if <code>value</code> is null and <code>value.Length</code> expression wouldn't result in <code>NullReferenceException</code>.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] |
**C#6 Update**
In [C#6 `?.` is now a language feature](https://msdn.microsoft.com/en-us/magazine/dn802602.aspx):
```
// C#1-5
propertyValue1 = myObject != null ? myObject.StringProperty : null;
// C#6
propertyValue1 = myObject?.StringProperty;
```
The question below still applies to older versions, but if developing a new application using the new `?.` operator is far better practice.
**Original Question:**
I regularly want to access properties on possibly null objects:
```
string propertyValue1 = null;
if( myObject1 != null )
propertyValue1 = myObject1.StringProperty;
int propertyValue2 = 0;
if( myObject2 != null )
propertyValue2 = myObject2.IntProperty;
```
And so on...
I use this so often that I have a snippet for it.
You can shorten this to some extent with an inline if:
```
propertyValue1 = myObject != null ? myObject.StringProperty : null;
```
However this is a little clunky, especially if setting lots of properties or if more than one level can be null, for instance:
```
propertyValue1 = myObject != null ?
(myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null : null;
```
What I really want is `??` style syntax, which works great for directly null types:
```
int? i = SomeFunctionWhichMightReturnNull();
propertyValue2 = i ?? 0;
```
So I came up with the following:
```
public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action, TResult valueIfNull )
where T : class
{
if ( input != null ) return action( input );
else return valueIfNull;
}
//lets us have a null default if the type is nullable
public static TResult IfNotNull<T, TResult>( this T input, Func<T, TResult> action )
where T : class
where TResult : class
{ return input.IfNotNull( action, null ); }
```
This lets me us this syntax:
```
propertyValue1 = myObject1.IfNotNull( x => x.StringProperty );
propertyValue2 = myObject2.IfNotNull( x => x.IntProperty, 0);
//or one with multiple levels
propertyValue1 = myObject.IfNotNull(
o => o.ObjectProp.IfNotNull( p => p.StringProperty ) );
```
This simplifies these calls, but I'm not sure about checking this sort of extension method in - it does make the code a little easier to read, but at the cost of extending object. This would appear on everything, although I could put it in a specifically referenced namespace.
This example is a rather simple one, a slightly more complex one would be comparing two nullable object properties:
```
if( ( obj1 == null && obj2 == null ) ||
( obj1 != null && obj2 != null && obj1.Property == obj2.Property ) )
...
//becomes
if( obj1.NullCompare( obj2, (x,y) => x.Property == y.Property )
...
```
What are the pitfalls of using extensions in this way? Are other coders likely to be confused? Is this just abuse of extensions?
---
I guess what I really want here is a compiler/language extension:
```
propertyValue1 = myObject != null ? myObject.StringProperty : null;
//becomes
propertyValue1 = myObject?StringProperty;
```
This would make the complex case far easier:
```
propertyValue1 = myObject != null ?
(myObject.ObjectProp != null ? myObject.ObjectProp.StringProperty) : null
//becomes
propertyValue1 = myObject?ObjectProp?StringProperty;
```
This would only work for value types, but you could return nullable equivalents:
```
int? propertyValue2 = myObject?ObjectProp?IntProperty;
//or
int propertyValue3 = myObject?ObjectProp?IntProperty ?? 0;
```
|
We independently came up with the exact same extension method name and implementation: [Null-propagating extension method](http://code.logos.com/blog/2008/01/nullpropagating_extension_meth.html). So we don't think it's confusing or an abuse of extension methods.
I would write your "multiple levels" example with chaining as follows:
```
propertyValue1 = myObject.IfNotNull(o => o.ObjectProp).IfNotNull(p => p.StringProperty);
```
There's a [now-closed bug on Microsoft Connect](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=192177) that proposed "?." as a new C# operator that would perform this null propagation. Mads Torgersen (from the C# language team) briefly explained why they won't implement it.
|
123,111 |
<p>I recently moved my website to a shared hosting solution at <a href="http://asmallorange.com" rel="nofollow noreferrer">asmallorange.com</a>, but I had to set my domain to use their provided nameservers in order for the site to properly resolve. I was determined to keep control of the domain's DNS but I could find no way to make my top level domain resolve to the shared location which was in the format of </p>
<pre><code>server.asmallorange.com/~username
</code></pre>
<p>So I know I'm missing something here, my question is this: </p>
<p><strong>What in their nameservers/DNS entry makes it possible for <em>server.sharedhost.com/~username</em> to serve as a top level domain? (ie. <a href="http://topleveldomain.com" rel="nofollow noreferrer">http://topleveldomain.com</a>)</strong></p>
|
[
{
"answer_id": 123133,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 4,
"selected": true,
"text": "<p>Nothing. DNS simply maps topleveldomain.com to server.sharedhost.com. It's the webserver which looks at the <code>Host: topleveldomain.com</code> header and knows that's equivalent to server.sharedhost.com/~username.</p>\n"
},
{
"answer_id": 123139,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 3,
"selected": false,
"text": "<p>Nothing. They are having your domain name resolve to the same IP that server.asmallorange.com resolves to, but then they are making their web server aware of the domain name topleveldomain.com, and telling the webserver that it is the same as server.asmallorange.com/~username.</p>\n\n<p>Virtual hosts aren't a DNS trick, they're an HTTP trick - the hostname requested is sent by the browser in a Host: field of every request.</p>\n"
},
{
"answer_id": 123179,
"author": "gehsekky",
"author_id": 21310,
"author_profile": "https://Stackoverflow.com/users/21310",
"pm_score": 0,
"selected": false,
"text": "<p>apache has a \"mod_user\" which you can enable in your apache conf file. Using this and virtual hosts is how that is accomplished.</p>\n"
},
{
"answer_id": 392337,
"author": "Amandasaurus",
"author_id": 161922,
"author_profile": "https://Stackoverflow.com/users/161922",
"pm_score": 0,
"selected": false,
"text": "<p>Virtual Hosts in Apache are how this is done.</p>\n\n<p>However just because you set the DNS up to go \"mydomain.com resolves to 1.2.3.4\", which is their IP address, doesn't mean that you're giving up control of your domain name.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339/"
] |
I recently moved my website to a shared hosting solution at [asmallorange.com](http://asmallorange.com), but I had to set my domain to use their provided nameservers in order for the site to properly resolve. I was determined to keep control of the domain's DNS but I could find no way to make my top level domain resolve to the shared location which was in the format of
```
server.asmallorange.com/~username
```
So I know I'm missing something here, my question is this:
**What in their nameservers/DNS entry makes it possible for *server.sharedhost.com/~username* to serve as a top level domain? (ie. <http://topleveldomain.com>)**
|
Nothing. DNS simply maps topleveldomain.com to server.sharedhost.com. It's the webserver which looks at the `Host: topleveldomain.com` header and knows that's equivalent to server.sharedhost.com/~username.
|
123,127 |
<p>I am running my junit tests via ant and they are running substantially slower than via the IDE. My ant call is:</p>
<pre><code> <junit fork="yes" forkmode="once" printsummary="off">
<classpath refid="test.classpath"/>
<formatter type="brief" usefile="false"/>
<batchtest todir="${test.results.dir}/xml">
<formatter type="xml"/>
<fileset dir="src" includes="**/*Test.java" />
</batchtest>
</junit>
</code></pre>
<p>The same test that runs in near instantaneously in my IDE (0.067s) takes 4.632s when run through Ant. In the past, I've been able to speed up test problems like this by using the junit fork parameter but this doesn't seem to be helping in this case. What properties or parameters can I look at to speed up these tests?</p>
<p>More info:</p>
<p>I am using the reported time from the IDE vs. the time that the junit task outputs. This is not the sum total time reported at the end of the ant run.</p>
<p>So, bizarrely, this problem has resolved itself. What could have caused this problem? The system runs on a local disk so that is not the problem.</p>
|
[
{
"answer_id": 123169,
"author": "Eric Asberry",
"author_id": 20437,
"author_profile": "https://Stackoverflow.com/users/20437",
"pm_score": 1,
"selected": false,
"text": "<p>Difficult to tell with that information. First thing I would do is look at the test results and determine if all the individual tests are running uniformly slower or if it can be narrowed down to a certain subset of test cases. </p>\n\n<p>(The zero'th thing I would do is make sure that my ant task is using the same JVM as Eclipse and that the classpath dependencies and imported JARs are really and truly identical)</p>\n"
},
{
"answer_id": 125305,
"author": "marcospereira",
"author_id": 4600,
"author_profile": "https://Stackoverflow.com/users/4600",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you are seeing that because Eclipse do incremental compiling and Ant don't. Can you confirm that this time is wasted only in the test target?</p>\n"
},
{
"answer_id": 140974,
"author": "bsanders",
"author_id": 22200,
"author_profile": "https://Stackoverflow.com/users/22200",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a blind guess: try increasing the maximum heap size available to the forked VM by using a nested <code><jvmarg></code> tag to set the <code>-Xmx</code> option.</p>\n"
},
{
"answer_id": 240495,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 0,
"selected": false,
"text": "<p>For the record, I found my problem. We have been using a code obfuscator for this project, and the string encryption portion of that obfuscator was set to \"maximum\". This slowed down any operation where strings were present.</p>\n\n<p>Turning down the string encryption to a faster mode fixed the problem.</p>\n"
},
{
"answer_id": 377899,
"author": "Risser",
"author_id": 7773,
"author_profile": "https://Stackoverflow.com/users/7773",
"pm_score": 2,
"selected": false,
"text": "<p>I'm guessing it's because your antscript is outputing results to XML files, whereas the IDE is keeping those in memory. It takes longer to write a file than to not write a file.</p>\n\n<pre><code>todir=\"${test.results.dir}/xml\"\n</code></pre>\n\n<p>That's the part of the <batchtest> call that tells it to stick the results into that directory. It looks like leaving it off just tells it to stick the results in the \"current directory\", whatever that is. At first glance I didn't see anything to turn it all the way off.</p>\n"
},
{
"answer_id": 36776206,
"author": "Kristof Neirynck",
"author_id": 11451,
"author_profile": "https://Stackoverflow.com/users/11451",
"pm_score": 0,
"selected": false,
"text": "<p>Try setting fork, forkmode and threads to these values:</p>\n\n<pre><code><junit fork=\"yes\" forkmode=\"perTest\" printsummary=\"off\" threads=\"4\">\n <classpath refid=\"test.classpath\"/>\n <formatter type=\"brief\" usefile=\"false\"/>\n <batchtest todir=\"${test.results.dir}/xml\">\n <formatter type=\"xml\"/>\n <fileset dir=\"src\" includes=\"**/*Test.java\" />\n </batchtest>\n</junit>\n</code></pre>\n\n<p>Also see <a href=\"https://ant.apache.org/manual/Tasks/junit.html\" rel=\"nofollow noreferrer\">https://ant.apache.org/manual/Tasks/junit.html</a></p>\n"
},
{
"answer_id": 44601405,
"author": "Chin",
"author_id": 1748450,
"author_profile": "https://Stackoverflow.com/users/1748450",
"pm_score": 0,
"selected": false,
"text": "<p>For me, adding <code>forkmode=\"once\"</code> for the <code><junit></code> element and adding <code>usefile=\"false\"</code> for the <code><formatter></code> element makes the tests run much faster. Also remove the formatters that you don't need.</p>\n"
}
] |
2008/09/23
|
[
"https://Stackoverflow.com/questions/123127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] |
I am running my junit tests via ant and they are running substantially slower than via the IDE. My ant call is:
```
<junit fork="yes" forkmode="once" printsummary="off">
<classpath refid="test.classpath"/>
<formatter type="brief" usefile="false"/>
<batchtest todir="${test.results.dir}/xml">
<formatter type="xml"/>
<fileset dir="src" includes="**/*Test.java" />
</batchtest>
</junit>
```
The same test that runs in near instantaneously in my IDE (0.067s) takes 4.632s when run through Ant. In the past, I've been able to speed up test problems like this by using the junit fork parameter but this doesn't seem to be helping in this case. What properties or parameters can I look at to speed up these tests?
More info:
I am using the reported time from the IDE vs. the time that the junit task outputs. This is not the sum total time reported at the end of the ant run.
So, bizarrely, this problem has resolved itself. What could have caused this problem? The system runs on a local disk so that is not the problem.
|
Here's a blind guess: try increasing the maximum heap size available to the forked VM by using a nested `<jvmarg>` tag to set the `-Xmx` option.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.