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
61,366
<p>This question is slightly related to <a href="https://stackoverflow.com/questions/61354/how-to-get-entire-chain-of-exceptions-in-applicationthreadexception-event-handl">this question about exception handling</a>. The workaround I found there consists of rolling my own message loop.</p> <p>So my Main method now looks basically like this:</p> <pre><code>[STAThread] static void Main() { // this is needed so there'll actually an exception be thrown by // Application.Run/Application.DoEvents, instead of the ThreadException // event being raised. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form form = new MainForm(); form.Show(); // the loop is here to keep app running if non-fatal exception is caught. do { try { Application.DoEvents(); Thread.Sleep(100); } catch (Exception ex) { ExceptionHandler.ConsumeException(ex); } } while (!form.IsDisposed); } </code></pre> <p>What I'm wondering though, <strong>is this a safe/decent way to replace the more typical 'Application.Run(new MainForm());'</strong>, whether it's used for exception handling or for whatever else, or should I always stick to using Application.Run?</p> <p>On another app that's in testing now a similar approach is used for both loading (splashscreen) and exception handling, and I don't think it has caused any troubles (yet :-))</p>
[ { "answer_id": 61393, "author": "ima", "author_id": 5733, "author_profile": "https://Stackoverflow.com/users/5733", "pm_score": 2, "selected": false, "text": "<p>Pitfall 1: </p>\n\n<pre><code>Thread.Sleep(100);\n</code></pre>\n\n<p>Never. Use WaitMessage().</p>\n\n<p>Otherwise, it is possible roll out your own message loop, but in your scenario it seems somewhat pointless.</p>\n\n<p>You may also want to examine Application.Run() code (with .Net Reflector, for instance).</p>\n" }, { "answer_id": 61420, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 0, "selected": false, "text": "<p>Yes... I think some components wont work with that code. Some of them require to live in a thread that has an Application.Run in it to effectively pick up their messages.</p>\n" }, { "answer_id": 63590, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "<p>If you want to customize message processing, consider implementing IMessageFilter, then call Application.AddMessageFilter to tell the standard message pump to call your filter function.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5422/" ]
This question is slightly related to [this question about exception handling](https://stackoverflow.com/questions/61354/how-to-get-entire-chain-of-exceptions-in-applicationthreadexception-event-handl). The workaround I found there consists of rolling my own message loop. So my Main method now looks basically like this: ``` [STAThread] static void Main() { // this is needed so there'll actually an exception be thrown by // Application.Run/Application.DoEvents, instead of the ThreadException // event being raised. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form form = new MainForm(); form.Show(); // the loop is here to keep app running if non-fatal exception is caught. do { try { Application.DoEvents(); Thread.Sleep(100); } catch (Exception ex) { ExceptionHandler.ConsumeException(ex); } } while (!form.IsDisposed); } ``` What I'm wondering though, **is this a safe/decent way to replace the more typical 'Application.Run(new MainForm());'**, whether it's used for exception handling or for whatever else, or should I always stick to using Application.Run? On another app that's in testing now a similar approach is used for both loading (splashscreen) and exception handling, and I don't think it has caused any troubles (yet :-))
Pitfall 1: ``` Thread.Sleep(100); ``` Never. Use WaitMessage(). Otherwise, it is possible roll out your own message loop, but in your scenario it seems somewhat pointless. You may also want to examine Application.Run() code (with .Net Reflector, for instance).
61,405
<p>I'm about to start on a large Qt application, which is made up of smaller components (groups of classes that work together). For example, there might be a dialog that is used in the project, but should be developed on its own before being integrated into the project. Instead of working on it in another folder somewhere and then copying it into the main project folder, can I create a sub-folder which is dedicated to that dialog, and then somehow incorporate it into the main project?</p>
[ { "answer_id": 61423, "author": "kokos", "author_id": 1065, "author_profile": "https://Stackoverflow.com/users/1065", "pm_score": 0, "selected": false, "text": "<p>For Qt on Windows you can create DLLs for every subproject you want. No problem with using them from the main project (exe) after that. You'll have to take care of dependencies but it's not very difficult.</p>\n" }, { "answer_id": 61427, "author": "Nick", "author_id": 4949, "author_profile": "https://Stackoverflow.com/users/4949", "pm_score": 1, "selected": false, "text": "<p>Yes, you can edit your main project (.pro) file to include your sub project's project file.</p>\n\n<p><a href=\"http://doc.qt.io/qt-4.8/qmake-project-files.html\" rel=\"nofollow noreferrer\">See here</a></p>\n" }, { "answer_id": 62009, "author": "Jérôme", "author_id": 2796, "author_profile": "https://Stackoverflow.com/users/2796", "pm_score": 6, "selected": true, "text": "<p>Here is what I would do. Let's say I want the following folder hierarchy :</p>\n\n<pre><code>/MyWholeApp\n</code></pre>\n\n<p>will contain the files for the whole application.</p>\n\n<pre><code>/MyWholeApp/DummyDlg/\n</code></pre>\n\n<p>will contain the files for the standalone dialogbox which will be eventually part of the whole application.</p>\n\n<p>I would develop the standalone dialog box and the related classes. I would create a Qt-project file which is going to be included. It will contain only the forms and files which will eventually be part of the whole application.</p>\n\n<p>File DummyDlg.pri, in /MyWholeApp/DummyDlg/ :</p>\n\n<pre><code># Input\nFORMS += dummydlg.ui\nHEADERS += dummydlg.h\nSOURCES += dummydlg.cpp\n</code></pre>\n\n<p>The above example is very simple. You could add other classes if needed.</p>\n\n<p>To develop the standalone dialog box, I would then create a Qt project file dedicated to this dialog :</p>\n\n<p>File DummyDlg.pro, in /MyWholeApp/DummyDlg/ :</p>\n\n<pre><code>TEMPLATE = app\nDEPENDPATH += .\nINCLUDEPATH += .\n\ninclude(DummyDlg.pri)\n\n# Input\nSOURCES += main.cpp\n</code></pre>\n\n<p>As you can see, this PRO file is including the PRI file created above, and is adding an additional file (main.cpp) which will contain the basic code for running the dialog box as a standalone :</p>\n\n<pre><code>#include &lt;QApplication&gt;\n#include \"dummydlg.h\"\n\nint main(int argc, char* argv[])\n{\n QApplication MyApp(argc, argv);\n\n DummyDlg MyDlg;\n MyDlg.show();\n return MyApp.exec();\n}\n</code></pre>\n\n<p>Then, to include this dialog box to the whole application you need to create a Qt-Project file :</p>\n\n<p>file WholeApp.pro, in /MyWholeApp/ :</p>\n\n<pre><code>TEMPLATE = app\nDEPENDPATH += . DummyDlg\nINCLUDEPATH += . DummyDlg\n\ninclude(DummyDlg/DummyDlg.pri)\n\n# Input\nFORMS += OtherDlg.ui\nHEADERS += OtherDlg.h\nSOURCES += OtherDlg.cpp WholeApp.cpp\n</code></pre>\n\n<p>Of course, the Qt-Project file above is very simplistic, but shows how I included the stand-alone dialog box.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ]
I'm about to start on a large Qt application, which is made up of smaller components (groups of classes that work together). For example, there might be a dialog that is used in the project, but should be developed on its own before being integrated into the project. Instead of working on it in another folder somewhere and then copying it into the main project folder, can I create a sub-folder which is dedicated to that dialog, and then somehow incorporate it into the main project?
Here is what I would do. Let's say I want the following folder hierarchy : ``` /MyWholeApp ``` will contain the files for the whole application. ``` /MyWholeApp/DummyDlg/ ``` will contain the files for the standalone dialogbox which will be eventually part of the whole application. I would develop the standalone dialog box and the related classes. I would create a Qt-project file which is going to be included. It will contain only the forms and files which will eventually be part of the whole application. File DummyDlg.pri, in /MyWholeApp/DummyDlg/ : ``` # Input FORMS += dummydlg.ui HEADERS += dummydlg.h SOURCES += dummydlg.cpp ``` The above example is very simple. You could add other classes if needed. To develop the standalone dialog box, I would then create a Qt project file dedicated to this dialog : File DummyDlg.pro, in /MyWholeApp/DummyDlg/ : ``` TEMPLATE = app DEPENDPATH += . INCLUDEPATH += . include(DummyDlg.pri) # Input SOURCES += main.cpp ``` As you can see, this PRO file is including the PRI file created above, and is adding an additional file (main.cpp) which will contain the basic code for running the dialog box as a standalone : ``` #include <QApplication> #include "dummydlg.h" int main(int argc, char* argv[]) { QApplication MyApp(argc, argv); DummyDlg MyDlg; MyDlg.show(); return MyApp.exec(); } ``` Then, to include this dialog box to the whole application you need to create a Qt-Project file : file WholeApp.pro, in /MyWholeApp/ : ``` TEMPLATE = app DEPENDPATH += . DummyDlg INCLUDEPATH += . DummyDlg include(DummyDlg/DummyDlg.pri) # Input FORMS += OtherDlg.ui HEADERS += OtherDlg.h SOURCES += OtherDlg.cpp WholeApp.cpp ``` Of course, the Qt-Project file above is very simplistic, but shows how I included the stand-alone dialog box.
61,418
<p>I have a function that gives me the following warning:</p> <blockquote> <p>[DCC Warning] filename.pas(6939): W1035 Return value of function 'function' might be undefined</p> </blockquote> <p>The function, however, is clean, small, and does have a known, expected, return value. The first statement in the function is:</p> <pre><code>Result := ''; </code></pre> <p>and there is no local variable or parameter called <code>Result</code> either.</p> <p>Is there any kind of pragma-like directive I can surround this method with to remove this warning? This is Delphi 2007.</p> <p>Unfortunately, the help system on this Delphi installation is not working, therefore i can't pop up the help for that warning right now.</p> <p>Anyone know off the top of their head what i can do?</p>
[ { "answer_id": 61424, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 1, "selected": false, "text": "<p>There seems to be some sort of bug in Delphi. Read this post, the last comment links to other bug-reports that may be the one that you have got:</p>\n\n<p><a href=\"http://qc.codegear.com/wc/qcmain.aspx?d=8144\" rel=\"nofollow noreferrer\">http://qc.codegear.com/wc/qcmain.aspx?d=8144</a></p>\n" }, { "answer_id": 61426, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 4, "selected": true, "text": "<p>Are you sure you have done everything to solve the warning? Maybe you could post the code for us to look at?</p>\n\n<p>You can turn off the warning locally this way:</p>\n\n<pre><code>{$WARN NO_RETVAL OFF}\nfunction func(...): string;\nbegin\n ...\nend;\n{$WARN NO_RETVAL ON}\n</code></pre>\n" }, { "answer_id": 61814, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 1, "selected": false, "text": "<p>The {$WARN NO_RETVAL OFF} is what you are looking for, but generally I like to find out why stuff like this happens. You might consider formatting it differently and seeing if that helps. </p>\n\n<p>Do you have any flow altering commands like Exit in there? Do you directly raise exceptions, etc? Does your case statement have an else at the end that sets a value on Result? </p>\n\n<p>Might try tweaking those elements and see if that eliminates the warning too. </p>\n" }, { "answer_id": 66982, "author": "Nick Hodges", "author_id": 2044, "author_profile": "https://Stackoverflow.com/users/2044", "pm_score": 1, "selected": false, "text": "<p>In order to get a good answer for this, you'll have to post the code. In general, the Delphi compiler will give this warning if there is a possible code path that could result in the Result not being defined. Sometimes that code path is less than obvious.</p>\n" }, { "answer_id": 69778, "author": "Lars Fosdal", "author_id": 10002, "author_profile": "https://Stackoverflow.com/users/10002", "pm_score": 2, "selected": false, "text": "<p>I am not sure that I want to see the code for this unit... after all, the error occurs at line 6939 ... Maybe some internal compiler table have been exceeded?</p>\n" }, { "answer_id": 2906623, "author": "Abelevich", "author_id": 11391, "author_profile": "https://Stackoverflow.com/users/11391", "pm_score": 1, "selected": false, "text": "<p>There is such a bug in Delphi compiler since, at least, Delphi4: if sum of numbers of function's parameters (including Self and Result) and local variables exceeds 31, it causes problems. For example, it can write W1035 warnings (result might be undefined). It can miss not used variables. Just try this project:</p>\n\n<pre><code>program TestCompilerProblems;\n\nprocedure Proc;\nvar\n a01, a02, a03, a04, a05, a06, a07, a08, a09, a10,\n a11, a12, a13, a14, a15, a16, a17, a18, a19, a20,\n a21, a22, a23, a24, a25, a26, a27, a28, a29, a30,\n a31, a32, a33, a34, a35, a36, a37, a38, a39, a40: Integer;\nbegin\nend;\n\nbegin\n Proc;\nend.\n</code></pre>\n\n<p>It would cause 31 hint, not 40.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
I have a function that gives me the following warning: > > [DCC Warning] filename.pas(6939): W1035 Return value of function 'function' might be undefined > > > The function, however, is clean, small, and does have a known, expected, return value. The first statement in the function is: ``` Result := ''; ``` and there is no local variable or parameter called `Result` either. Is there any kind of pragma-like directive I can surround this method with to remove this warning? This is Delphi 2007. Unfortunately, the help system on this Delphi installation is not working, therefore i can't pop up the help for that warning right now. Anyone know off the top of their head what i can do?
Are you sure you have done everything to solve the warning? Maybe you could post the code for us to look at? You can turn off the warning locally this way: ``` {$WARN NO_RETVAL OFF} function func(...): string; begin ... end; {$WARN NO_RETVAL ON} ```
61,421
<p>I'm making an example for someone who hasn't yet realized that controls like <code>ListBox</code> don't have to contain strings; he had been storing formatted strings and jumping through complicated parsing hoops to get the data back out of the <code>ListBox</code> and I'd like to show him there's a better way.</p> <p>I noticed that if I have an object stored in the <code>ListBox</code> then update a value that affects <code>ToString</code>, the <code>ListBox</code> does not update itself. I've tried calling <code>Refresh</code> and <code>Update</code> on the control, but neither works. Here's the code of the example I'm using, it requires you to drag a listbox and a button onto the form:</p> <pre><code>Public Class Form1 Protected Overrides Sub OnLoad(ByVal e As System.EventArgs) MyBase.OnLoad(e) For i As Integer = 1 To 3 Dim tempInfo As New NumberInfo() tempInfo.Count = i tempInfo.Number = i * 100 ListBox1.Items.Add(tempInfo) Next End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click For Each objItem As Object In ListBox1.Items Dim info As NumberInfo = DirectCast(objItem, NumberInfo) info.Count += 1 Next End Sub End Class Public Class NumberInfo Public Count As Integer Public Number As Integer Public Overrides Function ToString() As String Return String.Format("{0}, {1}", Count, Number) End Function End Class</code></pre> <p>I thought that perhaps the problem was using fields and tried implementing <em>INotifyPropertyChanged</em>, but this had no effect. (The reason I'm using fields is because it's an example and I don't feel like adding a few dozen lines that have nothing to do with the topic I'm demonstrating.)</p> <p>Honestly I've never tried updating items in place like this before; in the past I've always been adding/removing items, not editing them. So I've never noticed that I don't know how to make this work.</p> <p>So what am I missing?</p>
[ { "answer_id": 61425, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 3, "selected": false, "text": "<p>Use the datasource property and a BindingSource object in between the datasource and the datasource property of the listbox. Then refresh that.</p>\n\n<p><strong>update</strong> added example.</p>\n\n<p>Like so:</p>\n\n<pre><code>Public Class Form1\n\n Private datasource As New List(Of NumberInfo)\n Private bindingSource As New BindingSource\n\n Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)\n MyBase.OnLoad(e)\n\n For i As Integer = 1 To 3\n Dim tempInfo As New NumberInfo()\n tempInfo.Count = i\n tempInfo.Number = i * 100\n datasource.Add(tempInfo)\n Next\n bindingSource.DataSource = datasource\n ListBox1.DataSource = bindingSource\n End Sub\n\n Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n For Each objItem As Object In datasource\n Dim info As NumberInfo = DirectCast(objItem, NumberInfo)\n info.Count += 1\n Next\n bindingSource.ResetBindings(False)\n End Sub\nEnd Class\n\nPublic Class NumberInfo\n\n Public Count As Integer\n Public Number As Integer\n\n Public Overrides Function ToString() As String\n Return String.Format(\"{0}, {1}\", Count, Number)\n End Function\nEnd Class\n</code></pre>\n" }, { "answer_id": 61463, "author": "zeemz", "author_id": 6351, "author_profile": "https://Stackoverflow.com/users/6351", "pm_score": -1, "selected": false, "text": "<p>I don't know much about vb.net but in C# you should use datasource and then bind it by calling <code>listbox.bind()</code> would do the trick.</p>\n" }, { "answer_id": 61711, "author": "Ant", "author_id": 3709, "author_profile": "https://Stackoverflow.com/users/3709", "pm_score": 2, "selected": false, "text": "<p>If you derive from ListBox there is the RefreshItem protected method you can call. Just re-expose this method in your own type.</p>\n\n<pre><code>public class ListBox2 : ListBox {\n public void RefreshItem2(int index) {\n RefreshItem(index);\n }\n}\n</code></pre>\n\n<p>Then change your designer file to use your own type (in this case, ListBox2).</p>\n" }, { "answer_id": 61719, "author": "Brad Bruce", "author_id": 5008, "author_profile": "https://Stackoverflow.com/users/5008", "pm_score": 5, "selected": false, "text": "<p>I use this class when I need to have a list box that updates.</p>\n\n<p>Update the object in the list and then call either of the included methods, depending on if you have the index available or not. If you are updating an object that is contained in the list, but you don't have the index, you will have to call RefreshItems and update all of the items.</p>\n\n<pre><code>public class RefreshingListBox : ListBox\n{\n public new void RefreshItem(int index)\n {\n base.RefreshItem(index);\n }\n\n public new void RefreshItems()\n {\n base.RefreshItems();\n }\n}\n</code></pre>\n" }, { "answer_id": 930356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It's little bit unprofessional, but it works.\nI just removed and added the item (also selected it again).\nThe list was sorted according to \"displayed and changed\" property so, again, was fine for me. The side effect is that additional event (index changed) is raised.</p>\n\n<pre><code>if (objLstTypes.SelectedItem != null)\n{\n PublisherTypeDescriptor objType = (PublisherTypeDescriptor)objLstTypes.SelectedItem;\n objLstTypes.Items.Remove(objType);\n objLstTypes.Items.Add(objType);\n objLstTypes.SelectedItem = objType;\n}\n</code></pre>\n" }, { "answer_id": 993644, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>If objLstTypes is your ListBox name\nUse\nobjLstTypes.Items.Refresh();\nHope this works...</p>\n" }, { "answer_id": 2135255, "author": "geno", "author_id": 258739, "author_profile": "https://Stackoverflow.com/users/258739", "pm_score": 6, "selected": true, "text": "<p>BindingList handles updating the bindings by itself.</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace TestBindingList\n{\n public class Employee\n {\n public string Name { get; set; }\n public int Id { get; set; }\n }\n\n public partial class Form1 : Form\n {\n private BindingList&lt;Employee&gt; _employees;\n\n private ListBox lstEmployees;\n private TextBox txtId;\n private TextBox txtName;\n private Button btnRemove;\n\n public Form1()\n {\n InitializeComponent();\n\n FlowLayoutPanel layout = new FlowLayoutPanel();\n layout.Dock = DockStyle.Fill;\n Controls.Add(layout);\n\n lstEmployees = new ListBox();\n layout.Controls.Add(lstEmployees);\n\n txtId = new TextBox();\n layout.Controls.Add(txtId);\n\n txtName = new TextBox();\n layout.Controls.Add(txtName);\n\n btnRemove = new Button();\n btnRemove.Click += btnRemove_Click;\n btnRemove.Text = \"Remove\";\n layout.Controls.Add(btnRemove);\n\n Load+=new EventHandler(Form1_Load);\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n _employees = new BindingList&lt;Employee&gt;();\n for (int i = 0; i &lt; 10; i++)\n {\n _employees.Add(new Employee() { Id = i, Name = \"Employee \" + i.ToString() }); \n }\n\n lstEmployees.DisplayMember = \"Name\";\n lstEmployees.DataSource = _employees;\n\n txtId.DataBindings.Add(\"Text\", _employees, \"Id\");\n txtName.DataBindings.Add(\"Text\", _employees, \"Name\");\n }\n\n private void btnRemove_Click(object sender, EventArgs e)\n {\n Employee selectedEmployee = (Employee)lstEmployees.SelectedItem;\n if (selectedEmployee != null)\n {\n _employees.Remove(selectedEmployee);\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 4285934, "author": "Elton M", "author_id": 521450, "author_profile": "https://Stackoverflow.com/users/521450", "pm_score": 5, "selected": false, "text": "<pre><code>lstBox.Items[lstBox.SelectedIndex] = lstBox.SelectedItem;\n</code></pre>\n" }, { "answer_id": 4631419, "author": "Jon", "author_id": 567625, "author_profile": "https://Stackoverflow.com/users/567625", "pm_score": 4, "selected": false, "text": "<pre><code>typeof(ListBox).InvokeMember(\"RefreshItems\", \n BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod,\n null, myListBox, new object[] { });\n</code></pre>\n" }, { "answer_id": 29008084, "author": "JTIM", "author_id": 2076775, "author_profile": "https://Stackoverflow.com/users/2076775", "pm_score": 0, "selected": false, "text": "<p>If you use a draw method like:</p>\n\n<pre><code>private void listBox1_DrawItem(object sender, DrawItemEventArgs e)\n{\n e.DrawBackground();\n e.DrawFocusRectangle();\n\n Sensor toBeDrawn = (listBox1.Items[e.Index] as Sensor);\n e.Graphics.FillRectangle(new SolidBrush(toBeDrawn.ItemColor), e.Bounds);\n e.Graphics.DrawString(toBeDrawn.sensorName, new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold), new SolidBrush(Color.White),e.Bounds);\n}\n</code></pre>\n\n<p>Sensor is my class.</p>\n\n<p>So if I change the class <code>Color</code> somewhere, you can simply update it as:</p>\n\n<pre><code>int temp = listBoxName.SelectedIndex;\nlistBoxName.SelectedIndex = -1;\nlistBoxName.SelectedIndex = temp;\n</code></pre>\n\n<p>And the <code>Color</code> will update, just another solution :)</p>\n" }, { "answer_id": 71672910, "author": "Daniel Lidström", "author_id": 286406, "author_profile": "https://Stackoverflow.com/users/286406", "pm_score": 0, "selected": false, "text": "<p>If you are doing databinding, try this:</p>\n<pre><code>private void CheckBox_Click(object sender, EventArgs e)\n{\n // some kind of hack to make the ListBox refresh\n int currentPosition = bindingSource.Position;\n bindingSource.Position += 1;\n bindingSource.Position -= 1;\n bindingSource.Position = currentPosition;\n}\n</code></pre>\n<p>In this case there is a checkbox that updates an item in a data bound ListBox. Toggling the position of the binding source back and forth seems to work for me.</p>\n" }, { "answer_id": 71919054, "author": "John G", "author_id": 12492467, "author_profile": "https://Stackoverflow.com/users/12492467", "pm_score": 0, "selected": false, "text": "<p>Some code that I built some code in VBnet to help do this. The class for anObject has the ToString override to show the object's &quot;title/name&quot;.</p>\n<pre><code>Dim i = LstBox.SelectedIndex\nLstBox.Items(i) = anObject\nLstBox.Sorted = True\n</code></pre>\n" }, { "answer_id": 72072608, "author": "purple_2022", "author_id": 13008103, "author_profile": "https://Stackoverflow.com/users/13008103", "pm_score": 0, "selected": false, "text": "<p>you also can try with this fragment of code, it works fine:</p>\n<pre><code>Public Class Form1\n\nDim tempInfo As New NumberInfo()\n\nPrivate Sub Form1_Load() Handles Me.Load\n For i As Integer = 1 To 3\n tempInfo.Count = i\n tempInfo.Number = i * 100\n ListBox1.Items.Add(tempInfo)\n Next\nEnd Sub\n\nPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n Dim info As NumberInfo = tempInfo\n Dim obj As New Object\n info.Count += 1\n info.Number = info.Count * 100\n obj = info\n ListBox1.Items.Add(obj)\n ListBox1.Items.RemoveAt(0)\nEnd Sub\nEnd Class\n\nPublic Class NumberInfo\nPublic Count As Integer\nPublic Number As Integer\n Public Overrides Function ToString() As String\n Return String.Format(&quot;{0}, {1}&quot;, Count, Number)\n End Function\nEnd Class\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2547/" ]
I'm making an example for someone who hasn't yet realized that controls like `ListBox` don't have to contain strings; he had been storing formatted strings and jumping through complicated parsing hoops to get the data back out of the `ListBox` and I'd like to show him there's a better way. I noticed that if I have an object stored in the `ListBox` then update a value that affects `ToString`, the `ListBox` does not update itself. I've tried calling `Refresh` and `Update` on the control, but neither works. Here's the code of the example I'm using, it requires you to drag a listbox and a button onto the form: ``` Public Class Form1 Protected Overrides Sub OnLoad(ByVal e As System.EventArgs) MyBase.OnLoad(e) For i As Integer = 1 To 3 Dim tempInfo As New NumberInfo() tempInfo.Count = i tempInfo.Number = i * 100 ListBox1.Items.Add(tempInfo) Next End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click For Each objItem As Object In ListBox1.Items Dim info As NumberInfo = DirectCast(objItem, NumberInfo) info.Count += 1 Next End Sub End Class Public Class NumberInfo Public Count As Integer Public Number As Integer Public Overrides Function ToString() As String Return String.Format("{0}, {1}", Count, Number) End Function End Class ``` I thought that perhaps the problem was using fields and tried implementing *INotifyPropertyChanged*, but this had no effect. (The reason I'm using fields is because it's an example and I don't feel like adding a few dozen lines that have nothing to do with the topic I'm demonstrating.) Honestly I've never tried updating items in place like this before; in the past I've always been adding/removing items, not editing them. So I've never noticed that I don't know how to make this work. So what am I missing?
BindingList handles updating the bindings by itself. ``` using System; using System.ComponentModel; using System.Windows.Forms; namespace TestBindingList { public class Employee { public string Name { get; set; } public int Id { get; set; } } public partial class Form1 : Form { private BindingList<Employee> _employees; private ListBox lstEmployees; private TextBox txtId; private TextBox txtName; private Button btnRemove; public Form1() { InitializeComponent(); FlowLayoutPanel layout = new FlowLayoutPanel(); layout.Dock = DockStyle.Fill; Controls.Add(layout); lstEmployees = new ListBox(); layout.Controls.Add(lstEmployees); txtId = new TextBox(); layout.Controls.Add(txtId); txtName = new TextBox(); layout.Controls.Add(txtName); btnRemove = new Button(); btnRemove.Click += btnRemove_Click; btnRemove.Text = "Remove"; layout.Controls.Add(btnRemove); Load+=new EventHandler(Form1_Load); } private void Form1_Load(object sender, EventArgs e) { _employees = new BindingList<Employee>(); for (int i = 0; i < 10; i++) { _employees.Add(new Employee() { Id = i, Name = "Employee " + i.ToString() }); } lstEmployees.DisplayMember = "Name"; lstEmployees.DataSource = _employees; txtId.DataBindings.Add("Text", _employees, "Id"); txtName.DataBindings.Add("Text", _employees, "Name"); } private void btnRemove_Click(object sender, EventArgs e) { Employee selectedEmployee = (Employee)lstEmployees.SelectedItem; if (selectedEmployee != null) { _employees.Remove(selectedEmployee); } } } } ```
61,443
<p>I have a counter in hardware that I can observe for timing considerations. It counts miliseconds and is stored in a 16 bit unsigned value. How do I safely check if a timer value has passed a certain time and safely handle the inevitable rollover:</p> <pre><code>//this is a bit contrived, but it illustrates what I'm trying to do const uint16_t print_interval = 5000; // milliseconds static uint16_t last_print_time; if(ms_timer() - last_print_time &gt; print_interval) { printf("Fault!\n"); last_print_time = ms_timer(); } </code></pre> <p>This code will fail when ms_timer overflows to 0.</p>
[ { "answer_id": 61444, "author": "Jason Punyon", "author_id": 6212, "author_profile": "https://Stackoverflow.com/users/6212", "pm_score": 1, "selected": false, "text": "<p>Just check if ms_timer &lt; last_print_time and if so add 2^16 no?</p>\n\n<p>Edit: You also need to up to an uint32 for this if you can.</p>\n" }, { "answer_id": 61461, "author": "ReaperUnreal", "author_id": 4218, "author_profile": "https://Stackoverflow.com/users/4218", "pm_score": 1, "selected": false, "text": "<p>Probably the safest way to avoid the problem would be to use a signed 32-bit value. To use your example:</p>\n\n<pre><code>const int32 print_interval = 5000;\nstatic int32 last_print_time; // I'm assuming this gets initialized elsewhere\n\nint32 delta = ((int32)ms_timer()) - last_print_time; //allow a negative interval\nwhile(delta &lt; 0) delta += 65536; // move the difference back into range\nif(delta &lt; print_interval)\n{\n printf(\"Fault!\\n\");\n last_print_time = ms_timer();\n}\n</code></pre>\n" }, { "answer_id": 61466, "author": "JeffV", "author_id": 445087, "author_profile": "https://Stackoverflow.com/users/445087", "pm_score": 1, "selected": false, "text": "<p>This seems to work for intervals up to 64k/2, which is suitable for me:</p>\n\n<pre><code>const uint16_t print_interval = 5000; // milliseconds\nstatic uint16_t last_print_time; \n\nint next_print_time = (last_print_time + print_interval);\n\nif((int16_t) (x - next_print_time) &gt;= 0)\n{\n printf(\"Fault!\\n\");\n last_print_time = x;\n}\n</code></pre>\n\n<p>Makes use of nature of signed integers. (<a href=\"http://en.wikipedia.org/wiki/Twos_complement\" rel=\"nofollow noreferrer\">twos complement</a>)</p>\n" }, { "answer_id": 61572, "author": "smh", "author_id": 1077, "author_profile": "https://Stackoverflow.com/users/1077", "pm_score": 4, "selected": false, "text": "<p>You don't actually need to do anything here. The original code listed in your question will work fine, assuming <code>ms_timer()</code> returns a value of type uint16_t.</p>\n\n<p>(Also assuming that the timer doesn't overflow twice between checks...) </p>\n\n<p>To convince yourself this is the case, try the following test:</p>\n\n<pre><code>uint16_t t1 = 0xFFF0;\nuint16_t t2 = 0x0010;\nuint16_t dt = t2 - t1;\n</code></pre>\n\n<p><code>dt</code> will equal <code>0x20</code>.</p>\n" }, { "answer_id": 164182, "author": "Steve Karg", "author_id": 9016, "author_profile": "https://Stackoverflow.com/users/9016", "pm_score": 0, "selected": false, "text": "<p>I found that using a different timer API works better for me. I created a timer module that has two API calls:</p>\n\n<pre><code>void timer_milliseconds_reset(unsigned index);\nbool timer_milliseconds_elapsed(unsigned index, unsigned long value);\n</code></pre>\n\n<p>The timer indices are also defined in the timer header file:</p>\n\n<pre><code>#define TIMER_PRINT 0\n#define TIMER_LED 1\n#define MAX_MILLISECOND_TIMERS 2\n</code></pre>\n\n<p>I use unsigned long int for my timer counters (32-bit) since that is the native sized integer on my hardware platform, and that gives me elapsed times from 1 ms to about 49.7 days. You could have timer counters that are 16-bit which would give you elapsed times from 1 ms to about 65 seconds.</p>\n\n<p>The timer counters are an array, and are incremented by the hardware timer (interrupt, task, or polling of counter value). They can be limited to the maximum value of the datatype in the function that handles the increment for a no-rollover timer.</p>\n\n<pre><code>/* variable counts interrupts */\nstatic volatile unsigned long Millisecond_Counter[MAX_MILLISECOND_TIMERS];\nbool timer_milliseconds_elapsed(\n unsigned index,\n unsigned long value)\n{\n if (index &lt; MAX_MILLISECOND_TIMERS) {\n return (Millisecond_Counter[index] &gt;= value);\n }\n return false;\n}\n\nvoid timer_milliseconds_reset(\n unsigned index)\n{\n if (index &lt; MAX_MILLISECOND_TIMERS) {\n Millisecond_Counter[index] = 0;\n }\n}\n</code></pre>\n\n<p>Then your code becomes:</p>\n\n<pre><code>//this is a bit contrived, but it illustrates what I'm trying to do\nconst uint16_t print_interval = 5000; // milliseconds\n\nif (timer_milliseconds_elapsed(TIMER_PRINT, print_interval)) \n{\n printf(\"Fault!\\n\");\n timer_milliseconds_reset(TIMER_PRINT);\n}\n</code></pre>\n" }, { "answer_id": 2976575, "author": "bobc", "author_id": 358705, "author_profile": "https://Stackoverflow.com/users/358705", "pm_score": 2, "selected": false, "text": "<p>I use this code to illustrate the bug and possible solution using a signed comparison.</p>\n\n<pre><code>/* ========================================================================== */\n/* timers.c */\n/* */\n/* Description: Demonstrate unsigned vs signed timers */\n/* ========================================================================== */\n\n#include &lt;stdio.h&gt;\n#include &lt;limits.h&gt;\n\nint timer;\n\nint HW_DIGCTL_MICROSECONDS_RD()\n{\n printf (\"timer %x\\n\", timer);\n return timer++;\n}\n\n// delay up to UINT_MAX\n// this fails when start near UINT_MAX\nvoid delay_us (unsigned int us)\n{\n unsigned int start = HW_DIGCTL_MICROSECONDS_RD();\n\n while (start + us &gt; HW_DIGCTL_MICROSECONDS_RD()) \n ;\n}\n\n// works correctly for delay from 0 to INT_MAX\nvoid sdelay_us (int us)\n{\n int start = HW_DIGCTL_MICROSECONDS_RD();\n\n while (HW_DIGCTL_MICROSECONDS_RD() - start &lt; us) \n ;\n}\n\nint main()\n{\n printf (\"UINT_MAX = %x\\n\", UINT_MAX);\n printf (\"INT_MAX = %x\\n\\n\", INT_MAX);\n\n printf (\"unsigned, no wrap\\n\\n\");\n timer = 0;\n delay_us (10);\n\n printf (\"\\nunsigned, wrap\\n\\n\");\n timer = UINT_MAX - 8;\n delay_us (10);\n\n printf (\"\\nsigned, no wrap\\n\\n\");\n timer = 0;\n sdelay_us (10);\n\n printf (\"\\nsigned, wrap\\n\\n\");\n timer = INT_MAX - 8;\n sdelay_us (10);\n\n}\n</code></pre>\n\n<p>Sample output:</p>\n\n<pre><code>bob@hedgehog:~/work2/test$ ./timers|more\nUINT_MAX = ffffffff\nINT_MAX = 7fffffff\n\nunsigned, no wrap\n\ntimer 0\ntimer 1\ntimer 2\ntimer 3\ntimer 4\ntimer 5\ntimer 6\ntimer 7\ntimer 8\ntimer 9\ntimer a\n\nunsigned, wrap\n\ntimer fffffff7\ntimer fffffff8\n\nsigned, no wrap\n\ntimer 0\ntimer 1\ntimer 2\ntimer 3\ntimer 4\ntimer 5\ntimer 6\ntimer 7\ntimer 8\ntimer 9\ntimer a\n\nsigned, wrap\n\ntimer 7ffffff7\ntimer 7ffffff8\ntimer 7ffffff9\ntimer 7ffffffa\ntimer 7ffffffb\ntimer 7ffffffc\ntimer 7ffffffd\ntimer 7ffffffe\ntimer 7fffffff\ntimer 80000000\ntimer 80000001\nbob@hedgehog:~/work2/test$ \n</code></pre>\n" }, { "answer_id": 11911902, "author": "Jeff", "author_id": 877375, "author_profile": "https://Stackoverflow.com/users/877375", "pm_score": -1, "selected": false, "text": "<p>Sometimes I do it like this:</p>\n\n<pre><code>#define LIMIT 10 // Any value less then ULONG_MAX\nulong t1 = tick of last event;\nulong t2 = current tick;\n\n// This code needs to execute every tick\nif ( t1 &gt; t2 ){\n if ((ULONG_MAX-t1+t2+1)&gt;=LIMIT){\n do something\n }\n} else {\nif ( t2 - t1 &gt;= LIMT ){\n do something\n}\n</code></pre>\n" }, { "answer_id": 45852411, "author": "Hill", "author_id": 3239341, "author_profile": "https://Stackoverflow.com/users/3239341", "pm_score": 2, "selected": false, "text": "<p>I used to write code like following for the such case.<br>\nI tested with test case and assure that it works 100%.<br>\nIn addition, change to <code>uint32_t</code> from <code>uint16_t</code> and <code>0xFFFFFFFF</code> from <code>0xFFFF</code> in below code with 32 bits timer tick.</p>\n\n\n\n<pre><code>uint16_t get_diff_tick(uint16_t test_tick, uint16_t prev_tick)\n{\n if (test_tick &lt; prev_tick)\n {\n // time rollover(overflow)\n return (0xFFFF - prev_tick) + 1 + test_tick;\n }\n else\n {\n return test_tick - prev_tick;\n }\n}\n\n/* your code will be.. */\nuint16_t cur_tick = ms_timer();\nif(get_diff_tick(cur_tick, last_print_time) &gt; print_interval)\n{\n printf(\"Fault!\\n\");\n last_print_time = cur_tick;\n}\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
I have a counter in hardware that I can observe for timing considerations. It counts miliseconds and is stored in a 16 bit unsigned value. How do I safely check if a timer value has passed a certain time and safely handle the inevitable rollover: ``` //this is a bit contrived, but it illustrates what I'm trying to do const uint16_t print_interval = 5000; // milliseconds static uint16_t last_print_time; if(ms_timer() - last_print_time > print_interval) { printf("Fault!\n"); last_print_time = ms_timer(); } ``` This code will fail when ms\_timer overflows to 0.
You don't actually need to do anything here. The original code listed in your question will work fine, assuming `ms_timer()` returns a value of type uint16\_t. (Also assuming that the timer doesn't overflow twice between checks...) To convince yourself this is the case, try the following test: ``` uint16_t t1 = 0xFFF0; uint16_t t2 = 0x0010; uint16_t dt = t2 - t1; ``` `dt` will equal `0x20`.
61,446
<p>Particularly, what is the best snippets package out there?</p> <p>Features:</p> <ul> <li>easy to define new snippets (plain text, custom input with defaults)</li> <li>simple navigation between predefined positions in the snippet</li> <li>multiple insertion of the same custom input</li> <li>accepts currently selected text as a custom input</li> <li><em>cross-platform</em> (Windows, Linux)</li> <li>dynamically evaluated expressions (embedded code) written in a concise programming language (Perl, Python, Ruby are preferred)</li> <li>nicely coexists with others packages in Emacs</li> </ul> <p>Example of code template, a simple <code>for</code> loop in C:</p> <pre><code>for (int i = 0; i &lt; %N%; ++i) { _ } </code></pre> <p>It is a lot of typing for such common code. I want to invoke a code template or snippet which inserts that boilerplate code for me. Additionally it stops (on TAB or other keystroke) at <code>%N%</code> (my input replaces it) and final position of the cursor is <code>_</code>. </p>
[ { "answer_id": 61447, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 6, "selected": true, "text": "<p><a href=\"http://manual.macromates.com/en/snippets\" rel=\"nofollow noreferrer\">TextMate's snippets</a> is the most closest match but it is not a cross-platform solution and not for Emacs.</p>\n<p>The second closest thing is <a href=\"http://github.com/joaotavora/yasnippet/\" rel=\"nofollow noreferrer\" title=\"Yet Another Snippet Package for Emacs\">YASnippet</a> (<a href=\"http://www.youtube.com/watch?v=vOj7btx3ATg\" rel=\"nofollow noreferrer\" title=\"yasnippet screencast\">screencast</a> shows the main capabilities). But it interferes with <code>hippie-expand</code> package in my setup and the embedded language is EmacsLisp which I'm not comfortable with outside <code>.emacs</code>.</p>\n<p><strong>EDIT</strong>: Posted my answer here to allow voting on <code>YASnippet</code>.</p>\n" }, { "answer_id": 64249, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 3, "selected": false, "text": "<p>Personally, I've been using Dmacro for years (<a href=\"ftp://ftp.sgi.com/other/dmacro/dmacro.tar.gz\" rel=\"noreferrer\">ftp://ftp.sgi.com/other/dmacro/dmacro.tar.gz</a>).</p>\n\n<p>Here's a review of it that also mentions some alternatives: <a href=\"http://linuxgazette.net/issue39/marsden.html\" rel=\"noreferrer\">http://linuxgazette.net/issue39/marsden.html</a></p>\n" }, { "answer_id": 69580, "author": "Joe Hildebrand", "author_id": 8388, "author_profile": "https://Stackoverflow.com/users/8388", "pm_score": 2, "selected": false, "text": "<p>The EmacsWiki has a <a href=\"http://www.emacswiki.org/cgi-bin/wiki/CategoryTemplates\" rel=\"nofollow noreferrer\">page of template engines</a>.</p>\n\n<p>Of these, I've used <a href=\"http://www.emacswiki.org/cgi-bin/wiki/TempoMode\" rel=\"nofollow noreferrer\">tempo</a> in the (distant) past to add table support to <a href=\"http://www.nongnu.org/baol-hth/\" rel=\"nofollow noreferrer\">html-helper-mode</a>, but don't know how it has progressed in the last 15 years.</p>\n" }, { "answer_id": 732258, "author": "l0st3d", "author_id": 5100, "author_profile": "https://Stackoverflow.com/users/5100", "pm_score": 2, "selected": false, "text": "<p>I'd add my vote for <a href=\"http://www.emacswiki.org/emacs/TempoSnippets\" rel=\"nofollow noreferrer\">tempo snippets</a> ... easy to setup, powerful (you can run arbitrary elisp in your template - so that you can downcase things, lookup filenames &amp; classes, count things, etc), set the indentation, integrate with abbrevs ... I use it a lot ;)</p>\n" }, { "answer_id": 18829042, "author": "gavenkoa", "author_id": 173149, "author_profile": "https://Stackoverflow.com/users/173149", "pm_score": 2, "selected": false, "text": "<p>I vote for <a href=\"http://cedet.sourceforge.net/srecode.shtml\" rel=\"nofollow noreferrer\">http://cedet.sourceforge.net/srecode.shtml</a></p>\n<p>It has very clean syntax and has access to code environment through <code>Semantic</code>.</p>\n<p>Also it is a part of a large well supported <code>CEDET</code> distribution (which was built into Emacs for 24.x version series).</p>\n<p><strong>UPDATE</strong> <a href=\"https://github.com/joaotavora/yasnippet\" rel=\"nofollow noreferrer\">YASnippet</a> is also a powerful template engine. But it uses an ugly file naming schema (your file name === template name) for you can't put several templates into a single file and have issues with national character sets...</p>\n" }, { "answer_id": 50163924, "author": "Jiahao", "author_id": 9737937, "author_profile": "https://Stackoverflow.com/users/9737937", "pm_score": 1, "selected": false, "text": "<p>You can try a lightweight solution <a href=\"https://github.com/jiahaowork/muban.el\" rel=\"nofollow noreferrer\">muban.el</a></p>\n\n<p>It is written completely in Elisp and has a very simple syntax.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
Particularly, what is the best snippets package out there? Features: * easy to define new snippets (plain text, custom input with defaults) * simple navigation between predefined positions in the snippet * multiple insertion of the same custom input * accepts currently selected text as a custom input * *cross-platform* (Windows, Linux) * dynamically evaluated expressions (embedded code) written in a concise programming language (Perl, Python, Ruby are preferred) * nicely coexists with others packages in Emacs Example of code template, a simple `for` loop in C: ``` for (int i = 0; i < %N%; ++i) { _ } ``` It is a lot of typing for such common code. I want to invoke a code template or snippet which inserts that boilerplate code for me. Additionally it stops (on TAB or other keystroke) at `%N%` (my input replaces it) and final position of the cursor is `_`.
[TextMate's snippets](http://manual.macromates.com/en/snippets) is the most closest match but it is not a cross-platform solution and not for Emacs. The second closest thing is [YASnippet](http://github.com/joaotavora/yasnippet/ "Yet Another Snippet Package for Emacs") ([screencast](http://www.youtube.com/watch?v=vOj7btx3ATg "yasnippet screencast") shows the main capabilities). But it interferes with `hippie-expand` package in my setup and the embedded language is EmacsLisp which I'm not comfortable with outside `.emacs`. **EDIT**: Posted my answer here to allow voting on `YASnippet`.
61,451
<p>Does Django have any template tags to generate common HTML markup? For example, I know that I can get a url using</p> <pre><code>{% url mapper.views.foo %} </code></pre> <p>But that only gives me the URL and not the HTML code to create the link. Does Django have anything similar to Rails' link_to helper? I found <a href="http://code.google.com/p/django-helpers/" rel="noreferrer">django-helpers</a> but since this is a common thing I thought Django would have something built-in.</p>
[ { "answer_id": 61457, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 2, "selected": false, "text": "<p>it doesnt look like they're built in but here's a couple snippets. it looks like it'd be pretty easy to create these helpers:</p>\n\n<p><a href=\"http://www.djangosnippets.org/snippets/441/\" rel=\"nofollow noreferrer\">http://www.djangosnippets.org/snippets/441/</a></p>\n" }, { "answer_id": 67590, "author": "saturdayplace", "author_id": 3912, "author_profile": "https://Stackoverflow.com/users/3912", "pm_score": 6, "selected": true, "text": "<p>No it doesn't.</p>\n\n<p><a href=\"http://www.b-list.org/\" rel=\"noreferrer\">James Bennett</a> answered a <a href=\"http://www.b-list.org/weblog/2006/jul/02/django-and-ajax/\" rel=\"noreferrer\">similar question</a> a while back, regarding Rails' built-in JavaScript helpers.</p>\n\n<p>It's <em>really</em> unlikely that Django will ever have 'helper' functionality built-in. The reason, if I understand correctly, has to do with Django's core philosophy of keeping things <a href=\"http://docs.djangoproject.com/en/dev/misc/design-philosophies/#id1\" rel=\"noreferrer\">loosely coupled</a>. Having that kind of helper functionality built-in leads to coupling Django with a specific JavaScript library or (in your case) html document type. </p>\n\n<p>EG. What happens if/when HTML 5 is finally implemented and Django is generating HTML 4 or XHTML markup?</p>\n\n<p>Having said that, Django's template framework is really flexible, and it wouldn't be terribly difficult to <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-template-tags/\" rel=\"noreferrer\">write your own tags/filters</a> that did what you wanted. I'm mostly a designer myself, and I've been able to put together a couple custom tags that worked like a charm.</p>\n" }, { "answer_id": 67808, "author": "zuber", "author_id": 9812, "author_profile": "https://Stackoverflow.com/users/9812", "pm_score": 1, "selected": false, "text": "<p>Here is a <a href=\"http://docs.djangoproject.com/en/dev/ref/templates/builtins/\" rel=\"nofollow noreferrer\">list of all template tags and filters built into Django</a>. Django core doesn't have as much HTML helpers as Rails, because Django contributors assumed that web developer knows HTML very well. As stated by saturdaypalace, it's very unlikely for AJAX helpers to be added to Django, because it would lead to coupling Django with a specific JavaScript library.</p>\n\n<p>It's very easy to <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags\" rel=\"nofollow noreferrer\">write your own template tags</a> in Django (often you need just to define one function, similiar to Rails). You could reimplement most of Rails helpers in Django during a day or two.</p>\n" }, { "answer_id": 71598, "author": "Ali", "author_id": 11895, "author_profile": "https://Stackoverflow.com/users/11895", "pm_score": -1, "selected": false, "text": "<p>This won't answer directly to the question, but why not using <code>&lt;a href=\"{% url mapper.views.foo %}\"&gt;foo&lt;/a&gt;</code> in template then?</p>\n" }, { "answer_id": 82175, "author": "zgoda", "author_id": 12138, "author_profile": "https://Stackoverflow.com/users/12138", "pm_score": 0, "selected": false, "text": "<p>I bet if there would be any consent of what is <em>common html</em>, there would be helpers module too, just for completeness (or because others have it). ;)</p>\n\n<p>Other than that, Django template system is made mostly for HTML people, who already know how to write <code>p</code>, <code>img</code> and <code>a</code> tags and do not need any <em>helpers</em> for that. On the other side there are Python developers, who write code and do not care if the variable they put in context is enclosed by <code>div</code> or by <code>span</code> (perfect example of <em>separation of concerns</em> paradigm). If you need to have these two worlds to be joined, you have do to it by yourself (or look for other's code).</p>\n" }, { "answer_id": 1449028, "author": "Whatcould", "author_id": 175689, "author_profile": "https://Stackoverflow.com/users/175689", "pm_score": 5, "selected": false, "text": "<p>The purpose of helpers is not, as others here imply, to help developers who don't know how to write HTML. The purpose is to encapsulate common functionality -- so you don't need to write the same thing a thousand times -- and to provide a single place to edit common HTML used throughout your app.</p>\n\n<p>It's the same reason templates and SSI are useful -- not because people don't know how to write the HTML in their headers and footers, but sometimes you want to write it just once.</p>\n\n<blockquote>\n <p>EG. What happens if/when HTML 5 is\n finally implemented and Django is\n generating HTML 4 or XHTML markup?</p>\n</blockquote>\n\n<p>Same thing that happens when HTML 5 is implemented and all your templates are written in repetitive HTML, except a lot easier.</p>\n\n<p>The other posts have already answered the question, linking to the docs on <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-template-tags/\" rel=\"noreferrer\">custom template tags</a>; you can use tags and filters to build your own, but no, there aren't any built in.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796/" ]
Does Django have any template tags to generate common HTML markup? For example, I know that I can get a url using ``` {% url mapper.views.foo %} ``` But that only gives me the URL and not the HTML code to create the link. Does Django have anything similar to Rails' link\_to helper? I found [django-helpers](http://code.google.com/p/django-helpers/) but since this is a common thing I thought Django would have something built-in.
No it doesn't. [James Bennett](http://www.b-list.org/) answered a [similar question](http://www.b-list.org/weblog/2006/jul/02/django-and-ajax/) a while back, regarding Rails' built-in JavaScript helpers. It's *really* unlikely that Django will ever have 'helper' functionality built-in. The reason, if I understand correctly, has to do with Django's core philosophy of keeping things [loosely coupled](http://docs.djangoproject.com/en/dev/misc/design-philosophies/#id1). Having that kind of helper functionality built-in leads to coupling Django with a specific JavaScript library or (in your case) html document type. EG. What happens if/when HTML 5 is finally implemented and Django is generating HTML 4 or XHTML markup? Having said that, Django's template framework is really flexible, and it wouldn't be terribly difficult to [write your own tags/filters](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/) that did what you wanted. I'm mostly a designer myself, and I've been able to put together a couple custom tags that worked like a charm.
61,456
<p>After trying to avoid JavaScript for years, Iv started using Query for <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel="nofollow noreferrer">validation</a> in MVC asp.net, as there does not seem to be an official way of doing validation, Iv been surprised how good jQuery is. </p> <p>Firstly is there a way to get intellisense working for jQuery and its validation plugin, so that i don have to learn the api?</p> <p>Secondly how do I create a validation summary for this, it currently appends the error to the right of the text box.:</p> <pre><code>&lt;script type="text/javascript"&gt; $().ready(function() { $("#CreateLog").validate({ rules: { UserName: { required: true, minLength: 2, } }, messages: { UserName: { required: "Please enter a username", minLength: "Your username must consist of at least 2 characters", } } }); }); &lt;/script&gt; &lt;form id="CreateLog" action="Create" method="post" /&gt; &lt;label&gt;UserName&lt;/label&gt;&lt;br /&gt; &lt;%=Html.TextBox("UserName")%&gt; &lt;br /&gt; &lt;div class="error"&gt; &lt;/div&gt; &lt;input type=submit value=Save /&gt; &lt;/form&gt; </code></pre> <p>I tried adding this to the script:</p> <pre><code> errorLabelContainer: $("#CreateLog div.error") </code></pre> <p>and this to the html:</p> <pre><code> &lt;div class="error"&gt; &lt;/div&gt; </code></pre> <p>But this didn't work.</p>
[ { "answer_id": 61460, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>There is a Visual Studio 2008 hotfix for <a href=\"http://weblogs.asp.net/bradvincent/archive/2008/04/28/better-jquery-intellisense-in-vs2008.aspx\" rel=\"nofollow noreferrer\">JQuery IntelliSense</a> in <a href=\"http://weblogs.asp.net/scottgu/archive/2007/06/21/vs-2008-javascript-intellisense.aspx\" rel=\"nofollow noreferrer\">VS2008</a> . This might have been bundled with SP1 as well.</p>\n" }, { "answer_id": 66527, "author": "Dane O'Connor", "author_id": 1946, "author_profile": "https://Stackoverflow.com/users/1946", "pm_score": 5, "selected": true, "text": "<p>Try specifying both a wrapper and a label container in your options. I also added <code>display:none;</code> to the style of error-container to let jQuery decide when to show it.</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>$().ready(function() {\r\n $(\"#CreateLog\").validate({\r\n errorLabelContainer: $(\"ul\", $('div.error-container')),\r\n wrapper: 'li',\r\n rules: { \r\n UserName: {\r\n required: true,\r\n minLength: 2,\r\n\r\n }\r\n },\r\n messages: {\r\n UserName: {\r\n required: \"Please enter a username\",\r\n minLength: \"Your username must consist of at least 2 characters\"\r\n }\r\n }\r\n });\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\r\n&lt;div class=\"error-container\"&gt;\r\n &lt;ul&gt;&lt;/ul&gt;\r\n&lt;/div&gt;\r\n\r\n&lt;form id=\"CreateLog\" action=\"Create\" method=\"post\" /&gt; \r\n &lt;label&gt;UserName&lt;/label&gt;&lt;br /&gt;\r\n &lt;%=Html.TextBox(\"UserName\")%&gt; \r\n &lt;br /&gt; \r\n &lt;input type=submit value=Save /&gt;\r\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>That should work.</p>\n" }, { "answer_id": 298664, "author": "Tomas Aschan", "author_id": 38055, "author_profile": "https://Stackoverflow.com/users/38055", "pm_score": 1, "selected": false, "text": "<p>regarding intellisense for jquery (and other plugins): in order to have full intellisense in your own script files as well, just include the following line at the top of your .js file once for each file you want intellisensee from:</p>\n\n<pre><code>/// &lt;reference path=\"[insert path to script file here]\" /&gt;\n</code></pre>\n\n<p>simple, but very useful =)</p>\n" }, { "answer_id": 815368, "author": "Soni Ali", "author_id": 93141, "author_profile": "https://Stackoverflow.com/users/93141", "pm_score": 3, "selected": false, "text": "<p>You might want to check out <a href=\"http://codebetter.com/blogs/karlseguin/default.aspx\" rel=\"noreferrer\">Karl Seguin</a>'s ASP.NET MVC validation approach on <a href=\"http://codebetter.com\" rel=\"noreferrer\">CodeBetter.com</a> and his sample <a href=\"http://codebetter.com/blogs/karlseguin/archive/2009/04/28/presenting-codebetter-canvas.aspx\" rel=\"noreferrer\">application canvas</a>.</p>\n\n<p><a href=\"http://codebetter.com/blogs/karlseguin/archive/2009/04/26/validation-part-1-getting-started.aspx\" rel=\"noreferrer\">Validation - Part 1 - Getting Started</a></p>\n\n<p><a href=\"http://codebetter.com/blogs/karlseguin/archive/2009/04/27/validation-part-2-client-side.aspx\" rel=\"noreferrer\">Validation - Part 2 - Client-Side</a></p>\n\n<p><a href=\"http://codebetter.com/blogs/karlseguin/archive/2009/04/28/validation-part-3-server-side.aspx\" rel=\"noreferrer\">Validation - Part 3 - Server-Side</a></p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
After trying to avoid JavaScript for years, Iv started using Query for [validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) in MVC asp.net, as there does not seem to be an official way of doing validation, Iv been surprised how good jQuery is. Firstly is there a way to get intellisense working for jQuery and its validation plugin, so that i don have to learn the api? Secondly how do I create a validation summary for this, it currently appends the error to the right of the text box.: ``` <script type="text/javascript"> $().ready(function() { $("#CreateLog").validate({ rules: { UserName: { required: true, minLength: 2, } }, messages: { UserName: { required: "Please enter a username", minLength: "Your username must consist of at least 2 characters", } } }); }); </script> <form id="CreateLog" action="Create" method="post" /> <label>UserName</label><br /> <%=Html.TextBox("UserName")%> <br /> <div class="error"> </div> <input type=submit value=Save /> </form> ``` I tried adding this to the script: ``` errorLabelContainer: $("#CreateLog div.error") ``` and this to the html: ``` <div class="error"> </div> ``` But this didn't work.
Try specifying both a wrapper and a label container in your options. I also added `display:none;` to the style of error-container to let jQuery decide when to show it. ```js $().ready(function() { $("#CreateLog").validate({ errorLabelContainer: $("ul", $('div.error-container')), wrapper: 'li', rules: { UserName: { required: true, minLength: 2, } }, messages: { UserName: { required: "Please enter a username", minLength: "Your username must consist of at least 2 characters" } } }); }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="error-container"> <ul></ul> </div> <form id="CreateLog" action="Create" method="post" /> <label>UserName</label><br /> <%=Html.TextBox("UserName")%> <br /> <input type=submit value=Save /> </form> ``` That should work.
61,480
<p>In the past we declared properties like this:</p> <pre><code>public class MyClass { private int _age; public int Age { get{ return _age; } set{ _age = value; } } } </code></pre> <p>Now we can do:</p> <pre><code>public class MyClass { public int Age {get; set;} } </code></pre> <p>My question is, how can I access the private variable that is created automatically using this notation? </p> <p>I would rather access the private variable and not the public accessor 'Age'. Is there a default notation to access the private variable, or it is just not possible?</p>
[ { "answer_id": 61484, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 2, "selected": false, "text": "<p>You can't, it's a language feature as opposed to a IDE feature. To be honest i'd prefer then IDE to add the private variable in for you. I agree that it is slightly weird for the class to internally have to use the public entry point to access its own variables. Hence I don't use this new feature that much myself.</p>\n" }, { "answer_id": 61485, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Behind the scenes what happens is the injection of a private member variable, prefixed with &lt;>k__AutomaticallyGeneratedPropertyField#</p>\n</blockquote>\n\n<p>From <a href=\"http://community.bartdesmet.net/blogs/bart/archive/2007/03/03/c-3-0-automatic-properties-explained.aspx\" rel=\"noreferrer\">C# 3.0 Automatic Properties explained</a></p>\n\n<p>Although it may be possible to use that private member directly, it's very hacky and unnecessary.</p>\n" }, { "answer_id": 61493, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 4, "selected": false, "text": "<p>This syntax is commonly called \"syntax sugar\", which means that the compiler takes that syntax and translates it into something else. In your example, the compiler would generate code that looks something like this:</p>\n\n<pre><code>[CompilerGenerated]\nprivate int &lt;Age&gt;k_BackingField;\n\npublic int Age\n{\n [CompilerGenerated]\n get\n {\n return this.&lt;Age&gt;k_BackingField;\n }\n [CompilerGenerated]\n set\n {\n this.&lt;Age&gt;k_BackingField = value;\n }\n</code></pre>\n\n<p>Even knowing all of that, you could <strong>probably</strong> access the backing field directly but that sort of defeats the purpose of using automatic properties. I say probably here because you then depend on an implementation detail that could change at any point in a future release of the C# compiler.</p>\n" }, { "answer_id": 61494, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 5, "selected": false, "text": "<p>Your usage of automatic properties implies that you do not need any getting/setting logic for the property thus a private backing variable is unneccessary.</p>\n\n<p>Don't use automatic properties if you have any complex logic in your class. Just go <code>private int _age</code> and normal getters/setters as you normally would.</p>\n\n<p>IMO, automatic properties are more suited for quickly implementing throwaway objects or temporary data capsules like:</p>\n\n<pre><code>public class TempMessage {\n public int FromID { get; set; }\n public int ToID { get; set; }\n public string Message { get; set; }\n}\n</code></pre>\n\n<p>Where you don't need much logic.</p>\n" }, { "answer_id": 61503, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 7, "selected": false, "text": "<p>The aim of the new automatic properties is to reduce the amount of boilerplate code you need to write when you just have a simple property that doesn't need any special logic in the get or the set. </p>\n\n<p>If you want to access the private member that these properties use, that's usually for a few reasons:</p>\n\n<ul>\n<li>You need to more than just a simple get/set - in this case, you should just avoid using automatic properties for this member.</li>\n<li>You want to avoid the performance hit of going through the get or set and just use the member directly - in this case, I'd be surprised if there really was a performance hit. The simple get/set members are very very easy to inline, and in my (admittedly limited) testing I haven't found a difference between using the automatic properties and accessing the member directly. </li>\n<li><p>You only want to have public read access (i.e. just a 'get') and the class write to the member directly - in this case, you can use a private set in your automatic property. i.e.</p>\n\n<pre><code>public class MyClass\n{\n public int Age {get; private set;} \n}</code></pre></li>\n</ul>\n\n<p>This usually covers most the reasons for wanting to directly get to the backing field used by the automatic properties.</p>\n" }, { "answer_id": 61625, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": "<p>You shouldn't, and it's very unlikely you need to. If you need to access the property, just use the public property (e.g. this.Age). There's nothing special about the private field backing the public property, using it in preference to the property is just superstition.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
In the past we declared properties like this: ``` public class MyClass { private int _age; public int Age { get{ return _age; } set{ _age = value; } } } ``` Now we can do: ``` public class MyClass { public int Age {get; set;} } ``` My question is, how can I access the private variable that is created automatically using this notation? I would rather access the private variable and not the public accessor 'Age'. Is there a default notation to access the private variable, or it is just not possible?
The aim of the new automatic properties is to reduce the amount of boilerplate code you need to write when you just have a simple property that doesn't need any special logic in the get or the set. If you want to access the private member that these properties use, that's usually for a few reasons: * You need to more than just a simple get/set - in this case, you should just avoid using automatic properties for this member. * You want to avoid the performance hit of going through the get or set and just use the member directly - in this case, I'd be surprised if there really was a performance hit. The simple get/set members are very very easy to inline, and in my (admittedly limited) testing I haven't found a difference between using the automatic properties and accessing the member directly. * You only want to have public read access (i.e. just a 'get') and the class write to the member directly - in this case, you can use a private set in your automatic property. i.e. ``` public class MyClass { public int Age {get; private set;} } ``` This usually covers most the reasons for wanting to directly get to the backing field used by the automatic properties.
61,486
<p>I need to figure out what div is visible out of four possible divs using jQuery. Only one of those div's will be visible at any given time.</p> <p>This is what I have that works so far:</p> <pre><code>$("#FeatureImage1:visible, #FeatureImage2:visible, #FeatureImage3:visible, #FeatureImage4:visible").attr("id"); </code></pre> <p>Is there a way to refactor this? Is there an easier way to figure this out?</p>
[ { "answer_id": 61500, "author": "Gilean", "author_id": 6305, "author_profile": "https://Stackoverflow.com/users/6305", "pm_score": 5, "selected": true, "text": "<p>Assign the same class to each div then:</p>\n\n<pre><code>$(\"div.myClass:visible\").attr(\"id\");\n</code></pre>\n" }, { "answer_id": 64390, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 1, "selected": false, "text": "<p>When applicable, it's better to use contextual selectors rather than add spurious classes. For instance, if the <code>&lt;div&gt;</code> elements are the only children of an element with <code>id=\"foo\"</code>, then using <code>$(\"#foo &gt; div:visible\").attr(\"id\")</code> would better reflect the purpose of the code.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648/" ]
I need to figure out what div is visible out of four possible divs using jQuery. Only one of those div's will be visible at any given time. This is what I have that works so far: ``` $("#FeatureImage1:visible, #FeatureImage2:visible, #FeatureImage3:visible, #FeatureImage4:visible").attr("id"); ``` Is there a way to refactor this? Is there an easier way to figure this out?
Assign the same class to each div then: ``` $("div.myClass:visible").attr("id"); ```
61,517
<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p> <pre><code>&gt;&gt;&gt; class Foo: ... bar = 'hello' ... baz = 'world' ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello', 'baz' : 'world' } </code></pre> <p><strong>NOTE:</strong> It should not include methods. Only fields.</p>
[ { "answer_id": 61522, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 6, "selected": false, "text": "<p>The <code>dir</code> builtin will give you all the object's attributes, including special methods like <code>__str__</code>, <code>__dict__</code> and a whole bunch of others which you probably don't want. But you can do something like:</p>\n\n<pre><code>&gt;&gt;&gt; class Foo(object):\n... bar = 'hello'\n... baz = 'world'\n...\n&gt;&gt;&gt; f = Foo()\n&gt;&gt;&gt; [name for name in dir(f) if not name.startswith('__')]\n[ 'bar', 'baz' ]\n&gt;&gt;&gt; dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__')) \n{ 'bar': 'hello', 'baz': 'world' }\n</code></pre>\n\n<p>So can extend this to only return data attributes and not methods, by defining your <code>props</code> function like this:</p>\n\n<pre><code>import inspect\n\ndef props(obj):\n pr = {}\n for name in dir(obj):\n value = getattr(obj, name)\n if not name.startswith('__') and not inspect.ismethod(value):\n pr[name] = value\n return pr\n</code></pre>\n" }, { "answer_id": 61551, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": 5, "selected": false, "text": "<p>I've settled with a combination of both answers:</p>\n\n<pre><code>dict((key, value) for key, value in f.__dict__.iteritems() \n if not callable(value) and not key.startswith('__'))\n</code></pre>\n" }, { "answer_id": 62680, "author": "user6868", "author_id": 6868, "author_profile": "https://Stackoverflow.com/users/6868", "pm_score": 10, "selected": true, "text": "<p>Note that best practice in Python 2.7 is to use <em><a href=\"https://www.python.org/doc/newstyle/\" rel=\"noreferrer\">new-style</a></em> classes (not needed with Python 3), i.e.</p>\n\n<pre><code>class Foo(object):\n ...\n</code></pre>\n\n<p>Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary <em>object</em>, it's sufficient to use <code>__dict__</code>. Usually, you'll declare your methods at class level and your attributes at instance level, so <code>__dict__</code> should be fine. For example:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>&gt;&gt;&gt; class A(object):\n... def __init__(self):\n... self.b = 1\n... self.c = 2\n... def do_nothing(self):\n... pass\n...\n&gt;&gt;&gt; a = A()\n&gt;&gt;&gt; a.__dict__\n{'c': 2, 'b': 1}\n</code></pre>\n\n<p>A better approach (suggested by <a href=\"https://stackoverflow.com/users/409638/robert\">robert</a> in comments) is the builtin <a href=\"https://docs.python.org/3/library/functions.html#vars\" rel=\"noreferrer\"><code>vars</code></a> function:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>&gt;&gt;&gt; vars(a)\n{'c': 2, 'b': 1}\n</code></pre>\n\n<p>Alternatively, depending on what you want to do, it might be nice to inherit from <code>dict</code>. Then your class is <em>already</em> a dictionary, and if you want you can override <code>getattr</code> and/or <code>setattr</code> to call through and set the dict. For example:</p>\n\n<pre><code>class Foo(dict):\n def __init__(self):\n pass\n def __getattr__(self, attr):\n return self[attr]\n\n # etc...\n</code></pre>\n" }, { "answer_id": 63635, "author": "indentation", "author_id": 7706, "author_profile": "https://Stackoverflow.com/users/7706", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>To build a dictionary from an arbitrary <i>object</i>, it's sufficient to use <code>__dict__</code>.</p>\n</blockquote>\n\n<p>This misses attributes that the object inherits from its class. For example,</p>\n\n<pre><code>class c(object):\n x = 3\na = c()\n</code></pre>\n\n<p>hasattr(a, 'x') is true, but 'x' does not appear in a.__dict__</p>\n" }, { "answer_id": 17470565, "author": "Score_Under", "author_id": 1091693, "author_profile": "https://Stackoverflow.com/users/1091693", "pm_score": 3, "selected": false, "text": "<p>Late answer but provided for completeness and the benefit of googlers:</p>\n\n<pre><code>def props(x):\n return dict((key, getattr(x, key)) for key in dir(x) if key not in dir(x.__class__))\n</code></pre>\n\n<p>This will not show methods defined in the class, but it will still show fields including those assigned to lambdas or those which start with a double underscore.</p>\n" }, { "answer_id": 23937693, "author": "radtek", "author_id": 2023392, "author_profile": "https://Stackoverflow.com/users/2023392", "pm_score": 3, "selected": false, "text": "<p>I think the easiest way is to create a <strong>getitem</strong> attribute for the class. If you need to write to the object, you can create a custom <strong>setattr</strong> . Here is an example for <strong>getitem</strong>:</p>\n\n<pre><code>class A(object):\n def __init__(self):\n self.b = 1\n self.c = 2\n def __getitem__(self, item):\n return self.__dict__[item]\n\n# Usage: \na = A()\na.__getitem__('b') # Outputs 1\na.__dict__ # Outputs {'c': 2, 'b': 1}\nvars(a) # Outputs {'c': 2, 'b': 1}\n</code></pre>\n\n<p><strong>dict</strong> generates the objects attributes into a dictionary and the dictionary object can be used to get the item you need.</p>\n" }, { "answer_id": 29333136, "author": "Seaux", "author_id": 263175, "author_profile": "https://Stackoverflow.com/users/263175", "pm_score": 5, "selected": false, "text": "<p>I thought I'd take some time to show you how you can translate an object to dict via <code>dict(obj)</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class A(object):\n d = '4'\n e = '5'\n f = '6'\n\n def __init__(self):\n self.a = '1'\n self.b = '2'\n self.c = '3'\n\n def __iter__(self):\n # first start by grabbing the Class items\n iters = dict((x,y) for x,y in A.__dict__.items() if x[:2] != '__')\n\n # then update the class items with the instance items\n iters.update(self.__dict__)\n\n # now 'yield' through the items\n for x,y in iters.items():\n yield x,y\n\na = A()\nprint(dict(a)) \n# prints \"{'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4', 'f': '6'}\"\n</code></pre>\n\n<p>The key section of this code is the <code>__iter__</code> function. </p>\n\n<p>As the comments explain, the first thing we do is grab the Class items and prevent anything that starts with '__'.</p>\n\n<p>Once you've created that <code>dict</code>, then you can use the <code>update</code> dict function and pass in the instance <code>__dict__</code>.</p>\n\n<p>These will give you a complete class+instance dictionary of members. Now all that's left is to iterate over them and yield the returns.</p>\n\n<p>Also, if you plan on using this a lot, you can create an <code>@iterable</code> class decorator.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def iterable(cls):\n def iterfn(self):\n iters = dict((x,y) for x,y in cls.__dict__.items() if x[:2] != '__')\n iters.update(self.__dict__)\n\n for x,y in iters.items():\n yield x,y\n\n cls.__iter__ = iterfn\n return cls\n\n@iterable\nclass B(object):\n d = 'd'\n e = 'e'\n f = 'f'\n\n def __init__(self):\n self.a = 'a'\n self.b = 'b'\n self.c = 'c'\n\nb = B()\nprint(dict(b))\n</code></pre>\n" }, { "answer_id": 31770231, "author": "Berislav Lopac", "author_id": 122033, "author_profile": "https://Stackoverflow.com/users/122033", "pm_score": 8, "selected": false, "text": "<p>Instead of <code>x.__dict__</code>, it's actually more pythonic to use <code>vars(x)</code>.</p>\n" }, { "answer_id": 34662287, "author": "coanor", "author_id": 342348, "author_profile": "https://Stackoverflow.com/users/342348", "pm_score": 1, "selected": false, "text": "<p>If you want to list part of your attributes, override <code>__dict__</code>:</p>\n\n<pre><code>def __dict__(self):\n d = {\n 'attr_1' : self.attr_1,\n ...\n }\n return d\n\n# Call __dict__\nd = instance.__dict__()\n</code></pre>\n\n<p>This helps a lot if your <code>instance</code> get some large block data and you want to push <code>d</code> to Redis like message queue. </p>\n" }, { "answer_id": 48696573, "author": "spattanaik75", "author_id": 3094089, "author_profile": "https://Stackoverflow.com/users/3094089", "pm_score": 0, "selected": false, "text": "<h2>PYTHON 3:</h2>\n\n<pre><code>class DateTimeDecoder(json.JSONDecoder):\n\n def __init__(self, *args, **kargs):\n JSONDecoder.__init__(self, object_hook=self.dict_to_object,\n *args, **kargs)\n\n def dict_to_object(self, d):\n if '__type__' not in d:\n return d\n\n type = d.pop('__type__')\n try:\n dateobj = datetime(**d)\n return dateobj\n except:\n d['__type__'] = type\n return d\n\ndef json_default_format(value):\n try:\n if isinstance(value, datetime):\n return {\n '__type__': 'datetime',\n 'year': value.year,\n 'month': value.month,\n 'day': value.day,\n 'hour': value.hour,\n 'minute': value.minute,\n 'second': value.second,\n 'microsecond': value.microsecond,\n }\n if isinstance(value, decimal.Decimal):\n return float(value)\n if isinstance(value, Enum):\n return value.name\n else:\n return vars(value)\n except Exception as e:\n raise ValueError\n</code></pre>\n\n<p>Now you can use above code inside your own class :</p>\n\n<pre><code>class Foo():\n def toJSON(self):\n return json.loads(\n json.dumps(self, sort_keys=True, indent=4, separators=(',', ': '), default=json_default_format), cls=DateTimeDecoder)\n\n\nFoo().toJSON() \n</code></pre>\n" }, { "answer_id": 53823839, "author": "R H", "author_id": 2169290, "author_profile": "https://Stackoverflow.com/users/2169290", "pm_score": 4, "selected": false, "text": "<p>A downside of using <code>__dict__</code> is that it is shallow; it won't convert any subclasses to dictionaries.</p>\n\n<p>If you're using Python3.5 or higher, you can use <a href=\"https://jsons.readthedocs.io/en/latest/\" rel=\"noreferrer\"><code>jsons</code></a>:</p>\n\n<pre><code>&gt;&gt;&gt; import jsons\n&gt;&gt;&gt; jsons.dump(f)\n{'bar': 'hello', 'baz': 'world'}\n</code></pre>\n" }, { "answer_id": 61531302, "author": "Ricky Levi", "author_id": 281965, "author_profile": "https://Stackoverflow.com/users/281965", "pm_score": 3, "selected": false, "text": "<p><code>vars()</code> is great, but doesn't work for nested objects of objects</p>\n\n<p>Convert nested object of objects to dict:</p>\n\n<pre><code>def to_dict(self):\n return json.loads(json.dumps(self, default=lambda o: o.__dict__))\n</code></pre>\n" }, { "answer_id": 65469063, "author": "Anakhand", "author_id": 6117426, "author_profile": "https://Stackoverflow.com/users/6117426", "pm_score": 2, "selected": false, "text": "<p>As mentioned in <a href=\"https://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields/65469063#comment102192969_31770231\">one of the comments above</a>, <code>vars</code> currently isn't universal in that it doesn't work for objects with <a href=\"https://docs.python.org/3/reference/datamodel.html#slots\" rel=\"nofollow noreferrer\"><code>__slots__</code></a> instead of a normal <code>__dict__</code>. Moreover, some objecs (e.g., builtins like <code>str</code> or <code>int</code>) have <em>neither</em> a <code>__dict__</code> <em>nor</em> <code>__slots__</code>.</p>\n<p>For now, a more versatile solution could be this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def instance_attributes(obj: Any) -&gt; Dict[str, Any]:\n &quot;&quot;&quot;Get a name-to-value dictionary of instance attributes of an arbitrary object.&quot;&quot;&quot;\n try:\n return vars(obj)\n except TypeError:\n pass\n\n # object doesn't have __dict__, try with __slots__\n try:\n slots = obj.__slots__\n except AttributeError:\n # doesn't have __dict__ nor __slots__, probably a builtin like str or int\n return {}\n # collect all slots attributes (some might not be present)\n attrs = {}\n for name in slots:\n try:\n attrs[name] = getattr(obj, name)\n except AttributeError:\n continue\n return attrs\n</code></pre>\n<p>Example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Foo:\n class_var = &quot;spam&quot;\n\n\nclass Bar:\n class_var = &quot;eggs&quot;\n \n __slots__ = [&quot;a&quot;, &quot;b&quot;]\n</code></pre>\n<pre><code>&gt;&gt;&gt; foo = Foo()\n&gt;&gt;&gt; foo.a = 1\n&gt;&gt;&gt; foo.b = 2\n&gt;&gt;&gt; instance_attributes(foo)\n{'a': 1, 'b': 2}\n\n&gt;&gt;&gt; bar = Bar()\n&gt;&gt;&gt; bar.a = 3\n&gt;&gt;&gt; instance_attributes(bar)\n{'a': 3}\n\n&gt;&gt;&gt; instance_attributes(&quot;baz&quot;) \n{}\n\n</code></pre>\n<hr />\n<p>Rant:</p>\n<p>It's a pity that this isn't built into <code>vars</code> already. Many builtins in Python promise to be &quot;the&quot; solution to a problem but then there's always several special cases that aren't handled... And one just ends up having to write the code manually in any case.</p>\n" }, { "answer_id": 66727687, "author": "Reed Sandberg", "author_id": 1287091, "author_profile": "https://Stackoverflow.com/users/1287091", "pm_score": 3, "selected": false, "text": "<p>In 2021, and for nested objects/dicts/json use pydantic BaseModel - will convert nested dicts and nested json objects to python objects and JSON and vice versa:</p>\n<p><a href=\"https://pydantic-docs.helpmanual.io/usage/models/\" rel=\"noreferrer\">https://pydantic-docs.helpmanual.io/usage/models/</a></p>\n<pre><code>&gt;&gt;&gt; class Foo(BaseModel):\n... count: int\n... size: float = None\n... \n&gt;&gt;&gt; \n&gt;&gt;&gt; class Bar(BaseModel):\n... apple = 'x'\n... banana = 'y'\n... \n&gt;&gt;&gt; \n&gt;&gt;&gt; class Spam(BaseModel):\n... foo: Foo\n... bars: List[Bar]\n... \n&gt;&gt;&gt; \n&gt;&gt;&gt; m = Spam(foo={'count': 4}, bars=[{'apple': 'x1'}, {'apple': 'x2'}])\n</code></pre>\n<p><strong>Object to dict</strong></p>\n<pre><code>&gt;&gt;&gt; print(m.dict())\n{'foo': {'count': 4, 'size': None}, 'bars': [{'apple': 'x1', 'banana': 'y'}, {'apple': 'x2', 'banana': 'y'}]}\n</code></pre>\n<p><strong>Object to JSON</strong></p>\n<pre><code>&gt;&gt;&gt; print(m.json())\n{&quot;foo&quot;: {&quot;count&quot;: 4, &quot;size&quot;: null}, &quot;bars&quot;: [{&quot;apple&quot;: &quot;x1&quot;, &quot;banana&quot;: &quot;y&quot;}, {&quot;apple&quot;: &quot;x2&quot;, &quot;banana&quot;: &quot;y&quot;}]}\n</code></pre>\n<p><strong>Dict to object</strong></p>\n<pre><code>&gt;&gt;&gt; spam = Spam.parse_obj({'foo': {'count': 4, 'size': None}, 'bars': [{'apple': 'x1', 'banana': 'y'}, {'apple': 'x2', 'banana': 'y2'}]})\n&gt;&gt;&gt; spam\nSpam(foo=Foo(count=4, size=None), bars=[Bar(apple='x1', banana='y'), Bar(apple='x2', banana='y2')])\n</code></pre>\n<p><strong>JSON to object</strong></p>\n<pre><code>&gt;&gt;&gt; spam = Spam.parse_raw('{&quot;foo&quot;: {&quot;count&quot;: 4, &quot;size&quot;: null}, &quot;bars&quot;: [{&quot;apple&quot;: &quot;x1&quot;, &quot;banana&quot;: &quot;y&quot;}, {&quot;apple&quot;: &quot;x2&quot;, &quot;banana&quot;: &quot;y&quot;}]}')\n&gt;&gt;&gt; spam\nSpam(foo=Foo(count=4, size=None), bars=[Bar(apple='x1', banana='y'), Bar(apple='x2', banana='y')])\n</code></pre>\n" }, { "answer_id": 68982164, "author": "thetaprime", "author_id": 1968839, "author_profile": "https://Stackoverflow.com/users/1968839", "pm_score": 0, "selected": false, "text": "<p>Try:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from pprint import pformat\na_dict = eval(pformat(an_obj))\n</code></pre>\n" }, { "answer_id": 69088860, "author": "hizbul25", "author_id": 1534638, "author_profile": "https://Stackoverflow.com/users/1534638", "pm_score": 3, "selected": false, "text": "<p><strong>Python3.x</strong></p>\n<pre><code>return dict((key, value) for key, value in f.__dict__.items() if not callable(value) and not key.startswith('__'))\n</code></pre>\n" }, { "answer_id": 73388990, "author": "Surya Teja", "author_id": 5692181, "author_profile": "https://Stackoverflow.com/users/5692181", "pm_score": 2, "selected": false, "text": "<p>Dataclass(from Python 3.7) is another option which can be used for converting class properties to dict. <a href=\"https://docs.python.org/3/library/dataclasses.html#dataclasses.asdict\" rel=\"nofollow noreferrer\">asdict</a> can be used along with dataclass objects\nfor the conversion.</p>\n<p>Example:</p>\n<pre><code>@dataclass\nclass Point:\n x: int\n y: int\n\np = Point(10, 20)\nasdict(p) # it returns {'x': 10, 'y': 20}\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148/" ]
Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: ``` >>> class Foo: ... bar = 'hello' ... baz = 'world' ... >>> f = Foo() >>> props(f) { 'bar' : 'hello', 'baz' : 'world' } ``` **NOTE:** It should not include methods. Only fields.
Note that best practice in Python 2.7 is to use *[new-style](https://www.python.org/doc/newstyle/)* classes (not needed with Python 3), i.e. ``` class Foo(object): ... ``` Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary *object*, it's sufficient to use `__dict__`. Usually, you'll declare your methods at class level and your attributes at instance level, so `__dict__` should be fine. For example: ```python >>> class A(object): ... def __init__(self): ... self.b = 1 ... self.c = 2 ... def do_nothing(self): ... pass ... >>> a = A() >>> a.__dict__ {'c': 2, 'b': 1} ``` A better approach (suggested by [robert](https://stackoverflow.com/users/409638/robert) in comments) is the builtin [`vars`](https://docs.python.org/3/library/functions.html#vars) function: ```python >>> vars(a) {'c': 2, 'b': 1} ``` Alternatively, depending on what you want to do, it might be nice to inherit from `dict`. Then your class is *already* a dictionary, and if you want you can override `getattr` and/or `setattr` to call through and set the dict. For example: ``` class Foo(dict): def __init__(self): pass def __getattr__(self, attr): return self[attr] # etc... ```
61,552
<p><a href="http://www.stackoverflow.com/questions/61088/hidden-features-of-javascript#61118">Alan Storm's comments</a> in response to my answer regarding the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with" rel="noreferrer"><code>with</code> statement</a> got me thinking. I've seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I'm curious as to how I might make effective use of <code>with</code>, while avoiding its pitfalls.</p> <p>Where have you found the <code>with</code> statement useful?</p>
[ { "answer_id": 61566, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 4, "selected": false, "text": "<p>Visual Basic.NET has a similar <code>With</code> statement. One of the more common ways I use it is to quickly set a number of properties. Instead of:</p>\n\n<pre><code>someObject.Foo = ''\nsomeObject.Bar = ''\nsomeObject.Baz = ''\n</code></pre>\n\n<p>, I can write:</p>\n\n<pre><code>With someObject\n .Foo = ''\n .Bar = ''\n .Baz = ''\nEnd With\n</code></pre>\n\n<p>This isn't just a matter of laziness. It also makes for much more readable code. And unlike JavaScript, it does not suffer from ambiguity, as you have to prefix everything affected by the statement with a <code>.</code> (dot). So, the following two are clearly distinct:</p>\n\n<pre><code>With someObject\n .Foo = ''\nEnd With\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>With someObject\n Foo = ''\nEnd With\n</code></pre>\n\n<p>The former is <code>someObject.Foo</code>; the latter is <code>Foo</code> in the scope <em>outside</em> <code>someObject</code>.</p>\n\n<p>I find that JavaScript's lack of distinction makes it far less useful than Visual Basic's variant, as the risk of ambiguity is too high. Other than that, <code>with</code> is still a powerful idea that can make for better readability.</p>\n" }, { "answer_id": 61577, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 3, "selected": false, "text": "<p>I think the obvious use is as a shortcut. If you're e.g. initializing an object you simply save typing a lot of \"ObjectName.\" Kind of like lisp's \"with-slots\" which lets you write </p>\n\n<pre><code>(with-slots (foo bar) objectname\n \"some code that accesses foo and bar\"\n</code></pre>\n\n<p>which is the same as writing</p>\n\n<pre><code>\"some code that accesses (slot-value objectname 'foo) and (slot-value objectname 'bar)\"\"\n</code></pre>\n\n<p>It's more obvious why this is a shortcut then when your language allows \"Objectname.foo\" but still.</p>\n" }, { "answer_id": 61582, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 3, "selected": false, "text": "<p>Having experience with Delphi, I would say that using <em>with</em> should be a last-resort size optimization, possibly performed by some kind of javascript minimizer algorithm with access to static code analysis to verify its safety.</p>\n\n<p>The scoping problems you can get into with liberal use of the <em>with</em> statement can be a royal pain in the a** and I wouldn't want anyone to experience a debugging session to figure out what the he.. is going on in your code, only to find out that it captured an object member or the wrong local variable, instead of your global or outer scope variable which you intended.</p>\n\n<p>The VB <em>with</em> statement is better, in that it needs the dots to disambiguate the scoping, but the Delphi <em>with</em> statement is a loaded gun with a hairtrigger, and it looks to me as though the javascript one is similar enough to warrant the same warning.</p>\n" }, { "answer_id": 61586, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": false, "text": "<p>You can define a small helper function to provide the benefits of <code>with</code> without the ambiguity:</p>\n\n<pre><code>var with_ = function (obj, func) { func (obj); };\n\nwith_ (object_name_here, function (_)\n{\n _.a = \"foo\";\n _.b = \"bar\";\n});\n</code></pre>\n" }, { "answer_id": 61595, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 2, "selected": false, "text": "<p>I just really don't see how using the with is any more readable than just typing object.member. I don't think it's any less readable, but I don't think it's any more readable either.</p>\n\n<p>Like lassevk said, I can definitely see how using with would be more error prone than just using the very explicit \"object.member\" syntax.</p>\n" }, { "answer_id": 61601, "author": "Svend", "author_id": 2491, "author_profile": "https://Stackoverflow.com/users/2491", "pm_score": 2, "selected": false, "text": "<p>Using with also makes your code slower in many implementation, as everything now gets wrapped in an extra scope for lookup. There's no legitimate reason for using with in JavaScript.</p>\n" }, { "answer_id": 61676, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 6, "selected": false, "text": "<p>As my previous comments indicated, I don't think you can use <em><code>with</code></em> safely no matter how tempting it might be in any given situation. Since the issue isn't directly covered here, I'll repeat it. Consider the following code</p>\n\n<pre><code>user = {};\nsomeFunctionThatDoesStuffToUser(user);\nsomeOtherFunction(user);\n\nwith(user){\n name = 'Bob';\n age = 20;\n}\n</code></pre>\n\n<p>Without carefully investigating those function calls, there's no way to tell what the state of your program will be after this code runs. If <code>user.name</code> was already set, it will now be <code>Bob</code>. If it wasn't set, the global <code>name</code> will be initialized or changed to <code>Bob</code> and the <code>user</code> object will remain without a <code>name</code> property. </p>\n\n<p>Bugs happen. If you use <em>with</em> you will eventually do this and increase the chances your program will fail. Worse, you may encounter working code that sets a global in the with block, either deliberately or through the author not knowing about this quirk of the construct. It's a lot like encountering fall through on a switch, you have no idea if the author intended this and there's no way to know if \"fixing\" the code will introduce a regression.</p>\n\n<p>Modern programming languages are chocked full of features. Some features, after years of use, are discovered to be bad, and should be avoided. Javascript's <em><code>with</code></em> is one of them.</p>\n" }, { "answer_id": 61737, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 5, "selected": false, "text": "<p>Hardly seems worth it since you can do the following:</p>\n\n<pre><code>var o = incrediblyLongObjectNameThatNoOneWouldUse;\no.name = \"Bob\";\no.age = \"50\";\n</code></pre>\n" }, { "answer_id": 62103, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 2, "selected": false, "text": "<p>I think the with-statement can come in handy when converting a template language into JavaScript. For example <a href=\"http://code.google.com/p/base2/source/browse/trunk/src/base2/JST/Interpreter.js\" rel=\"nofollow noreferrer\">JST</a> in <a href=\"http://code.google.com/p/base2/\" rel=\"nofollow noreferrer\">base2</a>, but I've seen it more often. </p>\n\n<p>I agree one can program this without the with-statement. But because it doesn't give any problems it is a legitimate use. </p>\n" }, { "answer_id": 176406, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 2, "selected": false, "text": "<p>I think that the usefulness of <code>with</code> can be dependent on how well your code is written. For example, if you're writing code that appears like this:</p>\n\n<pre><code>var sHeader = object.data.header.toString();\nvar sContent = object.data.content.toString();\nvar sFooter = object.data.footer.toString();\n</code></pre>\n\n<p>then you could argue that <code>with</code> will improve the readability of the code by doing this:</p>\n\n<pre><code>var sHeader = null, sContent = null, sFooter = null;\nwith(object.data) {\n sHeader = header.toString();\n sContent = content.toString();\n sFooter = content.toString();\n}\n</code></pre>\n\n<p>Conversely, it could be argued that you're violating the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter</a>, but, then again, maybe not. I digress =).</p>\n\n<p>Above all else, know that Douglas Crockford recommends <strong>not</strong> using <code>with</code>. I urge you to check out his blog post regarding <code>with</code> and its alternatives <a href=\"http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 185283, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 9, "selected": false, "text": "<p>Another use occurred to me today, so I searched the web excitedly and found an existing mention of it: <a href=\"http://web.archive.org/web/20090111183416/http://www.hedgerwow.com/360/dhtml/js_block_scope.html\" rel=\"noreferrer\">Defining Variables inside Block Scope</a>.</p>\n<h3>Background</h3>\n<p>JavaScript, in spite of its superficial resemblance to C and C++, does not scope variables to the block they are defined in:</p>\n<pre><code>var name = &quot;Joe&quot;;\nif ( true )\n{\n var name = &quot;Jack&quot;;\n}\n// name now contains &quot;Jack&quot;\n</code></pre>\n<p>Declaring a closure in a loop is a common task where this can lead to errors:</p>\n<pre><code>for (var i=0; i&lt;3; ++i)\n{\n var num = i;\n setTimeout(function() { alert(num); }, 10);\n}\n</code></pre>\n<p>Because the for loop does not introduce a new scope, the same <code>num</code> - with a value of <code>2</code> - will be shared by all three functions.</p>\n<h3>A new scope: <code>let</code> and <code>with</code></h3>\n<p>With the introduction of the <code>let</code> statement in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"noreferrer\">ES6</a>, it becomes easy to introduce a new scope when necessary to avoid these problems:</p>\n<pre><code>// variables introduced in this statement \n// are scoped to each iteration of the loop\nfor (let i=0; i&lt;3; ++i)\n{\n setTimeout(function() { alert(i); }, 10);\n}\n</code></pre>\n<p>Or even:</p>\n<pre><code>for (var i=0; i&lt;3; ++i)\n{\n // variables introduced in this statement \n // are scoped to the block containing it.\n let num = i;\n setTimeout(function() { alert(num); }, 10);\n}\n</code></pre>\n<p>Until ES6 is universally available, this use remains limited to the newest browsers and developers willing to use transpilers. However, we can easily simulate this behavior using <code>with</code>:</p>\n<pre><code>for (var i=0; i&lt;3; ++i)\n{\n // object members introduced in this statement \n // are scoped to the block following it.\n with ({num: i})\n {\n setTimeout(function() { alert(num); }, 10);\n }\n}\n</code></pre>\n<p>The loop now works as intended, creating three separate variables with values from 0 to 2. Note that variables declared <em>within</em> the block are not scoped to it, unlike the behavior of blocks in C++ (in C, variables must be declared at the start of a block, so in a way it is similar). This behavior is actually quite similar to a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#let_blocks\" rel=\"noreferrer\"><code>let</code> block syntax</a> introduced in earlier versions of Mozilla browsers, but not widely adopted elsewhere.</p>\n" }, { "answer_id": 1028684, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>Yes, yes and yes. There is a very legitimate use. Watch:</p>\n\n<pre><code>with (document.getElementById(\"blah\").style) {\n background = \"black\";\n color = \"blue\";\n border = \"1px solid green\";\n}\n</code></pre>\n\n<p>Basically any other DOM or CSS hooks are fantastic uses of with. It's not like \"CloneNode\" will be undefined and go back to the global scope unless you went out of your way and decided to make it possible.</p>\n\n<p>Crockford's speed complaint is that a new context is created by with. Contexts are generally expensive. I agree. But if you just created a div and don't have some framework on hand for setting your css and need to set up 15 or so CSS properties by hand, then creating a context will probably be cheaper then variable creation and 15 dereferences:</p>\n\n<pre><code>var element = document.createElement(\"div\"),\n elementStyle = element.style;\n\nelementStyle.fontWeight = \"bold\";\nelementStyle.fontSize = \"1.5em\";\nelementStyle.color = \"#55d\";\nelementStyle.marginLeft = \"2px\";\n</code></pre>\n\n<p>etc...</p>\n" }, { "answer_id": 1462102, "author": "airportyh", "author_id": 5304, "author_profile": "https://Stackoverflow.com/users/5304", "pm_score": 7, "selected": false, "text": "<p>I have been using the with statement as a simple form of scoped import. Let's say you have a markup builder of some sort. Rather than writing:</p>\n\n<pre><code>markupbuilder.div(\n markupbuilder.p('Hi! I am a paragraph!',\n markupbuilder.span('I am a span inside a paragraph')\n )\n)\n</code></pre>\n\n<p>You could instead write:</p>\n\n<pre><code>with(markupbuilder){\n div(\n p('Hi! I am a paragraph!',\n span('I am a span inside a paragraph')\n )\n )\n}\n</code></pre>\n\n<p>For this use case, I am not doing any assignment, so I don't have the ambiguity problem associated with that.</p>\n" }, { "answer_id": 1463937, "author": "kangax", "author_id": 130652, "author_profile": "https://Stackoverflow.com/users/130652", "pm_score": 4, "selected": false, "text": "<p>I don't ever use with, don't see a reason to, and don't recommend it.</p>\n\n<p>The problem with <code>with</code> is that it <strong>prevents numerous lexical optimizations</strong> an ECMAScript implementation can perform. Given the rise of fast JIT-based engines, this issue will probably become even more important in the near future.</p>\n\n<p>It might look like <code>with</code> allows for cleaner constructs (when, say, introducing a new scope instead of a common anonymous function wrapper or replacing verbose aliasing), but it's <strong>really not worth it</strong>. Besides a decreased performance, there's always a danger of assigning to a property of a wrong object (when property is not found on an object in injected scope) and perhaps erroneously introducing global variables. IIRC, latter issue is the one that motivated Crockford to recommend to avoid <code>with</code>.</p>\n" }, { "answer_id": 2207355, "author": "alex", "author_id": 267082, "author_profile": "https://Stackoverflow.com/users/267082", "pm_score": 2, "selected": false, "text": "<p>The with statement can be used to decrease the code size or for private class members, example:</p>\n\n<pre><code>// demo class framework\nvar Class= function(name, o) {\n var c=function(){};\n if( o.hasOwnProperty(\"constructor\") ) {\n c= o.constructor;\n }\n delete o[\"constructor\"];\n delete o[\"prototype\"];\n c.prototype= {};\n for( var k in o ) c.prototype[k]= o[k];\n c.scope= Class.scope;\n c.scope.Class= c;\n c.Name= name;\n return c;\n}\nClass.newScope= function() {\n Class.scope= {};\n Class.scope.Scope= Class.scope;\n return Class.scope;\n}\n\n// create a new class\nwith( Class.newScope() ) {\n window.Foo= Class(\"Foo\",{\n test: function() {\n alert( Class.Name );\n }\n });\n}\n(new Foo()).test();\n</code></pre>\n\n<p>The with-statement is very usefull if you want to modify the scope, what is necessary for having your own global scope that you can manipulate at runtime. You can put constants on it or certain helper functions often used like e.g. \"toUpper\", \"toLower\" or \"isNumber\", \"clipNumber\" aso..</p>\n\n<p>About the bad performance I read that often: Scoping a function won't have any impact on the performance, in fact in my FF a scoped function runs faster then an unscoped:</p>\n\n<pre><code>var o={x: 5},r, fnRAW= function(a,b){ return a*b; }, fnScoped, s, e, i;\nwith( o ) {\n fnScoped= function(a,b){ return a*b; };\n}\n\ns= Date.now();\nr= 0;\nfor( i=0; i &lt; 1000000; i++ ) {\n r+= fnRAW(i,i);\n}\ne= Date.now();\nconsole.log( (e-s)+\"ms\" );\n\ns= Date.now();\nr= 0;\nfor( i=0; i &lt; 1000000; i++ ) {\n r+= fnScoped(i,i);\n}\ne= Date.now();\nconsole.log( (e-s)+\"ms\" );\n</code></pre>\n\n<p>So in the above mentioned way used the with-statement has no negative effect on performance, but a good one as it deceases the code size, what impacts the memory usage on mobile devices.</p>\n" }, { "answer_id": 2573547, "author": "aredridel", "author_id": 306320, "author_profile": "https://Stackoverflow.com/users/306320", "pm_score": 2, "selected": false, "text": "<p>It's good for putting code that runs in a relatively complicated environment into a container: I use it to make a local binding for \"window\" and such to run code meant for a web browser.</p>\n" }, { "answer_id": 2602245, "author": "Fire Crow", "author_id": 80479, "author_profile": "https://Stackoverflow.com/users/80479", "pm_score": 2, "selected": false, "text": "<p>I think the object literal use is interesting, like a drop-in replacement for using a closure</p>\n\n<pre><code>for(var i = nodes.length; i--;)\n{\n // info is namespaced in a closure the click handler can access!\n (function(info)\n { \n nodes[i].onclick = function(){ showStuff(info) };\n })(data[i]);\n}\n</code></pre>\n\n<p>or the with statement equivilent of a closure</p>\n\n<pre><code>for(var i = nodes.length; i--;)\n{\n // info is namespaced in a closure the click handler can access!\n with({info: data[i]})\n { \n nodes[i].onclick = function(){ showStuff(info) };\n } \n}\n</code></pre>\n\n<p>I think the real risk is accidently minipulating variables that are not part of the with statement, which is why I like the object literal being passed into with, you can see exactly what it will be in the added context in the code.</p>\n" }, { "answer_id": 3122593, "author": "Jonah", "author_id": 376785, "author_profile": "https://Stackoverflow.com/users/376785", "pm_score": 3, "selected": false, "text": "<p>Using \"with\" can make your code more dry.</p>\n\n<p>Consider the following code:</p>\n\n<pre><code>var photo = document.getElementById('photo');\nphoto.style.position = 'absolute';\nphoto.style.left = '10px';\nphoto.style.top = '10px';\n</code></pre>\n\n<p>You can dry it to the following:</p>\n\n<pre><code>with(document.getElementById('photo').style) {\n position = 'absolute';\n left = '10px';\n top = '10px';\n}\n</code></pre>\n\n<p>I guess it depends whether you have a preference for legibility or expressiveness. </p>\n\n<p>The first example is more legible and probably recommended for most code. But most code is pretty tame anyway. The second one is a bit more obscure but uses the expressive nature of the language to cut down on code size and superfluous variables.</p>\n\n<p>I imagine people who like Java or C# would choose the first way (object.member) and those who prefer Ruby or Python would choose the latter.</p>\n" }, { "answer_id": 3471239, "author": "palswim", "author_id": 393280, "author_profile": "https://Stackoverflow.com/users/393280", "pm_score": 2, "selected": false, "text": "<p>I created a \"merge\" function which eliminates some of this ambiguity with the <code>with</code> statement:</p>\n\n<pre><code>if (typeof Object.merge !== 'function') {\n Object.merge = function (o1, o2) { // Function to merge all of the properties from one object into another\n for(var i in o2) { o1[i] = o2[i]; }\n return o1;\n };\n}\n</code></pre>\n\n<p>I can use it similarly to <code>with</code>, but I can know it won't affect any scope which I don't intend for it to affect.</p>\n\n<p>Usage:</p>\n\n<pre><code>var eDiv = document.createElement(\"div\");\nvar eHeader = Object.merge(eDiv.cloneNode(false), {className: \"header\", onclick: function(){ alert(\"Click!\"); }});\nfunction NewObj() {\n Object.merge(this, {size: 4096, initDate: new Date()});\n}\n</code></pre>\n" }, { "answer_id": 3637640, "author": "Jordão", "author_id": 31158, "author_profile": "https://Stackoverflow.com/users/31158", "pm_score": 3, "selected": false, "text": "<p>You can use <code>with</code> to introduce the contents of an object as local variables to a block, like it's being done with this <a href=\"http://ejohn.org/blog/javascript-micro-templating/\" rel=\"noreferrer\">small template engine</a>.</p>\n" }, { "answer_id": 3666255, "author": "Elvis Salaris", "author_id": 442248, "author_profile": "https://Stackoverflow.com/users/442248", "pm_score": 1, "selected": false, "text": "<p>You got to see the validation of a form in javascript at W3schools <a href=\"http://www.w3schools.com/js/js_form_validation.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/js/js_form_validation.asp</a> where the object form is \"scanned\" through to find an input with name 'email'</p>\n\n<p>But i've modified it to get from ANY form all the fields validate as not empty, regardless of the name or quantity of field in a form. Well i've tested only text-fields.</p>\n\n<p>But the with() made things simpler. Here's the code:</p>\n\n<pre><code>function validate_required(field)\n{\nwith (field)\n {\n if (value==null||value==\"\")\n {\n alert('All fields are mandtory');return false;\n }\n else\n {\n return true;\n }\n }\n}\n\nfunction validate_form(thisform)\n{\nwith (thisform)\n {\n for(fiie in elements){\n if (validate_required(elements[fiie])==false){\n elements[fiie].focus();\n elements[fiie].style.border='1px solid red';\n return false;\n } else {elements[fiie].style.border='1px solid #7F9DB9';}\n }\n\n }\n return false;\n}\n</code></pre>\n" }, { "answer_id": 3976785, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 6, "selected": false, "text": "<p>I actually found the <code>with</code> statement to be incredibly useful recently. This technique never really occurred to me until I started my current project - a command line console written in JavaScript. I was trying to emulate the Firebug/WebKit console APIs where special commands can be entered into the console but they don't override any variables in the global scope. I thought of this when trying to overcome a problem I mentioned in the comments to <a href=\"https://stackoverflow.com/questions/61552/are-there-legitimate-uses-for-javascripts-with-statement/185283#185283\">Shog9's excellent answer</a>.</p>\n\n<p>To achieve this effect, I used two with statements to \"layer\" a scope behind the global scope:</p>\n\n<pre><code>with (consoleCommands) {\n with (window) {\n eval(expression); \n }\n}\n</code></pre>\n\n<p>The great thing about this technique is that, aside from the performance disadvantages, it doesn't suffer the usual fears of the <code>with</code> statement, because we're evaluating in the global scope anyway - there's no danger of variables outside our pseudo-scope from being modified. </p>\n\n<p>I was inspired to post this answer when, to my surprise, I managed to find the same technique used elsewhere - the <a href=\"https://chromium.googlesource.com/chromium/blink/+/791be071ca6682c629942f3e19c24cf997582a97/WebCore/inspector/front-end/InjectedScript.js#545\" rel=\"noreferrer\">Chromium source code</a>!</p>\n\n<pre><code>InjectedScript._evaluateOn = function(evalFunction, object, expression) {\n InjectedScript._ensureCommandLineAPIInstalled();\n // Surround the expression in with statements to inject our command line API so that\n // the window object properties still take more precedent than our API functions.\n expression = \"with (window._inspectorCommandLineAPI) { with (window) { \" + expression + \" } }\";\n return evalFunction.call(object, expression);\n}\n</code></pre>\n\n<p><strong>EDIT:</strong> Just checked the Firebug source, they <a href=\"http://code.google.com/p/fbug/source/browse/branches/eval/content/firebug/commandLine.js#16\" rel=\"noreferrer\">chain 4 with statements together</a> for even more layers. Crazy!</p>\n\n<pre><code>const evalScript = \"with (__win__.__scope__.vars) { with (__win__.__scope__.api) { with (__win__.__scope__.userVars) { with (__win__) {\" +\n \"try {\" +\n \"__win__.__scope__.callback(eval(__win__.__scope__.expr));\" +\n \"} catch (exc) {\" +\n \"__win__.__scope__.callback(exc, true);\" +\n \"}\" +\n\"}}}}\";\n</code></pre>\n" }, { "answer_id": 6360857, "author": "Trevor Burnham", "author_id": 66226, "author_profile": "https://Stackoverflow.com/users/66226", "pm_score": 1, "selected": false, "text": "<p>CoffeeScript's <a href=\"http://github.com/satyr/coco\" rel=\"nofollow\">Coco</a> fork has a <code>with</code> keyword, but it simply sets <code>this</code> (also writable as <code>@</code> in CoffeeScript/Coco) to the target object within the block. This removes ambiguity and achieves ES5 strict mode compliance:</p>\n\n<pre><code>with long.object.reference\n @a = 'foo'\n bar = @b\n</code></pre>\n" }, { "answer_id": 10077345, "author": "rplantiko", "author_id": 1092785, "author_profile": "https://Stackoverflow.com/users/1092785", "pm_score": 2, "selected": false, "text": "<p>For some short code pieces, I would like to use the trigonometric functions like <code>sin</code>, <code>cos</code> etc. in degree mode instead of in radiant mode. For this purpose, I use an <code>AngularDegree</code>object: </p>\n\n<pre class=\"lang-js prettyprint-override\"><code>AngularDegree = new function() {\nthis.CONV = Math.PI / 180;\nthis.sin = function(x) { return Math.sin( x * this.CONV ) };\nthis.cos = function(x) { return Math.cos( x * this.CONV ) };\nthis.tan = function(x) { return Math.tan( x * this.CONV ) };\nthis.asin = function(x) { return Math.asin( x ) / this.CONV };\nthis.acos = function(x) { return Math.acos( x ) / this.CONV };\nthis.atan = function(x) { return Math.atan( x ) / this.CONV };\nthis.atan2 = function(x,y) { return Math.atan2(x,y) / this.CONV };\n};\n</code></pre>\n\n<p>Then I can use the trigonometric functions in degree mode without further language noise in a <code>with</code> block: </p>\n\n<pre><code>function getAzimut(pol,pos) {\n ...\n var d = pos.lon - pol.lon;\n with(AngularDegree) {\n var z = atan2( sin(d), cos(pol.lat)*tan(pos.lat) - sin(pol.lat)*cos(d) );\n return z;\n }\n }\n</code></pre>\n\n<p>This means: I use an object as a collection of functions, which I enable in a limited code region for direct access. I find this useful.</p>\n" }, { "answer_id": 13052179, "author": "ianaz", "author_id": 704916, "author_profile": "https://Stackoverflow.com/users/704916", "pm_score": 3, "selected": false, "text": "<p>Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with\" rel=\"noreferrer\">Source: Mozilla.org</a></p>\n" }, { "answer_id": 14428133, "author": "avanderveen", "author_id": 1472460, "author_profile": "https://Stackoverflow.com/users/1472460", "pm_score": 0, "selected": false, "text": "<p>Here's a good use for <code>with</code>: adding new elements to an Object Literal, based on values stored in that Object. Here's an example that I just used today:</p>\n\n<p>I had a set of possible tiles (with openings facing top, bottom, left, or right) that could be used, and I wanted a quick way of adding a list of tiles which would be always placed and locked at the start of the game. I didn't want to keep typing <code>types.tbr</code> for each type in the list, so I just used <code>with</code>.</p>\n\n<pre><code>Tile.types = (function(t,l,b,r) {\n function j(a) { return a.join(' '); }\n // all possible types\n var types = { \n br: j( [b,r]),\n lbr: j([l,b,r]),\n lb: j([l,b] ), \n tbr: j([t,b,r]),\n tbl: j([t,b,l]),\n tlr: j([t,l,r]),\n tr: j([t,r] ), \n tl: j([t,l] ), \n locked: []\n }; \n // store starting (base/locked) tiles in types.locked\n with( types ) { locked = [ \n br, lbr, lbr, lb, \n tbr, tbr, lbr, tbl,\n tbr, tlr, tbl, tbl,\n tr, tlr, tlr, tl\n ] } \n return types;\n})(\"top\",\"left\",\"bottom\",\"right\");\n</code></pre>\n" }, { "answer_id": 19012662, "author": "Dexygen", "author_id": 34806, "author_profile": "https://Stackoverflow.com/users/34806", "pm_score": 0, "selected": false, "text": "<p>You can use <code>with</code> to avoid having to explicitly manage arity when using require.js:</p>\n<pre><code>var modules = requirejs.declare([{\n 'App' : 'app/app'\n}]);\n\nrequire(modules.paths(), function() { with (modules.resolve(arguments)) {\n App.run();\n}});\n</code></pre>\n<p>Implementation of requirejs.declare:</p>\n<pre><code>requirejs.declare = function(dependencyPairs) {\n var pair;\n var dependencyKeys = [];\n var dependencyValues = [];\n\n for (var i=0, n=dependencyPairs.length; i&lt;n; i++) {\n pair = dependencyPairs[i];\n for (var key in dependencyPairs[i]) {\n dependencyKeys.push(key);\n dependencyValues.push(pair[key]);\n break;\n }\n };\n\n return {\n paths : function() {\n return dependencyValues;\n },\n \n resolve : function(args) {\n var modules = {};\n for (var i=0, n=args.length; i&lt;n; i++) {\n modules[dependencyKeys[i]] = args[i];\n }\n return modules;\n }\n } \n}\n</code></pre>\n" }, { "answer_id": 23285657, "author": "Jackson", "author_id": 1468130, "author_profile": "https://Stackoverflow.com/users/1468130", "pm_score": 0, "selected": false, "text": "<p>As Andy E pointed out in the comments of Shog9's answer, this potentially-unexpected behavior occurs when using <code>with</code> with an object literal:</p>\n\n<pre><code>for (var i = 0; i &lt; 3; i++) {\n function toString() {\n return 'a';\n }\n with ({num: i}) {\n setTimeout(function() { console.log(num); }, 10);\n console.log(toString()); // prints \"[object Object]\"\n }\n}\n</code></pre>\n\n<p>Not that unexpected behavior wasn't <em>already</em> a hallmark of <code>with</code>.</p>\n\n<p>If you really still want to use this technique, at least use an object with a null prototype.</p>\n\n<pre><code>function scope(o) {\n var ret = Object.create(null);\n if (typeof o !== 'object') return ret;\n Object.keys(o).forEach(function (key) {\n ret[key] = o[key];\n });\n return ret;\n}\n\nfor (var i = 0; i &lt; 3; i++) {\n function toString() {\n return 'a';\n }\n with (scope({num: i})) {\n setTimeout(function() { console.log(num); }, 10);\n console.log(toString()); // prints \"a\"\n }\n}\n</code></pre>\n\n<p>But this will only work in ES5+. Also don't use <code>with</code>.</p>\n" }, { "answer_id": 26707742, "author": "kevin.groat", "author_id": 2939688, "author_profile": "https://Stackoverflow.com/users/2939688", "pm_score": 0, "selected": false, "text": "<p>I am working on a project that will allow users to upload code in order to modify the behavior of parts of the application. In this scenario, I have been using a <code>with</code> clause to keep their code from modifying anything outside of the scope that I want them to mess around with. The (simplified) portion of code I use to do this is:</p>\n\n<pre><code>// this code is only executed once\nvar localScope = {\n build: undefined,\n\n // this is where all of the values I want to hide go; the list is rather long\n window: undefined,\n console: undefined,\n ...\n};\nwith(localScope) {\n build = function(userCode) {\n eval('var builtFunction = function(options) {' + userCode + '}');\n return builtFunction;\n }\n}\nvar build = localScope.build;\ndelete localScope.build;\n\n// this is how I use the build method\nvar userCode = 'return \"Hello, World!\";';\nvar userFunction = build(userCode);\n</code></pre>\n\n<p>This code ensures (somewhat) that the user-defined code neither has access to any globally-scoped objects such as <code>window</code> nor to any of my local variables through a closure.</p>\n\n<p>Just as a word to the wise, I still have to perform static code checks on the user-submitted code to ensure they aren't using other sneaky manners to access global scope. For instance, the following user-defined code grabs direct access to <code>window</code>:</p>\n\n<pre><code>test = function() {\n return this.window\n};\nreturn test();\n</code></pre>\n" }, { "answer_id": 29690322, "author": "user2782001", "author_id": 2782001, "author_profile": "https://Stackoverflow.com/users/2782001", "pm_score": -1, "selected": false, "text": "<p>Just wanted to add you can get \"with()\" functionality with pretty syntax and no ambiguity with your own clever method...</p>\n\n<pre><code> //utility function\n function _with(context){\n var ctx=context;\n this.set=function(obj){\n for(x in obj){\n //should add hasOwnProperty(x) here\n ctx[x]=obj[x];\n }\n } \n\n return this.set; \n }\n\n //how calling it would look in code...\n\n _with(Hemisphere.Continent.Nation.Language.Dialect.Alphabet)({\n\n a:\"letter a\",\n b:\"letter b\",\n c:\"letter c\",\n d:\"letter a\",\n e:\"letter b\",\n f:\"letter c\",\n // continue through whole alphabet...\n\n });//look how readable I am!!!!\n</code></pre>\n\n<p>..or if you <em>really</em> want to use \"with()\" without ambiguity and no custom method, wrap it in an anonymous function and use .call </p>\n\n<pre><code>//imagine a deeply nested object \n//Hemisphere.Continent.Nation.Language.Dialect.Alphabet\n(function(){\n with(Hemisphere.Continent.Nation.Language.Dialect.Alphabet){ \n this.a=\"letter a\";\n this.b=\"letter b\";\n this.c=\"letter c\";\n this.d=\"letter a\";\n this.e=\"letter b\";\n this.f=\"letter c\";\n // continue through whole alphabet...\n }\n}).call(Hemisphere.Continent.Nation.Language.Dialect.Alphabet)\n</code></pre>\n\n<p>However as others have pointed out, its somewhat pointless since you can do...</p>\n\n<pre><code> //imagine a deeply nested object Hemisphere.Continent.Nation.Language.Dialect.Alphabet\n var ltr=Hemisphere.Continent.Nation.Language.Dialect.Alphabet \n ltr.a=\"letter a\";\n ltr.b=\"letter b\";\n ltr.c=\"letter c\";\n ltr.d=\"letter a\";\n ltr.e=\"letter b\";\n ltr.f=\"letter c\";\n // continue through whole alphabet...\n</code></pre>\n" }, { "answer_id": 37640530, "author": "Little Alien", "author_id": 6267925, "author_profile": "https://Stackoverflow.com/users/6267925", "pm_score": 1, "selected": false, "text": "<p>My </p>\n\n<pre><code>switch(e.type) {\n case gapi.drive.realtime.ErrorType.TOKEN_REFRESH_REQUIRED: blah\n case gapi.drive.realtime.ErrorType.CLIENT_ERROR: blah\n case gapi.drive.realtime.ErrorType.NOT_FOUND: blah\n}\n</code></pre>\n\n<p>boils down to</p>\n\n<pre><code>with(gapi.drive.realtime.ErrorType) {switch(e.type) {\n case TOKEN_REFRESH_REQUIRED: blah\n case CLIENT_ERROR: blah\n case NOT_FOUND: blah\n}}\n</code></pre>\n\n<p>Can you trust so low-quality code? No, we see that it was made absolutely unreadable. This example undeniably proves that there is no need for with-statement, if I am taking readability right ;)</p>\n" }, { "answer_id": 65077825, "author": "shabaany", "author_id": 12220097, "author_profile": "https://Stackoverflow.com/users/12220097", "pm_score": 1, "selected": false, "text": "<p><strong>using &quot;with&quot; statement with proxy objects</strong></p>\n<p>I recently want to write a plugin for <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">babel</a> that enables macros. I would like to have a separate variable namespace that keeps my macro variables, and I can run my macro codes in that space. Also, I want to detect new variables that are defined in the macro codes(Because they are new macros).</p>\n<p>First, I choose the <a href=\"https://nodejs.org/api/vm.html\" rel=\"nofollow noreferrer\">vm</a> module, but I found global variables in the vm module like Array, Object, etc. are different from the main program, and I cant implement <code>module</code> and <code>require</code> that be fully compatible with that global objects(Because I cant reconstruct the core modules). In the end, I find the &quot;with&quot; statement.</p>\n<pre><code>const runInContext = function(code, context) {\n context.global = context;\n const proxyOfContext = new Proxy(context, { has: () =&gt; true });\n let run = new Function(\n &quot;proxyOfContext&quot;,\n `\n with(proxyOfContext){\n with(global){\n ${code}\n }\n }\n `\n );\n return run(proxyOfContext);\n};\n</code></pre>\n<p>This proxy object traps search of all variables and says: &quot;yes, I have that variable.&quot; and If the proxy object doesn't really have that variable, show its value as <code>undefined</code>.</p>\n<p>In this way, if any variable is defined in the macro <code>code</code> with the <code>var</code> statement, I can find it in the context object(like the vm module). But variables that are defined with <code>let</code> or <code>const</code> only available in that time and will not be saved in the context object(the vm module saves them but doesn't expose them).</p>\n<p><strong>Performance</strong>: Performance of this method is better than <code>vm.runInContext</code>.</p>\n<p><strong>safety</strong>: If you want to run code in a sandbox, this is not safe in any way, and you must use the vm module. It only provides a new namespace.</p>\n" }, { "answer_id": 73360501, "author": "nzn", "author_id": 932256, "author_profile": "https://Stackoverflow.com/users/932256", "pm_score": 0, "selected": false, "text": "<p><code>with</code> is useful coupled with shorthand object notation when you need to transform object structures from flat to hierarchical. So if you have:</p>\n<pre><code>var a = {id: 123, name: 'abc', attr1: 'efg', attr2: 'zxvc', attr3: '4321'};\n</code></pre>\n<p>So instead of:</p>\n<pre><code>var b = {\n id: a.id,\n name: a.name\n metadata: {name: a.name, attr1: a.attr1}\n extrastuff: {attr2: a.attr2, attr3: a.attr3}\n}\n</code></pre>\n<p>You can simply write:</p>\n<pre><code>with (a) {\n var b = {\n id,\n name,\n metadata: {name, attr1}\n extrastuff: {attr2, attr3}\n }\n}\n</code></pre>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/811/" ]
[Alan Storm's comments](http://www.stackoverflow.com/questions/61088/hidden-features-of-javascript#61118) in response to my answer regarding the [`with` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with) got me thinking. I've seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I'm curious as to how I might make effective use of `with`, while avoiding its pitfalls. Where have you found the `with` statement useful?
Another use occurred to me today, so I searched the web excitedly and found an existing mention of it: [Defining Variables inside Block Scope](http://web.archive.org/web/20090111183416/http://www.hedgerwow.com/360/dhtml/js_block_scope.html). ### Background JavaScript, in spite of its superficial resemblance to C and C++, does not scope variables to the block they are defined in: ``` var name = "Joe"; if ( true ) { var name = "Jack"; } // name now contains "Jack" ``` Declaring a closure in a loop is a common task where this can lead to errors: ``` for (var i=0; i<3; ++i) { var num = i; setTimeout(function() { alert(num); }, 10); } ``` Because the for loop does not introduce a new scope, the same `num` - with a value of `2` - will be shared by all three functions. ### A new scope: `let` and `with` With the introduction of the `let` statement in [ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), it becomes easy to introduce a new scope when necessary to avoid these problems: ``` // variables introduced in this statement // are scoped to each iteration of the loop for (let i=0; i<3; ++i) { setTimeout(function() { alert(i); }, 10); } ``` Or even: ``` for (var i=0; i<3; ++i) { // variables introduced in this statement // are scoped to the block containing it. let num = i; setTimeout(function() { alert(num); }, 10); } ``` Until ES6 is universally available, this use remains limited to the newest browsers and developers willing to use transpilers. However, we can easily simulate this behavior using `with`: ``` for (var i=0; i<3; ++i) { // object members introduced in this statement // are scoped to the block following it. with ({num: i}) { setTimeout(function() { alert(num); }, 10); } } ``` The loop now works as intended, creating three separate variables with values from 0 to 2. Note that variables declared *within* the block are not scoped to it, unlike the behavior of blocks in C++ (in C, variables must be declared at the start of a block, so in a way it is similar). This behavior is actually quite similar to a [`let` block syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#let_blocks) introduced in earlier versions of Mozilla browsers, but not widely adopted elsewhere.
61,604
<p>Do you often see in API documentation (as in 'javadoc of public functions' for example) the description of "value limits" as well as the classic documentation ?</p> <p><strong>Note:</strong> I am not talking about <a href="https://stackoverflow.com/questions/20922/do-you-comment-your-code">comments within the code</a></p> <p>By "value limits", I mean:</p> <ul> <li>does a parameter can support a null value (or an empty String, or...) ?</li> <li>does a 'return value' can be null or is guaranteed to never be null (or can be "empty", or...) ?</li> </ul> <p><strong>Sample:</strong></p> <p>What I often see (without having access to source code) is:</p> <pre><code>/** * Get all readers name for this current Report. &lt;br /&gt; * &lt;b&gt;Warning&lt;/b&gt;The Report must have been published first. * @param aReaderNameRegexp filter in order to return only reader matching the regexp * @return array of reader names */ String[] getReaderNames(final String aReaderNameRegexp); </code></pre> <p>What I <em>like to see</em> would be:</p> <pre><code>/** * Get all readers name for this current Report. &lt;br /&gt; * &lt;b&gt;Warning&lt;/b&gt;The Report must have been published first. * @param aReaderNameRegexp filter in order to return only reader matching the regexp * (can be null or empty) * @return array of reader names * (null if Report has not yet been published, * empty array if no reader match criteria, * reader names array matching regexp, or all readers if regexp is null or empty) */ String[] getReaderNames(final String aReaderNameRegexp); </code></pre> <p><strong>My point is:</strong></p> <p>When I use a library with a getReaderNames() function in it, I often do not even need to read the API documentation to guess what it does. But I need to be sure <em>how to use it</em>.</p> <p>My only concern when I want to use this function is: what should I expect in term of parameters and return values ? That is all I need to know to safely setup my parameters and safely test the return value, yet I almost never see that kind of information in API documentation...</p> <p><strong>Edit:</strong> </p> <p>This can influence the usage or not for <em><a href="https://stackoverflow.com/questions/27578#73355">checked or unchecked exceptions</a></em>.</p> <p>What do you think ? value limits and API, do they belong together or not ?</p>
[ { "answer_id": 61608, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 1, "selected": false, "text": "<p>I think they do, and have always placed comments in the header files (c++) arcordingly.</p>\n\n<p>In addition to valid input/output/return comments, I also note which exceptions are likly to be thrown by the function (since I often want to use the return value for...well returning a value, I prefer exceptions over error codes)</p>\n\n<pre><code>//File:\n// Should be a path to the teexture file to load, if it is not a full path (eg \"c:\\example.png\") it will attempt to find the file usign the paths provided by the DataSearchPath list\n//Return: The pointer to a Texture instance is returned, in the event of an error, an exception is thrown. When you are finished with the texture you chould call the Free() method.\n//Exceptions:\n//except::FileNotFound\n//except::InvalidFile\n//except::InvalidParams\n//except::CreationFailed\nTexture *GetTexture(const std::string &amp;File);\n</code></pre>\n" }, { "answer_id": 61610, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "<p>I think those kinds of boundary conditions most definitely belong in the API. However, I would (and often do) go a step further and indicate WHAT those null values mean. Either I indicate it will throw an exception, or I explain what the expected results are when the boundary value is passed in.</p>\n\n<p>It's hard to remember to always do this, but it's a good thing for users of your class. It's also difficult to maintain it if the contract the method presents changes (like null values are changed to no be allowed)... you have to be diligent also to update the docs when you change the semantics of the method.</p>\n" }, { "answer_id": 61612, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 4, "selected": true, "text": "<p>I think they <strong>can</strong> belong together but don't necessarily <strong>have</strong> to belong together. In your scenario, it seems like it makes sense that the limits are documented in such a way that they appear in the generated API documentation and intellisense (if the language/IDE support it).</p>\n\n<p>I think it does depend on the language as well. For example, Ada has a native data type that is a \"restricted integer\", where you define an integer variable and explicitly indicate that it will only (and always) be within a certain numeric range. In that case, the datatype itself indicates the restriction. It should still be visible and discoverable through the API documentation and intellisense, but wouldn't be something that a developer has to specify in the comments.</p>\n\n<p>However, languages like Java and C# don't have this type of restricted integer, so the developer would have to specify it in the comments if it were information that should become part of the public documentation.</p>\n" }, { "answer_id": 61631, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "<p>@Fire Lancer: Right! I forgot about exception, but I would like to see them mentioned, especially the unchecked 'runtime' exception that this public method could throw</p>\n\n<p>@Mike Stone: </p>\n\n<blockquote>\n <p>you have to be diligent also to update the docs when you change the semantics of the method.</p>\n</blockquote>\n\n<p>Mmmm I sure hope that the <em>public API documentation</em> is at the very least updated whenever a change -- that affects the contract of the function -- takes place. If not, those API documentations could be drop altogether.</p>\n\n<p>To add food to yours thoughts (and go with @Scott Dorman), I just stumble upon <a href=\"http://today.java.net/pub/a/today/2008/09/11/jsr-305-annotations.html\" rel=\"nofollow noreferrer\">the future of java7 annotations</a></p>\n\n<p>What does that means ? That certain 'boundary conditions', rather than being in the documentation, should be better off in the API itself, and automatically used, at compilation time, with appropriate 'assert' generated code.</p>\n\n<p>That way, if a '@CheckForNull' is in the API, the writer of the function might get away with not even documenting it! And if the semantic change, its API will reflect that change (like 'no more @CheckForNull' for instance)</p>\n\n<p>That kind of approach suggests that documentation, for 'boundary conditions', is an extra bonus rather than a mandatory practice.</p>\n\n<p>However, that does not cover the special values of the return object of a function. For that, a <em>complete</em> documentation is still needed.</p>\n" }, { "answer_id": 24224149, "author": "taringamberini", "author_id": 1972317, "author_profile": "https://Stackoverflow.com/users/1972317", "pm_score": 2, "selected": false, "text": "<p><strong>Question 1</strong></p>\n\n<blockquote>\n <p>Do you often see in API documentation (as in 'javadoc of public functions' for example) the description of \"value limits\" as well as the classic documentation?</p>\n</blockquote>\n\n<p>Almost never.</p>\n\n<p><strong>Question 2</strong></p>\n\n<blockquote>\n <p>My only concern when I want to use this function is: what should I expect in term of parameters and return values ? That is all I need to know to safely setup my parameters and safely test the return value, yet I almost never see that kind of information in API documentation...</p>\n</blockquote>\n\n<p>If I used a function not properly I would expect a <code>RuntimeException</code> thrown by the method or a <code>RuntimeException</code> in another (sometimes very far) part of the program.</p>\n\n<p>Comments like <code>@param aReaderNameRegexp filter in order to ... (can be null or empty)</code> seems to me a way to implement <strong><a href=\"http://en.wikipedia.org/wiki/Design_by_contract\" rel=\"nofollow noreferrer\">Design by Contract</a></strong> in a human-being language inside <a href=\"http://en.wikipedia.org/wiki/Javadoc\" rel=\"nofollow noreferrer\">Javadoc</a>.</p>\n\n<p>Using Javadoc to enforce Design by Contract was used by <code>iContract</code>, now resurrected into <a href=\"http://jcontracts.sourceforge.net/addingContracts.html\" rel=\"nofollow noreferrer\"><code>JcontractS</code></a>, that let you specify <em>invariants, preconditions, postconditions</em>, in more formalized way compared to the human-being language.</p>\n\n<p><strong>Question 3</strong></p>\n\n<blockquote>\n <p>This can influence the usage or not for checked or unchecked exceptions.\n What do you think ? value limits and API, do they belong together or not ?</p>\n</blockquote>\n\n<p>Java language doesn't have a Design by Contract feature, so you might be tempted to use <code>Execption</code> but I agree with you about the fact that you have to be aware about <a href=\"https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions#73355\">When to choose checked and unchecked exceptions</a>. Probably you might use unchecked <code>IllegalArgumentException</code>, <code>IllegalStateException</code>, or you might use unit testing, but the major problem is how to communicate to other programmers that such code is about Design By Contract and should be considered as a contract before changing it too lightly.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6309/" ]
Do you often see in API documentation (as in 'javadoc of public functions' for example) the description of "value limits" as well as the classic documentation ? **Note:** I am not talking about [comments within the code](https://stackoverflow.com/questions/20922/do-you-comment-your-code) By "value limits", I mean: * does a parameter can support a null value (or an empty String, or...) ? * does a 'return value' can be null or is guaranteed to never be null (or can be "empty", or...) ? **Sample:** What I often see (without having access to source code) is: ``` /** * Get all readers name for this current Report. <br /> * <b>Warning</b>The Report must have been published first. * @param aReaderNameRegexp filter in order to return only reader matching the regexp * @return array of reader names */ String[] getReaderNames(final String aReaderNameRegexp); ``` What I *like to see* would be: ``` /** * Get all readers name for this current Report. <br /> * <b>Warning</b>The Report must have been published first. * @param aReaderNameRegexp filter in order to return only reader matching the regexp * (can be null or empty) * @return array of reader names * (null if Report has not yet been published, * empty array if no reader match criteria, * reader names array matching regexp, or all readers if regexp is null or empty) */ String[] getReaderNames(final String aReaderNameRegexp); ``` **My point is:** When I use a library with a getReaderNames() function in it, I often do not even need to read the API documentation to guess what it does. But I need to be sure *how to use it*. My only concern when I want to use this function is: what should I expect in term of parameters and return values ? That is all I need to know to safely setup my parameters and safely test the return value, yet I almost never see that kind of information in API documentation... **Edit:** This can influence the usage or not for *[checked or unchecked exceptions](https://stackoverflow.com/questions/27578#73355)*. What do you think ? value limits and API, do they belong together or not ?
I think they **can** belong together but don't necessarily **have** to belong together. In your scenario, it seems like it makes sense that the limits are documented in such a way that they appear in the generated API documentation and intellisense (if the language/IDE support it). I think it does depend on the language as well. For example, Ada has a native data type that is a "restricted integer", where you define an integer variable and explicitly indicate that it will only (and always) be within a certain numeric range. In that case, the datatype itself indicates the restriction. It should still be visible and discoverable through the API documentation and intellisense, but wouldn't be something that a developer has to specify in the comments. However, languages like Java and C# don't have this type of restricted integer, so the developer would have to specify it in the comments if it were information that should become part of the public documentation.
61,605
<p>In python, you can have a function return multiple values. Here's a contrived example:</p> <pre><code>def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) </code></pre> <p>This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also").</p> <p>When should you draw the line and define a different method? </p>
[ { "answer_id": 61629, "author": "Jason Etheridge", "author_id": 2193, "author_profile": "https://Stackoverflow.com/users/2193", "pm_score": 5, "selected": false, "text": "<p>Firstly, note that Python allows for the following (no need for the parenthesis):</p>\n\n<pre><code>q, r = divide(22, 7)\n</code></pre>\n\n<p>Regarding your question, there's no hard and fast rule either way. For simple (and usually contrived) examples, it may seem that it's always possible for a given function to have a single purpose, resulting in a single value. However, when using Python for real-world applications, you quickly run into many cases where returning multiple values is necessary, and results in cleaner code.</p>\n\n<p>So, I'd say do whatever makes sense, and don't try to conform to an artificial convention. Python supports multiple return values, so use it when appropriate.</p>\n" }, { "answer_id": 61636, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 8, "selected": true, "text": "<p>Absolutely (for the example you provided).</p>\n\n<h3>Tuples are first class citizens in Python</h3>\n\n<p>There is a builtin function <a href=\"https://docs.python.org/3/library/functions.html#divmod\" rel=\"noreferrer\"><code>divmod()</code></a> that does exactly that.</p>\n\n<pre><code>q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x\n</code></pre>\n\n<p>There are other examples: <code>zip</code>, <code>enumerate</code>, <code>dict.items</code>. </p>\n\n<pre><code>for i, e in enumerate([1, 3, 3]):\n print \"index=%d, element=%s\" % (i, e)\n\n# reverse keys and values in a dictionary\nd = dict((v, k) for k, v in adict.items()) # or \nd = dict(zip(adict.values(), adict.keys()))\n</code></pre>\n\n<p>BTW, parentheses are not necessary most of the time.\nCitation from <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=type%20seq#tuple\" rel=\"noreferrer\">Python Library Reference</a>: </p>\n\n<blockquote>\n <p>Tuples may be constructed in a number of ways:</p>\n \n <ul>\n <li>Using a pair of parentheses to denote the empty tuple: ()</li>\n <li>Using a trailing comma for a singleton tuple: a, or (a,)</li>\n <li>Separating items with commas: a, b, c or (a, b, c)</li>\n <li>Using the tuple() built-in: tuple() or tuple(iterable)</li>\n </ul>\n</blockquote>\n\n<h3>Functions should serve single purpose</h3>\n\n<p>Therefore they should return a single object. In your case this object is a tuple. Consider tuple as an ad-hoc compound data structure. There are languages where almost every single function returns multiple values (list in Lisp).</p>\n\n<p>Sometimes it is sufficient to return <code>(x, y)</code> instead of <code>Point(x, y)</code>.</p>\n\n<h3>Named tuples</h3>\n\n<p>With the introduction of named tuples in Python 2.6 it is preferable in many cases to return named tuples instead of plain tuples.</p>\n\n<pre><code>&gt;&gt;&gt; import collections\n&gt;&gt;&gt; Point = collections.namedtuple('Point', 'x y')\n&gt;&gt;&gt; x, y = Point(0, 1)\n&gt;&gt;&gt; p = Point(x, y)\n&gt;&gt;&gt; x, y, p\n(0, 1, Point(x=0, y=1))\n&gt;&gt;&gt; p.x, p.y, p[0], p[1]\n(0, 1, 0, 1)\n&gt;&gt;&gt; for i in p:\n... print(i)\n...\n0\n1\n</code></pre>\n" }, { "answer_id": 61637, "author": "Nathan Jones", "author_id": 5848, "author_profile": "https://Stackoverflow.com/users/5848", "pm_score": 4, "selected": false, "text": "<p>The example you give is actually a python builtin function, called <code>divmod</code>. So someone, at some point in time, thought that it was pythonic enough to include in the core functionality.</p>\n\n<p>To me, if it makes the code cleaner, it is pythonic. Compare these two code blocks:</p>\n\n<pre><code>seconds = 1234\nminutes, seconds = divmod(seconds, 60)\nhours, minutes = divmod(minutes, 60)\n\nseconds = 1234\nminutes = seconds / 60\nseconds = seconds % 60\nhours = minutes / 60\nminutes = minutes % 60\n</code></pre>\n" }, { "answer_id": 63528, "author": "Will Harris", "author_id": 4702, "author_profile": "https://Stackoverflow.com/users/4702", "pm_score": 0, "selected": false, "text": "<p>It's fine to return multiple values using a tuple for simple functions such as <code>divmod</code>. If it makes the code readable, it's Pythonic.</p>\n\n<p>If the return value starts to become confusing, check whether the function is doing too much and split it if it is. If a big tuple is being used like an object, make it an object. Also, consider using <a href=\"http://code.activestate.com/recipes/500261/\" rel=\"nofollow noreferrer\">named tuples</a>, which will be part of the standard library in Python 2.6.</p>\n" }, { "answer_id": 63549, "author": "indentation", "author_id": 7706, "author_profile": "https://Stackoverflow.com/users/7706", "pm_score": 1, "selected": false, "text": "<p>It's definitely pythonic. The fact that you can return multiple values from a function the boilerplate you would have in a language like C where you need to define a struct for every combination of types you return somewhere.</p>\n\n<p>However, if you reach the point where you are returning something crazy like 10 values from a single function, you should seriously consider bundling them in a class because at that point it gets unwieldy.</p>\n" }, { "answer_id": 63809, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 1, "selected": false, "text": "<p>Returning a tuple is cool. Also note the new namedtuple\nwhich was added in python 2.6 which may make this more palatable for you:\n<a href=\"http://docs.python.org/dev/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\">http://docs.python.org/dev/library/collections.html#collections.namedtuple</a></p>\n" }, { "answer_id": 64110, "author": "zweiterlinde", "author_id": 6592, "author_profile": "https://Stackoverflow.com/users/6592", "pm_score": 2, "selected": false, "text": "<p>Yes, returning multiple values (i.e., a tuple) is definitely pythonic. As others have pointed out, there are plenty of examples in the Python standard library, as well as in well-respected Python projects. Two additional comments:</p>\n\n<ol>\n<li>Returning multiple values is sometimes very, very useful. Take, for example, a method that optionally handles an event (returning some value in doing so) and also returns success or failure. This might arise in a chain of responsibility pattern. In other cases, you want to return multiple, closely linked pieces of data---as in the example given. In this setting, returning multiple values is akin to returning a single instance of an anonymous class with several member variables.</li>\n<li><p>Python's handling of method arguments necessitates the ability to directly return multiple values. In C++, for example, method arguments can be passed by reference, so you can assign output values to them, in addition to the formal return value. In Python, arguments are passed \"by reference\" (but in the sense of Java, not C++). You can't assign new values to method arguments and have it reflected outside method scope. For example:</p>\n\n<pre><code>// C++\nvoid test(int&amp; arg)\n{\n arg = 1;\n}\n\nint foo = 0;\ntest(foo); // foo is now 1!\n</code></pre>\n\n<p>Compare with:</p>\n\n<pre><code># Python\ndef test(arg):\n arg = 1\n\nfoo = 0\ntest(foo) # foo is still 0\n</code></pre></li>\n</ol>\n" }, { "answer_id": 66967, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 0, "selected": false, "text": "<p>I'm fairly new to Python, but the tuple technique seems very pythonic to me. However, I've had another idea that may enhance readability. Using a dictionary allows access to the different values by name rather than position. For example:</p>\n\n<pre><code>def divide(x, y):\n return {'quotient': x/y, 'remainder':x%y }\n\nanswer = divide(22, 7)\nprint answer['quotient']\nprint answer['remainder']\n</code></pre>\n" }, { "answer_id": 640632, "author": "NevilleDNZ", "author_id": 77431, "author_profile": "https://Stackoverflow.com/users/77431", "pm_score": 1, "selected": false, "text": "<p>OT: RSRE's Algol68 has the curious \"/:=\" operator. eg.</p>\n\n<pre><code>INT quotient:=355, remainder;\nremainder := (quotient /:= 113);\n</code></pre>\n\n<p>Giving a quotient of 3, and a remainder of 16. </p>\n\n<p>Note: typically the value of \"(x/:=y)\" is discarded as quotient \"x\" is assigned by reference, but in RSRE's case the returned value is the remainder.</p>\n\n<p>c.f. <a href=\"http://rosettacode.org/wiki/Basic_integer_arithmetic#ALGOL_68\" rel=\"nofollow noreferrer\">Integer Arithmetic - Algol68</a></p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
In python, you can have a function return multiple values. Here's a contrived example: ``` def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) ``` This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as an intermediate value. Let's have X return that value also"). When should you draw the line and define a different method?
Absolutely (for the example you provided). ### Tuples are first class citizens in Python There is a builtin function [`divmod()`](https://docs.python.org/3/library/functions.html#divmod) that does exactly that. ``` q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x ``` There are other examples: `zip`, `enumerate`, `dict.items`. ``` for i, e in enumerate([1, 3, 3]): print "index=%d, element=%s" % (i, e) # reverse keys and values in a dictionary d = dict((v, k) for k, v in adict.items()) # or d = dict(zip(adict.values(), adict.keys())) ``` BTW, parentheses are not necessary most of the time. Citation from [Python Library Reference](https://docs.python.org/3/library/stdtypes.html?highlight=type%20seq#tuple): > > Tuples may be constructed in a number of ways: > > > * Using a pair of parentheses to denote the empty tuple: () > * Using a trailing comma for a singleton tuple: a, or (a,) > * Separating items with commas: a, b, c or (a, b, c) > * Using the tuple() built-in: tuple() or tuple(iterable) > > > ### Functions should serve single purpose Therefore they should return a single object. In your case this object is a tuple. Consider tuple as an ad-hoc compound data structure. There are languages where almost every single function returns multiple values (list in Lisp). Sometimes it is sufficient to return `(x, y)` instead of `Point(x, y)`. ### Named tuples With the introduction of named tuples in Python 2.6 it is preferable in many cases to return named tuples instead of plain tuples. ``` >>> import collections >>> Point = collections.namedtuple('Point', 'x y') >>> x, y = Point(0, 1) >>> p = Point(x, y) >>> x, y, p (0, 1, Point(x=0, y=1)) >>> p.x, p.y, p[0], p[1] (0, 1, 0, 1) >>> for i in p: ... print(i) ... 0 1 ```
61,638
<p>I was wondering if anyone could suggest a utility library that has useful functions for handling dates in ASP.NET easily taking away some of the leg work you normally have to do when handling dates?</p> <p>Subsonic Sugar has some really nice functions:</p> <p><a href="http://subsonichelp.com/html/1413bafa-b5aa-99aa-0478-10875abe82ec.htm" rel="nofollow noreferrer">http://subsonichelp.com/html/1413bafa-b5aa-99aa-0478-10875abe82ec.htm</a> <a href="http://subsonicproject.googlecode.com/svn/trunk/SubSonic/Sugar/" rel="nofollow noreferrer">http://subsonicproject.googlecode.com/svn/trunk/SubSonic/Sugar/</a></p> <p>Is there anything better out there?</p> <p>I was wanting to work out the start(mon) and end(sun) dates of the last 5 weeks.</p> <p>I was thinking something like this:</p> <pre><code> DateTime Now = DateTime.Now; while(Now.DayOfWeek != DayOfWeek.Monday) { Now.AddDays(-1); } for(int i=0; i&lt;5;i++) { AddToDatesList(Now, Now.AddDays(7)); Now.AddDays(-7); } </code></pre> <p>but this seems crappy? Plus this is not exactly what i want because i need the time of that start date to be <code>00:00:00</code> and the time of the end date to be <code>23:59:59</code></p>
[ { "answer_id": 61645, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "<p>Is there a specific problem you are trying to handle with dates? If the existing date API in .NET can handle your problem cleanly, I see no reason to consider a 3rd party library to do it. When I was in .NET, we had to deal with dates quite a bit, and the standard libraries provided a fair amount of functionality to us.</p>\n" }, { "answer_id": 61698, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>What exactly do you want to do that System.DateTime and System.Timespan can't handle?</p>\n" }, { "answer_id": 62088, "author": "Rikalous", "author_id": 4271, "author_profile": "https://Stackoverflow.com/users/4271", "pm_score": 0, "selected": false, "text": "<p>CSLA has a useful helper class called SmartDate that addresses quite a lot of the problems when using dates in real applications. As far as I can recall it's coupled to the rest of the framework.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
I was wondering if anyone could suggest a utility library that has useful functions for handling dates in ASP.NET easily taking away some of the leg work you normally have to do when handling dates? Subsonic Sugar has some really nice functions: <http://subsonichelp.com/html/1413bafa-b5aa-99aa-0478-10875abe82ec.htm> <http://subsonicproject.googlecode.com/svn/trunk/SubSonic/Sugar/> Is there anything better out there? I was wanting to work out the start(mon) and end(sun) dates of the last 5 weeks. I was thinking something like this: ``` DateTime Now = DateTime.Now; while(Now.DayOfWeek != DayOfWeek.Monday) { Now.AddDays(-1); } for(int i=0; i<5;i++) { AddToDatesList(Now, Now.AddDays(7)); Now.AddDays(-7); } ``` but this seems crappy? Plus this is not exactly what i want because i need the time of that start date to be `00:00:00` and the time of the end date to be `23:59:59`
Is there a specific problem you are trying to handle with dates? If the existing date API in .NET can handle your problem cleanly, I see no reason to consider a 3rd party library to do it. When I was in .NET, we had to deal with dates quite a bit, and the standard libraries provided a fair amount of functionality to us.
61,675
<p>I'm reading lines of input on a TCP socket, similar to this:</p> <pre><code>class Bla def getcmd @sock.gets unless @sock.closed? end def start srv = TCPServer.new(5000) @sock = srv.accept while ! @sock.closed? ans = getcmd end end end </code></pre> <p>If the endpoint terminates the connection while getline() is running then gets() hangs. </p> <p>How can I work around this? Is it necessary to do non-blocking or timed I/O?</p>
[ { "answer_id": 61732, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": -1, "selected": false, "text": "<p>If you believe the <a href=\"http://www.ruby-doc.org/stdlib/libdoc/socket/rdoc/index.html\" rel=\"nofollow noreferrer\">rdoc</a> for ruby sockets, they don't implement <code>gets</code>. This leads me to believe gets is being provided by a higher level of abstraction (maybe the IO libraries?) and probably isn't aware of socket-specific things like 'connection closed.'</p>\n\n<p>Try using <a href=\"http://www.ruby-doc.org/stdlib/libdoc/socket/rdoc/classes/Socket.html#M004238\" rel=\"nofollow noreferrer\"><code>recvfrom</code></a> instead of <code>gets</code></p>\n" }, { "answer_id": 64313, "author": "manveru", "author_id": 8367, "author_profile": "https://Stackoverflow.com/users/8367", "pm_score": 3, "selected": false, "text": "<p>You can use select to see whether you can safely gets from the socket, see following implementation of a TCPServer using this technique.</p>\n\n<pre><code>require 'socket'\n\nhost, port = 'localhost', 7000\n\nTCPServer.open(host, port) do |server|\n while client = server.accept\n readfds = true\n got = nil\n begin\n readfds, writefds, exceptfds = select([client], nil, nil, 0.1)\n p :r =&gt; readfds, :w =&gt; writefds, :e =&gt; exceptfds\n\n if readfds\n got = client.gets \n p got\n end\n end while got\n end\nend\n</code></pre>\n\n<p>And here a client that tries to break the server:</p>\n\n<pre><code>require 'socket'\n\nhost, port = 'localhost', 7000\n\nTCPSocket.open(host, port) do |socket|\n socket.puts \"Hey there\"\n socket.write 'he'\n socket.flush\n socket.close\nend\n</code></pre>\n" }, { "answer_id": 92255, "author": "Roman", "author_id": 12695, "author_profile": "https://Stackoverflow.com/users/12695", "pm_score": 2, "selected": false, "text": "<p>The IO#closed? returns true when both reader and writer are closed.\nIn your case, the @sock.gets returns nil, and then you call the getcmd again, and this runs in a never ending loop. You can either use select, or close the socket when gets returns nil.</p>\n" }, { "answer_id": 6005803, "author": "Ben Flynn", "author_id": 449161, "author_profile": "https://Stackoverflow.com/users/449161", "pm_score": 0, "selected": false, "text": "<p>I recommend using readpartial to read from your socket and also catching peer resets:</p>\n\n<pre><code>while true\n sockets_ready = select(@sockets, nil, nil, nil)\n if sockets_ready != nil\n sockets_ready[0].each do |socket|\n begin\n if (socket == @server_socket)\n # puts \"Connection accepted!\"\n @sockets &lt;&lt; @server_socket.accept\n else\n # Received something on a client socket\n if socket.eof?\n # puts \"Disconnect!\"\n socket.close\n @sockets.delete(socket)\n else\n data = \"\"\n recv_length = 256\n while (tmp = socket.readpartial(recv_length))\n data += tmp\n break if (!socket.ready?)\n end\n listen socket, data\n end\n end\n rescue Exception =&gt; exception\n case exception\n when Errno::ECONNRESET,Errno::ECONNABORTED,Errno::ETIMEDOUT\n # puts \"Socket: #{exception.class}\"\n @sockets.delete(socket)\n else\n raise exception\n end\n end\n end\n end\n end\n</code></pre>\n\n<p>This code borrows heavily from some <a href=\"https://www6.software.ibm.com/developerworks/education/l-rubysocks/l-rubysocks-a4.pdf\" rel=\"nofollow\">nice IBM code</a> by M. Tim Jones. Note that @server_socket is initialized by: </p>\n\n<pre><code>@server_socket = TCPServer.open(port)\n</code></pre>\n\n<p>@sockets is just an array of sockets.</p>\n" }, { "answer_id": 36076434, "author": "wakeupbuddy", "author_id": 1464263, "author_profile": "https://Stackoverflow.com/users/1464263", "pm_score": 0, "selected": false, "text": "<p>I simply pgrep \"ruby\" to find the pid, and kill -9 the pid and restart.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3796/" ]
I'm reading lines of input on a TCP socket, similar to this: ``` class Bla def getcmd @sock.gets unless @sock.closed? end def start srv = TCPServer.new(5000) @sock = srv.accept while ! @sock.closed? ans = getcmd end end end ``` If the endpoint terminates the connection while getline() is running then gets() hangs. How can I work around this? Is it necessary to do non-blocking or timed I/O?
You can use select to see whether you can safely gets from the socket, see following implementation of a TCPServer using this technique. ``` require 'socket' host, port = 'localhost', 7000 TCPServer.open(host, port) do |server| while client = server.accept readfds = true got = nil begin readfds, writefds, exceptfds = select([client], nil, nil, 0.1) p :r => readfds, :w => writefds, :e => exceptfds if readfds got = client.gets p got end end while got end end ``` And here a client that tries to break the server: ``` require 'socket' host, port = 'localhost', 7000 TCPSocket.open(host, port) do |socket| socket.puts "Hey there" socket.write 'he' socket.flush socket.close end ```
61,677
<p>Suppose I have a COM object which users can access via a call such as:</p> <pre><code>Set s = CreateObject("Server") </code></pre> <p>What I'd like to be able to do is allow the user to specify an event handler for the object, like so:</p> <pre><code>Function ServerEvent MsgBox "Event handled" End Function s.OnDoSomething = ServerEvent </code></pre> <p>Is this possible and, if so, how do I expose this in my type library in C++ (specifically BCB 2007)?</p>
[ { "answer_id": 61723, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>I'm a little hazy on the details, but maybe the link below might help:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms974564.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms974564.aspx</a></p>\n\n<p>It looks like your server object needs to implement <code>IProvideClassInfo</code> and then you call <code>ConnectObject</code> in your VBScript code. See also:</p>\n\n<p><a href=\"http://blogs.msdn.com/ericlippert/archive/2005/02/15/373330.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/ericlippert/archive/2005/02/15/373330.aspx</a></p>\n" }, { "answer_id": 61762, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 3, "selected": false, "text": "<p>This is how I did it just recently. Add an interface that implements IDispatch and a coclass for that interface to your IDL:</p>\n\n<pre><code>[\n object,\n uuid(6EDA5438-0915-4183-841D-D3F0AEDFA466),\n nonextensible,\n oleautomation,\n pointer_default(unique)\n]\ninterface IServerEvents : IDispatch\n{\n [id(1)]\n HRESULT OnServerEvent();\n}\n\n//...\n\n[\n uuid(FA8F24B3-1751-4D44-8258-D649B6529494),\n]\ncoclass ServerEvents\n{\n [default] interface IServerEvents;\n [default, source] dispinterface IServerEvents;\n};\n</code></pre>\n\n<p>This is the declaration of the CServerEvents class:</p>\n\n<pre><code>class ATL_NO_VTABLE CServerEvents :\n public CComObjectRootEx&lt;CComSingleThreadModel&gt;,\n public CComCoClass&lt;CServerEvents, &amp;CLSID_ServerEvents&gt;,\n public IDispatchImpl&lt;IServerEvents, &amp;IID_IServerEvents , &amp;LIBID_YourLibrary, -1, -1&gt;,\n public IConnectionPointContainerImpl&lt;CServerEvents&gt;,\n public IConnectionPointImpl&lt;CServerEvents,&amp;__uuidof(IServerEvents)&gt;\n{\npublic:\n CServerEvents()\n {\n }\n\n // ...\n\nBEGIN_COM_MAP(CServerEvents)\n COM_INTERFACE_ENTRY(IServerEvents)\n COM_INTERFACE_ENTRY(IDispatch)\n COM_INTERFACE_ENTRY(IConnectionPointContainer)\nEND_COM_MAP()\n\nBEGIN_CONNECTION_POINT_MAP(CServerEvents)\n CONNECTION_POINT_ENTRY(__uuidof(IServerEvents))\nEND_CONNECTION_POINT_MAP()\n\n // ..\n\n // IServerEvents\n STDMETHOD(OnServerEvent)();\n\nprivate:\n CRITICAL_SECTION m_csLock; \n};\n</code></pre>\n\n<p>The key here is the implementation of the IConnectionPointImpl and IConnectionPointContainerImpl interfaces and the connection point map. The definition of the OnServerEvent method looks like this:</p>\n\n<pre><code>STDMETHODIMP CServerEvents::OnServerEvent()\n{\n ::EnterCriticalSection( &amp;m_csLock );\n\n IUnknown* pUnknown;\n\n for ( unsigned i = 0; ( pUnknown = m_vec.GetAt( i ) ) != NULL; ++i )\n { \n CComPtr&lt;IDispatch&gt; spDisp;\n pUnknown-&gt;QueryInterface( &amp;spDisp );\n\n if ( spDisp )\n {\n spDisp.Invoke0( CComBSTR( L\"OnServerEvent\" ) );\n }\n }\n\n ::LeaveCriticalSection( &amp;m_csLock );\n\n return S_OK;\n}\n</code></pre>\n\n<p>You need to provide a way for your client to specify their handler for your events. You can do this with a dedicated method like \"SetHandler\" or something, but I prefer to make the handler an argument to the method that is called asynchronously. This way, the user only has to call one method:</p>\n\n<pre><code>STDMETHOD(DoSomethingAsynchronous)( IServerEvents *pCallback );\n</code></pre>\n\n<p>Store the pointer to the IServerEvents, and then when you want to fire your event, just call the method:</p>\n\n<pre><code>m_pCallback-&gt;OnServerEvent();\n</code></pre>\n\n<p>As for the VB code, the syntax for dealing with events is a little different than what you suggested:</p>\n\n<pre><code>Private m_server As Server\nPrivate WithEvents m_serverEvents As ServerEvents\n\nPrivate Sub MainMethod()\n Set s = CreateObject(\"Server\")\n Set m_serverEvents = New ServerEvents\n\n Call m_searchService.DoSomethingAsynchronous(m_serverEvents)\nEnd Sub\n\nPrivate Sub m_serverEvents_OnServerEvent()\n MsgBox \"Event handled\"\nEnd Sub\n</code></pre>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 67506, "author": "Carl", "author_id": 5449, "author_profile": "https://Stackoverflow.com/users/5449", "pm_score": 1, "selected": false, "text": "<p>I ended up following the technique described <a href=\"http://www.mp3car.com/vbulletin/digitalmods-scripts-api/81425-how-create-c-com-object-streetdeck.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5449/" ]
Suppose I have a COM object which users can access via a call such as: ``` Set s = CreateObject("Server") ``` What I'd like to be able to do is allow the user to specify an event handler for the object, like so: ``` Function ServerEvent MsgBox "Event handled" End Function s.OnDoSomething = ServerEvent ``` Is this possible and, if so, how do I expose this in my type library in C++ (specifically BCB 2007)?
This is how I did it just recently. Add an interface that implements IDispatch and a coclass for that interface to your IDL: ``` [ object, uuid(6EDA5438-0915-4183-841D-D3F0AEDFA466), nonextensible, oleautomation, pointer_default(unique) ] interface IServerEvents : IDispatch { [id(1)] HRESULT OnServerEvent(); } //... [ uuid(FA8F24B3-1751-4D44-8258-D649B6529494), ] coclass ServerEvents { [default] interface IServerEvents; [default, source] dispinterface IServerEvents; }; ``` This is the declaration of the CServerEvents class: ``` class ATL_NO_VTABLE CServerEvents : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CServerEvents, &CLSID_ServerEvents>, public IDispatchImpl<IServerEvents, &IID_IServerEvents , &LIBID_YourLibrary, -1, -1>, public IConnectionPointContainerImpl<CServerEvents>, public IConnectionPointImpl<CServerEvents,&__uuidof(IServerEvents)> { public: CServerEvents() { } // ... BEGIN_COM_MAP(CServerEvents) COM_INTERFACE_ENTRY(IServerEvents) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IConnectionPointContainer) END_COM_MAP() BEGIN_CONNECTION_POINT_MAP(CServerEvents) CONNECTION_POINT_ENTRY(__uuidof(IServerEvents)) END_CONNECTION_POINT_MAP() // .. // IServerEvents STDMETHOD(OnServerEvent)(); private: CRITICAL_SECTION m_csLock; }; ``` The key here is the implementation of the IConnectionPointImpl and IConnectionPointContainerImpl interfaces and the connection point map. The definition of the OnServerEvent method looks like this: ``` STDMETHODIMP CServerEvents::OnServerEvent() { ::EnterCriticalSection( &m_csLock ); IUnknown* pUnknown; for ( unsigned i = 0; ( pUnknown = m_vec.GetAt( i ) ) != NULL; ++i ) { CComPtr<IDispatch> spDisp; pUnknown->QueryInterface( &spDisp ); if ( spDisp ) { spDisp.Invoke0( CComBSTR( L"OnServerEvent" ) ); } } ::LeaveCriticalSection( &m_csLock ); return S_OK; } ``` You need to provide a way for your client to specify their handler for your events. You can do this with a dedicated method like "SetHandler" or something, but I prefer to make the handler an argument to the method that is called asynchronously. This way, the user only has to call one method: ``` STDMETHOD(DoSomethingAsynchronous)( IServerEvents *pCallback ); ``` Store the pointer to the IServerEvents, and then when you want to fire your event, just call the method: ``` m_pCallback->OnServerEvent(); ``` As for the VB code, the syntax for dealing with events is a little different than what you suggested: ``` Private m_server As Server Private WithEvents m_serverEvents As ServerEvents Private Sub MainMethod() Set s = CreateObject("Server") Set m_serverEvents = New ServerEvents Call m_searchService.DoSomethingAsynchronous(m_serverEvents) End Sub Private Sub m_serverEvents_OnServerEvent() MsgBox "Event handled" End Sub ``` I hope this helps.
61,680
<p>I need to create a 2D int array of size 800x800. But doing so creates a stack overflow (ha ha).</p> <p>I'm new to C++, so should I do something like a vector of vectors? And just encapsulate the 2d array into a class?</p> <p>Specifically, this array is my zbuffer in a graphics program. I need to store a z value for every pixel on the screen (hence the large size of 800x800).</p> <p>Thanks!</p>
[ { "answer_id": 61684, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 5, "selected": true, "text": "<p>You need about 2.5 megs, so just using the heap should be fine. You don't need a vector unless you need to resize it. See <a href=\"https://isocpp.org/wiki/faq/freestore-mgmt#multidim-arrays\" rel=\"nofollow noreferrer\">C++ FAQ Lite</a> for an example of using a \"2D\" heap array.</p>\n\n<pre><code>int *array = new int[800*800];\n</code></pre>\n\n<p>(Don't forget to <code>delete[]</code> it when you're done.)</p>\n" }, { "answer_id": 61685, "author": "Niall", "author_id": 6049, "author_profile": "https://Stackoverflow.com/users/6049", "pm_score": 2, "selected": false, "text": "<p>You could do a vector of vectors, but that would have some overhead. For a z-buffer the more typical method would be to create an array of size 800*800=640000.</p>\n\n<pre><code>const int width = 800;\nconst int height = 800;\nunsigned int* z_buffer = new unsigned int[width*height];\n</code></pre>\n\n<p>Then access the pixels as follows:</p>\n\n<pre><code>unsigned int z = z_buffer[y*width+x];\n</code></pre>\n" }, { "answer_id": 61689, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>I might create a single dimension array of 800*800. It is probably more efficient to use a single allocation like this, rather than allocating 800 separate vectors.</p>\n\n<pre><code>int *ary=new int[800*800];\n</code></pre>\n\n<p>Then, probably encapsulate that in a class that acted like a 2D array.</p>\n\n<pre><code>class _2DArray\n{\n public:\n int *operator[](const size_t &amp;idx)\n {\n return &amp;ary[idx*800];\n }\n const int *operator[](const size_t &amp;idx) const\n {\n return &amp;ary[idx*800];\n }\n};\n</code></pre>\n\n<p>The abstraction shown here has a lot of holes, e.g, what happens if you access out past the end of a \"row\"? The book \"Effective C++\" has a pretty good discussion of writing good multi dimensional arrays in C++.</p>\n" }, { "answer_id": 61690, "author": "Free Wildebeest", "author_id": 1849, "author_profile": "https://Stackoverflow.com/users/1849", "pm_score": 1, "selected": false, "text": "<p>There's the C like way of doing:</p>\n\n<pre><code>const int xwidth = 800;\nconst int ywidth = 800;\nint* array = (int*) new int[xwidth * ywidth];\n// Check array is not NULL here and handle the allocation error if it is\n// Then do stuff with the array, such as zero initialize it\nfor(int x = 0; x &lt; xwidth; ++x)\n{\n for(int y = 0; y &lt; ywidth; ++y)\n {\n array[y * xwidth + x] = 0;\n }\n}\n// Just use array[y * xwidth + x] when you want to access your class.\n\n// When you're done with it, free the memory you allocated with\ndelete[] array;\n</code></pre>\n\n<p>You could encapsulate the <code>y * xwidth + x</code> inside a class with an easy get and set method (possibly with overloading the <code>[]</code> operator if you want to start getting into more advanced C++). I'd recommend getting to this slowly though if you're just starting with C++ and not start creating re-usable fully class templates for n-dimension arrays which will just confuse you when you're starting off.</p>\n\n<p>As soon as you get into graphics work you might find that the overhead of having extra class calls might slow down your code. However don't worry about this until your application isn't fast enough and you can profile it to show where the time is lost, rather than making it more difficult to use at the start with possible unnecessary complexity.</p>\n\n<p>I found that the C++ lite FAQ was great for information such as this. In particular your question is answered by:</p>\n\n<p><a href=\"http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.16\" rel=\"nofollow noreferrer\">http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.16</a></p>\n" }, { "answer_id": 61693, "author": "ReaperUnreal", "author_id": 4218, "author_profile": "https://Stackoverflow.com/users/4218", "pm_score": -1, "selected": false, "text": "<p>Well, building on what Niall Ryan started, if performance is an issue, you can take this one step further by optimizing the math and encapsulating this into a class.</p>\n\n<p>So we'll start with a bit of math. Recall that 800 can be written in powers of 2 as:</p>\n\n<pre><code>800 = 512 + 256 + 32 = 2^5 + 2^8 + 2^9\n</code></pre>\n\n<p>So we can write our addressing function as:</p>\n\n<pre><code>int index = y &lt;&lt; 9 + y &lt;&lt; 8 + y &lt;&lt; 5 + x;\n</code></pre>\n\n<p>So if we encapsulate everything into a nice class we get:</p>\n\n<pre><code>class ZBuffer\n{\npublic:\n const int width = 800;\n const int height = 800;\n\n ZBuffer()\n {\n for(unsigned int i = 0, *pBuff = zbuff; i &lt; width * height; i++, pBuff++)\n *pBuff = 0;\n }\n\n inline unsigned int getZAt(unsigned int x, unsigned int y)\n {\n return *(zbuff + y &lt;&lt; 9 + y &lt;&lt; 8 + y &lt;&lt; 5 + x);\n }\n\n inline unsigned int setZAt(unsigned int x, unsigned int y, unsigned int z)\n {\n *(zbuff + y &lt;&lt; 9 + y &lt;&lt; 8 + y &lt;&lt; 5 + x) = z;\n }\nprivate:\n unsigned int zbuff[width * height];\n};\n</code></pre>\n" }, { "answer_id": 61936, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 3, "selected": false, "text": "<p>Every post so far leaves the memory management for the programmer. This can and should be avoided. ReaperUnreal is darn close to what I'd do, except I'd use a vector rather than an array and also make the dimensions template parameters and change the access functions -- and oh just IMNSHO clean things up a bit:</p>\n\n<pre><code>template &lt;class T, size_t W, size_t H&gt;\nclass Array2D\n{\npublic:\n const int width = W;\n const int height = H;\n typedef typename T type;\n\n Array2D()\n : buffer(width*height)\n {\n }\n\n inline type&amp; at(unsigned int x, unsigned int y)\n {\n return buffer[y*width + x];\n }\n\n inline const type&amp; at(unsigned int x, unsigned int y) const\n {\n return buffer[y*width + x];\n }\n\nprivate:\n std::vector&lt;T&gt; buffer;\n};\n</code></pre>\n\n<p>Now you can allocate this 2-D array on the stack just fine:</p>\n\n<pre><code>void foo()\n{\n Array2D&lt;int, 800, 800&gt; zbuffer;\n\n // Do something with zbuffer...\n}\n</code></pre>\n\n<p>I hope this helps!</p>\n\n<p>EDIT: Removed array specification from <code>Array2D::buffer</code>. Thanks to Andreas for catching that!</p>\n" }, { "answer_id": 61946, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 1, "selected": false, "text": "<p>One thing you can do is change the stack size (if you really want the array on the stack) with VC the flag to do this is [/F](<a href=\"http://msdn.microsoft.com/en-us/library/tdkhxaks(VS.80).aspx)\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/tdkhxaks(VS.80).aspx)</a>. </p>\n\n<p>But the solution you probably want is to put the memory in the heap rather than on the stack, for that you should use a <code>vector</code> of <code>vectors</code>.</p>\n\n<p>The following line declares a <code>vector</code> of 800 elements, each element is a <code>vector</code> of 800 <code>int</code>s and saves you from managing the memory manually.</p>\n\n<pre><code>std::vector&lt;std::vector&lt;int&gt; &gt; arr(800, std::vector&lt;int&gt;(800));\n</code></pre>\n\n<p>Note the space between the two closing angle brackets (<code>&gt; &gt;</code>) which is required in order disambiguate it from the shift right operator (which will no longer be needed in <a href=\"http://en.wikipedia.org/wiki/C_0x#Angle_bracket\" rel=\"nofollow noreferrer\">C++0x</a>).</p>\n" }, { "answer_id": 61960, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 2, "selected": false, "text": "<p>Kevin's example is good, however:</p>\n\n<blockquote>\n<pre><code>std::vector&lt;T&gt; buffer[width * height];\n</code></pre>\n</blockquote>\n\n<p>Should be</p>\n\n<pre><code>std::vector&lt;T&gt; buffer;\n</code></pre>\n\n<p>Expanding it a bit you could of course add operator-overloads instead of the at()-functions:</p>\n\n<pre><code>const T &amp;operator()(int x, int y) const\n{\n return buffer[y * width + x];\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>T &amp;operator()(int x, int y)\n{\n return buffer[y * width + x];\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>int main()\n{\n Array2D&lt;int, 800, 800&gt; a;\n a(10, 10) = 50;\n std::cout &lt;&lt; \"A(10, 10)=\" &lt;&lt; a(10, 10) &lt;&lt; std::endl;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 61980, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 1, "selected": false, "text": "<p>Or you could try something like:</p>\n\n<pre><code>boost::shared_array&lt;int&gt; zbuffer(new int[width*height]);\n</code></pre>\n\n<p>You should still be able to do this too:</p>\n\n<pre><code>++zbuffer[0];\n</code></pre>\n\n<p>No more worries about managing the memory, no custom classes to take care of, and it's easy to throw around.</p>\n" }, { "answer_id": 62611, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can allocate array on static storage (in file's scope, or add <code>static</code> qualifier in function scope), if you need only one instance.</p>\n\n<pre><code>int array[800][800];\n\nvoid fn()\n{\n static int array[800][800];\n}\n</code></pre>\n\n<p>This way it will not go to the stack, and you not have to deal with dynamic memory.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396/" ]
I need to create a 2D int array of size 800x800. But doing so creates a stack overflow (ha ha). I'm new to C++, so should I do something like a vector of vectors? And just encapsulate the 2d array into a class? Specifically, this array is my zbuffer in a graphics program. I need to store a z value for every pixel on the screen (hence the large size of 800x800). Thanks!
You need about 2.5 megs, so just using the heap should be fine. You don't need a vector unless you need to resize it. See [C++ FAQ Lite](https://isocpp.org/wiki/faq/freestore-mgmt#multidim-arrays) for an example of using a "2D" heap array. ``` int *array = new int[800*800]; ``` (Don't forget to `delete[]` it when you're done.)
61,691
<p>The .NET Setup project seems to have a lot of options, but I don't see an "Uninstall" option. </p> <p>I'd prefer if people could "uninstall" from the standard "start menu" folder rather than send them to the control panel to uninstall my app, so can someone please tell me how to do this?</p> <p>Also, I am aware of non Microsoft installers that have this feature, but if possible I'd like to stay with the Microsoft toolkit.</p>
[ { "answer_id": 61697, "author": "Mladen Janković", "author_id": 6300, "author_profile": "https://Stackoverflow.com/users/6300", "pm_score": 4, "selected": true, "text": "<p>You can make shortcut to:</p>\n\n<pre><code>msiexec /uninstall [path to msi or product code]\n</code></pre>\n" }, { "answer_id": 5278703, "author": "Jan Hettich", "author_id": 315595, "author_profile": "https://Stackoverflow.com/users/315595", "pm_score": 1, "selected": false, "text": "<p>Setup Projects have a \"RemovePreviousVersons\" feature that covers perhaps the most compelling use case for uninstall, but it keys off the \"Product Code\". See <a href=\"http://msdn.microsoft.com/en-us/library/y63fxdw6.aspx\" rel=\"nofollow\">MSDN documentation</a>. This \"Product Code\" doesn't seem to have been very well named, as it needs to be changed every time you update the Version number. In fact, VS2010 prompts you to do so. Unfortunately, neither the Product Code nor the Version number appears in the file properties of the generated .msi file.</p>\n\n<p>This solution suffers from similar limitations with respect to maintainability as the prior suggestion that includes this same inscrutable Product Code in a hard-coded shortcut.</p>\n\n<p>In reality, there don't seem to be any very attractive options here. </p>\n" }, { "answer_id": 36390790, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Visual Studio 2013 allows you to create an Uninstall shortcut in the shortcut design page if you use the Installshield Add-on.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4050/" ]
The .NET Setup project seems to have a lot of options, but I don't see an "Uninstall" option. I'd prefer if people could "uninstall" from the standard "start menu" folder rather than send them to the control panel to uninstall my app, so can someone please tell me how to do this? Also, I am aware of non Microsoft installers that have this feature, but if possible I'd like to stay with the Microsoft toolkit.
You can make shortcut to: ``` msiexec /uninstall [path to msi or product code] ```
61,692
<p>I have a Java application which I want to shutdown 'nicely' when the user selects Start->Shutdown. I've tried using JVM shutdown listeners via Runtime.addShutdownHook(...) but this doesn't work as I can't use any UI elements from it.</p> <p>I've also tried using the exit handler on my main application UI window but it has no way to pause or halt shutdown as far as I can tell. How can I handle shutdown nicely?</p>
[ { "answer_id": 61697, "author": "Mladen Janković", "author_id": 6300, "author_profile": "https://Stackoverflow.com/users/6300", "pm_score": 4, "selected": true, "text": "<p>You can make shortcut to:</p>\n\n<pre><code>msiexec /uninstall [path to msi or product code]\n</code></pre>\n" }, { "answer_id": 5278703, "author": "Jan Hettich", "author_id": 315595, "author_profile": "https://Stackoverflow.com/users/315595", "pm_score": 1, "selected": false, "text": "<p>Setup Projects have a \"RemovePreviousVersons\" feature that covers perhaps the most compelling use case for uninstall, but it keys off the \"Product Code\". See <a href=\"http://msdn.microsoft.com/en-us/library/y63fxdw6.aspx\" rel=\"nofollow\">MSDN documentation</a>. This \"Product Code\" doesn't seem to have been very well named, as it needs to be changed every time you update the Version number. In fact, VS2010 prompts you to do so. Unfortunately, neither the Product Code nor the Version number appears in the file properties of the generated .msi file.</p>\n\n<p>This solution suffers from similar limitations with respect to maintainability as the prior suggestion that includes this same inscrutable Product Code in a hard-coded shortcut.</p>\n\n<p>In reality, there don't seem to be any very attractive options here. </p>\n" }, { "answer_id": 36390790, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Visual Studio 2013 allows you to create an Uninstall shortcut in the shortcut design page if you use the Installshield Add-on.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1849/" ]
I have a Java application which I want to shutdown 'nicely' when the user selects Start->Shutdown. I've tried using JVM shutdown listeners via Runtime.addShutdownHook(...) but this doesn't work as I can't use any UI elements from it. I've also tried using the exit handler on my main application UI window but it has no way to pause or halt shutdown as far as I can tell. How can I handle shutdown nicely?
You can make shortcut to: ``` msiexec /uninstall [path to msi or product code] ```
61,699
<p>Until recently we were using Inno Setup for our installations, something I would like to continue doing, unless we can get an <a href="https://stackoverflow.com/questions/61691/how-to-add-uninstall-option-in-net-setup-project">uninstall option in the start menu</a> (thanks Giovanni Galbo), however we now need to GAC some external libraries, something I suspect is only doable (or at least only supported) though the .NET Setup Project.</p> <p>Is it possible to call a GAC'ing library from another setup application?</p>
[ { "answer_id": 61701, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "<p>Not sure about library, but you can call <a href=\"http://msdn.microsoft.com/en-us/library/ex0ss12c%28VS.80%29.aspx\" rel=\"nofollow noreferrer\">gacutil.exe</a> to install/uninstall assemblies.</p>\n" }, { "answer_id": 1476781, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 4, "selected": true, "text": "<p>According to <a href=\"http://jrsoftware.org/files/is5-whatsnew.htm\" rel=\"noreferrer\">http://jrsoftware.org/files/is5-whatsnew.htm</a> you should be able to do it with v5.3 and above</p>\n\n<blockquote>\n <p>Added .NET support (these cause an\n internal error if used on a system\n with no .NET Framework present):</p>\n\n<pre><code>* Added new [Files] section flag: gacinstall.\n* Added new [Files] section parameter: StrongAssemblyName.\n* Added new constants: {regasmexe}, {regasmexe32}, {regasmexe64}.\n</code></pre>\n</blockquote>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
Until recently we were using Inno Setup for our installations, something I would like to continue doing, unless we can get an [uninstall option in the start menu](https://stackoverflow.com/questions/61691/how-to-add-uninstall-option-in-net-setup-project) (thanks Giovanni Galbo), however we now need to GAC some external libraries, something I suspect is only doable (or at least only supported) though the .NET Setup Project. Is it possible to call a GAC'ing library from another setup application?
According to <http://jrsoftware.org/files/is5-whatsnew.htm> you should be able to do it with v5.3 and above > > Added .NET support (these cause an > internal error if used on a system > with no .NET Framework present): > > > > ``` > * Added new [Files] section flag: gacinstall. > * Added new [Files] section parameter: StrongAssemblyName. > * Added new constants: {regasmexe}, {regasmexe32}, {regasmexe64}. > > ``` > >
61,718
<p>When you are doing integration tests with either just your data access layer or the majority of the application stack. What is the best way prevent multiple tests from clashing with each other if they are run on the same database?</p>
[ { "answer_id": 61720, "author": "Free Wildebeest", "author_id": 1849, "author_profile": "https://Stackoverflow.com/users/1849", "pm_score": 3, "selected": false, "text": "<p>For simple database applications I find using <a href=\"http://www.sqlite.org/\" rel=\"noreferrer\">SQLite</a> invaluable. It allows you to have a unique and standalone database for each test.</p>\n\n<p>However it does only work if you're using simple generic SQL functionality or can easily hide the slight differences between SQLite and your production database system behind a class, but I've always found that to be fairly easy in the SQL applications I've developed.</p>\n" }, { "answer_id": 61721, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": true, "text": "<p>Transactions.</p>\n\n<p>What the ruby on rails unit test framework does is this:</p>\n\n<pre><code>Load all fixture data.\n\nFor each test:\n\n BEGIN TRANSACTION\n\n # Yield control to user code\n\n ROLLBACK TRANSACTION\n\nEnd for each\n</code></pre>\n\n<p>This means that</p>\n\n<ol>\n<li>Any changes your test makes to the database won't affect other threads while it's in-progress</li>\n<li>The next test's data isn't polluted by prior tests</li>\n<li>This is about a zillion times faster than manually reloading data for each test.</li>\n</ol>\n\n<p>I for one think this is pretty cool</p>\n" }, { "answer_id": 61722, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 0, "selected": false, "text": "<p>I wanted to accept both Free Wildebeest's and Orion Edwards' answers but it would not let me. The reason I wanted to do this is that I'd come to the conclusion that these were the two main ways to do it, but which one to chose depends on the individual case (mostly the size of the database).</p>\n" }, { "answer_id": 61764, "author": "Techboy", "author_id": 2699, "author_profile": "https://Stackoverflow.com/users/2699", "pm_score": 0, "selected": false, "text": "<p>Also run the tests at different times, so that they do not impact the performance or validity of each other.</p>\n" }, { "answer_id": 73274, "author": "Bradley Harris", "author_id": 10503, "author_profile": "https://Stackoverflow.com/users/10503", "pm_score": 1, "selected": false, "text": "<p>Just to add to Free Wildebeest's answer I have also used <a href=\"http://hsqldb.org/\" rel=\"nofollow noreferrer\">HSQLDB</a> to do a similar type testing where each test gets a clean instance of the DB. </p>\n" }, { "answer_id": 95312, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>While not as clever as the Rails unit test framework in one of the other answers here, creating distinct data per test or group of tests is another way of doing it. The level of tediousness with this solution depends on the number of test cases you have and how dependant they are on one another. The tediousness will hold true if you have one database per test or group of dependant tests.</p>\n\n<p>When running the test suite, you load the data at the start, run the test suite, unload/compare results making sure the actual result meets the expected result. If not, do the cycle again. Load, run suite, unload/compare.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6369/" ]
When you are doing integration tests with either just your data access layer or the majority of the application stack. What is the best way prevent multiple tests from clashing with each other if they are run on the same database?
Transactions. What the ruby on rails unit test framework does is this: ``` Load all fixture data. For each test: BEGIN TRANSACTION # Yield control to user code ROLLBACK TRANSACTION End for each ``` This means that 1. Any changes your test makes to the database won't affect other threads while it's in-progress 2. The next test's data isn't polluted by prior tests 3. This is about a zillion times faster than manually reloading data for each test. I for one think this is pretty cool
61,733
<p>Which of the following is better code in c# and why?</p> <pre><code>((DateTime)g[0]["MyUntypedDateField"]).ToShortDateString() </code></pre> <p>or</p> <pre><code>DateTime.Parse(g[0]["MyUntypedDateField"].ToString()).ToShortDateString() </code></pre> <p>Ultimately, is it better to cast or to parse?</p>
[ { "answer_id": 61740, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 5, "selected": true, "text": "<p>If g[0][\"MyUntypedDateField\"] is really a DateTime object, then the cast is the better choice. If it's not really a DateTime, then you have no choice but to use the Parse (you would get an InvalidCastException if you tried to use the cast)</p>\n" }, { "answer_id": 61743, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>As @Brian R. Bondy pointed it depends on implementation of <strong>g[0][\"MyUntypedDateField\"]</strong>. Safe practice is to use <strong>DateTime.TryParse</strong> and <strong>as</strong> operator. </p>\n" }, { "answer_id": 61768, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 0, "selected": false, "text": "<p>Parse requires a string for input, casting requires an object, so in the second example you provide above, then you are required to perform two casts: one from an object to a string, then from a string to a DateTime. The first does not. </p>\n\n<p>However, if there is a risk of an exception when you perform the cast, then you might want to go the second route so you can TryParse and avoid an expensive exception to be thrown. Otherwise, go the most efficient route and just cast once (from object to DateTime) rather than twice (from object to string to DateTime).</p>\n" }, { "answer_id": 61771, "author": "sgwill", "author_id": 1204, "author_profile": "https://Stackoverflow.com/users/1204", "pm_score": 0, "selected": false, "text": "<p>There's comparison of the different techniques at <a href=\"http://blogs.msdn.com/bclteam/archive/2005/02/11/371436.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/bclteam/archive/2005/02/11/371436.aspx</a>. </p>\n" }, { "answer_id": 61931, "author": "qbeuek", "author_id": 5348, "author_profile": "https://Stackoverflow.com/users/5348", "pm_score": 2, "selected": false, "text": "<p>Casting is the <strong>only</strong> good answer.</p>\n\n<p>You have to remember, that ToString and Parse results are not always exact - there are cases, when you cannot safely roundtrip between those two functions.</p>\n\n<p>The documentation of ToString says, it uses current thread culture settings. The documentation of Parse says, it also uses current thread culture settings (so far so good - they are using the same culture), but there is an explicit remark, that:</p>\n\n<blockquote>\n <p>Formatting is influenced by properties of the current DateTimeFormatInfo object, which by default are derived from the Regional and Language Options item in Control Panel. <strong>One reason the Parse method can unexpectedly throw FormatException is if the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator properties are set to the same value.</strong></p>\n</blockquote>\n\n<p>So depending on the users settings, the ToString/Parse code can and will unexpectedly fail...</p>\n" }, { "answer_id": 62619, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 1, "selected": false, "text": "<p>Your code suggests that the variable may be either a date or a string that looks like a date. Dates you can simply return wit a cast, but strings must be parsed. Parsing comes with two caveats;</p>\n\n<ol>\n<li><p>if you aren't certain this string can be parsed, then use <code>DateTime.TryParse()</code>. </p></li>\n<li><p>Always include a reference to the culture you want to parse as. <code>ToShortDateString()</code> returns different outputs in different places. You will almost certainly want to parse using the same culture. I suggest this function dealing with both situations;</p>\n\n<pre><code>private DateTime ParseDateTime(object data)\n{\n if (data is DateTime)\n {\n // already a date-time.\n return (DateTime)data;\n }\n else if (data is string)\n {\n // it's a local-format string.\n string dateString = (string)data;\n DateTime parseResult;\n if (DateTime.TryParse(dateString, CultureInfo.CurrentCulture,\n DateTimeStyles.AssumeLocal, out parseResult))\n {\n return parseResult;\n }\n else\n {\n throw new ArgumentOutOfRangeException(\"data\", \n \"could not parse this datetime:\" + data);\n }\n }\n else\n {\n // it's neither a DateTime or a string; that's a problem.\n throw new ArgumentOutOfRangeException(\"data\", \n \"could not understand data of this type\");\n }\n}\n</code></pre></li>\n</ol>\n\n<p>Then call like this;</p>\n\n<pre><code>ParseDateTime(g[0][\"MyUntypedDateField\").ToShortDateString();\n</code></pre>\n\n<p>Note that bad data throws an exception, so you'll want to catch that.</p>\n\n<p>Also; the 'as' operator does not work with the DateTime data type, as this only works with reference types, and DateTime is a value type.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4246/" ]
Which of the following is better code in c# and why? ``` ((DateTime)g[0]["MyUntypedDateField"]).ToShortDateString() ``` or ``` DateTime.Parse(g[0]["MyUntypedDateField"].ToString()).ToShortDateString() ``` Ultimately, is it better to cast or to parse?
If g[0]["MyUntypedDateField"] is really a DateTime object, then the cast is the better choice. If it's not really a DateTime, then you have no choice but to use the Parse (you would get an InvalidCastException if you tried to use the cast)
61,739
<p>I'm drawing old school (unthemed - themed radios are a whole other problem) radio buttons myself using DrawFrameControl:</p> <pre><code>DrawFrameControl(dc, &amp;rectRadio, DFC_BUTTON, isChecked() ? DFCS_BUTTONRADIO | DFCS_CHECKED : DFCS_BUTTONRADIO); </code></pre> <p>I've never been able to figure out a sure fire way to figure out what to pass for the RECT. I've been using a 12x12 rectangle but I'de like Windows to tell me the size of a radio button.</p> <p>DrawFrameControl seems to scale the radio button to fit the rect I pass so I have to be close to the "right" size of the radio looks off from other (non-owner drawn) radios on the screen.</p> <p>Anyone know how to do this? </p>
[ { "answer_id": 124737, "author": "David L Morris", "author_id": 3137, "author_profile": "https://Stackoverflow.com/users/3137", "pm_score": 2, "selected": false, "text": "<p>It has been a while since I worked on this, so what I am describing is what I did, and not necessarily a direct answer to the question.</p>\n\n<p>I happen to use bit maps 13 x 13 rather than 12 x 12. The bitmap part of the check box seems to be passed in the WM_DRAWITEM. However, I had also set up WM_MEASUREITEM and fed it the same values, so my answer may well be \"Begging the question\" in the correct philosophical sense.</p>\n\n<pre>\n case WM_MEASUREITEM:\n lpmis = (LPMEASUREITEMSTRUCT) lParam;\n\n lpmis->itemHeight = 13;\n lpmis->itemWidth = 13;\n\n break;\n\n\n case WM_DRAWITEM:\n lpdis = (LPDRAWITEMSTRUCT) lParam;\n hdcMem = CreateCompatibleDC(lpdis->hDC); \n\n\n\n if (lpdis->itemState & ODS_CHECKED) // if selected\n {\n SelectObject(hdcMem, hbmChecked);\n }\n else\n {\n if (lpdis->itemState & ODS_GRAYED)\n {\n SelectObject(hdcMem, hbmDefault);\n }\n else\n {\n SelectObject(hdcMem, hbmUnChecked);\n }\n }\n StretchBlt(\n lpdis->hDC, // destination DC\n lpdis->rcItem.left, // x upper left\n lpdis->rcItem.top, // y upper left\n\n // The next two lines specify the width and\n // height.\n lpdis->rcItem.right - lpdis->rcItem.left,\n lpdis->rcItem.bottom - lpdis->rcItem.top,\n hdcMem, // source device context\n 0, 0, // x and y upper left\n 13, // source bitmap width\n 13, // source bitmap height\n SRCCOPY); // raster operation\n\n DeleteDC(hdcMem);\n return TRUE;\n</pre>\n\n<p>This seems to work well for both Win2000 and XP, though I have nbo idea what Vista might do.</p>\n\n<p>It might be worth an experiment to see what leaving out WM_MEASUREITEM does, though I usually discover with old code that I usually had perfectly good reason for doing something that looks redundant.</p>\n" }, { "answer_id": 124770, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 2, "selected": false, "text": "<p>This page shows some sizing guidelines for controls. Note that the sizes are given in both DLU (dialog units) and pixels, depending on whether you are placing the control on a dialog or not:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa511279.aspx#controlsizing\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa511279.aspx#controlsizing</a></p>\n\n<p>I thought the <code>GetSystemMetrics</code> API might return the standard size for some of the common controls, but I didn't find anything. There might be a common control specific API to determine sizing.</p>\n" } ]
2008/09/14
[ "https://Stackoverflow.com/questions/61739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3655/" ]
I'm drawing old school (unthemed - themed radios are a whole other problem) radio buttons myself using DrawFrameControl: ``` DrawFrameControl(dc, &rectRadio, DFC_BUTTON, isChecked() ? DFCS_BUTTONRADIO | DFCS_CHECKED : DFCS_BUTTONRADIO); ``` I've never been able to figure out a sure fire way to figure out what to pass for the RECT. I've been using a 12x12 rectangle but I'de like Windows to tell me the size of a radio button. DrawFrameControl seems to scale the radio button to fit the rect I pass so I have to be close to the "right" size of the radio looks off from other (non-owner drawn) radios on the screen. Anyone know how to do this?
It has been a while since I worked on this, so what I am describing is what I did, and not necessarily a direct answer to the question. I happen to use bit maps 13 x 13 rather than 12 x 12. The bitmap part of the check box seems to be passed in the WM\_DRAWITEM. However, I had also set up WM\_MEASUREITEM and fed it the same values, so my answer may well be "Begging the question" in the correct philosophical sense. ``` case WM_MEASUREITEM: lpmis = (LPMEASUREITEMSTRUCT) lParam; lpmis->itemHeight = 13; lpmis->itemWidth = 13; break; case WM_DRAWITEM: lpdis = (LPDRAWITEMSTRUCT) lParam; hdcMem = CreateCompatibleDC(lpdis->hDC); if (lpdis->itemState & ODS_CHECKED) // if selected { SelectObject(hdcMem, hbmChecked); } else { if (lpdis->itemState & ODS_GRAYED) { SelectObject(hdcMem, hbmDefault); } else { SelectObject(hdcMem, hbmUnChecked); } } StretchBlt( lpdis->hDC, // destination DC lpdis->rcItem.left, // x upper left lpdis->rcItem.top, // y upper left // The next two lines specify the width and // height. lpdis->rcItem.right - lpdis->rcItem.left, lpdis->rcItem.bottom - lpdis->rcItem.top, hdcMem, // source device context 0, 0, // x and y upper left 13, // source bitmap width 13, // source bitmap height SRCCOPY); // raster operation DeleteDC(hdcMem); return TRUE; ``` This seems to work well for both Win2000 and XP, though I have nbo idea what Vista might do. It might be worth an experiment to see what leaving out WM\_MEASUREITEM does, though I usually discover with old code that I usually had perfectly good reason for doing something that looks redundant.
61,747
<p>How can I get PDO to work on my mac (os x 10.5)? I'm using the built in php and php in Zend/Eclipse. Can't seem to find useful drivers for it at all.</p>
[ { "answer_id": 61799, "author": "Alan", "author_id": 5878, "author_profile": "https://Stackoverflow.com/users/5878", "pm_score": 1, "selected": false, "text": "<p>I'm not sure this will help with the PDO drivers specifically, but you might look into <a href=\"http://bitnami.org/stack/mappstack\" rel=\"nofollow noreferrer\">BitNami's MAPPStack</a>.</p>\n\n<p>I had a ton of trouble with Postgres, PHP, and Apache on my Mac, some of it having to do with 64- vs 32-bit versions of some or all of them. So far, the BitNami MAPPStack install is working nicely in general. Maybe it will help with your PDO issues as well.</p>\n" }, { "answer_id": 61804, "author": "Wilco", "author_id": 5291, "author_profile": "https://Stackoverflow.com/users/5291", "pm_score": 2, "selected": false, "text": "<p>Take a look at this PECL package: <a href=\"http://pecl.php.net/package/PDO_PGSQL\" rel=\"nofollow noreferrer\">PDO_PGSQL</a></p>\n\n<p>I haven't tried it myself, but I've been interested in playing with Postgres as an alternative to MySQL. If I have a chance to try it soon, I'll throw my results up here in case it helps.</p>\n" }, { "answer_id": 1286153, "author": "hbw", "author_id": 90155, "author_profile": "https://Stackoverflow.com/users/90155", "pm_score": 6, "selected": true, "text": "<p>I had to install the PDO_PGSQL driver recently on Leopard, and I ran across a multitude of problems. In my search for answers, I stumbled across this question. Now I have it successfully installed, and so, even though this question is quite old, I hope that what I've found can help others (like myself) who will undoubtedly run into similar problems.</p>\n\n<p>The first thing you'll need to do is <a href=\"http://pear.php.net/manual/en/installation.getting.php\" rel=\"noreferrer\">install PEAR</a>, if you haven't done so already, since it doesn't come installed on Leopard by default.</p>\n\n<p>Once you do that, use the PECL installer to download the PDO_PGSQL package:</p>\n\n<pre><code>$ pecl download pdo_pgsql\n$ tar xzf PDO_PGSQL-1.0.2.tgz\n</code></pre>\n\n<p>(Note: you may have to run <code>pecl</code> as the superuser, i.e. <code>sudo pecl</code>.)</p>\n\n<p>After that, since the PECL installer can't install the extension directly, you'll need to build and install it yourself:</p>\n\n<pre><code>$ cd PDO_PGSQL-1.0.2\n$ phpize\n$ ./configure --with-pdo-pgsql=/path/to/your/PostgreSQL/installation\n$ make &amp;&amp; sudo make install\n</code></pre>\n\n<p>If all goes well, you should have a file called \"<code>pdo_pgsql.so</code>\" sitting in a directory that should look something like \"<code>/usr/lib/php/extensions/no-debug-non-zts-20060613/</code>\" (the PECL installation should have outputted the directory it installed the extension to).</p>\n\n<p>To finalize the installation, you'll need to edit your <code>php.ini</code> file. Find the section labeled \"Dynamic Extensions\", and underneath the list of (probably commented out) extensions, add this line:</p>\n\n<pre><code>extension=pdo_pgsql.so\n</code></pre>\n\n<p>Now, assuming this is the first time you've installed PHP extensions, there are two additional steps you need to take in order to get this working. First, in <code>php.ini</code>, find the <code>extension_dir</code> directive (under \"Paths and Directories\"), and change it to the directory that the <code>pdo_pgsql.so</code> file was installed in. For example, my <code>extension_dir</code> directive looks like:</p>\n\n<pre><code>extension_dir = \"/usr/lib/php/extensions/no-debug-non-zts-20060613\"\n</code></pre>\n\n<p>The second step, if you're on a 64-bit Intel Mac, involves making Apache run in 32-bit mode. (If there's a better strategy, I'd like to know, but for now, this is the best I could find.) In order to do this, edit the property list file located at <code>/System/Library/LaunchDaemons/org.apache.httpd.plist</code>. Find these two lines:</p>\n\n<pre><code>&lt;key&gt;ProgramArguments&lt;/key&gt;\n&lt;array&gt;\n</code></pre>\n\n<p>Under them, add these three lines:</p>\n\n<pre><code>&lt;string&gt;arch&lt;/string&gt;\n&lt;string&gt;-arch&lt;/string&gt;\n&lt;string&gt;i386&lt;/string&gt;\n</code></pre>\n\n<p>Now, just restart Apache, and PDO_PGSQL will be up and running.</p>\n" }, { "answer_id": 35874398, "author": "Mark Horgan", "author_id": 628709, "author_profile": "https://Stackoverflow.com/users/628709", "pm_score": 0, "selected": false, "text": "<p>This is what worked for me</p>\n\n<pre><code>brew install php55-pdo-pgsql\n</code></pre>\n\n<p>This installs PHP 5.5.32 and PostgreSQL 9.5. I already had PostgreSQL 9.4 installed so I uninstalled the homebrew version with:</p>\n\n<pre><code>brew uninstall postgres\n</code></pre>\n\n<p>You then have to update /etc/apache2/httpd.conf to point to the correct PHP version and restart Apache:</p>\n\n<pre><code>LoadModule php5_module /usr/local/Cellar/php55/5.5.32/libexec/apache2/libphp5.so\n</code></pre>\n\n<p>My OSX version is Yosemite.</p>\n" }, { "answer_id": 43703695, "author": "yongrui", "author_id": 2079846, "author_profile": "https://Stackoverflow.com/users/2079846", "pm_score": 1, "selected": false, "text": "<p>Install new php version via brew and restart server, and php -v, all issues are removed.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6371/" ]
How can I get PDO to work on my mac (os x 10.5)? I'm using the built in php and php in Zend/Eclipse. Can't seem to find useful drivers for it at all.
I had to install the PDO\_PGSQL driver recently on Leopard, and I ran across a multitude of problems. In my search for answers, I stumbled across this question. Now I have it successfully installed, and so, even though this question is quite old, I hope that what I've found can help others (like myself) who will undoubtedly run into similar problems. The first thing you'll need to do is [install PEAR](http://pear.php.net/manual/en/installation.getting.php), if you haven't done so already, since it doesn't come installed on Leopard by default. Once you do that, use the PECL installer to download the PDO\_PGSQL package: ``` $ pecl download pdo_pgsql $ tar xzf PDO_PGSQL-1.0.2.tgz ``` (Note: you may have to run `pecl` as the superuser, i.e. `sudo pecl`.) After that, since the PECL installer can't install the extension directly, you'll need to build and install it yourself: ``` $ cd PDO_PGSQL-1.0.2 $ phpize $ ./configure --with-pdo-pgsql=/path/to/your/PostgreSQL/installation $ make && sudo make install ``` If all goes well, you should have a file called "`pdo_pgsql.so`" sitting in a directory that should look something like "`/usr/lib/php/extensions/no-debug-non-zts-20060613/`" (the PECL installation should have outputted the directory it installed the extension to). To finalize the installation, you'll need to edit your `php.ini` file. Find the section labeled "Dynamic Extensions", and underneath the list of (probably commented out) extensions, add this line: ``` extension=pdo_pgsql.so ``` Now, assuming this is the first time you've installed PHP extensions, there are two additional steps you need to take in order to get this working. First, in `php.ini`, find the `extension_dir` directive (under "Paths and Directories"), and change it to the directory that the `pdo_pgsql.so` file was installed in. For example, my `extension_dir` directive looks like: ``` extension_dir = "/usr/lib/php/extensions/no-debug-non-zts-20060613" ``` The second step, if you're on a 64-bit Intel Mac, involves making Apache run in 32-bit mode. (If there's a better strategy, I'd like to know, but for now, this is the best I could find.) In order to do this, edit the property list file located at `/System/Library/LaunchDaemons/org.apache.httpd.plist`. Find these two lines: ``` <key>ProgramArguments</key> <array> ``` Under them, add these three lines: ``` <string>arch</string> <string>-arch</string> <string>i386</string> ``` Now, just restart Apache, and PDO\_PGSQL will be up and running.
61,805
<p>I had a working solution using ASP.NET MVC Preview 3 (was upgraded from a Preview 2 solution) that uses an untyped ViewMasterPage like so:</p> <pre><code>public partial class Home : ViewMasterPage </code></pre> <p>On Home.Master there is a display statement like this:</p> <pre><code>&lt;%= ((GenericViewData)ViewData["Generic"]).Skin %&gt; </code></pre> <p>However, a developer on the team just changed the assembly references to Preview 4.</p> <p>Following this, the code will no longer populate ViewData with indexed values like the above.</p> <p>Instead, ViewData["Generic"] is null.</p> <p>As per <a href="https://stackoverflow.com/questions/18787/aspnet-mvc-user-control-viewdata">this question</a>, ViewData.Eval("Generic") works, and ViewData.Model is also populated correctly.</p> <p>However, the reason this solution isn't using typed pages etc. is because it is kind of a legacy solution. As such, it is impractical to go through this fairly large solution and update all .aspx pages (especially as the compiler doesn't detect this sort of stuff).</p> <p>I have tried reverting the assemblies by removing the reference and then adding a reference to the Preview 3 assembly in the 'bin' folder of the project. This did not change anything. I have even tried reverting the Project file to an earlier version and that still did not seem to fix the problem.</p> <p>I have other solutions using the same technique that continue to work.</p> <p>Is there anything you can suggest as to why this has suddenly stopped working and how I might go about fixing it (any hint in the right direction would be appreciated)?</p>
[ { "answer_id": 61808, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 0, "selected": false, "text": "<p>I've decided to replace all instances of ViewData[\"blah\"] with ViewData.Eval(\"blah\").\nHowever, I'd like to know the cause of this change if possible because:</p>\n\n<ol>\n<li>If it happens on my other projects it'd be nice to be able to fix.</li>\n<li>It would be nice to leave the deployed working code and not overwrite with these changes.</li>\n<li>It would be nice to know that nothing else has changed that I haven't noticed.</li>\n</ol>\n" }, { "answer_id": 61835, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 0, "selected": false, "text": "<p>How are you setting the viewdata? This works for me:</p>\n\n<p>Controller:</p>\n\n<pre><code>ViewData[\"CategoryName\"] = a.Name;\n</code></pre>\n\n<p>View:</p>\n\n<pre><code>&lt;%= ViewData[\"CategoryName\"] %&gt;\n</code></pre>\n\n<p>BTW, I am on Preview 5 now. But this has worked on 3 and 4...</p>\n" }, { "answer_id": 61846, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 0, "selected": false, "text": "<p>Re: Ricky</p>\n\n<p>I am just passing an object when I call the View() method from the Controller.</p>\n\n<p>I've also noticed that on my deployed server where nothing has been updated, ViewData.Eval fails and ViewData[\"index\"] works.</p>\n\n<p>On my development server ViewData[\"index\"] fails and ViewData.Eval works...</p>\n" }, { "answer_id": 63293, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 0, "selected": false, "text": "<p>Yeah, so whatever you pass into the View is accessible in the View as ViewData.Model. But that will be just a good old object if you don't do the strongly typed Views...</p>\n" }, { "answer_id": 93938, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 2, "selected": true, "text": "<p>We made that change because we wanted a bit of symmetry with the [] indexer. The Eval() method uses reflection and looks into the model to retrieve values. The indexer only looks at items directly added to the dictionary.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I had a working solution using ASP.NET MVC Preview 3 (was upgraded from a Preview 2 solution) that uses an untyped ViewMasterPage like so: ``` public partial class Home : ViewMasterPage ``` On Home.Master there is a display statement like this: ``` <%= ((GenericViewData)ViewData["Generic"]).Skin %> ``` However, a developer on the team just changed the assembly references to Preview 4. Following this, the code will no longer populate ViewData with indexed values like the above. Instead, ViewData["Generic"] is null. As per [this question](https://stackoverflow.com/questions/18787/aspnet-mvc-user-control-viewdata), ViewData.Eval("Generic") works, and ViewData.Model is also populated correctly. However, the reason this solution isn't using typed pages etc. is because it is kind of a legacy solution. As such, it is impractical to go through this fairly large solution and update all .aspx pages (especially as the compiler doesn't detect this sort of stuff). I have tried reverting the assemblies by removing the reference and then adding a reference to the Preview 3 assembly in the 'bin' folder of the project. This did not change anything. I have even tried reverting the Project file to an earlier version and that still did not seem to fix the problem. I have other solutions using the same technique that continue to work. Is there anything you can suggest as to why this has suddenly stopped working and how I might go about fixing it (any hint in the right direction would be appreciated)?
We made that change because we wanted a bit of symmetry with the [] indexer. The Eval() method uses reflection and looks into the model to retrieve values. The indexer only looks at items directly added to the dictionary.
61,817
<p>I am wondering what the best way to obtain the current domain is in ASP.NET?</p> <p>For instance:</p> <p><a href="http://www.domainname.com/subdir/" rel="noreferrer">http://www.domainname.com/subdir/</a> should yield <a href="http://www.domainname.com" rel="noreferrer">http://www.domainname.com</a> <a href="http://www.sub.domainname.com/subdir/" rel="noreferrer">http://www.sub.domainname.com/subdir/</a> should yield <a href="http://sub.domainname.com" rel="noreferrer">http://sub.domainname.com</a></p> <p>As a guide, I should be able to add a url like "/Folder/Content/filename.html" (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work.</p>
[ { "answer_id": 61819, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 5, "selected": false, "text": "<p>As per <a href=\"http://www.velocityreviews.com/forums/t89365-get-hostdomain-name.html\" rel=\"noreferrer\">this link</a> a good starting point is:</p>\n\n<pre><code>Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host \n</code></pre>\n\n<p>However, if the domain is <a href=\"http://www.domainname.com:500\" rel=\"noreferrer\">http://www.domainname.com:500</a> this will fail.</p>\n\n<p>Something like the following is tempting to resolve this:</p>\n\n<pre><code>int defaultPort = Request.IsSecureConnection ? 443 : 80;\nRequest.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host \n + (Request.Url.Port != defaultPort ? \":\" + Request.Url.Port : \"\");\n</code></pre>\n\n<p>However, port 80 and 443 will depend on configuration.</p>\n\n<p>As such, you should use <code>IsDefaultPort</code> as in the <a href=\"https://stackoverflow.com/a/2878350/364\">Accepted Answer</a> above from Carlos Muñoz.</p>\n" }, { "answer_id": 61822, "author": "jwalkerjr", "author_id": 689, "author_profile": "https://Stackoverflow.com/users/689", "pm_score": -1, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>String domain = \"http://\" + Request.Url.Host\n</code></pre>\n" }, { "answer_id": 64045, "author": "derek lawless", "author_id": 400464, "author_profile": "https://Stackoverflow.com/users/400464", "pm_score": 1, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>NameValueCollection vars = HttpContext.Current.Request.ServerVariables;\nstring protocol = vars[\"SERVER_PORT_SECURE\"] == \"1\" ? \"https://\" : \"http://\";\nstring domain = vars[\"SERVER_NAME\"];\nstring port = vars[\"SERVER_PORT\"];\n</code></pre>\n" }, { "answer_id": 2326934, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Another way:</p>\n\n<pre><code>\nstring domain;\nUri url = HttpContext.Current.Request.Url;\ndomain= url.AbsoluteUri.Replace(url.PathAndQuery, string.Empty);\n</code></pre>\n" }, { "answer_id": 2878350, "author": "Carlos Muñoz", "author_id": 186133, "author_profile": "https://Stackoverflow.com/users/186133", "pm_score": 9, "selected": true, "text": "<p>Same answer as MattMitchell's but with some modification.\nThis checks for the default port instead.</p>\n\n<blockquote>\n <p>Edit: Updated syntax and using <code>Request.Url.Authority</code> as suggested </p>\n</blockquote>\n\n<pre><code>$\"{Request.Url.Scheme}{System.Uri.SchemeDelimiter}{Request.Url.Authority}\"\n</code></pre>\n" }, { "answer_id": 5845311, "author": "Thirlan", "author_id": 590059, "author_profile": "https://Stackoverflow.com/users/590059", "pm_score": 4, "selected": false, "text": "<p><strong>WARNING!</strong> To anyone who uses <strong>Current.Request</strong>.Url.Host. Understand that you are working based on the CURRENT REQUEST and that the current request will not ALWAYS be with your server and can sometimes be with other servers.</p>\n\n<p>So if you use this in something like, Application_BeginRequest() in Global.asax, then 99.9% of the time it will be fine, but 0.1% you might get something other than your own server's host name. </p>\n\n<p>A good example of this is something I discovered not long ago. My server tends to hit <a href=\"http://proxyjudge1.proxyfire.net/fastenv\" rel=\"noreferrer\">http://proxyjudge1.proxyfire.net/fastenv</a> from time to time. Application_BeginRequest() gladly handles this request so if you call Request.Url.Host when it's making this request you'll get back proxyjudge1.proxyfire.net. Some of you might be thinking \"no duh\" but worth noting because it was a very hard bug to notice since it only happened 0.1% of the time : P</p>\n\n<p>This bug has forced me to insert my domain host as a string in the config files.</p>\n" }, { "answer_id": 6727511, "author": "Korayem", "author_id": 80434, "author_profile": "https://Stackoverflow.com/users/80434", "pm_score": 4, "selected": false, "text": "<p>Why not use</p>\n\n<p><code>Request.Url.Authority</code></p>\n\n<p>It returns the whole domain AND the port.</p>\n\n<p>You still need to figure http or https</p>\n" }, { "answer_id": 8686506, "author": "izlence", "author_id": 1123996, "author_profile": "https://Stackoverflow.com/users/1123996", "pm_score": 5, "selected": false, "text": "<pre><code>Request.Url.GetLeftPart(UriPartial.Authority)\n</code></pre>\n\n<p>This is included scheme.</p>\n" }, { "answer_id": 29385136, "author": "Darren", "author_id": 329367, "author_profile": "https://Stackoverflow.com/users/329367", "pm_score": 0, "selected": false, "text": "<p>Using UriBuilder:</p>\n\n<pre><code> var relativePath = \"\"; // or whatever-path-you-want\n var uriBuilder = new UriBuilder\n {\n Host = Request.Url.Host,\n Path = relativePath,\n Scheme = Request.Url.Scheme\n };\n\n if (!Request.Url.IsDefaultPort)\n uriBuilder.Port = Request.Url.Port;\n\n var fullPathToUse = uriBuilder.ToString();\n</code></pre>\n" }, { "answer_id": 45777954, "author": "Ramin Bateni", "author_id": 1474613, "author_profile": "https://Stackoverflow.com/users/1474613", "pm_score": 2, "selected": false, "text": "<p><strong>Simple</strong> and <strong>short</strong> way (it support schema, domain and port):</p>\n<h2><strong>Use <code>Request.GetFullDomain()</code></strong></h2>\n<pre><code>// Add this class to your project\npublic static class HttpRequestExtensions{\n public static string GetFullDomain(this HttpRequestBase request)\n {\n var uri= request?.UrlReferrer;\n if (uri== null)\n return string.Empty;\n return uri.Scheme + Uri.SchemeDelimiter + uri.Authority;\n }\n}\n\n// Now Use it like this:\nRequest.GetFullDomain();\n// Example output: https://example.com:5031\n// Example output: http://example.com:5031\n</code></pre>\n" }, { "answer_id": 63976140, "author": "Dastan Alybaev", "author_id": 10049738, "author_profile": "https://Stackoverflow.com/users/10049738", "pm_score": 1, "selected": false, "text": "<p>In <strong>Asp.Net Core 3.1</strong> if you want to get a full domain, here is what you need to do:</p>\n<p>Step 1: Define variable</p>\n<pre><code>private readonly IHttpContextAccessor _contextAccessor;\n</code></pre>\n<p>Step 2: DI into the constructor</p>\n<pre><code>public SomeClass(IHttpContextAccessor contextAccessor)\n{\n _contextAccessor = contextAccessor;\n}\n</code></pre>\n<p>Step 3: Add this method in your class:</p>\n<pre><code>private string GenerateFullDomain()\n{\n string domain = _contextAccessor.HttpContext.Request.Host.Value;\n string scheme = _contextAccessor.HttpContext.Request.Scheme;\n string delimiter = System.Uri.SchemeDelimiter;\n string fullDomainToUse = scheme + delimiter + domain;\n return fullDomainToUse;\n}\n//Examples of usage GenerateFullDomain() method:\n//https://example.com:5031\n//http://example.com:5031\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I am wondering what the best way to obtain the current domain is in ASP.NET? For instance: <http://www.domainname.com/subdir/> should yield <http://www.domainname.com> <http://www.sub.domainname.com/subdir/> should yield <http://sub.domainname.com> As a guide, I should be able to add a url like "/Folder/Content/filename.html" (say as generated by Url.RouteUrl() in ASP.NET MVC) straight onto the URL and it should work.
Same answer as MattMitchell's but with some modification. This checks for the default port instead. > > Edit: Updated syntax and using `Request.Url.Authority` as suggested > > > ``` $"{Request.Url.Scheme}{System.Uri.SchemeDelimiter}{Request.Url.Authority}" ```
61,838
<p>If I have something like a UILabel linked to a xib file, do I need to release it on dealloc of my view? The reason I ask is because I don't alloc it, which makes me think I don't need to release it either? eg (in the header):</p> <pre><code>IBOutlet UILabel *lblExample; </code></pre> <p>in the implementation:</p> <pre><code>.... [lblExample setText:@"whatever"]; .... -(void)dealloc{ [lblExample release];//????????? } </code></pre>
[ { "answer_id": 61841, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 0, "selected": false, "text": "<p>Related: <a href=\"https://stackoverflow.com/questions/6578/understanding-reference-counting-with-cocoa-objective-c\">Understanding reference counting with Cocoa / Objective C</a></p>\n" }, { "answer_id": 61867, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 0, "selected": false, "text": "<p>You do alloc the label, in a sense, by creating it in IB.</p>\n\n<p>What IB does, is look at your IBOutlets and how they are defined. If you have a class variable that IB is to assign a reference to some object, IB will send a retain message to that object for you.</p>\n\n<p>If you are using properties, IB will make use of the property you have to set the value and not explicitly retain the value. Thus you would normally mark IBOutlet properties as retain:</p>\n\n<pre><code>@property (nonatomic, retain) UILabel *lblExample;\n</code></pre>\n\n<p>Thus in ether case (using properties or not) you should call release in your dealloc.</p>\n" }, { "answer_id": 61942, "author": "rustyshelf", "author_id": 6044, "author_profile": "https://Stackoverflow.com/users/6044", "pm_score": 2, "selected": false, "text": "<p>I found what I was looking for in the Apple docs. In short you can set up your objects as properties that you release and retain (or just @property, @synthesize), but you don't have to for things like UILabels:</p>\n\n<p><a href=\"http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/chapter_3_section_4.html#//apple_ref/doc/uid/10000051i-CH4-SW18\" rel=\"nofollow noreferrer\">http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/LoadingResources/CocoaNibs/chapter_3_section_4.html#//apple_ref/doc/uid/10000051i-CH4-SW18</a></p>\n" }, { "answer_id": 62985, "author": "Eric Allam", "author_id": 7434, "author_profile": "https://Stackoverflow.com/users/7434", "pm_score": 0, "selected": false, "text": "<p>Any IBOutlet that is a subview of your Nib's main view does not need to be released, because they will be sent the autorelease message upon object creation. The only IBOutlet's you need to release in your dealloc are top level objects like controllers or other NSObject's. This is all mentioned in the Apple doc linked to above.</p>\n" }, { "answer_id": 191935, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 6, "selected": true, "text": "<p>If you follow what is now considered to be best practice, you <em>should</em> release outlet properties, because you should have retained them in the set accessor:</p>\n\n<pre><code>@interface MyController : MySuperclass {\n Control *uiElement;\n}\n@property (nonatomic, retain) IBOutlet Control *uiElement;\n@end\n\n\n@implementation MyController\n\n@synthesize uiElement;\n\n- (void)dealloc {\n [uiElement release];\n [super dealloc];\n}\n@end\n</code></pre>\n\n<p>The advantage of this approach is that it makes the memory management semantics explicit and clear, <em>and it works consistently across all platforms for all nib files</em>.</p>\n\n<p>Note: The following comments apply only to iOS prior to 3.0. With 3.0 and later, you should instead simply nil out property values in viewDidUnload.</p>\n\n<p>One consideration here, though, is when your controller might dispose of its user interface and reload it dynamically on demand (for example, if you have a view controller that loads a view from a nib file, but on request -- say under memory pressure -- releases it, with the expectation that it can be reloaded if the view is needed again). In this situation, you want to make sure that when the main view is disposed of you also relinquish ownership of any other outlets so that they too can be deallocated. For UIViewController, you can deal with this issue by overriding <code>setView:</code> as follows:</p>\n\n<pre><code>- (void)setView:(UIView *)newView {\n if (newView == nil) {\n self.uiElement = nil;\n }\n [super setView:aView];\n}\n</code></pre>\n\n<p>Unfortunately this gives rise to a further issue. Because UIViewController currently implements its <code>dealloc</code> method using the <code>setView:</code> accessor method (rather than simply releasing the variable directly), <code>self.anOutlet = nil</code> will be called in <code>dealloc</code> as well as in response to a memory warning... This will lead to a crash in <code>dealloc</code>.</p>\n\n<p>The remedy is to ensure that outlet variables are also set to <code>nil</code> in <code>dealloc</code>:</p>\n\n<pre><code>- (void)dealloc {\n // release outlets and set variables to nil\n [anOutlet release], anOutlet = nil;\n [super dealloc];\n}\n</code></pre>\n" }, { "answer_id": 567962, "author": "Wil Shipley", "author_id": 30602, "author_profile": "https://Stackoverflow.com/users/30602", "pm_score": 2, "selected": false, "text": "<p>The </p>\n\n<pre><code>[anOutlet release], anOutlet = nil;\n</code></pre>\n\n<p>Part is completely superfluous if you've written setView: correctly.</p>\n" }, { "answer_id": 2295783, "author": "Shaikh Sonny Aman", "author_id": 133539, "author_profile": "https://Stackoverflow.com/users/133539", "pm_score": 1, "selected": false, "text": "<p>If you don’t release it on dealloc it will raise the memory footprint. </p>\n\n<p><a href=\"http://amanpages.com/iphone-app-development-core-sdk-cocoa/iphone-iboutlet-should-be-released-manually/\" rel=\"nofollow noreferrer\">See more detail here with instrument ObjectAlloc graph</a></p>\n" }, { "answer_id": 10135225, "author": "stephen", "author_id": 680161, "author_profile": "https://Stackoverflow.com/users/680161", "pm_score": 0, "selected": false, "text": "<p>If you dont set the IBOutlet as a property but simply as a instance variable, you still must release it. This is because upon initWithNib, memory will be allocated for all IBOutlets. So this is one of the special cases you must release even though you haven't retained or alloc'd any memory in code.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ]
If I have something like a UILabel linked to a xib file, do I need to release it on dealloc of my view? The reason I ask is because I don't alloc it, which makes me think I don't need to release it either? eg (in the header): ``` IBOutlet UILabel *lblExample; ``` in the implementation: ``` .... [lblExample setText:@"whatever"]; .... -(void)dealloc{ [lblExample release];//????????? } ```
If you follow what is now considered to be best practice, you *should* release outlet properties, because you should have retained them in the set accessor: ``` @interface MyController : MySuperclass { Control *uiElement; } @property (nonatomic, retain) IBOutlet Control *uiElement; @end @implementation MyController @synthesize uiElement; - (void)dealloc { [uiElement release]; [super dealloc]; } @end ``` The advantage of this approach is that it makes the memory management semantics explicit and clear, *and it works consistently across all platforms for all nib files*. Note: The following comments apply only to iOS prior to 3.0. With 3.0 and later, you should instead simply nil out property values in viewDidUnload. One consideration here, though, is when your controller might dispose of its user interface and reload it dynamically on demand (for example, if you have a view controller that loads a view from a nib file, but on request -- say under memory pressure -- releases it, with the expectation that it can be reloaded if the view is needed again). In this situation, you want to make sure that when the main view is disposed of you also relinquish ownership of any other outlets so that they too can be deallocated. For UIViewController, you can deal with this issue by overriding `setView:` as follows: ``` - (void)setView:(UIView *)newView { if (newView == nil) { self.uiElement = nil; } [super setView:aView]; } ``` Unfortunately this gives rise to a further issue. Because UIViewController currently implements its `dealloc` method using the `setView:` accessor method (rather than simply releasing the variable directly), `self.anOutlet = nil` will be called in `dealloc` as well as in response to a memory warning... This will lead to a crash in `dealloc`. The remedy is to ensure that outlet variables are also set to `nil` in `dealloc`: ``` - (void)dealloc { // release outlets and set variables to nil [anOutlet release], anOutlet = nil; [super dealloc]; } ```
61,861
<p>I would like to make my web control more readable in design mode, basically I want the tag declaration to look like:</p> <pre><code>&lt;cc1:Ctrl ID="Value1" runat="server"&gt; &lt;Values&gt;string value 1&lt;/Value&gt; &lt;Values&gt;string value 2&lt;/Value&gt; &lt;/cc1:Ctrl&gt; </code></pre> <p>Lets say I have a private variable in the code behind:</p> <pre><code>List&lt;string&gt; values = new List&lt;string&gt;(); </code></pre> <p>So how can I make my user control fill out the private variable with the values that are declared in the markup?</p> <hr> <p>Sorry I should have been more explicit. Basically I like the functionality that the ITemplate provides (<a href="http://msdn.microsoft.com/en-us/library/aa719834.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa719834.aspx</a>)</p> <p>But in this case you need to know at runtime how many templates can be instansitated, i.e.</p> <pre><code>void Page_Init() { if (messageTemplate != null) { for (int i=0; i&lt;5; i++) { MessageContainer container = new MessageContainer(i); messageTemplate.InstantiateIn(container); msgholder.Controls.Add(container); } } </code></pre> <p>}</p> <p>In the given example the markup looks like:</p> <pre><code>&lt;acme:test runat=server&gt; &lt;MessageTemplate&gt; Hello #&lt;%# Container.Index %&gt;.&lt;br&gt; &lt;/MessageTemplate&gt; &lt;/acme:test&gt; </code></pre> <p>Which is nice and clean, it does not have any tag prefixes etc. I really want the nice clean tags.</p> <p>I'm probably being silly in wanting the markup to be clean, I'm just wondering if there is something simple that I'm missing.</p>
[ { "answer_id": 61925, "author": "Matt", "author_id": 4154, "author_profile": "https://Stackoverflow.com/users/4154", "pm_score": 0, "selected": false, "text": "<p>I see two options, but both depend on your web control implementing some sort of collection for your values. The first option is to just use the control's collection instead of your private variable. The other option is to copy the control's collection to your private variable at run-time (maybe in the Page_Load event handler, for example).</p>\n\n<p>Say you have web control that implements a collection of items, like a listbox. The tag looks like this in the source view:</p>\n\n<pre><code> &lt;asp:ListBox ID=\"ListBox1\" runat=\"server\"&gt;\n &lt;asp:ListItem&gt;String 1&lt;/asp:ListItem&gt;\n &lt;asp:ListItem&gt;String 2&lt;/asp:ListItem&gt;\n &lt;asp:ListItem&gt;String 3&lt;/asp:ListItem&gt;\n &lt;/asp:ListBox&gt;&lt;br /&gt;\n</code></pre>\n\n<p>Then you might use code like this to load your private variable:</p>\n\n<pre><code> List&lt;String&gt; values = new List&lt;String&gt;();\n\n foreach (ListItem item in ListBox1.Items)\n {\n values.Add(item.Value.ToString());\n }\n</code></pre>\n\n<p>If you do this in Page_Load you'll probably want to only execute on the initial load (i.e. not on postbacks). On the other hand, depending on how you use it, you could just use the ListBox1.Items collection instead of declaring and initializing the values variable.</p>\n\n<p>I can think of no way to do this declaratively (since your list won't be instantiated until run-time anyway).</p>\n" }, { "answer_id": 62589, "author": "Luca Molteni", "author_id": 4206, "author_profile": "https://Stackoverflow.com/users/4206", "pm_score": 3, "selected": true, "text": "<p>I think what you are searching for is the attribute:</p>\n\n<pre><code>[PersistenceMode(PersistenceMode.InnerProperty)]\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.persistencemode.aspx\" rel=\"nofollow noreferrer\">Persistence Mode</a></p>\n\n<p>Remember that you have to register your namespace and prefix with:</p>\n\n<pre><code>&lt;%@ Register Namespace=\"MyNamespace\" TagPrefix=\"Pref\" %&gt;\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2758/" ]
I would like to make my web control more readable in design mode, basically I want the tag declaration to look like: ``` <cc1:Ctrl ID="Value1" runat="server"> <Values>string value 1</Value> <Values>string value 2</Value> </cc1:Ctrl> ``` Lets say I have a private variable in the code behind: ``` List<string> values = new List<string>(); ``` So how can I make my user control fill out the private variable with the values that are declared in the markup? --- Sorry I should have been more explicit. Basically I like the functionality that the ITemplate provides (<http://msdn.microsoft.com/en-us/library/aa719834.aspx>) But in this case you need to know at runtime how many templates can be instansitated, i.e. ``` void Page_Init() { if (messageTemplate != null) { for (int i=0; i<5; i++) { MessageContainer container = new MessageContainer(i); messageTemplate.InstantiateIn(container); msgholder.Controls.Add(container); } } ``` } In the given example the markup looks like: ``` <acme:test runat=server> <MessageTemplate> Hello #<%# Container.Index %>.<br> </MessageTemplate> </acme:test> ``` Which is nice and clean, it does not have any tag prefixes etc. I really want the nice clean tags. I'm probably being silly in wanting the markup to be clean, I'm just wondering if there is something simple that I'm missing.
I think what you are searching for is the attribute: ``` [PersistenceMode(PersistenceMode.InnerProperty)] ``` [Persistence Mode](http://msdn.microsoft.com/en-us/library/system.web.ui.persistencemode.aspx) Remember that you have to register your namespace and prefix with: ``` <%@ Register Namespace="MyNamespace" TagPrefix="Pref" %> ```
61,872
<p>We are rewriting our legacy <a href="https://en.wikipedia.org/wiki/Accounting_information_system" rel="nofollow noreferrer">accounting system</a> in VB.NET and SQL Server. We brought in a new team of .NET/ SQL Programmers to do the rewrite. Most of the system is already completed with the dollar amounts using floats. The legacy system language, I programmed in, did not have a float, so I probably would have used a decimal.</p> <p>What is your recommendation?</p> <p>Should the float or decimal data type be used for dollar amounts?</p> <p>What are some of the pros and cons for either?</p> <p>One <em>con</em> mentioned in our <a href="https://en.wikipedia.org/wiki/Scrum_%28software_development%29#Daily_scrum" rel="nofollow noreferrer">daily scrum</a> was you have to be careful when you calculate an amount that returns a result that is over two decimal positions. It sounds like you will have to round the amount to two decimal positions.</p> <p>Another <em>con</em> is all displays and printed amounts have to have a <em>format statement</em> that shows two decimal positions. I noticed a few times where this was not done and the amounts did not look correct. (i.e. 10.2 or 10.2546)</p> <p>A <em>pro</em> is the float-only approach takes up eight bytes on disk where the decimal would take up nine bytes (decimal 12,2).</p>
[ { "answer_id": 61875, "author": "Niall", "author_id": 6049, "author_profile": "https://Stackoverflow.com/users/6049", "pm_score": 2, "selected": false, "text": "<p>Floats are not exact representations, precision issues are possible, for example when adding very large and very small values. That's why decimal types are recommended for currency, even though the precision issue may be sufficiently rare.</p>\n\n<p>To clarify, the decimal 12,2 type will store those 14 digits exactly, whereas the float will not as it uses a binary representation internally. For example, 0.01 cannot be represented exactly by a floating point number - the closest representation is actually 0.0099999998</p>\n" }, { "answer_id": 61876, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 1, "selected": false, "text": "<p>Have you considered using the money-data type to store dollar-amounts?</p>\n<p>Regarding the con that decimal takes up one more byte, I would say don't care about it. In 1 million rows you will only use 1 more MB and storage is very cheap these days.</p>\n" }, { "answer_id": 61877, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>Whatever you do, you need to be careful of rounding errors. Calculate using a greater degree of precision than you display in.</p>\n" }, { "answer_id": 61878, "author": "David Singer", "author_id": 4618, "author_profile": "https://Stackoverflow.com/users/4618", "pm_score": 2, "selected": false, "text": "<p>The only reason to use Float for money is if you don't care about accurate answers. </p>\n" }, { "answer_id": 61896, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Ask your accountants! They will frown upon you for using float. Like <a href=\"https://stackoverflow.com/questions/61872/use-float-or-decimal-for-accounting-application-dollar-amount/61878#61878\">David Singer said</a>, use float <em>only</em> if you don't care for accuracy. Although I would always be against it when it comes to money.</p>\n<p>In accounting software is <em>not</em> acceptable a float. Use decimal with four decimal points.</p>\n" }, { "answer_id": 61994, "author": "Rich Schuler", "author_id": 6391, "author_profile": "https://Stackoverflow.com/users/6391", "pm_score": 5, "selected": false, "text": "<p>First you should read <em><a href=\"http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.6768\" rel=\"nofollow noreferrer\" title=\"What Every Computer Scientist Should Know About Floating Point Arithmetic\">What Every Computer Scientist Should Know About Floating Point Arithmetic</a></em>. Then you should really consider using some type of <a href=\"http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic\" rel=\"nofollow noreferrer\">fixed point / arbitrary-precision number</a> package (e.g., Java BigNum or Python decimal module). Otherwise, you'll be in for a world of hurt. Then figure out if using the native SQL decimal type is enough.</p>\n<p>Floats and doubles exist(ed) to expose the fast <a href=\"https://en.wikipedia.org/wiki/Intel_8087\" rel=\"nofollow noreferrer\">x87 floating-point coprocessor</a> that is now pretty much obsolete. Don't use them if you care about the accuracy of the computations and/or don't fully compensate for their limitations.</p>\n" }, { "answer_id": 62071, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "<p>Floating points have unexpected irrational numbers.</p>\n<p>For instance you can't store 1/3 as a decimal, it would be 0.3333333333... (and so on)</p>\n<p>Floats are actually stored as a binary value and a power of 2 exponent.</p>\n<p>So 1.5 is stored as 3 x 2 to the -1 (or 3/2)</p>\n<p>Using these base-2 exponents create some odd irrational numbers, for instance:</p>\n<p>Convert 1.1 to a float and then convert it back again, your result will be something like: 1.0999999999989</p>\n<p>This is because the binary representation of 1.1 is actually 154811237190861 x 2^-47, more than a double can handle.</p>\n<p>More about this issue on <a href=\"http://bizvprog.blogspot.com/2008/05/floating-point-numbers-more-inaccurate.html\" rel=\"nofollow noreferrer\">my blog</a>, but basically, for storage, you're better off with decimals.</p>\n<p>On Microsoft SQL server you have the <code>money</code> data type - this is usually best for financial storage. It is accurate to 4 decimal positions.</p>\n<p>For calculations you have more of a problem - the inaccuracy is a tiny fraction, but put it into a power function and it quickly becomes significant.</p>\n<p>However decimals aren't very good for any sort of maths - there's no native support for decimal powers, for instance.</p>\n" }, { "answer_id": 62132, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 2, "selected": false, "text": "<p>For a banking system I helped develop, I was responsible for the \"interest accrual\" part of the system. Each day, my code calculated how much interest had been accrued (earnt) on the balance that day.</p>\n\n<p>For that calculation, extreme accuracy and fidelity was required (we used Oracle's FLOAT) so we could record the \"billionth's of a penny\" being accrued.</p>\n\n<p>When it came to \"capitalising\" the interest (ie. paying the interest back into your account) the amount was rounded to the penny. The data type for the account balances was two decimal places. (In fact it was more complicated as it was a multi-currency system that could work in many decimal places - but we always rounded to the \"penny\" of that currency). Yes - there where \"fractions\" of loss and gain, but when the computers figures were actualised (money paid out or paid in) it was always REAL money values.</p>\n\n<p>This satisfied the accountants, auditors and testers.</p>\n\n<p>So, check with your customers. They will tell you their banking/accounting rules and practices.</p>\n" }, { "answer_id": 62493, "author": "David T. Macknet", "author_id": 6850, "author_profile": "https://Stackoverflow.com/users/6850", "pm_score": 0, "selected": false, "text": "<p>Your accountants will want to control how you round. Using float means that you'll be constantly rounding, usually with a <code>FORMAT()</code> type statement, which isn't the way you want to do it (use <code>floor</code> / <code>ceiling</code> instead).</p>\n\n<p>You have currency datatypes (<code>money</code>, <code>smallmoney</code>), which should be used instead of float or real. Storing decimal (12,2) will eliminate your roundings, but will also eliminate them during intermediate steps - which really isn't what you'll want at all in a financial application.</p>\n" }, { "answer_id": 62518, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Always use Decimal. Float will give you inaccurate values due to rounding issues.</p>\n" }, { "answer_id": 62553, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 0, "selected": false, "text": "<p>Floating point numbers can <em>only</em> represent numbers that are a sum of negative multiples of the base - for binary floating point, of course, that's two.</p>\n\n<p>There are only four decimal fractions representable precisely in binary floating point: 0, 0.25, 0.5 and 0.75. Everything else is an approximation, in the same way that 0.3333... is an approximation for 1/3 in decimal arithmetic.</p>\n\n<p>Floating point is a good choice for computations where the scale of the result is what is important. It's a bad choice where you're trying to be accurate to some number of decimal places.</p>\n" }, { "answer_id": 62781, "author": "user6931", "author_id": 6931, "author_profile": "https://Stackoverflow.com/users/6931", "pm_score": 1, "selected": false, "text": "<p>You will probably want to use some form of fixed point representation for currency values. You will also want to investigate <a href=\"https://en.wikipedia.org/wiki/Rounding#Round_half_to_even\" rel=\"nofollow noreferrer\">banker's rounding</a> (also known as &quot;round half to even&quot;). It avoids bias that exist in the usual &quot;round half up&quot; method.</p>\n" }, { "answer_id": 62802, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 3, "selected": false, "text": "<p>Just as an additional warning, SQL Server and the .NET framework use a different default algorithm for rounding. Make sure you check out the MidPointRounding parameter in Math.Round(). .NET framework uses <a href=\"https://en.wikipedia.org/wiki/Rounding#Round_half_to_even\" rel=\"nofollow noreferrer\">bankers' rounding</a> by default and SQL Server uses Symmetric Algorithmic Rounding. Check out the Wikipedia article <a href=\"http://en.wikipedia.org/wiki/Rounding\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 66678, "author": "TSK", "author_id": 9959, "author_profile": "https://Stackoverflow.com/users/9959", "pm_score": 8, "selected": true, "text": "<blockquote>\n<p>Should Float or Decimal data type be used for dollar amounts?</p>\n</blockquote>\n<p>The answer is easy. Never floats. <em>NEVER</em>!</p>\n<p>Floats were according to <a href=\"http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=4610933\" rel=\"nofollow noreferrer\">IEEE 754</a> always binary, only the new standard <a href=\"http://www.intel.com/technology/itj/2007/v11i1/s2-decimal/1-sidebar.htm\" rel=\"nofollow noreferrer\">IEEE 754R</a> defined decimal formats. Many of the fractional binary parts can never equal the exact decimal representation.</p>\n<p>Any binary number can be written as <code>m/2^n</code> (<code>m</code>, <code>n</code> positive integers), any decimal number as <code>m/(2^n*5^n)</code>.\nAs binaries lack the prime <code>factor 5</code>, all binary numbers can be exactly represented by decimals, but not vice versa.</p>\n<pre><code>0.3 = 3/(2^1 * 5^1) = 0.3\n\n0.3 = [0.25/0.5] [0.25/0.375] [0.25/3.125] [0.2825/3.125]\n\n 1/4 1/8 1/16 1/32\n</code></pre>\n<p>So you end up with a number either higher or lower than the given decimal number. Always.</p>\n<p>Why does that matter? Rounding.</p>\n<p>Normal rounding means 0..4 down, 5..9 up. So it <em>does</em> matter if the result is\neither <code>0.049999999999</code>.... or <code>0.0500000000</code>... You may know that it means 5 cent, but the the computer does not know that and rounds <code>0.4999</code>... down (wrong) and <code>0.5000</code>... up (right).</p>\n<p>Given that the result of floating point computations always contain small error terms, the decision is pure luck. It gets hopeless if you want decimal round-to-even handling with binary numbers.</p>\n<p>Unconvinced? You insist that in your account system everything is perfectly ok?\nAssets and liabilities equal? Ok, then take each of the given formatted numbers of each entry, parse them and sum them with an independent decimal system!</p>\n<p>Compare that with the formatted sum. Oops, there is something wrong, isn't it?</p>\n<blockquote>\n<p>For that calculation, extreme accuracy and fidelity was required (we used Oracle's\nFLOAT) so we could record the &quot;billionth's of a penny&quot; being accured.</p>\n</blockquote>\n<p>It doesn't help against this error. Because all people automatically assume that the computer sums right, and practically no one checks independently.</p>\n" }, { "answer_id": 70868, "author": "Peter Stuifzand", "author_id": 1633, "author_profile": "https://Stackoverflow.com/users/1633", "pm_score": 2, "selected": false, "text": "<p>Even better than using decimals is using just plain old integers (or maybe some kind of bigint). This way you always have the highest accuracy possible, but the precision can be specified. For example the number <code>100</code> could mean <code>1.00</code>, which is formatted like this:</p>\n\n<pre><code>int cents = num % 100;\nint dollars = (num - cents) / 100;\nprintf(\"%d.%02d\", dollars, cents);\n</code></pre>\n\n<p>If you like to have more precision, you can change the 100 to a bigger value, like: 10 ^ n, where n is the number of decimals.</p>\n" }, { "answer_id": 110374, "author": "Tomer Pintel", "author_id": 15556, "author_profile": "https://Stackoverflow.com/users/15556", "pm_score": 2, "selected": false, "text": "<p>You can always write something like a Money type for .NET.</p>\n<p>Take a look at this article: <a href=\"http://www.codeproject.com/KB/recipes/MoneyTypeForCLR.aspx\" rel=\"nofollow noreferrer\">A Money type for the CLR</a>. The author did an excellent work in my opinion.</p>\n" }, { "answer_id": 257679, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": false, "text": "<p>Use SQL Server's <strong>decimal</strong> type.</p>\n<p>Do not use <em>money</em> or <em>float</em>.</p>\n<p><em>money</em> uses four decimal places and is faster than using decimal, <em><strong>but</strong></em> suffers from some obvious and some not so obvious problems with rounding (<a href=\"http://groups.google.com/group/microsoft.public.sqlserver.server/browse_thread/thread/e19bf068e208dd5b/f79e614829931537?hl=en&amp;lnk=st&amp;q=author%3Akass+money+accuracy&amp;pli=1\" rel=\"nofollow noreferrer\">see this connect issue</a>).</p>\n" }, { "answer_id": 257694, "author": "Joshua", "author_id": 14768, "author_profile": "https://Stackoverflow.com/users/14768", "pm_score": 3, "selected": false, "text": "<p>I'd recommend using 64-bit integers that store the whole thing in cents.</p>\n" }, { "answer_id": 528264, "author": "George", "author_id": 64187, "author_profile": "https://Stackoverflow.com/users/64187", "pm_score": 2, "selected": false, "text": "<p>I had been using SQL's money type for storing monetary values. Recently, I've had to work with a number of online payment systems and have noticed that some of them use integers for storing monetary values. In my current and new projects I've started using integers and I'm pretty content with this solution.</p>\n" }, { "answer_id": 528908, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 3, "selected": false, "text": "<p>A bit of background here....</p>\n\n<p>No number system can handle all real numbers accurately. All have their limitations, and this includes both the standard IEEE floating point and signed decimal. The IEEE floating point is more accurate per bit used, but that doesn't matter here.</p>\n\n<p>Financial numbers are based on centuries of paper-and-pen practice, with associated conventions. They are reasonably accurate, but, more importantly, they're reproducible. Two accountants working with various numbers and rates should come up with the same number. Any room for discrepancy is room for fraud.</p>\n\n<p>Therefore, for financial calculations, the right answer is whatever gives the same answer as a CPA who's good at arithmetic. This is decimal arithmetic, not IEEE floating point.</p>\n" }, { "answer_id": 528962, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 2, "selected": false, "text": "<p>Another thing you should be aware of in accounting systems is that no one should have direct access to the tables. This means all access to the accounting system must be through <a href=\"https://en.wikipedia.org/wiki/Stored_procedure\" rel=\"nofollow noreferrer\">stored procedures</a>.</p>\n<p>This is to prevent fraud, not just <a href=\"https://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">SQL injection</a> attacks. An internal user who wants to commit fraud should not have the ability to directly change data in the database tables, ever. This is a critical internal control on your system.</p>\n<p>Do you really want some disgruntled employee to go to the backend of your database and have it start writing them checks? Or hide that they approved an expense to an unauthorized vendor when they don't have approval authority? Only two people in your whole organization should be able to directly access data in your financial database, your database administrator (DBA) and his backup. If you have many DBAs, only two of them should have this access.</p>\n<p>I mention this because if your programmers used float in an accounting system, likely they are completely unfamiliar with the idea of internal controls and did not consider them in their programming effort.</p>\n" }, { "answer_id": 3991553, "author": "Lars Bohl", "author_id": 438960, "author_profile": "https://Stackoverflow.com/users/438960", "pm_score": 2, "selected": false, "text": "<p>Out of the 100 fractions n/100, where n is a natural number such that 0 &lt;= n and n &lt; 100, only four can be represented as floating point numbers. Take a look at the output of this C program:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n printf(\"Mapping 100 numbers between 0 and 1 \");\n printf(\"to their hexadecimal exponential form (HEF).\\n\");\n printf(\"Most of them do not equal their HEFs. That means \");\n printf(\"that their representations as floats \");\n printf(\"differ from their actual values.\\n\");\n double f = 0.01;\n int i;\n for (i = 0; i &lt; 100; i++) {\n printf(\"%1.2f -&gt; %a\\n\",f*i,f*i);\n }\n printf(\"Printing 128 'float-compatible' numbers \");\n printf(\"together with their HEFs for comparison.\\n\");\n f = 0x1p-7; // ==0.0071825\n for (i = 0; i &lt; 0x80; i++) {\n printf(\"%1.7f -&gt; %a\\n\",f*i,f*i);\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 4001766, "author": "Nakilon", "author_id": 322020, "author_profile": "https://Stackoverflow.com/users/322020", "pm_score": 6, "selected": false, "text": "<p>This photo answers:</p>\n\n<p><img src=\"https://i.stack.imgur.com/RqaoR.jpg\" alt=\"photo1,C.O.\"></p>\n\n<p>This is another situation: <a href=\"http://web.archive.org/web/20120731044947/http://www.wwlp.com/dpp/news/i_team/I-Team:Man-gets-a-$0-foreclosure-notice\" rel=\"noreferrer\"><em>man from Northampton got a letter stating his home would be seized if he didn't pay up zero dollars and zero cents!</em></a></p>\n\n<p><img src=\"https://i.stack.imgur.com/ssMtJ.jpg\" alt=\"photo2,C.O.\"></p>\n" }, { "answer_id": 4002088, "author": "BrokeMyLegBiking", "author_id": 97686, "author_profile": "https://Stackoverflow.com/users/97686", "pm_score": 0, "selected": false, "text": "<p>This is an excellent article describing <a href=\"http://sqlblog.com/blogs/hugo_kornelis/archive/2007/10/17/so-called-exact-numerics-are-not-at-all-exact.aspx\" rel=\"nofollow\">when to use float and decimal</a>. Float stores an approximate value and decimal stores an exact value.</p>\n\n<p>In summary, exact values like money should use decimal, and approximate values like scientific measurements should use float. </p>\n\n<p>Here is an interesting example that shows that both float and decimal are capable of losing precision. When adding a number that is not an integer and then subtracting that same number float results in losing precision while decimal does not:</p>\n\n<pre><code> DECLARE @Float1 float, @Float2 float, @Float3 float, @Float4 float; \n SET @Float1 = 54; \n SET @Float2 = 3.1; \n SET @Float3 = 0 + @Float1 + @Float2; \n SELECT @Float3 - @Float1 - @Float2 AS \"Should be 0\";\n\nShould be 0 \n---------------------- \n1.13797860024079E-15\n</code></pre>\n\n<p>When multiplying a non integer and dividing by that same number, decimals lose precision while floats do not.</p>\n\n<pre><code>DECLARE @Fixed1 decimal(8,4), @Fixed2 decimal(8,4), @Fixed3 decimal(8,4); \nSET @Fixed1 = 54; \nSET @Fixed2 = 0.03; \nSET @Fixed3 = 1 * @Fixed1 / @Fixed2; \nSELECT @Fixed3 / @Fixed1 * @Fixed2 AS \"Should be 1\";\n\nShould be 1 \n--------------------------------------- \n0.99999999999999900\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4964/" ]
We are rewriting our legacy [accounting system](https://en.wikipedia.org/wiki/Accounting_information_system) in VB.NET and SQL Server. We brought in a new team of .NET/ SQL Programmers to do the rewrite. Most of the system is already completed with the dollar amounts using floats. The legacy system language, I programmed in, did not have a float, so I probably would have used a decimal. What is your recommendation? Should the float or decimal data type be used for dollar amounts? What are some of the pros and cons for either? One *con* mentioned in our [daily scrum](https://en.wikipedia.org/wiki/Scrum_%28software_development%29#Daily_scrum) was you have to be careful when you calculate an amount that returns a result that is over two decimal positions. It sounds like you will have to round the amount to two decimal positions. Another *con* is all displays and printed amounts have to have a *format statement* that shows two decimal positions. I noticed a few times where this was not done and the amounts did not look correct. (i.e. 10.2 or 10.2546) A *pro* is the float-only approach takes up eight bytes on disk where the decimal would take up nine bytes (decimal 12,2).
> > Should Float or Decimal data type be used for dollar amounts? > > > The answer is easy. Never floats. *NEVER*! Floats were according to [IEEE 754](http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=4610933) always binary, only the new standard [IEEE 754R](http://www.intel.com/technology/itj/2007/v11i1/s2-decimal/1-sidebar.htm) defined decimal formats. Many of the fractional binary parts can never equal the exact decimal representation. Any binary number can be written as `m/2^n` (`m`, `n` positive integers), any decimal number as `m/(2^n*5^n)`. As binaries lack the prime `factor 5`, all binary numbers can be exactly represented by decimals, but not vice versa. ``` 0.3 = 3/(2^1 * 5^1) = 0.3 0.3 = [0.25/0.5] [0.25/0.375] [0.25/3.125] [0.2825/3.125] 1/4 1/8 1/16 1/32 ``` So you end up with a number either higher or lower than the given decimal number. Always. Why does that matter? Rounding. Normal rounding means 0..4 down, 5..9 up. So it *does* matter if the result is either `0.049999999999`.... or `0.0500000000`... You may know that it means 5 cent, but the the computer does not know that and rounds `0.4999`... down (wrong) and `0.5000`... up (right). Given that the result of floating point computations always contain small error terms, the decision is pure luck. It gets hopeless if you want decimal round-to-even handling with binary numbers. Unconvinced? You insist that in your account system everything is perfectly ok? Assets and liabilities equal? Ok, then take each of the given formatted numbers of each entry, parse them and sum them with an independent decimal system! Compare that with the formatted sum. Oops, there is something wrong, isn't it? > > For that calculation, extreme accuracy and fidelity was required (we used Oracle's > FLOAT) so we could record the "billionth's of a penny" being accured. > > > It doesn't help against this error. Because all people automatically assume that the computer sums right, and practically no one checks independently.
61,893
<p>I am attempting to copy a custom struct from kernel space to user space. inside user space errno returns 'bad address'. What is the usual cause of a bad address error?</p> <pre><code>if(copy_to_user(info, &amp;kernel_info, sizeof(struct prinfo))) </code></pre>
[ { "answer_id": 61948, "author": "roo", "author_id": 716, "author_profile": "https://Stackoverflow.com/users/716", "pm_score": 3, "selected": false, "text": "<p>Bad Address error means that the address location that you have given is invalid. With the case you have above I would guess it is because you are passing a copy of <code>info</code> instead of a pointer to <code>info</code>'s memory location.</p>\n\n<p>Looking at the docs, <code>copy_to_user</code> is defined as</p>\n\n<pre><code>copy_to_user(void __user * to, const void * from, unsigned long n);\n</code></pre>\n\n<p>So unless your <code>info</code> variable is a pointer I would update your code to be:</p>\n\n<pre><code>if(copy_to_user(&amp;info, &amp;kernel_info, sizeof(struct prinfo)) ) {\n //some stuff here i guess\n}\n</code></pre>\n" }, { "answer_id": 74144, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 2, "selected": false, "text": "<p>Assuming that info is a pointer type and that info is pointing to a valid location it is still possible that info is pointing to an address that is not in user space which is required by the function.</p>\n" }, { "answer_id": 29774005, "author": "Vijay Kumar Kanta", "author_id": 1103688, "author_profile": "https://Stackoverflow.com/users/1103688", "pm_score": -1, "selected": false, "text": "<p>I had a same problem while writing a small char driver. All I was doing wrong was the function copy_to_user returns non-zero on failure, so you have to do this..</p>\n\n<pre><code>if(copy_to_user(void *userbuf, void *kernelbuf, long len))\n return -EFAULT;\n\n// Continue with code..\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am attempting to copy a custom struct from kernel space to user space. inside user space errno returns 'bad address'. What is the usual cause of a bad address error? ``` if(copy_to_user(info, &kernel_info, sizeof(struct prinfo))) ```
Bad Address error means that the address location that you have given is invalid. With the case you have above I would guess it is because you are passing a copy of `info` instead of a pointer to `info`'s memory location. Looking at the docs, `copy_to_user` is defined as ``` copy_to_user(void __user * to, const void * from, unsigned long n); ``` So unless your `info` variable is a pointer I would update your code to be: ``` if(copy_to_user(&info, &kernel_info, sizeof(struct prinfo)) ) { //some stuff here i guess } ```
61,894
<p>So I've done the trivial "warmup" apps with GAE. Now I'd like to build something with a more complex directory structure. Something along the lines of:</p> <pre><code>siteroot/ models/ controllers/ controller1/ controller2/ ... templates/ template1/ template2/ ... </code></pre> <p>..etc. The controllers will be Python modules handling requests. They would then need to locate (Django-style) templates in associated folders. Most of the demo apps I've seen resolve template paths like this:</p> <pre><code>path = os.path.join(os.path.dirname(__file__), 'myPage.html') </code></pre> <p>...the __ file __ property resolves to the currently executing script. So, in my above example, if a Python script were running in controllers/controller1/, then the 'myPage.html' would resolve to that same directory -- controllers/controller1/myPage.html -- and I would rather cleanly separate my Python code and templates.</p> <p>The solution I've hacked together feels... hacky:</p> <pre><code>base_paths = os.path.split(os.path.dirname(__file__)) template_dir = os.path.join(base_paths[0], "templates") </code></pre> <p>So, I'm just snipping off the last element of the path for the currently running script and appending the template directory to the new path. The other (non-GAE specific) solutions I've seen for resolving Python paths seem pretty heavyweight (such as splitting paths into lists and manipulating accordingly). Django seems to have an answer for this, but I'd rather stick to the GAE API, vs. creating a full Django app and modifying it for GAE.</p> <p>I'm assuming anything hard-coded would be non-starter, since the apps live on Google's infinite server farm. So what's a better way?</p>
[ { "answer_id": 62121, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 1, "selected": false, "text": "<p>The <code>dirname</code> function returns an absolute path, use relative paths. See what is the current directory when your controllers are executed with <code>os.path.abspath(os.path.curdir)</code> and build a path to the templates relative to that location (without the <code>os.path.abspath</code> part of course).</p>\n\n<p>This will only work if the current directory is somewhere inside <em>siteroot</em>, else you could do something like this:</p>\n\n<pre><code>template_dir = os.path.join(os.path.dirname(__file__), os.path.pardir, \"templates\")\n</code></pre>\n" }, { "answer_id": 102572, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 3, "selected": true, "text": "<p>You can't use relative paths, as Toni suggests, because you have no guarantee that the path from your working directory to your app's directory will remain the same.</p>\n\n<p>The correct solution is to either use os.path.split, as you are, or to use something like:</p>\n\n<pre><code>path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'myPage.html')\n</code></pre>\n\n<p>My usual approach is to generate a path to the template directory using the above method, and store it as a member of my controller object, and provide a \"getTemplatePath\" method that takes the provided filename and joins it with the basename.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4904/" ]
So I've done the trivial "warmup" apps with GAE. Now I'd like to build something with a more complex directory structure. Something along the lines of: ``` siteroot/ models/ controllers/ controller1/ controller2/ ... templates/ template1/ template2/ ... ``` ..etc. The controllers will be Python modules handling requests. They would then need to locate (Django-style) templates in associated folders. Most of the demo apps I've seen resolve template paths like this: ``` path = os.path.join(os.path.dirname(__file__), 'myPage.html') ``` ...the \_\_ file \_\_ property resolves to the currently executing script. So, in my above example, if a Python script were running in controllers/controller1/, then the 'myPage.html' would resolve to that same directory -- controllers/controller1/myPage.html -- and I would rather cleanly separate my Python code and templates. The solution I've hacked together feels... hacky: ``` base_paths = os.path.split(os.path.dirname(__file__)) template_dir = os.path.join(base_paths[0], "templates") ``` So, I'm just snipping off the last element of the path for the currently running script and appending the template directory to the new path. The other (non-GAE specific) solutions I've seen for resolving Python paths seem pretty heavyweight (such as splitting paths into lists and manipulating accordingly). Django seems to have an answer for this, but I'd rather stick to the GAE API, vs. creating a full Django app and modifying it for GAE. I'm assuming anything hard-coded would be non-starter, since the apps live on Google's infinite server farm. So what's a better way?
You can't use relative paths, as Toni suggests, because you have no guarantee that the path from your working directory to your app's directory will remain the same. The correct solution is to either use os.path.split, as you are, or to use something like: ``` path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'myPage.html') ``` My usual approach is to generate a path to the template directory using the above method, and store it as a member of my controller object, and provide a "getTemplatePath" method that takes the provided filename and joins it with the basename.
61,902
<p>I want to embed a wikipedia article into a page but I don't want all the wrapper (navigation, etc.) that sits around the articles. I saw it done here: <a href="http://www.dayah.com/periodic/" rel="nofollow noreferrer">http://www.dayah.com/periodic/</a>. Click on an element and the iframe is displayed and links to the article only (no wrapper). So how'd they do that? Seems like JavaScript handles showing the iframe and constructing the href but after browsing the pages javascript (<a href="http://www.dayah.com/periodic/Script/interactivity.js" rel="nofollow noreferrer">http://www.dayah.com/periodic/Script/interactivity.js</a>) I still can't figure out how the url is built. Thanks.</p>
[ { "answer_id": 61907, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": -1, "selected": false, "text": "<p>You could always download the site and scrap it. I think everything inside <code>&lt;div id=\"bodyContent\"&gt;</code> is the content of the article - sans navigation, header, footer, etc..</p>\n\n<p>Don't forget to credit. ;)</p>\n" }, { "answer_id": 61922, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 5, "selected": true, "text": "<p>The periodic table example loads the printer-friendly version of the wiki artice into an iframe. <a href=\"http://en.wikipedia.org/wiki/Potasium\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Potasium</a>?<b>printable=yes</b></p>\n\n<p>it's done in <i>function click_wiki(e)</i> (line 534, interactivity.js)</p>\n\n<blockquote><pre>\nvar article = el.childNodes[0].childNodes[n_name].innerHTML;\n...\nwindow.frames[\"WikiFrame\"].location.replace(\"http://\" + language + \".wikipedia.org/w/index.php?title=\" + encodeURIComponent(article) + \"&printable=yes\");\n</pre></blockquote>\n" }, { "answer_id": 62020, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 2, "selected": false, "text": "<p>@VolkerK is right, they are using the printable version.</p>\n\n<p>Here is an easy way to find out when you know the site is displaying the page in an iframe.</p>\n\n<p>In Firefox right click anywhere inside the iframe, from the context menu select \"This Frame\" then \"View frame info\"</p>\n\n<p>You get the info you need including the Address:</p>\n\n<blockquote>\n <p>Address: <a href=\"http://en.wikipedia.org/w/index.php?title=Chromium&amp;printable=yes\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/w/index.php?title=Chromium&amp;printable=yes</a></p>\n</blockquote>\n" }, { "answer_id": 62681, "author": "Henrik N", "author_id": 6962, "author_profile": "https://Stackoverflow.com/users/6962", "pm_score": 0, "selected": false, "text": "<p>The jQuery library lets you specify part of a page to retrieve by an Ajax call, with a CSS-like syntax: <a href=\"http://docs.jquery.com/Ajax/load\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Ajax/load</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5234/" ]
I want to embed a wikipedia article into a page but I don't want all the wrapper (navigation, etc.) that sits around the articles. I saw it done here: <http://www.dayah.com/periodic/>. Click on an element and the iframe is displayed and links to the article only (no wrapper). So how'd they do that? Seems like JavaScript handles showing the iframe and constructing the href but after browsing the pages javascript (<http://www.dayah.com/periodic/Script/interactivity.js>) I still can't figure out how the url is built. Thanks.
The periodic table example loads the printer-friendly version of the wiki artice into an iframe. <http://en.wikipedia.org/wiki/Potasium>?**printable=yes** it's done in *function click\_wiki(e)* (line 534, interactivity.js) > > ``` > > var article = el.childNodes[0].childNodes[n_name].innerHTML; > ... > window.frames["WikiFrame"].location.replace("http://" + language + ".wikipedia.org/w/index.php?title=" + encodeURIComponent(article) + "&printable=yes"); > > ``` >
61,906
<p>In Hibernate we have two classes with the following classes with JPA mapping:</p> <pre><code>package com.example.hibernate import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class Foo { private long id; private Bar bar; @Id @GeneratedValue(strategy = GenerationType.AUTO) public long getId() { return id; } public void setId(long id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) public Bar getBar() { return bar; } public void setBar(Bar bar) { this.bar = bar; } } package com.example.hibernate import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; public class Bar { private long id; private String title; @Id @GeneratedValue(strategy = GenerationType.AUTO) public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } </code></pre> <p>Now when we load from the database an object from class Foo using session get e.g:</p> <p>Foo foo = (Foo)session.get(Foo.class, 1 /* or some other id that exists in the DB*/); the Bar member of foo is a proxy object (in our case javassist proxy but it can be cglib one depending on the bytecode provider you use), that is not initialized. If you then use session.get to fetch the Bar object that is the member of the Foo class just loaded (we are in the same session), Hibernate does not issue another DB query and fetches the object from the session (first level) cache. The problem is this is a proxy to Bar class which is not initialized and trying to call this object getId() will return 0, and getTitle() will return null. Our current solution is pretty ugly and checks if the object returned from get is a proxy here is the code (form a generic DAO implementation):</p> <pre><code>@SuppressWarnings("unchecked") @Override @Transactional(readOnly = true) public &lt;T extends IEntity&gt; T get(Class&lt;T&gt; clazz, Serializable primaryKey) throws DataAccessException { T entity = (T) currentSession().get(clazz, primaryKey); if (entity != null) { if (LOG.isWarnEnabled()) { LOG.warn("Object not found for class " + clazz.getName() + " with primary key " + primaryKey); } } else if (entity instanceof HibernateProxy){ // TODO: force initialization due to Hibernate bug HibernateProxy proxy = (HibernateProxy)entity; if (!Hibernate.isInitialized(proxy)) { Hibernate.initialize(proxy); } entity = (T)proxy.getHibernateLazyInitializer().getImplementation(); } return entity; } </code></pre> <p>Is there a better way to do this, couldn't find a solution in the Hibernate forum, and didn't find the issue in Hibernate's JIRA.</p> <p>Note: we cannot just use foo.getBar() (which will initialize the proxy properly) to get the Bar class object, because the session.get operation to fetch the Bar object does not know (or care for that matter) that the Bar class is also a lazy member of a Foo object that was just fetched.</p>
[ { "answer_id": 61935, "author": "Chris Kimpton", "author_id": 48310, "author_profile": "https://Stackoverflow.com/users/48310", "pm_score": 0, "selected": false, "text": "<p>Not really seen this problem, although we do get intermittent Lazy Load errors - so perhaps we have the same problem, anyway, is it an option to use a different session for the loading of the Bar object - that should load it from scratch, I would expect...</p>\n" }, { "answer_id": 61989, "author": "Binil Thomas", "author_id": 3973, "author_profile": "https://Stackoverflow.com/users/3973", "pm_score": 0, "selected": false, "text": "<p>I am unable to reproduce the behaviour you are seeing. Here is my code:</p>\n\n<pre><code>@Entity\npublic class Foo {\n private Long id; private String name; private Bar bar;\n\n public Foo() { }\n public Foo(String name) { this.name = name; }\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n public Long getId() { return id; }\n public void setId(Long id) { this.id = id; }\n\n @Basic\n public String getName() { return name; }\n public void setName(String name) { this.name = name; }\n\n @ManyToOne(fetch = FetchType.LAZY)\n public Bar getBar() { return bar; }\n public void setBar(Bar bar) { this.bar = bar; }\n}\n\n@Entity\npublic class Bar {\n private Long id; private String name;\n\n public Bar() { }\n public Bar(String name) { this.name = name; }\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n public Long getId() { return id; }\n public void setId(Long id) { this.id = id; }\n\n @Basic\n public String getName() { return name; }\n public void setName(String name) { this.name = name; }\n}\n\n public void testGets() {\n SessionFactory sf = new AnnotationConfiguration()\n .addPackage(\"hibtest\")\n .addAnnotatedClass(Foo.class)\n .addAnnotatedClass(Bar.class)\n .configure().buildSessionFactory();\n Session session = null;\n Transaction txn = null;\n\n // Create needed data\n try {\n session = sf.openSession();\n txn = session.beginTransaction();\n\n // Create a Bar\n Bar bar = new Bar(\"Test Bar\");\n session.save(bar);\n\n // Create a Foo\n Foo foo = new Foo(\"Test Foo\");\n session.save(foo);\n\n foo.setBar(bar);\n\n txn.commit();\n } catch (HibernateException ex) {\n if (txn != null) txn.rollback();\n throw ex;\n } finally {\n if (session != null) session.close();\n }\n\n // Try the fetch\n try {\n session = sf.openSession();\n Foo foo = (Foo) session.get(Foo.class, 1L);\n Bar bar = (Bar) session.get(Bar.class, 1L);\n System.out.println(bar.getName());\n } finally {\n if (session != null) session.close();\n }\n }\n</code></pre>\n\n<p>And it all works fine, as one would expect.</p>\n" }, { "answer_id": 62246, "author": "Darren Greaves", "author_id": 151, "author_profile": "https://Stackoverflow.com/users/151", "pm_score": 0, "selected": false, "text": "<p>Do you actually need to do lazy loading?<br>\nCould you not set FetchType to EAGER instead and have it always loaded (properly) using a join?</p>\n" }, { "answer_id": 120242, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I had a similar problem:</p>\n\n<ul>\n<li>I did Session.save(nastyItem) to save an object into the Session.\nHowever, I did not fill in the property buyer which is mapped as update=\"false\" insert=\"false\" (this happens a lot when you have a composed primary key, then you map the many-to-one's as insert=\"false\" update=\"false\")</li>\n<li>I a query to load a list of items, and the item which I just saved, happens to be part of the result set</li>\n<li>now what goes wrong? Hibernate sees that the item was already in the cache, and Hibernate does not replace (probably not to break my earlier reference nastyItem) it with the newly loaded value, but uses MY nastyItem I have put into the Session cache myself. Even worse, now the lazy loading of the buyer is broken: it contains null.</li>\n</ul>\n\n<p>To avoid these Session issues, I always do a flush and a clear after a save, merge, update or delete. Having to solve these nasty problems takes too much of my time.</p>\n" }, { "answer_id": 178835, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 0, "selected": false, "text": "<p>You are doing something wrong. I did not test your code, but you should never need to force the initialization of proxies, the property accessors do that for you. If you are using Hibernate explicitly, never mind using JPA, since you already have lost portability.</p>\n\n<p>Hibernate should detect automatically whenever it needs to fetch or write to db. If you issue a getProperty() from a proxy, hibernate or any other jpa provider should fetch the correspondent row from the db.</p>\n\n<p>The only situation I'm not sure hibernate is <em>clever</em> enough is if you issue a save() and then issue a get() with the id of the saved object, there might be a problem if the save() didn't flush the object to db.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3332/" ]
In Hibernate we have two classes with the following classes with JPA mapping: ``` package com.example.hibernate import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class Foo { private long id; private Bar bar; @Id @GeneratedValue(strategy = GenerationType.AUTO) public long getId() { return id; } public void setId(long id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) public Bar getBar() { return bar; } public void setBar(Bar bar) { this.bar = bar; } } package com.example.hibernate import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; public class Bar { private long id; private String title; @Id @GeneratedValue(strategy = GenerationType.AUTO) public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } ``` Now when we load from the database an object from class Foo using session get e.g: Foo foo = (Foo)session.get(Foo.class, 1 /\* or some other id that exists in the DB\*/); the Bar member of foo is a proxy object (in our case javassist proxy but it can be cglib one depending on the bytecode provider you use), that is not initialized. If you then use session.get to fetch the Bar object that is the member of the Foo class just loaded (we are in the same session), Hibernate does not issue another DB query and fetches the object from the session (first level) cache. The problem is this is a proxy to Bar class which is not initialized and trying to call this object getId() will return 0, and getTitle() will return null. Our current solution is pretty ugly and checks if the object returned from get is a proxy here is the code (form a generic DAO implementation): ``` @SuppressWarnings("unchecked") @Override @Transactional(readOnly = true) public <T extends IEntity> T get(Class<T> clazz, Serializable primaryKey) throws DataAccessException { T entity = (T) currentSession().get(clazz, primaryKey); if (entity != null) { if (LOG.isWarnEnabled()) { LOG.warn("Object not found for class " + clazz.getName() + " with primary key " + primaryKey); } } else if (entity instanceof HibernateProxy){ // TODO: force initialization due to Hibernate bug HibernateProxy proxy = (HibernateProxy)entity; if (!Hibernate.isInitialized(proxy)) { Hibernate.initialize(proxy); } entity = (T)proxy.getHibernateLazyInitializer().getImplementation(); } return entity; } ``` Is there a better way to do this, couldn't find a solution in the Hibernate forum, and didn't find the issue in Hibernate's JIRA. Note: we cannot just use foo.getBar() (which will initialize the proxy properly) to get the Bar class object, because the session.get operation to fetch the Bar object does not know (or care for that matter) that the Bar class is also a lazy member of a Foo object that was just fetched.
I had a similar problem: * I did Session.save(nastyItem) to save an object into the Session. However, I did not fill in the property buyer which is mapped as update="false" insert="false" (this happens a lot when you have a composed primary key, then you map the many-to-one's as insert="false" update="false") * I a query to load a list of items, and the item which I just saved, happens to be part of the result set * now what goes wrong? Hibernate sees that the item was already in the cache, and Hibernate does not replace (probably not to break my earlier reference nastyItem) it with the newly loaded value, but uses MY nastyItem I have put into the Session cache myself. Even worse, now the lazy loading of the buyer is broken: it contains null. To avoid these Session issues, I always do a flush and a clear after a save, merge, update or delete. Having to solve these nasty problems takes too much of my time.
61,953
<p>Let's say I have the following simple enum:</p> <pre><code>enum Response { Yes = 1, No = 2, Maybe = 3 } </code></pre> <p>How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected?</p>
[ { "answer_id": 61961, "author": "Mark Glorie", "author_id": 952, "author_profile": "https://Stackoverflow.com/users/952", "pm_score": 8, "selected": true, "text": "<p>I probably wouldn't <strong>bind</strong> the data as it's an enum, and it won't change after compile time (unless I'm having one of those <em>stoopid</em> moments). </p>\n\n<p>Better just to iterate through the enum: </p>\n\n<pre><code>Dim itemValues As Array = System.Enum.GetValues(GetType(Response))\nDim itemNames As Array = System.Enum.GetNames(GetType(Response))\n\nFor i As Integer = 0 To itemNames.Length - 1\n Dim item As New ListItem(itemNames(i), itemValues(i))\n dropdownlist.Items.Add(item)\nNext\n</code></pre>\n\n<p>Or the same in C# </p>\n\n<pre><code>Array itemValues = System.Enum.GetValues(typeof(Response));\nArray itemNames = System.Enum.GetNames(typeof(Response));\n\nfor (int i = 0; i &lt;= itemNames.Length - 1 ; i++) {\n ListItem item = new ListItem(itemNames[i], itemValues[i]);\n dropdownlist.Items.Add(item);\n}\n</code></pre>\n" }, { "answer_id": 61962, "author": "roman m", "author_id": 3661, "author_profile": "https://Stackoverflow.com/users/3661", "pm_score": 1, "selected": false, "text": "<p>That's not quite what you're looking for, but might help:</p>\n\n<p><a href=\"http://blog.jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx\" rel=\"nofollow noreferrer\">http://blog.jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx</a></p>\n" }, { "answer_id": 61965, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 3, "selected": false, "text": "<p>I am not sure how to do it in ASP.NET but check out <a href=\"https://stackoverflow.com/questions/58743/databinding-an-enum-property-to-a-combobox-in-wpf#58819\">this</a> post... it might help?</p>\n\n<pre><code>Enum.GetValues(typeof(Response));\n</code></pre>\n" }, { "answer_id": 62023, "author": "Leyu", "author_id": 3359, "author_profile": "https://Stackoverflow.com/users/3359", "pm_score": 6, "selected": false, "text": "<p>Use the following utility class <code>Enumeration</code> to get an <code>IDictionary&lt;int,string&gt;</code> (Enum value &amp; name pair) from an <strong>Enumeration</strong>; you then bind the <strong>IDictionary</strong> to a bindable Control.</p>\n\n<pre><code>public static class Enumeration\n{\n public static IDictionary&lt;int, string&gt; GetAll&lt;TEnum&gt;() where TEnum: struct\n {\n var enumerationType = typeof (TEnum);\n\n if (!enumerationType.IsEnum)\n throw new ArgumentException(\"Enumeration type is expected.\");\n\n var dictionary = new Dictionary&lt;int, string&gt;();\n\n foreach (int value in Enum.GetValues(enumerationType))\n {\n var name = Enum.GetName(enumerationType, value);\n dictionary.Add(value, name);\n }\n\n return dictionary;\n }\n}\n</code></pre>\n\n<p><strong>Example:</strong> Using the utility class to bind enumeration data to a control</p>\n\n<pre><code>ddlResponse.DataSource = Enumeration.GetAll&lt;Response&gt;();\nddlResponse.DataTextField = \"Value\";\nddlResponse.DataValueField = \"Key\";\nddlResponse.DataBind();\n</code></pre>\n" }, { "answer_id": 62252, "author": "Johan Danforth", "author_id": 6415, "author_profile": "https://Stackoverflow.com/users/6415", "pm_score": 3, "selected": false, "text": "<p>As others have already said - don't databind to an enum, unless you need to bind to different enums depending on situation. There are several ways to do this, a couple of examples below.</p>\n\n<p><strong>ObjectDataSource</strong></p>\n\n<p>A declarative way of doing it with ObjectDataSource. First, create a BusinessObject class that will return the List to bind the DropDownList to:</p>\n\n<pre><code>public class DropDownData\n{\n enum Responses { Yes = 1, No = 2, Maybe = 3 }\n\n public String Text { get; set; }\n public int Value { get; set; }\n\n public List&lt;DropDownData&gt; GetList()\n {\n var items = new List&lt;DropDownData&gt;();\n foreach (int value in Enum.GetValues(typeof(Responses)))\n {\n items.Add(new DropDownData\n {\n Text = Enum.GetName(typeof (Responses), value),\n Value = value\n });\n }\n return items;\n }\n}\n</code></pre>\n\n<p>Then add some HTML markup to the ASPX page to point to this BO class:</p>\n\n<pre><code>&lt;asp:DropDownList ID=\"DropDownList1\" runat=\"server\" \n DataSourceID=\"ObjectDataSource1\" DataTextField=\"Text\" DataValueField=\"Value\"&gt;\n&lt;/asp:DropDownList&gt;\n&lt;asp:ObjectDataSource ID=\"ObjectDataSource1\" runat=\"server\" \n SelectMethod=\"GetList\" TypeName=\"DropDownData\"&gt;&lt;/asp:ObjectDataSource&gt;\n</code></pre>\n\n<p>This option requires no code behind.</p>\n\n<p><strong>Code Behind DataBind</strong></p>\n\n<p>To minimize the HTML in the ASPX page and do bind in Code Behind:</p>\n\n<pre><code>enum Responses { Yes = 1, No = 2, Maybe = 3 }\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n if (!IsPostBack)\n {\n foreach (int value in Enum.GetValues(typeof(Responses)))\n {\n DropDownList1.Items.Add(new ListItem(Enum.GetName(typeof(Responses), value), value.ToString()));\n }\n }\n}\n</code></pre>\n\n<p>Anyway, the trick is to let the Enum type methods of GetValues, GetNames etc. to do work for you.</p>\n" }, { "answer_id": 135822, "author": "VanOrman", "author_id": 4550, "author_profile": "https://Stackoverflow.com/users/4550", "pm_score": 5, "selected": false, "text": "<p>My version is just a compressed form of the above:</p>\n\n<pre><code>foreach (Response r in Enum.GetValues(typeof(Response)))\n{\n ListItem item = new ListItem(Enum.GetName(typeof(Response), r), r.ToString());\n DropDownList1.Items.Add(item);\n}\n</code></pre>\n" }, { "answer_id": 290408, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<pre><code>public enum Color\n{\n RED,\n GREEN,\n BLUE\n}\n</code></pre>\n\n<p>Every Enum type derives from System.Enum. There are two static methods that help bind data to a drop-down list control (and retrieve the value). These are Enum.GetNames and Enum.Parse. Using GetNames, you are able to bind to your drop-down list control as follows:</p>\n\n<pre><code>protected System.Web.UI.WebControls.DropDownList ddColor;\n\nprivate void Page_Load(object sender, System.EventArgs e)\n{\n if(!IsPostBack)\n {\n ddColor.DataSource = Enum.GetNames(typeof(Color));\n ddColor.DataBind();\n }\n}\n</code></pre>\n\n<p>Now if you want the Enum value Back on Selection ....</p>\n\n<pre><code> private void ddColor_SelectedIndexChanged(object sender, System.EventArgs e)\n {\n Color selectedColor = (Color)Enum.Parse(typeof(Color),ddColor.SelectedValue\n }\n</code></pre>\n" }, { "answer_id": 540741, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>Array itemValues = Enum.GetValues(typeof(TaskStatus));\nArray itemNames = Enum.GetNames(typeof(TaskStatus));\n\nfor (int i = 0; i &lt;= itemNames.Length; i++)\n{\n ListItem item = new ListItem(itemNames.GetValue(i).ToString(),\n itemValues.GetValue(i).ToString());\n ddlStatus.Items.Add(item);\n}\n</code></pre>\n" }, { "answer_id": 1831886, "author": "Mostafa", "author_id": 1904217, "author_profile": "https://Stackoverflow.com/users/1904217", "pm_score": 1, "selected": false, "text": "<p>Why not use like this to be able pass every listControle :\n<pre><code>\npublic static void BindToEnum(Type enumType, ListControl lc)\n {\n // get the names from the enumeration\n string[] names = Enum.GetNames(enumType);\n // get the values from the enumeration\n Array values = Enum.GetValues(enumType);\n // turn it into a hash table\n Hashtable ht = new Hashtable();\n for (int i = 0; i &lt; names.Length; i++)\n // note the cast to integer here is important\n // otherwise we'll just get the enum string back again\n ht.Add(names[i], (int)values.GetValue(i));\n // return the dictionary to be bound to\n lc.DataSource = ht;\n lc.DataTextField = \"Key\";\n lc.DataValueField = \"Value\";\n lc.DataBind();\n }\n</pre></code>\nAnd use is just as simple as :\n<pre><code>\nBindToEnum(typeof(NewsType), DropDownList1);\nBindToEnum(typeof(NewsType), CheckBoxList1);\nBindToEnum(typeof(NewsType), RadoBuuttonList1);\n</pre></code></p>\n" }, { "answer_id": 2080385, "author": "Muhammed Qasim", "author_id": 252516, "author_profile": "https://Stackoverflow.com/users/252516", "pm_score": 2, "selected": false, "text": "<p>Generic Code Using Answer six.</p>\n\n<pre><code>public static void BindControlToEnum(DataBoundControl ControlToBind, Type type)\n{\n //ListControl\n\n if (type == null)\n throw new ArgumentNullException(\"type\");\n else if (ControlToBind==null )\n throw new ArgumentNullException(\"ControlToBind\");\n if (!type.IsEnum)\n throw new ArgumentException(\"Only enumeration type is expected.\");\n\n Dictionary&lt;int, string&gt; pairs = new Dictionary&lt;int, string&gt;();\n\n foreach (int i in Enum.GetValues(type))\n {\n pairs.Add(i, Enum.GetName(type, i));\n }\n ControlToBind.DataSource = pairs;\n ListControl lstControl = ControlToBind as ListControl;\n if (lstControl != null)\n {\n lstControl.DataTextField = \"Value\";\n lstControl.DataValueField = \"Key\";\n }\n ControlToBind.DataBind();\n\n}\n</code></pre>\n" }, { "answer_id": 2416623, "author": "Feryt", "author_id": 82539, "author_profile": "https://Stackoverflow.com/users/82539", "pm_score": 5, "selected": false, "text": "<p>I use this for <strong>ASP.NET MVC</strong>:</p>\n\n<pre><code>Html.DropDownListFor(o =&gt; o.EnumProperty, Enum.GetValues(typeof(enumtype)).Cast&lt;enumtype&gt;().Select(x =&gt; new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))\n</code></pre>\n" }, { "answer_id": 2511877, "author": "Ben Hughes", "author_id": 286796, "author_profile": "https://Stackoverflow.com/users/286796", "pm_score": 2, "selected": false, "text": "<p>After finding this answer I came up with what I think is a better (at least more elegant) way of doing this, thought I'd come back and share it here.</p>\n\n<p>Page_Load:</p>\n\n<pre><code>DropDownList1.DataSource = Enum.GetValues(typeof(Response));\nDropDownList1.DataBind();\n</code></pre>\n\n<p>LoadValues:</p>\n\n<pre><code>Response rIn = Response.Maybe;\nDropDownList1.Text = rIn.ToString();\n</code></pre>\n\n<p>SaveValues:</p>\n\n<pre><code>Response rOut = (Response) Enum.Parse(typeof(Response), DropDownList1.Text);\n</code></pre>\n" }, { "answer_id": 5120974, "author": "Diego Mendes", "author_id": 484222, "author_profile": "https://Stackoverflow.com/users/484222", "pm_score": 0, "selected": false, "text": "<p>This is my solution for Order an Enum and DataBind(Text and Value)to Dropdown using LINQ</p>\n\n<pre><code>var mylist = Enum.GetValues(typeof(MyEnum)).Cast&lt;MyEnum&gt;().ToList&lt;MyEnum&gt;().OrderBy(l =&gt; l.ToString());\nforeach (MyEnum item in mylist)\n ddlDivisao.Items.Add(new ListItem(item.ToString(), ((int)item).ToString()));\n</code></pre>\n" }, { "answer_id": 5608266, "author": "justin", "author_id": 700363, "author_profile": "https://Stackoverflow.com/users/700363", "pm_score": 0, "selected": false, "text": "<p>Both asp.net and winforms tutorial with combobox and dropdownlist:\n<a href=\"http://www.docstorus.com/viewer.aspx?code=833d27e2-5e3b-4ec0-b950-02c8fc2ec572&amp;title=How%20to%20use%20Enum%20with%20Combobox%20in%20C#%20WinForms%20and%20Asp.Net\" rel=\"nofollow\">How to use Enum with Combobox in C# WinForms and Asp.Net</a></p>\n\n<p>hope helps</p>\n" }, { "answer_id": 6517806, "author": "sankalp gurha", "author_id": 820671, "author_profile": "https://Stackoverflow.com/users/820671", "pm_score": 2, "selected": false, "text": "<pre><code>public enum Color\n{\n RED,\n GREEN,\n BLUE\n}\n\nddColor.DataSource = Enum.GetNames(typeof(Color));\nddColor.DataBind();\n</code></pre>\n" }, { "answer_id": 7071406, "author": "Stuart Leeks", "author_id": 202415, "author_profile": "https://Stackoverflow.com/users/202415", "pm_score": 0, "selected": false, "text": "<p>Check out my post on creating a custom helper \"ASP.NET MVC - Creating a DropDownList helper for enums\": <a href=\"http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx</a></p>\n" }, { "answer_id": 7750678, "author": "Josh Stribling", "author_id": 464386, "author_profile": "https://Stackoverflow.com/users/464386", "pm_score": 0, "selected": false, "text": "<p>If you would like to have a more user friendly description in your combo box (or other control) you can use the Description attribute with the following function:</p>\n\n<pre><code> public static object GetEnumDescriptions(Type enumType)\n {\n var list = new List&lt;KeyValuePair&lt;Enum, string&gt;&gt;();\n foreach (Enum value in Enum.GetValues(enumType))\n {\n string description = value.ToString();\n FieldInfo fieldInfo = value.GetType().GetField(description);\n var attribute = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).First();\n if (attribute != null)\n {\n description = (attribute as DescriptionAttribute).Description;\n }\n list.Add(new KeyValuePair&lt;Enum, string&gt;(value, description));\n }\n return list;\n }\n</code></pre>\n\n<p>Here is an example of an enum with Description attributes applied:</p>\n\n<pre><code> enum SampleEnum\n {\n NormalNoSpaces,\n [Description(\"Description With Spaces\")]\n DescriptionWithSpaces,\n [Description(\"50%\")]\n Percent_50,\n }\n</code></pre>\n\n<p>Then Bind to control like so...</p>\n\n<pre><code> m_Combo_Sample.DataSource = GetEnumDescriptions(typeof(SampleEnum));\n m_Combo_Sample.DisplayMember = \"Value\";\n m_Combo_Sample.ValueMember = \"Key\";\n</code></pre>\n\n<p>This way you can put whatever text you want in the drop down without it having to look like a variable name</p>\n" }, { "answer_id": 9900016, "author": "Trisped", "author_id": 641833, "author_profile": "https://Stackoverflow.com/users/641833", "pm_score": 0, "selected": false, "text": "<p>You could also use Extension methods. For those not familar with extensions I suggest checking the <a href=\"http://msdn.microsoft.com/en-us/library/bb384936.aspx\" rel=\"nofollow\">VB</a> and <a href=\"http://msdn.microsoft.com/en-us/library/bb383977.aspx\" rel=\"nofollow\">C#</a> documentation.</p>\n\n<hr>\n\n<p>VB Extension:</p>\n\n<pre><code>Namespace CustomExtensions\n Public Module ListItemCollectionExtension\n\n &lt;Runtime.CompilerServices.Extension()&gt; _\n Public Sub AddEnum(Of TEnum As Structure)(items As System.Web.UI.WebControls.ListItemCollection)\n Dim enumerationType As System.Type = GetType(TEnum)\n Dim enumUnderType As System.Type = System.Enum.GetUnderlyingType(enumType)\n\n If Not enumerationType.IsEnum Then Throw New ArgumentException(\"Enumeration type is expected.\")\n\n Dim enumTypeNames() As String = System.Enum.GetNames(enumerationType)\n Dim enumTypeValues() As TEnum = System.Enum.GetValues(enumerationType)\n\n For i = 0 To enumTypeNames.Length - 1\n items.Add(New System.Web.UI.WebControls.ListItem(saveResponseTypeNames(i), TryCast(enumTypeValues(i), System.Enum).ToString(\"d\")))\n Next\n End Sub\n End Module\nEnd Namespace\n</code></pre>\n\n<p>To use the extension:</p>\n\n<pre><code>Imports &lt;projectName&gt;.CustomExtensions.ListItemCollectionExtension\n\n...\n\nyourDropDownList.Items.AddEnum(Of EnumType)()\n</code></pre>\n\n<hr>\n\n<p>C# Extension:</p>\n\n<pre><code>namespace CustomExtensions\n{\n public static class ListItemCollectionExtension\n {\n public static void AddEnum&lt;TEnum&gt;(this System.Web.UI.WebControls.ListItemCollection items) where TEnum : struct\n {\n System.Type enumType = typeof(TEnum);\n System.Type enumUnderType = System.Enum.GetUnderlyingType(enumType);\n\n if (!enumType.IsEnum) throw new Exception(\"Enumeration type is expected.\");\n\n string[] enumTypeNames = System.Enum.GetNames(enumType);\n TEnum[] enumTypeValues = (TEnum[])System.Enum.GetValues(enumType);\n\n for (int i = 0; i &lt; enumTypeValues.Length; i++)\n {\n items.add(new System.Web.UI.WebControls.ListItem(enumTypeNames[i], (enumTypeValues[i] as System.Enum).ToString(\"d\")));\n }\n }\n }\n}\n</code></pre>\n\n<p>To use the extension:</p>\n\n<pre><code>using CustomExtensions.ListItemCollectionExtension;\n\n...\n\nyourDropDownList.Items.AddEnum&lt;EnumType&gt;()\n</code></pre>\n\n<hr>\n\n<p>If you want to set the selected item at the same time replace</p>\n\n<pre><code>items.Add(New System.Web.UI.WebControls.ListItem(saveResponseTypeNames(i), saveResponseTypeValues(i).ToString(\"d\")))\n</code></pre>\n\n<p>with</p>\n\n<pre><code>Dim newListItem As System.Web.UI.WebControls.ListItem\nnewListItem = New System.Web.UI.WebControls.ListItem(enumTypeNames(i), Convert.ChangeType(enumTypeValues(i), enumUnderType).ToString())\nnewListItem.Selected = If(EqualityComparer(Of TEnum).Default.Equals(selected, saveResponseTypeValues(i)), True, False)\nitems.Add(newListItem)\n</code></pre>\n\n<p>By converting to System.Enum rather then int size and output issues are avoided. For example 0xFFFF0000 would be 4294901760 as an uint but would be -65536 as an int.</p>\n\n<p>TryCast and as System.Enum are slightly faster than Convert.ChangeType(enumTypeValues[i], enumUnderType).ToString() (12:13 in my speed tests).</p>\n" }, { "answer_id": 24769726, "author": "Amir Chatrbahr", "author_id": 922713, "author_profile": "https://Stackoverflow.com/users/922713", "pm_score": 4, "selected": false, "text": "<p>After reading all posts I came up with a comprehensive solution to support showing enum description in dropdown list as well as selecting proper value from Model in dropdown when displaying in Edit mode:</p>\n\n<p>enum:</p>\n\n<pre><code>using System.ComponentModel;\npublic enum CompanyType\n{\n [Description(\"\")]\n Null = 1,\n\n [Description(\"Supplier\")]\n Supplier = 2,\n\n [Description(\"Customer\")]\n Customer = 3\n}\n</code></pre>\n\n<p>enum extension class:</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Linq;\nusing System.Web.Mvc;\n\npublic static class EnumExtension\n{\n public static string ToDescription(this System.Enum value)\n {\n var attributes = (DescriptionAttribute[])value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);\n return attributes.Length &gt; 0 ? attributes[0].Description : value.ToString();\n }\n\n public static IEnumerable&lt;SelectListItem&gt; ToSelectList&lt;T&gt;(this System.Enum enumValue)\n {\n return\n System.Enum.GetValues(enumValue.GetType()).Cast&lt;T&gt;()\n .Select(\n x =&gt;\n new SelectListItem\n {\n Text = ((System.Enum)(object) x).ToDescription(),\n Value = x.ToString(),\n Selected = (enumValue.Equals(x))\n });\n }\n}\n</code></pre>\n\n<p>Model class:</p>\n\n<pre><code>public class Company\n{\n public string CompanyName { get; set; }\n public CompanyType Type { get; set; }\n}\n</code></pre>\n\n<p>and View:</p>\n\n<pre><code>@Html.DropDownListFor(m =&gt; m.Type,\[email protected]&lt;CompanyType&gt;())\n</code></pre>\n\n<p>and if you are using that dropdown without binding to Model, you can use this instead:</p>\n\n<pre><code>@Html.DropDownList(\"type\", \nEnum.GetValues(typeof(CompanyType)).Cast&lt;CompanyType&gt;()\n.Select(x =&gt; new SelectListItem {Text = x.ToDescription(), Value = x.ToString()}))\n</code></pre>\n\n<p>So by doing so you can expect your dropdown displays Description instead of enum values. Also when it comes to Edit, your model will be updated by dropdown selected value after posting page.</p>\n" }, { "answer_id": 27000004, "author": "bradlis7", "author_id": 179311, "author_profile": "https://Stackoverflow.com/users/179311", "pm_score": 1, "selected": false, "text": "<p>ASP.NET has since been updated with some more functionality, and you can now use built-in enum to dropdown.</p>\n\n<p>If you want to bind on the Enum itself, use this:</p>\n\n<pre><code>@Html.DropDownList(\"response\", EnumHelper.GetSelectList(typeof(Response)))\n</code></pre>\n\n<p>If you're binding on an instance of Response, use this:</p>\n\n<pre><code>// Assuming Model.Response is an instance of Response\[email protected](m =&gt; m.Response)\n</code></pre>\n" }, { "answer_id": 33767663, "author": "KrishnaDhungana", "author_id": 2330518, "author_profile": "https://Stackoverflow.com/users/2330518", "pm_score": 3, "selected": false, "text": "<p>You could use linq:</p>\n\n<pre><code>var responseTypes= Enum.GetNames(typeof(Response)).Select(x =&gt; new { text = x, value = (int)Enum.Parse(typeof(Response), x) });\n DropDownList.DataSource = responseTypes;\n DropDownList.DataTextField = \"text\";\n DropDownList.DataValueField = \"value\";\n DropDownList.DataBind();\n</code></pre>\n" }, { "answer_id": 41553362, "author": "Pecheneg", "author_id": 1872210, "author_profile": "https://Stackoverflow.com/users/1872210", "pm_score": 0, "selected": false, "text": "<p>The accepted solution doesn't work, but the code below will help others looking for the shortest solution.</p>\n\n<pre><code> foreach (string value in Enum.GetNames(typeof(Response)))\n ddlResponse.Items.Add(new ListItem()\n {\n Text = value,\n Value = ((int)Enum.Parse(typeof(Response), value)).ToString()\n });\n</code></pre>\n" }, { "answer_id": 42448307, "author": "Marie McDonley", "author_id": 7307726, "author_profile": "https://Stackoverflow.com/users/7307726", "pm_score": 2, "selected": false, "text": "<p>This is probably an old question.. but this is how I did mine.</p>\n\n<p>Model: </p>\n\n<pre><code>public class YourEntity\n{\n public int ID { get; set; }\n public string Name{ get; set; }\n public string Description { get; set; }\n public OptionType Types { get; set; }\n}\n\npublic enum OptionType\n{\n Unknown,\n Option1, \n Option2,\n Option3\n}\n</code></pre>\n\n<p>Then in the View: here's how to use populate the dropdown.</p>\n\n<pre><code>@Html.EnumDropDownListFor(model =&gt; model.Types, htmlAttributes: new { @class = \"form-control\" })\n</code></pre>\n\n<p>This should populate everything in your enum list. Hope this helps.. </p>\n" }, { "answer_id": 59394848, "author": "Henkie85", "author_id": 11846363, "author_profile": "https://Stackoverflow.com/users/11846363", "pm_score": 0, "selected": false, "text": "<p>You can do this a lot shorter</p>\n\n<pre><code>public enum Test\n {\n Test1 = 1,\n Test2 = 2,\n Test3 = 3\n }\n class Program\n {\n static void Main(string[] args)\n {\n\n var items = Enum.GetValues(typeof(Test));\n\n foreach (var item in items)\n {\n //Gives you the names\n Console.WriteLine(item);\n }\n\n\n foreach(var item in (Test[])items)\n {\n // Gives you the numbers\n Console.WriteLine((int)item);\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 64668876, "author": "MaxOvrdrv", "author_id": 1583649, "author_profile": "https://Stackoverflow.com/users/1583649", "pm_score": 0, "selected": false, "text": "<p>For those of us that want a working C# solution that works with any drop and enum...</p>\n<pre><code>private void LoadConsciousnessDrop()\n{\n string sel_val = this.drp_Consciousness.SelectedValue;\n this.drp_Consciousness.Items.Clear();\n string[] names = Enum.GetNames(typeof(Consciousness));\n \n for (int i = 0; i &lt; names.Length; i++)\n this.drp_Consciousness.Items.Add(new ListItem(names[i], ((int)((Consciousness)Enum.Parse(typeof(Consciousness), names[i]))).ToString()));\n\n this.drp_Consciousness.SelectedValue = String.IsNullOrWhiteSpace(sel_val) ? null : sel_val;\n}\n</code></pre>\n" }, { "answer_id": 66405336, "author": "TheRealSheldon", "author_id": 3037489, "author_profile": "https://Stackoverflow.com/users/3037489", "pm_score": 0, "selected": false, "text": "<p>I realize this post is older and for Asp.net, but I wanted to provide a solution I used recently for a c# Windows Forms Project. The idea is to build a dictionary where the keys are the names of the Enumerated elements and the values are the Enumerated values. You then bind the dictionary to the combobox. See a generic function that takes a ComboBox and Enum Type as arguments.</p>\n<pre><code> private void BuildComboBoxFromEnum(ComboBox box, Type enumType) {\n var dict = new Dictionary&lt;string, int&gt;();\n foreach (var foo in Enum.GetValues(enumType)) {\n dict.Add(foo.ToString(), (int)foo);\n }\n box.DropDownStyle = ComboBoxStyle.DropDownList; // Forces comboBox to ReadOnly\n box.DataSource = new BindingSource(dict, null);\n box.DisplayMember = &quot;Key&quot;;\n box.ValueMember = &quot;Value&quot;;\n // Register a callback that prints the Name and Value of the \n // selected enum. This should be removed after initial testing.\n box.SelectedIndexChanged += (o, e) =&gt; {\n Console.WriteLine(&quot;{0} {1}&quot;, box.Text, box.SelectedValue);\n };\n }\n</code></pre>\n<p>This function can be used as follows:</p>\n<pre><code>BuildComboBoxFromEnum(comboBox1,typeof(Response));\n</code></pre>\n" }, { "answer_id": 68136328, "author": "combatc2", "author_id": 1491388, "author_profile": "https://Stackoverflow.com/users/1491388", "pm_score": 0, "selected": false, "text": "<p>In ASP.NET Core you can use the following Html helper (comes from Microsoft.AspNetCore.Mvc.Rendering):</p>\n<pre><code>&lt;select asp-items=&quot;Html.GetEnumSelectList&lt;GridReportingStatusFilters&gt;()&quot;&gt;\n &lt;option value=&quot;&quot;&gt;&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
Let's say I have the following simple enum: ``` enum Response { Yes = 1, No = 2, Maybe = 3 } ``` How can I bind this enum to a DropDownList control so that the descriptions are displayed in the list as well as retrieve the associated numeric value (1,2,3) once an option has been selected?
I probably wouldn't **bind** the data as it's an enum, and it won't change after compile time (unless I'm having one of those *stoopid* moments). Better just to iterate through the enum: ``` Dim itemValues As Array = System.Enum.GetValues(GetType(Response)) Dim itemNames As Array = System.Enum.GetNames(GetType(Response)) For i As Integer = 0 To itemNames.Length - 1 Dim item As New ListItem(itemNames(i), itemValues(i)) dropdownlist.Items.Add(item) Next ``` Or the same in C# ``` Array itemValues = System.Enum.GetValues(typeof(Response)); Array itemNames = System.Enum.GetNames(typeof(Response)); for (int i = 0; i <= itemNames.Length - 1 ; i++) { ListItem item = new ListItem(itemNames[i], itemValues[i]); dropdownlist.Items.Add(item); } ```
61,967
<p>Let's say I have the following simple table variable:</p> <pre><code>declare @databases table ( DatabaseID int, Name varchar(15), Server varchar(15) ) -- insert a bunch rows into @databases </code></pre> <p>Is declaring and using a cursor my only option if I wanted to iterate through the rows? Is there another way?</p>
[ { "answer_id": 61981, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 2, "selected": false, "text": "<p>You can use a while loop:</p>\n\n<pre><code>While (Select Count(*) From #TempTable) &gt; 0\nBegin\n Insert Into @Databases...\n\n Delete From #TempTable Where x = x\nEnd\n</code></pre>\n" }, { "answer_id": 62130, "author": "Martynnw", "author_id": 5466, "author_profile": "https://Stackoverflow.com/users/5466", "pm_score": 10, "selected": true, "text": "<p>First of all you should be absolutely sure you need to iterate through each row — set based operations will perform faster in every case I can think of and will normally use simpler code.</p>\n\n<p>Depending on your data it may be possible to loop using just <code>SELECT</code> statements as shown below:</p>\n\n<pre><code>Declare @Id int\n\nWhile (Select Count(*) From ATable Where Processed = 0) &gt; 0\nBegin\n Select Top 1 @Id = Id From ATable Where Processed = 0\n\n --Do some processing here\n\n Update ATable Set Processed = 1 Where Id = @Id \n\nEnd\n</code></pre>\n\n<p>Another alternative is to use a temporary table: </p>\n\n<pre><code>Select *\nInto #Temp\nFrom ATable\n\nDeclare @Id int\n\nWhile (Select Count(*) From #Temp) &gt; 0\nBegin\n\n Select Top 1 @Id = Id From #Temp\n\n --Do some processing here\n\n Delete #Temp Where Id = @Id\n\nEnd\n</code></pre>\n\n<p>The option you should choose really depends on the structure and volume of your data.</p>\n\n<p><strong>Note:</strong> If you are using SQL Server you would be better served using:</p>\n\n<pre><code>WHILE EXISTS(SELECT * FROM #Temp)\n</code></pre>\n\n<p>Using <code>COUNT</code> will have to touch every single row in the table, the <code>EXISTS</code> only needs to touch the first one (see <a href=\"https://stackoverflow.com/a/65294/963542\">Josef's answer</a> below).</p>\n" }, { "answer_id": 63031, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 4, "selected": false, "text": "<p>Here is how I would do it:</p>\n\n<pre><code>Select Identity(int, 1,1) AS PK, DatabaseID\nInto #T\nFrom @databases\n\nDeclare @maxPK int;Select @maxPK = MAX(PK) From #T\nDeclare @pk int;Set @pk = 1\n\nWhile @pk &lt;= @maxPK\nBegin\n\n -- Get one record\n Select DatabaseID, Name, Server\n From @databases\n Where DatabaseID = (Select DatabaseID From #T Where PK = @pk)\n\n --Do some processing here\n -- \n\n Select @pk = @pk + 1\nEnd\n</code></pre>\n\n<hr>\n\n<p>[Edit] Because I probably skipped the word \"variable\" when I first time read the question, here is an updated response...</p>\n\n<hr>\n\n<pre><code>declare @databases table\n(\n PK int IDENTITY(1,1), \n DatabaseID int,\n Name varchar(15), \n Server varchar(15)\n)\n-- insert a bunch rows into @databases\n--/*\nINSERT INTO @databases (DatabaseID, Name, Server) SELECT 1,'MainDB', 'MyServer'\nINSERT INTO @databases (DatabaseID, Name, Server) SELECT 1,'MyDB', 'MyServer2'\n--*/\n\nDeclare @maxPK int;Select @maxPK = MAX(PK) From @databases\nDeclare @pk int;Set @pk = 1\n\nWhile @pk &lt;= @maxPK\nBegin\n\n /* Get one record (you can read the values into some variables) */\n Select DatabaseID, Name, Server\n From @databases\n Where PK = @pk\n\n /* Do some processing here */\n /* ... */ \n\n Select @pk = @pk + 1\nEnd\n</code></pre>\n" }, { "answer_id": 63440, "author": "Tim Lentine", "author_id": 2833, "author_profile": "https://Stackoverflow.com/users/2833", "pm_score": 1, "selected": false, "text": "<p>I agree with the previous post that set-based operations will typically perform better, but if you do need to iterate over the rows here's the approach I would take:</p>\n\n<ol>\n<li>Add a new field to your table variable (Data Type Bit, default 0)</li>\n<li>Insert your data</li>\n<li>Select the Top 1 Row where fUsed = 0 <em>(Note: fUsed is the name of the field in step 1)</em></li>\n<li>Perform whatever processing you need to do</li>\n<li>Update the record in your table variable by setting fUsed = 1 for the record</li>\n<li><p>Select the next unused record from the table and repeat the process</p>\n\n<pre><code>DECLARE @databases TABLE \n( \n DatabaseID int, \n Name varchar(15), \n Server varchar(15), \n fUsed BIT DEFAULT 0 \n) \n\n-- insert a bunch rows into @databases\n\nDECLARE @DBID INT\n\nSELECT TOP 1 @DBID = DatabaseID from @databases where fUsed = 0 \n\nWHILE @@ROWCOUNT &lt;&gt; 0 and @DBID IS NOT NULL \nBEGIN \n -- Perform your processing here \n\n --Update the record to \"used\" \n\n UPDATE @databases SET fUsed = 1 WHERE DatabaseID = @DBID \n\n --Get the next record \n SELECT TOP 1 @DBID = DatabaseID from @databases where fUsed = 0 \nEND\n</code></pre></li>\n</ol>\n" }, { "answer_id": 65294, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 7, "selected": false, "text": "<p>Just a quick note, if you are using SQL Server (2008 and above), the examples that have:</p>\n\n<pre><code>While (Select Count(*) From #Temp) &gt; 0\n</code></pre>\n\n<p>Would be better served with </p>\n\n<pre><code>While EXISTS(SELECT * From #Temp)\n</code></pre>\n\n<p>The Count will have to touch every single row in the table, the <code>EXISTS</code> only needs to touch the first one.</p>\n" }, { "answer_id": 77062, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>If you have no choice than to go row by row creating a FAST_FORWARD cursor. It will be as fast as building up a while loop and much easier to maintain over the long haul.</p>\n\n<p>FAST_FORWARD\n Specifies a FORWARD_ONLY, READ_ONLY cursor with performance optimizations enabled. FAST_FORWARD cannot be specified if SCROLL or FOR_UPDATE is also specified. </p>\n" }, { "answer_id": 77601, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 5, "selected": false, "text": "<p>Define your temp table like this -</p>\n\n<pre><code>declare @databases table\n(\n RowID int not null identity(1,1) primary key,\n DatabaseID int,\n Name varchar(15), \n Server varchar(15)\n)\n\n-- insert a bunch rows into @databases\n</code></pre>\n\n<p>Then do this -</p>\n\n<pre><code>declare @i int\nselect @i = min(RowID) from @databases\ndeclare @max int\nselect @max = max(RowID) from @databases\n\nwhile @i &lt;= @max begin\n select DatabaseID, Name, Server from @database where RowID = @i --do some stuff\n set @i = @i + 1\nend\n</code></pre>\n" }, { "answer_id": 680272, "author": "dance2die", "author_id": 4035, "author_profile": "https://Stackoverflow.com/users/4035", "pm_score": 2, "selected": false, "text": "<p>I really do not see the point why you would need to resort to using dreaded <code>cursor</code>.\nBut here is another option if you are using SQL Server version 2005/2008\n<br />\nUse <strong>Recursion</strong></p>\n\n<pre><code>declare @databases table\n(\n DatabaseID int,\n Name varchar(15), \n Server varchar(15)\n)\n\n--; Insert records into @databases...\n\n--; Recurse through @databases\n;with DBs as (\n select * from @databases where DatabaseID = 1\n union all\n select A.* from @databases A \n inner join DBs B on A.DatabaseID = B.DatabaseID + 1\n)\nselect * from DBs\n</code></pre>\n" }, { "answer_id": 2084732, "author": "Trevor", "author_id": 253034, "author_profile": "https://Stackoverflow.com/users/253034", "pm_score": 6, "selected": false, "text": "<p>This is how I do it:</p>\n\n<pre><code>declare @RowNum int, @CustId nchar(5), @Name1 nchar(25)\n\nselect @CustId=MAX(USERID) FROM UserIDs --start with the highest ID\nSelect @RowNum = Count(*) From UserIDs --get total number of records\nWHILE @RowNum &gt; 0 --loop until no more records\nBEGIN \n select @Name1 = username1 from UserIDs where USERID= @CustID --get other info from that row\n print cast(@RowNum as char(12)) + ' ' + @CustId + ' ' + @Name1 --do whatever\n\n select top 1 @CustId=USERID from UserIDs where USERID &lt; @CustID order by USERID desc--get the next one\n set @RowNum = @RowNum - 1 --decrease count\nEND\n</code></pre>\n\n<p>No Cursors, no temporary tables, no extra columns.\nThe USERID column must be a unique integer, as most Primary Keys are.</p>\n" }, { "answer_id": 2135015, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 2, "selected": false, "text": "<p>I'm going to provide the set-based solution.</p>\n\n<pre><code>insert @databases (DatabaseID, Name, Server)\nselect DatabaseID, Name, Server \nFrom ... (Use whatever query you would have used in the loop or cursor)\n</code></pre>\n\n<p>This is far faster than any looping techique and is easier to write and maintain. </p>\n" }, { "answer_id": 10371631, "author": "Syed Umar Ahmed", "author_id": 861216, "author_profile": "https://Stackoverflow.com/users/861216", "pm_score": 2, "selected": false, "text": "<pre><code>-- [PO_RollBackOnReject] 'FININV10532'\nalter procedure PO_RollBackOnReject\n@CaseID nvarchar(100)\n\nAS\nBegin\nSELECT *\nINTO #tmpTable\nFROM PO_InvoiceItems where CaseID = @CaseID\n\nDeclare @Id int\nDeclare @PO_No int\nDeclare @Current_Balance Money\n\n\nWhile (Select ROW_NUMBER() OVER(ORDER BY PO_LineNo DESC) From #tmpTable) &gt; 0\nBegin\n Select Top 1 @Id = PO_LineNo, @Current_Balance = Current_Balance,\n @PO_No = PO_No\n From #Temp\n update PO_Details\n Set Current_Balance = Current_Balance + @Current_Balance,\n Previous_App_Amount= Previous_App_Amount + @Current_Balance,\n Is_Processed = 0\n Where PO_LineNumber = @Id\n AND PO_No = @PO_No\n update PO_InvoiceItems\n Set IsVisible = 0,\n Is_Processed= 0\n ,Is_InProgress = 0 , \n Is_Active = 0\n Where PO_LineNo = @Id\n AND PO_No = @PO_No\nEnd\nEnd\n</code></pre>\n" }, { "answer_id": 17713828, "author": "SReiderB", "author_id": 2571174, "author_profile": "https://Stackoverflow.com/users/2571174", "pm_score": 3, "selected": false, "text": "<p>Another approach without having to change your schema or using temp tables:</p>\n\n<pre><code>DECLARE @rowCount int = 0\n ,@currentRow int = 1\n ,@databaseID int\n ,@name varchar(15)\n ,@server varchar(15);\n\nSELECT @rowCount = COUNT(*)\nFROM @databases;\n\nWHILE (@currentRow &lt;= @rowCount)\nBEGIN\n SELECT TOP 1\n @databaseID = rt.[DatabaseID]\n ,@name = rt.[Name]\n ,@server = rt.[Server]\n FROM (\n SELECT ROW_NUMBER() OVER (\n ORDER BY t.[DatabaseID], t.[Name], t.[Server]\n ) AS [RowNumber]\n ,t.[DatabaseID]\n ,t.[Name]\n ,t.[Server]\n FROM @databases t\n ) rt\n WHERE rt.[RowNumber] = @currentRow;\n\n EXEC [your_stored_procedure] @databaseID, @name, @server;\n\n SET @currentRow = @currentRow + 1;\nEND\n</code></pre>\n" }, { "answer_id": 23432301, "author": "OrganicCoder", "author_id": 2611808, "author_profile": "https://Stackoverflow.com/users/2611808", "pm_score": 3, "selected": false, "text": "<p>This will work in SQL SERVER 2012 version.</p>\n\n<pre><code>declare @Rowcount int \nselect @Rowcount=count(*) from AddressTable;\n\nwhile( @Rowcount&gt;0)\n begin \n select @Rowcount=@Rowcount-1;\n SELECT * FROM AddressTable order by AddressId desc OFFSET @Rowcount ROWS FETCH NEXT 1 ROWS ONLY;\nend \n</code></pre>\n" }, { "answer_id": 23524660, "author": "howmnsk", "author_id": 3613336, "author_profile": "https://Stackoverflow.com/users/3613336", "pm_score": 0, "selected": false, "text": "<p>This is the code that I am using 2008 R2. This code that I am using is to build indexes on key fields (SSNO &amp; EMPR_NO) n all tales</p>\n\n<pre><code>if object_ID('tempdb..#a')is not NULL drop table #a\n\nselect 'IF EXISTS (SELECT name FROM sysindexes WHERE name ='+CHAR(39)+''+'IDX_'+COLUMN_NAME+'_'+SUBSTRING(table_name,5,len(table_name)-3)+char(39)+')' \n+' begin DROP INDEX [IDX_'+COLUMN_NAME+'_'+SUBSTRING(table_name,5,len(table_name)-3)+'] ON '+table_schema+'.'+table_name+' END Create index IDX_'+COLUMN_NAME+'_'+SUBSTRING(table_name,5,len(table_name)-3)+ ' on '+ table_schema+'.'+table_name+' ('+COLUMN_NAME+') ' 'Field'\n,ROW_NUMBER() over (order by table_NAMe) as 'ROWNMBR'\ninto #a\nfrom INFORMATION_SCHEMA.COLUMNS\nwhere (COLUMN_NAME like '%_SSNO_%' or COLUMN_NAME like'%_EMPR_NO_')\n and TABLE_SCHEMA='dbo'\n\ndeclare @loopcntr int\ndeclare @ROW int\ndeclare @String nvarchar(1000)\nset @loopcntr=(select count(*) from #a)\nset @ROW=1 \n\nwhile (@ROW &lt;= @loopcntr)\n begin\n select top 1 @String=a.Field \n from #A a\n where a.ROWNMBR = @ROW\n execute sp_executesql @String\n set @ROW = @ROW + 1\n end \n</code></pre>\n" }, { "answer_id": 23768656, "author": "Bob Alley", "author_id": 3658181, "author_profile": "https://Stackoverflow.com/users/3658181", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT @pk = @pk + 1\n</code></pre>\n\n<p>would be better: </p>\n\n<pre><code>SET @pk += @pk\n</code></pre>\n\n<p>Avoid using SELECT if you are not referencing tables are are just assigning values.</p>\n" }, { "answer_id": 25618719, "author": "Srinivas Maale", "author_id": 3999541, "author_profile": "https://Stackoverflow.com/users/3999541", "pm_score": 1, "selected": false, "text": "<p>Step1: Below select statement creates a temp table with unique row number for each record.</p>\n\n<pre><code>select eno,ename,eaddress,mobno int,row_number() over(order by eno desc) as rno into #tmp_sri from emp \n</code></pre>\n\n<p>Step2:Declare required variables</p>\n\n<pre><code>DECLARE @ROWNUMBER INT\nDECLARE @ename varchar(100)\n</code></pre>\n\n<p>Step3: Take total rows count from temp table</p>\n\n<pre><code>SELECT @ROWNUMBER = COUNT(*) FROM #tmp_sri\ndeclare @rno int\n</code></pre>\n\n<p>Step4: Loop temp table based on unique row number create in temp</p>\n\n<pre><code>while @rownumber&gt;0\nbegin\n set @rno=@rownumber\n select @ename=ename from #tmp_sri where rno=@rno **// You can take columns data from here as many as you want**\n set @rownumber=@rownumber-1\n print @ename **// instead of printing, you can write insert, update, delete statements**\nend\n</code></pre>\n" }, { "answer_id": 37035265, "author": "Control Freak", "author_id": 916535, "author_profile": "https://Stackoverflow.com/users/916535", "pm_score": 2, "selected": false, "text": "<p>Lightweight, without having to make extra tables, if you have an integer <code>ID</code> on the table</p>\n\n<pre><code>Declare @id int = 0, @anything nvarchar(max)\nWHILE(1=1) BEGIN\n Select Top 1 @anything=[Anything],@id=@id+1 FROM Table WHERE ID&gt;@id\n if(@@ROWCOUNT=0) break;\n\n --Process @anything\n\nEND\n</code></pre>\n" }, { "answer_id": 37867029, "author": "Sean", "author_id": 240430, "author_profile": "https://Stackoverflow.com/users/240430", "pm_score": 1, "selected": false, "text": "<p>This approach only requires one variable and does not delete any rows from @databases. I know there are a lot of answers here, but I don't see one that uses MIN to get your next ID like this.</p>\n\n<pre><code>DECLARE @databases TABLE\n(\n DatabaseID int,\n Name varchar(15), \n Server varchar(15)\n)\n\n-- insert a bunch rows into @databases\n\nDECLARE @CurrID INT\n\nSELECT @CurrID = MIN(DatabaseID)\nFROM @databases\n\nWHILE @CurrID IS NOT NULL\nBEGIN\n\n -- Do stuff for @CurrID\n\n SELECT @CurrID = MIN(DatabaseID)\n FROM @databases\n WHERE DatabaseID &gt; @CurrID\n\nEND\n</code></pre>\n" }, { "answer_id": 40109813, "author": "Yves A Martin", "author_id": 1579352, "author_profile": "https://Stackoverflow.com/users/1579352", "pm_score": 2, "selected": false, "text": "<p>I prefer using the Offset Fetch if you have a unique ID you can sort your table by:</p>\n\n<pre><code>DECLARE @TableVariable (ID int, Name varchar(50));\nDECLARE @RecordCount int;\nSELECT @RecordCount = COUNT(*) FROM @TableVariable;\n\nWHILE @RecordCount &gt; 0\nBEGIN\nSELECT ID, Name FROM @TableVariable ORDER BY ID OFFSET @RecordCount - 1 FETCH NEXT 1 ROW;\nSET @RecordCount = @RecordCount - 1;\nEND\n</code></pre>\n\n<p>This way I don't need to add fields to the table or use a window function.</p>\n" }, { "answer_id": 42760525, "author": "Alexandre Pezzutto", "author_id": 7702229, "author_profile": "https://Stackoverflow.com/users/7702229", "pm_score": 2, "selected": false, "text": "<p>It's possible to use a cursor to do this:</p>\n\n<p>create function [dbo].f_teste_loop\nreturns @tabela table\n(\n cod int,\n nome varchar(10)\n)\nas \nbegin</p>\n\n<pre><code>insert into @tabela values (1, 'verde');\ninsert into @tabela values (2, 'amarelo');\ninsert into @tabela values (3, 'azul');\ninsert into @tabela values (4, 'branco');\n\nreturn;\n</code></pre>\n\n<p>end</p>\n\n<p>create procedure [dbo].[sp_teste_loop]\nas\nbegin</p>\n\n<pre><code>DECLARE @cod int, @nome varchar(10);\n\nDECLARE curLoop CURSOR STATIC LOCAL \nFOR\nSELECT \n cod\n ,nome\nFROM \n dbo.f_teste_loop();\n\nOPEN curLoop;\n\nFETCH NEXT FROM curLoop\n INTO @cod, @nome;\n\nWHILE (@@FETCH_STATUS = 0)\nBEGIN\n PRINT @nome;\n\n FETCH NEXT FROM curLoop\n INTO @cod, @nome;\nEND\n\nCLOSE curLoop;\nDEALLOCATE curLoop;\n</code></pre>\n\n<p>end</p>\n" }, { "answer_id": 43052926, "author": "Mass Dot Net", "author_id": 165494, "author_profile": "https://Stackoverflow.com/users/165494", "pm_score": 1, "selected": false, "text": "<p>Here's my solution, which makes use of an infinite loop, the <code>BREAK</code> statement, and the <code>@@ROWCOUNT</code> function. No cursors or temporary table are necessary, and I only need to write one query to get the next row in the <code>@databases</code> table:</p>\n\n<pre><code>declare @databases table\n(\n DatabaseID int,\n [Name] varchar(15), \n [Server] varchar(15)\n);\n\n\n-- Populate the [@databases] table with test data.\ninsert into @databases (DatabaseID, [Name], [Server])\nselect X.DatabaseID, X.[Name], X.[Server]\nfrom (values \n (1, 'Roger', 'ServerA'),\n (5, 'Suzy', 'ServerB'),\n (8675309, 'Jenny', 'TommyTutone')\n) X (DatabaseID, [Name], [Server])\n\n\n-- Create an infinite loop &amp; ensure that a break condition is reached in the loop code.\ndeclare @databaseId int;\n\nwhile (1=1)\nbegin\n -- Get the next database ID.\n select top(1) @databaseId = DatabaseId \n from @databases \n where DatabaseId &gt; isnull(@databaseId, 0);\n\n -- If no rows were found by the preceding SQL query, you're done; exit the WHILE loop.\n if (@@ROWCOUNT = 0) break;\n\n -- Otherwise, do whatever you need to do with the current [@databases] table row here.\n print 'Processing @databaseId #' + cast(@databaseId as varchar(50));\nend\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
Let's say I have the following simple table variable: ``` declare @databases table ( DatabaseID int, Name varchar(15), Server varchar(15) ) -- insert a bunch rows into @databases ``` Is declaring and using a cursor my only option if I wanted to iterate through the rows? Is there another way?
First of all you should be absolutely sure you need to iterate through each row — set based operations will perform faster in every case I can think of and will normally use simpler code. Depending on your data it may be possible to loop using just `SELECT` statements as shown below: ``` Declare @Id int While (Select Count(*) From ATable Where Processed = 0) > 0 Begin Select Top 1 @Id = Id From ATable Where Processed = 0 --Do some processing here Update ATable Set Processed = 1 Where Id = @Id End ``` Another alternative is to use a temporary table: ``` Select * Into #Temp From ATable Declare @Id int While (Select Count(*) From #Temp) > 0 Begin Select Top 1 @Id = Id From #Temp --Do some processing here Delete #Temp Where Id = @Id End ``` The option you should choose really depends on the structure and volume of your data. **Note:** If you are using SQL Server you would be better served using: ``` WHILE EXISTS(SELECT * FROM #Temp) ``` Using `COUNT` will have to touch every single row in the table, the `EXISTS` only needs to touch the first one (see [Josef's answer](https://stackoverflow.com/a/65294/963542) below).
61,995
<p>Given the following XML:</p> <pre><code>&lt;current&gt; &lt;login_name&gt;jd&lt;/login_name&gt; &lt;/current&gt; &lt;people&gt; &lt;person&gt; &lt;first&gt;John&lt;/first&gt; &lt;last&gt;Doe&lt;/last&gt; &lt;login_name&gt;jd&lt;/login_name&gt; &lt;/preson&gt; &lt;person&gt; &lt;first&gt;Pierre&lt;/first&gt; &lt;last&gt;Spring&lt;/last&gt; &lt;login_name&gt;ps&lt;/login_name&gt; &lt;/preson&gt; &lt;/people&gt; </code></pre> <p>How can I get "John Doe" from within the current/login matcher?</p> <p>I tried the following:</p> <pre><code>&lt;xsl:template match="current/login_name"&gt; &lt;xsl:value-of select="../people/first[login_name = .]"/&gt; &lt;xsl:text&gt; &lt;/xsl:text&gt; &lt;xsl:value-of select="../people/last[login_name = .]"/&gt; &lt;/xsl:template&gt; </code></pre>
[ { "answer_id": 62010, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 0, "selected": false, "text": "<p>I think what he actually wanted was the replacement in the match for the \"current\" node, not a match in the person node:</p>\n\n<pre><code>&lt;xsl:variable name=\"login\" select=\"//current/login_name/text()\"/&gt;\n\n&lt;xsl:template match=\"current/login_name\"&gt;\n&lt;xsl:value-of select='concat(../../people/person[login_name=$login]/first,\" \", ../../people/person[login_name=$login]/last)'/&gt;\n\n&lt;/xsl:template&gt;\n</code></pre>\n" }, { "answer_id": 62011, "author": "jelovirt", "author_id": 2679, "author_profile": "https://Stackoverflow.com/users/2679", "pm_score": 2, "selected": false, "text": "<p>You want <a href=\"http://www.w3.org/TR/xslt#function-current\" rel=\"nofollow noreferrer\"><code>current()</code></a> function</p>\n\n<pre><code>&lt;xsl:template match=\"current/login_name\"&gt;\n &lt;xsl:value-of select=\"../../people/person[login_name = current()]/first\"/&gt;\n &lt;xsl:text&gt; &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"../../people/person[login_name = current()]/last\"/&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>or a bit more cleaner:</p>\n\n<pre><code>&lt;xsl:template match=\"current/login_name\"&gt;\n &lt;xsl:for-each select=\"../../people/person[login_name = current()]\"&gt;\n &lt;xsl:value-of select=\"first\"/&gt;\n &lt;xsl:text&gt; &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"last\"/&gt;\n &lt;/xsl:for-each&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n" }, { "answer_id": 62081, "author": "Matt Large", "author_id": 2978, "author_profile": "https://Stackoverflow.com/users/2978", "pm_score": 0, "selected": false, "text": "<p>Just to add my thoughts to the stack</p>\n\n<pre><code>&lt;xsl:template match=\"login_name[parent::current]\"&gt;\n &lt;xsl:variable name=\"login\" select=\"text()\"/&gt;\n &lt;xsl:value-of select='concat(ancestor::people/child::person[login_name=$login]/child::first/text(),\" \",ancestor::people/child::person[login_name=$login]/child::last/text())'/&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>I always prefer to use the axes explicitly in my XPath, more verbose but clearer IMHO.</p>\n\n<p>Depending on how the rest of the XML documents looks (assuming this is just a fragment) you might need to constrain the reference to \"ancestor::people\" for example using \"ancestor::people[1]\" to constrain to the first people ancestor.</p>\n" }, { "answer_id": 62429, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 4, "selected": true, "text": "<p>I'd define a key to index the people:</p>\n\n<pre><code>&lt;xsl:key name=\"people\" match=\"person\" use=\"login_name\" /&gt;\n</code></pre>\n\n<p>Using a key here simply keeps the code clean, but you might also find it helpful for efficiency if you're often having to retrieve the <code>&lt;person&gt;</code> elements based on their <code>&lt;login_name&gt;</code> child.</p>\n\n<p>I'd have a template that returned the formatted name of a given <code>&lt;person&gt;</code>:</p>\n\n<pre><code>&lt;xsl:template match=\"person\" mode=\"name\"&gt;\n &lt;xsl:value-of select=\"concat(first, ' ', last)\" /&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>And then I'd do:</p>\n\n<pre><code>&lt;xsl:template match=\"current/login_name\"&gt;\n &lt;xsl:apply-templates select=\"key('people', .)\" mode=\"name\" /&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n" }, { "answer_id": 77868, "author": "leekelleher", "author_id": 12787, "author_profile": "https://Stackoverflow.com/users/12787", "pm_score": 1, "selected": false, "text": "<p>If you need to access multiple users, then <a href=\"https://stackoverflow.com/questions/61995/xslt-and-xpath-match-conditionally-upon-current-node-value#62429\">JeniT's <code>&lt;xsl:key /&gt;</code> approach</a> is ideal.</p>\n\n<p>Here is my alternative take on it:</p>\n\n<pre><code>&lt;xsl:template match=\"current/login_name\"&gt;\n &lt;xsl:variable name=\"person\" select=\"//people/person[login_name = .]\" /&gt;\n &lt;xsl:value-of select=\"concat($person/first, ' ', $person/last)\" /&gt;\n&lt;/xsl:template&gt;\n</code></pre>\n\n<p>We assign the selected <code>&lt;person&gt;</code> node to a variable, then we use the <code>concat()</code> function to output the first/last names.</p>\n\n<p>There is also an error in your example XML. The <code>&lt;person&gt;</code> node incorrectly ends with <code>&lt;/preson&gt;</code> (typo)</p>\n\n<p>A better solution could be given if we knew the overall structure of the XML document (with root nodes, etc.)</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/61995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1532/" ]
Given the following XML: ``` <current> <login_name>jd</login_name> </current> <people> <person> <first>John</first> <last>Doe</last> <login_name>jd</login_name> </preson> <person> <first>Pierre</first> <last>Spring</last> <login_name>ps</login_name> </preson> </people> ``` How can I get "John Doe" from within the current/login matcher? I tried the following: ``` <xsl:template match="current/login_name"> <xsl:value-of select="../people/first[login_name = .]"/> <xsl:text> </xsl:text> <xsl:value-of select="../people/last[login_name = .]"/> </xsl:template> ```
I'd define a key to index the people: ``` <xsl:key name="people" match="person" use="login_name" /> ``` Using a key here simply keeps the code clean, but you might also find it helpful for efficiency if you're often having to retrieve the `<person>` elements based on their `<login_name>` child. I'd have a template that returned the formatted name of a given `<person>`: ``` <xsl:template match="person" mode="name"> <xsl:value-of select="concat(first, ' ', last)" /> </xsl:template> ``` And then I'd do: ``` <xsl:template match="current/login_name"> <xsl:apply-templates select="key('people', .)" mode="name" /> </xsl:template> ```
62,013
<p>I set up a website to use SqlMembershipProvider as written on <a href="http://msdn.microsoft.com/en-us/library/ms998347.aspx" rel="nofollow noreferrer">this page</a>.</p> <p>I followed every step. I have the database, I modified the Web.config to use this provider, with the correct connection string, and the authentication mode is set to Forms. Created some users to test with.</p> <p>I created a Login.aspx and put the Login control on it. Everything works fine until the point that a user can log in. </p> <p>I call Default.aspx, it gets redirected to Login.aspx, I enter the user and the correct password. No error message, nothing seems to be wrong, but I see again the Login form, to enter the user's login information. However if I check the cookies in the browser, I can see that the cookie with the specified name exists.</p> <p>I already tried to handle the events by myself and check, what is happening in them, but no success.</p> <p>I'm using VS2008, Website in filesystem, SQL Express 2005 to store aspnetdb, no role management, tested with K-Meleon, IE7.0 and Chrome.</p> <p>Any ideas?</p> <p><strong>Resolution:</strong> After some mailing with Rob we have the ideal solution, which is now the accepted answer.</p>
[ { "answer_id": 62036, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<p>What is the role of the username you are logging in with? Have you permitted this role to access Default.aspx?</p>\n\n<p>I experienced this once (a long time ago) and went \"doh!\" when I realized that not even admin roles can access the main folder!</p>\n" }, { "answer_id": 62039, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "<p>Have you checked that the redirect path is being sent to the login form? Off my head I think it is <strong>ReturnURL</strong>?</p>\n" }, { "answer_id": 62047, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 0, "selected": false, "text": "<p>@Jon: I'm not using roles yet. If I check the Web Admin Tool, it says: Roles are not enabled .</p>\n\n<p>@Rob: Yes, it is there.</p>\n\n<p>I also checked the events in order: LoggingIn, Authenticate, LoggedIn, so it is following the correct path, but no redirect and it does not see that it was authenticated.</p>\n" }, { "answer_id": 62050, "author": "Leo Moore", "author_id": 6336, "author_profile": "https://Stackoverflow.com/users/6336", "pm_score": 2, "selected": false, "text": "<p>You normally have a initial folder with the generally accessable forms and a seperate folder with all the login protected items. In the initial folder you have a webconfig with:</p>\n\n<pre><code> &lt;!--Deny all users --&gt;\n &lt;authorization&gt;\n &lt;deny users=\"*\" /&gt;\n &lt;/authorization&gt;\n</code></pre>\n\n<p>In the other folder you can put a seperate webconfig with settings like:</p>\n\n<pre><code> &lt;!--Deny all users unless autherticated --&gt;\n &lt;authorization&gt;\n &lt;deny users=\"?\" /&gt;\n &lt;/authorization&gt;\n</code></pre>\n\n<p>If you want to further refine it you can allow access to a particular role only.</p>\n\n<pre><code>&lt;configuration&gt;\n &lt;system.web&gt;\n &lt;authorization&gt;\n &lt;allow roles=\"Admins\"/&gt;\n &lt;deny users=\"*\"/&gt;\n &lt;/authorization&gt;\n &lt;/system.web&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>This will deny access to anyone who does not have a role of admin, which they can only get if they are logged in sucessfully.</p>\n\n<p>If you want some good background I recommend the DNR TV episode with Miguel Castro on <a href=\"http://www.dnrtv.com/default.aspx?showNum=20\" rel=\"nofollow noreferrer\">ASP.NET Membership</a></p>\n" }, { "answer_id": 62058, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 1, "selected": false, "text": "<p>I ran into a similar problem a while ago, and I remember it was solved by <em>not naming the login page \"login.aspx\"</em>. Just naming it something else (userLogin.aspx, for example) solved it for me.</p>\n" }, { "answer_id": 62084, "author": "Chris Driver", "author_id": 5217, "author_profile": "https://Stackoverflow.com/users/5217", "pm_score": 0, "selected": false, "text": "<p>Do you have <code>requireSSL=\"true\"</code> in your web.config?\nI had similar symptoms to you. If you set requireSSL to true, there are some <a href=\"http://msdn.microsoft.com/en-us/library/ms998347.aspx#paght000022_additionalconsiderations\" rel=\"nofollow noreferrer\">additional considerations</a>.</p>\n" }, { "answer_id": 62092, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 3, "selected": false, "text": "<h2>RE: The Accepted Answer</h2>\n<p>I <strong>do not</strong> like the hack given.</p>\n<p>I have a site that uses a login form called &quot;<em>login.aspx</em>&quot; and all works <strong>fine</strong>. I think we should actually find the answer rather than hack. Since all the [presumably] tested sites work. <strong>Do you not think we should actually use StackOverflow to find the ACTUAL problem?</strong> (making it much more useful than anywhere else?)</p>\n<p>In the <strong>LoginCtl_Authenticate</strong> event are you setting the <strong>EventArgs.Authenticated</strong> property to <strong>true</strong>?</p>\n<p>e.g.</p>\n<pre><code>protected void LoginCtl_Authenticate(object sender, AuthenticateEventArgs e)\n{\n // Check the Credentials against DB\n bool authed = DAL.Authenticate(user, pass);\n e.Authenticated = authed;\n}\n</code></pre>\n" }, { "answer_id": 62104, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 0, "selected": false, "text": "<p>@Rob: You are right from your point of view.</p>\n\n<p>From my point of view it is my test project to check some things. If it is working in any way, that fits to me. I haven't found any similair problem on the net, so it can be something else, absolutely not related to ASP.NET.</p>\n\n<p>However I'm open, so that next time I also can say: aha, I know this!</p>\n\n<p>I started over the project:</p>\n\n<p>Default.aspx: added LoginStatus and LoginName controls</p>\n\n<p>Login.aspx: added Login control and CreateUserWizard control</p>\n\n<p>web.config: added</p>\n\n<pre><code>&lt;authentication mode=\"Forms\"&gt;\n &lt;forms name=\"SqlAuthCookie\" timeout=\"10\" loginUrl=\"Login.aspx\"/&gt;\n&lt;/authentication&gt;\n&lt;authorization&gt;\n &lt;deny users=\"?\"/&gt;\n &lt;allow users=\"*\"/&gt;\n&lt;/authorization&gt;\n&lt;membership defaultProvider=\"MySqlMembershipProvider\"&gt;\n &lt;providers&gt;\n &lt;clear/&gt;\n &lt;add name=\"MySqlMembershipProvider\" connectionStringName=\"MyLocalSQLServer\" applicationName=\"MyAppName\" type=\"System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/&gt;\n &lt;/providers&gt;\n&lt;/membership&gt;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>&lt;connectionStrings&gt;\n &lt;add name=\"MyLocalSQLServer\" connectionString=\"Initial Catalog=aspnetdb;data source=iballanb\\sqlexpress;uid=full;pwd=full;\"/&gt;\n&lt;/connectionStrings&gt;\n</code></pre>\n\n<p>Create the database with <code>aspnet_regsql -E -S iballanb\\sqlexpress -A all</code>, created an SQL user called <em>full</em> with password <em>full</em>.</p>\n\n<p>Start the project, I got redirected to Login.aspx, create one user, it is created in database. Entering user data to login form, catching events: LoggingIn, Authenticate, LoggedIn, so I'm logged in ( I don't do anything in these events, I don't authenticate myself, I'm only interested in what is fired and in which order). RedirectURL is correctly pointing to Default.aspx, but has no effect.</p>\n\n<p>This is it so far.</p>\n" }, { "answer_id": 62124, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "<p>If you are overriding the events, are you <strong>calling the default implementation?</strong> If you are overriding them to confirm their execution, then the actual code will not be getting executed either, which may be the break in the plumbing..</p>\n" }, { "answer_id": 65670, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 4, "selected": true, "text": "<p>I have checked the code over in the files you have sent me (thanks again for sending them through).</p>\n<p><strong>Note: I have not tested this since I have not installed the database etc..</strong></p>\n<p>However, I am pretty sure this is the issue.</p>\n<p>You need to set the <em>MembershipProvider</em> Property for your ASP.NET controls. Making the definitions for them:</p>\n<pre><code>&lt;asp:Login ID=&quot;Login1&quot; runat=&quot;server&quot; \n MembershipProvider=&quot;MySqlMembershipProvider&quot;&gt;\n &lt;LayoutTemplate&gt;\n &lt;!-- template code snipped for brevity --&gt;\n &lt;/LayoutTemplate&gt;\n&lt;/asp:Login&gt;\n</code></pre>\n<p>And..</p>\n<pre><code>&lt;asp:CreateUserWizard ID=&quot;CreateUserWizard1&quot; runat=&quot;server&quot; \n MembershipProvider=&quot;MySqlMembershipProvider&quot;&gt;\n &lt;WizardSteps&gt;\n &lt;asp:CreateUserWizardStep runat=&quot;server&quot; /&gt;\n &lt;asp:CompleteWizardStep runat=&quot;server&quot; /&gt;\n &lt;/WizardSteps&gt;\n &lt;/asp:CreateUserWizard&gt;\n</code></pre>\n<p>This then binds the controls to the Membership Provider with the given name (which you have specified in the Web.Config.</p>\n<p>Give this a whirl in your solution and let me know how you get on.\nI hope this works for you :)</p>\n<h3>Edit</h3>\n<p>I should also add, I know you shouldn't need to do this as the default provider is set, but I <em>have</em> had problems in the past with this.. I ended up setting them all to manual and all worked fine.</p>\n" }, { "answer_id": 1747578, "author": "Daniel Osterhaus", "author_id": 212728, "author_profile": "https://Stackoverflow.com/users/212728", "pm_score": 1, "selected": false, "text": "<p>I just solved my problem of this happening. Check out the applicationName for your membership provider. \n<a href=\"http://weblogs.asp.net/scottgu/archive/2006/04/22/Always-set-the-_2200_applicationName_2200_-property-when-configuring-ASP.NET-2.0-Membership-and-other-Providers.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/scottgu/archive/2006/04/22/Always-set-the-_2200_applicationName_2200_-property-when-configuring-ASP.NET-2.0-Membership-and-other-Providers.aspx</a></p>\n" }, { "answer_id": 17679617, "author": "Cabous", "author_id": 2587849, "author_profile": "https://Stackoverflow.com/users/2587849", "pm_score": 0, "selected": false, "text": "<p>Try adding the path element. It must be the same as your virtual site path, for example\nif you test to /localhost/Authentication</p>\n\n<p>path must be = \"/Authentication\"</p>\n\n<pre><code>&lt;forms loginUrl=\"Login.aspx\" protection=\"All\" timeout=\"30\" name=\"AuthTestCookie\"\npath=\"/Authentication\" requireSSL=\"false\" slidingExpiration=\"true\"\ndefaultUrl=\"default.aspx\" cookieless=\"UseCookies\" enableCrossAppRedirects=\"false\"/&gt;\n</code></pre>\n" }, { "answer_id": 33831438, "author": "Zachary Weber", "author_id": 2171090, "author_profile": "https://Stackoverflow.com/users/2171090", "pm_score": 0, "selected": false, "text": "<p>I know this is an old post, but I found an additional answer... For others in the future with this problem, I found that my web.config file somehow had the following added to the bottom (not sure how). Once I commented the <em></em> out, it worked fine :) Even though I had everything above in the file set properly, this one line caused me over an hour of headache...</p>\n\n<pre><code>&lt;system.webServer&gt;\n &lt;modules&gt;\n &lt;remove name=\"FormsAuthentication\" /&gt;\n &lt;/modules&gt;\n&lt;/system.webServer&gt;\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/968/" ]
I set up a website to use SqlMembershipProvider as written on [this page](http://msdn.microsoft.com/en-us/library/ms998347.aspx). I followed every step. I have the database, I modified the Web.config to use this provider, with the correct connection string, and the authentication mode is set to Forms. Created some users to test with. I created a Login.aspx and put the Login control on it. Everything works fine until the point that a user can log in. I call Default.aspx, it gets redirected to Login.aspx, I enter the user and the correct password. No error message, nothing seems to be wrong, but I see again the Login form, to enter the user's login information. However if I check the cookies in the browser, I can see that the cookie with the specified name exists. I already tried to handle the events by myself and check, what is happening in them, but no success. I'm using VS2008, Website in filesystem, SQL Express 2005 to store aspnetdb, no role management, tested with K-Meleon, IE7.0 and Chrome. Any ideas? **Resolution:** After some mailing with Rob we have the ideal solution, which is now the accepted answer.
I have checked the code over in the files you have sent me (thanks again for sending them through). **Note: I have not tested this since I have not installed the database etc..** However, I am pretty sure this is the issue. You need to set the *MembershipProvider* Property for your ASP.NET controls. Making the definitions for them: ``` <asp:Login ID="Login1" runat="server" MembershipProvider="MySqlMembershipProvider"> <LayoutTemplate> <!-- template code snipped for brevity --> </LayoutTemplate> </asp:Login> ``` And.. ``` <asp:CreateUserWizard ID="CreateUserWizard1" runat="server" MembershipProvider="MySqlMembershipProvider"> <WizardSteps> <asp:CreateUserWizardStep runat="server" /> <asp:CompleteWizardStep runat="server" /> </WizardSteps> </asp:CreateUserWizard> ``` This then binds the controls to the Membership Provider with the given name (which you have specified in the Web.Config. Give this a whirl in your solution and let me know how you get on. I hope this works for you :) ### Edit I should also add, I know you shouldn't need to do this as the default provider is set, but I *have* had problems in the past with this.. I ended up setting them all to manual and all worked fine.
62,044
<p>I'm trying to construct a find command to process a bunch of files in a directory using two different executables. Unfortunately, <code>-exec</code> on find doesn't allow to use pipe or even <code>\|</code> because the shell interprets that character first. </p> <p>Here is specifically what I'm trying to do (which doesn't work because pipe ends the find command):</p> <pre><code>find /path/to/jpgs -type f -exec jhead -v {} | grep 123 \; -print </code></pre>
[ { "answer_id": 62054, "author": "Xetius", "author_id": 274, "author_profile": "https://Stackoverflow.com/users/274", "pm_score": 1, "selected": false, "text": "<p>As this outputs a list would you not :</p>\n\n<pre><code>find /path/to/jpgs -type f -exec jhead -v {} \\; | grep 123\n</code></pre>\n\n<p>or </p>\n\n<pre><code>find /path/to/jpgs -type f -print -exec jhead -v {} \\; | grep 123\n</code></pre>\n\n<p>Put your grep on the results of the find -exec.</p>\n" }, { "answer_id": 62060, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 8, "selected": true, "text": "<p>Try this</p>\n\n<pre><code>find /path/to/jpgs -type f -exec sh -c 'jhead -v {} | grep 123' \\; -print\n</code></pre>\n\n<p>Alternatively you could try to embed your exec statement inside a sh script and then do:</p>\n\n<pre><code>find -exec some_script {} \\;\n</code></pre>\n" }, { "answer_id": 62066, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 2, "selected": false, "text": "<p>With <code>-exec</code> you can only run a single executable with some arguments, not arbitrary shell commands. To circumvent this, you can use <code>sh -c '&lt;shell command&gt;'</code>.</p>\n\n<p>Do note that the use of <code>-exec</code> is quite inefficient. For each file that is found, the command has to be executed again. It would be more efficient if you can avoid this. (For example, by moving the <code>grep</code> outside the <code>-exec</code> or piping the results of <code>find</code> to <code>xargs</code> as suggested by <a href=\"https://stackoverflow.com/questions/62044/how-do-i-use-a-pipe-in-the-exec-parameter-for-a-find-command#62142\">Palmin</a>.)</p>\n" }, { "answer_id": 62142, "author": "Palmin", "author_id": 5949, "author_profile": "https://Stackoverflow.com/users/5949", "pm_score": 4, "selected": false, "text": "<p>A slightly different approach would be to use xargs:</p>\n\n<pre><code>find /path/to/jpgs -type f -print0 | xargs -0 jhead -v | grep 123\n</code></pre>\n\n<p>which I always found a bit easier to understand and to adapt (the -print0 and -0 arguments are necessary to cope with filenames containing blanks)</p>\n\n<p>This <em>might</em> (not tested) be more effective than using -exec because it will pipe the list of files to xargs and xargs makes sure that the jhead commandline does not get too long.</p>\n" }, { "answer_id": 5131251, "author": "Dimitar", "author_id": 636119, "author_profile": "https://Stackoverflow.com/users/636119", "pm_score": 2, "selected": false, "text": "<p>Using <code>find</code> command for this type of a task is maybe not the best alternative. I use the following command frequently to find files that contain the requested information:</p>\n\n<pre><code>for i in dist/*.jar; do echo \"&gt;&gt; $i\"; jar -tf \"$i\" | grep BeanException; done\n</code></pre>\n" }, { "answer_id": 48566089, "author": "linuxgeek", "author_id": 8906994, "author_profile": "https://Stackoverflow.com/users/8906994", "pm_score": 0, "selected": false, "text": "<p>There is kind of another way you can do it but it is also pretty ghetto.</p>\n\n<p>Using the shell option extquote you can do something similar to this in order to make find exec stuff and then pipe it to sh.</p>\n\n<pre><code>root@ifrit findtest # find -type f -exec echo ls $\"|\" cat \\;|sh\nfilename\n</code></pre>\n\n<p><br></p>\n\n<pre><code>root@ifrit findtest # find -type f -exec echo ls $\"|\" cat $\"|\" xargs cat\\;|sh\nh\n</code></pre>\n\n<p>I just figured I'd add that because at least the way i visualized it, it was closer to the OP's original question of using pipes within exec.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3499/" ]
I'm trying to construct a find command to process a bunch of files in a directory using two different executables. Unfortunately, `-exec` on find doesn't allow to use pipe or even `\|` because the shell interprets that character first. Here is specifically what I'm trying to do (which doesn't work because pipe ends the find command): ``` find /path/to/jpgs -type f -exec jhead -v {} | grep 123 \; -print ```
Try this ``` find /path/to/jpgs -type f -exec sh -c 'jhead -v {} | grep 123' \; -print ``` Alternatively you could try to embed your exec statement inside a sh script and then do: ``` find -exec some_script {} \; ```
62,079
<p>I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output.</p> <blockquote> <p>1) Is it actually worth taking such things into account?</p> <p>2) Assuming it is worth taking it into account, how do I do this?</p> </blockquote> <p>I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.</p>
[ { "answer_id": 62094, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "<p>If your idea is to compare the languages, I'd say anything outside them is not relevant for comparison purposes. </p>\n\n<p>Nonetheless you can use the time command to measure everything and can compare it with the timing within a script.</p>\n\n<p>Like this:</p>\n\n<pre><code>$ time script.php\nHI!\n\nreal 0m3.218s\nuser 0m0.080s\nsys 0m0.064s\n</code></pre>\n\n<p>It will give you clock time, user time (php interpreter) and sys time (OS time)</p>\n\n<p>If you are thinking web, then it gets a lot harder because you would be mixing webserver overhead and that is not always easy to compare if, say, you are using WSGI v/s mod_php. Then you'd have to hook probes into the webserving parts of the chain as well</p>\n" }, { "answer_id": 62097, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 1, "selected": false, "text": "<ol>\n<li><p>It's worth taking speed into account if you're optimizing code. You should generally know why you're optimizing code (as in: a specific task in your existing codebase is taking too long, not \"I heard PHP is slower than Python\"). It's <em>not</em> worth taking speed into account if you don't actually plan on switching languages. Just because one tiny module does something slightly faster doesn't mean rewriting your app in another language is a good idea. There are many other factors to choosing a language besides speed.</p></li>\n<li><p>You benchmark, of course. Run the two codebases multiple times and compare the timing. You can use the <a href=\"http://unixhelp.ed.ac.uk/CGI/man-cgi?time\" rel=\"nofollow noreferrer\">time</a> command if both scripts are executable from the shell, or use respective benchmarking functionality from each language; the latter case depends heavily on the actual language, naturally.</p></li>\n</ol>\n" }, { "answer_id": 62099, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 1, "selected": false, "text": "<p>Well, you can use the \"time\" command to help:</p>\n\n<pre><code>you@yourmachine:~$ time echo \"hello world\"\nhello world\n\nreal 0m0.000s\nuser 0m0.000s\nsys 0m0.000s\nyou@yourmachine:~$ \n</code></pre>\n\n<p>And this will get around timing outside of the environment.</p>\n\n<p>As for whether you need to actually time that extra work... that entirely depends on what you are doing. I assume this is for some kind of web application of some sort, so it depends on how the framework you use actually works... does it cache some kind of compiled (or parsed) version of the script? If so, then startup time will be totally irrelevant (since the first hit will be the only one that startup time exists in).</p>\n\n<p>Also, make sure to run your tests in a loop so you can discount the first run (and include the cost on the first run in your report if you want). I have done some tests in Java, and the first run is always slowest due to the JIT doing its job (and the same sort of hit may exist in PHP, Python and any other languages you try).</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include). Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output. > > 1) Is it actually worth taking such things into account? > > > 2) Assuming it is worth taking it into account, how do I do this? > > > I'm using a Mac so I've got access to Linux commands and I'm not afraid to compile/create a command to help me, I just don't know how to write such a command.
If your idea is to compare the languages, I'd say anything outside them is not relevant for comparison purposes. Nonetheless you can use the time command to measure everything and can compare it with the timing within a script. Like this: ``` $ time script.php HI! real 0m3.218s user 0m0.080s sys 0m0.064s ``` It will give you clock time, user time (php interpreter) and sys time (OS time) If you are thinking web, then it gets a lot harder because you would be mixing webserver overhead and that is not always easy to compare if, say, you are using WSGI v/s mod\_php. Then you'd have to hook probes into the webserving parts of the chain as well
62,086
<p>I am using Adobe Flex/Air here, but as far as I know this applies to all of JavaScript. I have come across this problem a few times, and there must be an easy solution out there!</p> <p>Suppose I have the following XML (using e4x):</p> <pre><code>var xml:XML = &lt;root&gt;&lt;example&gt;foo&lt;/example&gt;&lt;/root&gt; </code></pre> <p>I can change the contents of the example node using the following code:</p> <pre><code>xml.example = "bar"; </code></pre> <p>However, if I have this:</p> <pre><code>var xml:XML = &lt;root&gt;foo&lt;/root&gt; </code></pre> <p>How do i change the contents of the root node?</p> <pre><code>xml = "bar"; </code></pre> <p>Obviously doesn't work as I'm attempting to assign a string to an XML object.</p>
[ { "answer_id": 62165, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 0, "selected": false, "text": "<p>If you're trying to change the root element of a document, you don't really need to-- just throw out the existing document and replace it. Alternatively, just wrap your element in a more proper root element (you shouldn't be editing the root node anyway) and you'd be set.</p>\n\n<p>Of course, that doesn't answer your question. There's an ugly JS hack that can do what you want, but bear in mind that it's likely far slower than doing the above. Anyway, here it is:</p>\n\n<pre><code>var xml = &lt;root&gt;foo&lt;/root&gt;; // &lt;/fix_syntax_highlighter&gt;\nvar parser = new DOMParser();\nvar serializer = new XMLSerializer();\n\n// Parse xml as DOM document\n// Must inject \"&lt;root&gt;&lt;/root&gt;\" wrapper because \n// E4X's toString() method doesn't give it to us\n// Not sure if this is expected behaviour.. doesn't seem so to me.\nvar xmlDoc = parser.parseFromString(\"&lt;root&gt;\" + \n xml.toString() + \"&lt;/root&gt;\", \"text/xml\");\n\n// Make the change\nxmlDoc.documentElement.firstChild.nodeValue = \"CHANGED\";\n\n// Serialize back to string and then to E4X XML()\nxml = new XML(serializer.serializeToString(xmlDoc));\n</code></pre>\n\n<p>You can ignore the fix_syntax_highlighter comment.</p>\n" }, { "answer_id": 62926, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 4, "selected": true, "text": "<p>It seems you confuse variables for the values they contain. The assignment</p>\n\n<pre><code>node = textInput.text;\n</code></pre>\n\n<p>changes the value the <em>variable</em> <code>node</code> points to, it doesn't change anything with the object that <code>node</code> currently points to. To do what you want to do you can use the <code>setChildren</code> method of the <code>XML</code> class:</p>\n\n<pre><code>node.setChildren(textInput.text)\n</code></pre>\n" }, { "answer_id": 63002, "author": "Grokys", "author_id": 6448, "author_profile": "https://Stackoverflow.com/users/6448", "pm_score": 1, "selected": false, "text": "<p>Ah thank you Theo - indeed seems I was confused there. I think the root of the confustion came from the fact I was able to assign </p>\n\n<pre><code>textInput.text = node; \n</code></pre>\n\n<p>Which I now guess is just implicity calling XML.toString() to convert XML->String. setChildren() is what I was looking for.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6448/" ]
I am using Adobe Flex/Air here, but as far as I know this applies to all of JavaScript. I have come across this problem a few times, and there must be an easy solution out there! Suppose I have the following XML (using e4x): ``` var xml:XML = <root><example>foo</example></root> ``` I can change the contents of the example node using the following code: ``` xml.example = "bar"; ``` However, if I have this: ``` var xml:XML = <root>foo</root> ``` How do i change the contents of the root node? ``` xml = "bar"; ``` Obviously doesn't work as I'm attempting to assign a string to an XML object.
It seems you confuse variables for the values they contain. The assignment ``` node = textInput.text; ``` changes the value the *variable* `node` points to, it doesn't change anything with the object that `node` currently points to. To do what you want to do you can use the `setChildren` method of the `XML` class: ``` node.setChildren(textInput.text) ```
62,137
<p>I've just heard the term covered index in some database discussion - what does it mean?</p>
[ { "answer_id": 62140, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 7, "selected": true, "text": "<p>A <em>covering index</em> is an index that contains all of, and possibly more, the columns you need for your query.</p>\n\n<p>For instance, this:</p>\n\n<pre><code>SELECT *\nFROM tablename\nWHERE criteria\n</code></pre>\n\n<p>will typically use indexes to speed up the resolution of which rows to retrieve using <em>criteria</em>, but then it will go to the full table to retrieve the rows.</p>\n\n<p>However, if the index contained the columns <em>column1, column2</em> and <em>column3</em>, then this sql:</p>\n\n<pre><code>SELECT column1, column2\nFROM tablename\nWHERE criteria\n</code></pre>\n\n<p>and, provided that particular index could be used to speed up the resolution of which rows to retrieve, the index already contains the values of the columns you're interested in, so it won't have to go to the table to retrieve the rows, but can produce the results directly from the index.</p>\n\n<p>This can also be used if you see that a typical query uses 1-2 columns to resolve which rows, and then typically adds another 1-2 columns, it could be beneficial to append those extra columns (if they're the same all over) to the index, so that the query processor can get everything from the index itself.</p>\n\n<p>Here's an <a href=\"http://www.devx.com/dbzone/Article/29530\" rel=\"noreferrer\">article: Index Covering Boosts SQL Server Query Performance</a> on the subject.</p>\n" }, { "answer_id": 62143, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": false, "text": "<p>Covering index is just an ordinary index. It's called \"covering\" if it can satisfy query without necessity to analyze data.</p>\n\n<p>example:</p>\n\n<pre><code>CREATE TABLE MyTable\n(\n ID INT IDENTITY PRIMARY KEY, \n Foo INT\n) \n\nCREATE NONCLUSTERED INDEX index1 ON MyTable(ID, Foo)\n\nSELECT ID, Foo FROM MyTable -- All requested data are covered by index\n</code></pre>\n\n<p>This is one of the fastest methods to retrieve data from SQL server.</p>\n" }, { "answer_id": 37800438, "author": "Thomas W", "author_id": 768795, "author_profile": "https://Stackoverflow.com/users/768795", "pm_score": 2, "selected": false, "text": "<p>Covering indexes are indexes which \"cover\" all columns needed from a specific table, removing the need to access the physical table at all for a given query/ operation.</p>\n\n<p>Since the index contains the desired columns (or a superset of them), table access can be replaced with an index lookup or scan -- which is generally much faster.</p>\n\n<p>Columns to cover:</p>\n\n<ul>\n<li>parameterized or static conditions; columns restricted by a parameterized or constant condition.</li>\n<li>join columns; columns dynamically used for joining</li>\n<li>selected columns; to answer selected values.</li>\n</ul>\n\n<p>While covering indexes can often provide good benefit for retrieval, they do add somewhat to insert/ update overhead; due to the need to write extra or larger index rows on every update. </p>\n\n<h2>Covering indexes for Joined Queries</h2>\n\n<p>Covering indexes are probably most valuable as a performance technique for joined queries. This is because joined queries are more costly &amp; more likely then single-table retrievals to suffer high cost performance problems. </p>\n\n<ul>\n<li>in a joined query, covering indexes should be considered per-table.</li>\n<li>each 'covering index' removes a physical table access from the plan &amp; replaces it with index-only access.</li>\n<li>investigate the plan costs &amp; experiment with which tables are most worthwhile to replace by a covering index. </li>\n<li>by this means, the multiplicative cost of large join plans can be significantly reduced. </li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>select oi.title, c.name, c.address\nfrom porderitem poi\njoin porder po on po.id = poi.fk_order\njoin customer c on c.id = po.fk_customer\nwhere po.orderdate &gt; ? and po.status = 'SHIPPING';\n\ncreate index porder_custitem on porder (orderdate, id, status, fk_customer);\n</code></pre>\n\n<p>See:</p>\n\n<ul>\n<li><a href=\"http://literatejava.com/sql/covering-indexes-query-optimization/\" rel=\"nofollow\">http://literatejava.com/sql/covering-indexes-query-optimization/</a></li>\n</ul>\n" }, { "answer_id": 40494784, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Lets say you have a simple table with the below columns, you have only indexed Id here:</p>\n\n<pre><code>Id (Int), Telephone_Number (Int), Name (VARCHAR), Address (VARCHAR)\n</code></pre>\n\n<p>Imagine you have to run the below query and check whether its using index, and whether performing efficiently without I/O calls or not. Remember, you have only created an index on <code>Id</code>.</p>\n\n<pre><code>SELECT Id FROM mytable WHERE Telephone_Number = '55442233';\n</code></pre>\n\n<p>When you check for performance on this query you will be dissappointed, since <code>Telephone_Number</code> is not indexed this needs to fetch rows from table using I/O calls. So, this is not a covering indexed since there is some column in query which is not indexed, which leads to frequent I/O calls.</p>\n\n<p>To make it a covered index you need to create a composite index on <code>(Id, Telephone_Number)</code>. </p>\n\n<p>For more details, please refer to this blog:\n<a href=\"https://www.percona.com/blog/2006/11/23/covering-index-and-prefix-indexes/\" rel=\"nofollow noreferrer\">https://www.percona.com/blog/2006/11/23/covering-index-and-prefix-indexes/</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5466/" ]
I've just heard the term covered index in some database discussion - what does it mean?
A *covering index* is an index that contains all of, and possibly more, the columns you need for your query. For instance, this: ``` SELECT * FROM tablename WHERE criteria ``` will typically use indexes to speed up the resolution of which rows to retrieve using *criteria*, but then it will go to the full table to retrieve the rows. However, if the index contained the columns *column1, column2* and *column3*, then this sql: ``` SELECT column1, column2 FROM tablename WHERE criteria ``` and, provided that particular index could be used to speed up the resolution of which rows to retrieve, the index already contains the values of the columns you're interested in, so it won't have to go to the table to retrieve the rows, but can produce the results directly from the index. This can also be used if you see that a typical query uses 1-2 columns to resolve which rows, and then typically adds another 1-2 columns, it could be beneficial to append those extra columns (if they're the same all over) to the index, so that the query processor can get everything from the index itself. Here's an [article: Index Covering Boosts SQL Server Query Performance](http://www.devx.com/dbzone/Article/29530) on the subject.
62,153
<p>Several times now I've been faced with plans from a team that wants to build their own bug tracking system - Not as a product, but as an internal tool.</p> <p>The arguments I've heard in favous are usually along the lines of :</p> <ul> <li>Wanting to 'eat our own dog food' in terms of some internally built web framework</li> <li>Needing some highly specialised report, or the ability to tweak some feature in some allegedly unique way</li> <li>Believing that it isn't difficult to build a bug tracking system</li> </ul> <p>What arguments might you use to support buying an existing bug tracking system? In particular, what features sound easy but turn out hard to implement, or are difficult and important but often overlooked?</p>
[ { "answer_id": 62162, "author": "Slavo", "author_id": 1801, "author_profile": "https://Stackoverflow.com/users/1801", "pm_score": 3, "selected": false, "text": "<p>The most basic argument for me would be the time loss. I doubt it could be completed in less than a month or two. Why spend the time when there are soooo many good bug tracking systems available? Give me an example of a feature that you have to tweak and is not readily available.</p>\n\n<p>I think a good bug tracking system has to reflect your development process. A very custom development process is inherently bad for a company/team. Most agile practices favor <a href=\"http://en.wikipedia.org/wiki/Scrum_%28development%29\" rel=\"nofollow noreferrer\">Scrum</a> or these kinds of things, and most bug tracking systems are in line with such suggestions and methods. Don't get too bureaucratic about this.</p>\n" }, { "answer_id": 62163, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 3, "selected": false, "text": "<p>I would just say it's a matter of money - buying a finished product you know is good for you (and sometimes not even buying if it's free) is better than having to go and develop one on your own. It's a simple game of <strong>pay now</strong> vs. <strong>pay later</strong>.</p>\n" }, { "answer_id": 62170, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 5, "selected": false, "text": "<p>I would want to turn the question around. WHY on earth would you want to build your own?<br>\nIf you need some extra fields, go with an existing package that can be modified.<br>\nSpecial report? Tap into the database and make it. </p>\n\n<p>Believing that it isn't difficult? Try then. Spec it up, and see the list of features and hours grow. Then after the list is complete, try to find an existing package that can be modified before you implement your own. </p>\n\n<p>In short, don't reinvent the wheel when another one just needs some tweaking to fit.</p>\n" }, { "answer_id": 62171, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 2, "selected": false, "text": "<p>I'd say one of the biggest stumbling blocks would be agonising over the data model / workflow. I predict this will take a <strong>long</strong> time and involve many arguments about what should happen to a bug under certain circumstances, what really constitutes a bug, etc. Rather than spend months arguing to-and-fro, if you were to just roll out a pre-built system, most people will learn how to use it and make the best of it, no matter what decisions are already fixed. Choose something open-source, and you can always tweak it later if need be - that will be <strong>much</strong> quicker than rolling your own from scratch.</p>\n" }, { "answer_id": 62179, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 4, "selected": false, "text": "<p>Programmers like to build their own ticket system because, having seen and used dozens of them, they know everything about it. That way they can stay in the comfort zone. </p>\n\n<p>It's like checking out a new restaurant: it might be rewarding, but it carries a risk. Better to order pizza again.</p>\n\n<p>There's also a great fact of decision making buried in there: there are always two reasons to do something: a good one and the right one. We make a decision (\"Build our own\"), then justify it (\"we need full control\"). Most people aren't even aware of their true motivation.</p>\n\n<p>To change their minds, you have to attack the <strong>real</strong> reason, not the justification.</p>\n" }, { "answer_id": 62180, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 3, "selected": false, "text": "<p>Most importantly, where will you submit the bugs for your bug tracker before it's finished?</p>\n\n<p>But seriously. The tools already exist, there's no need to reinvent the wheel. Modifying tracking tools to add certain specific features is one thing (I've modified <a href=\"http://en.wikipedia.org/wiki/Trac\" rel=\"nofollow noreferrer\">Trac</a> before)... rewriting one is just silly. </p>\n\n<p>The most important thing you can point out is that if all they want to do is add a couple of specialized reports, it doesn't require a ground-up solution. And besides, the LAST place \"your homebrew solution\" matters is for internal tools. Who cares what you're using internally if it's getting the job done as you need it?</p>\n" }, { "answer_id": 62183, "author": "Tony Pitale", "author_id": 1167846, "author_profile": "https://Stackoverflow.com/users/1167846", "pm_score": 2, "selected": false, "text": "<p>At this point, without a large new direction in bug tracking/ticketing, it would simply be re-inventing the wheel. Which seems to be what everyone else thinks, generally.</p>\n" }, { "answer_id": 62186, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 4, "selected": false, "text": "<h1>Not Invented Here syndrome!</h1>\n<p>Build your own bug tracker? Why not build your own mail client, project management tool, etc.</p>\n<p>As <a href=\"https://stackoverflow.com/questions/62153/reasons-not-to-build-your-own-bug-tracking-system/62163#62163\">Omer van Kloeten says</a> elsewhere, pay now or pay later.</p>\n" }, { "answer_id": 62193, "author": "Rikalous", "author_id": 4271, "author_profile": "https://Stackoverflow.com/users/4271", "pm_score": 2, "selected": false, "text": "<p>Your discussions will start with what consitutes a bug and evolve into what workflow to apply and end up with a massive argument about how to manage software engineering projects. Do you really want that? :-) Nah, thought not - go and buy one!</p>\n" }, { "answer_id": 62203, "author": "Ram Prasad", "author_id": 6361, "author_profile": "https://Stackoverflow.com/users/6361", "pm_score": 2, "selected": false, "text": "<p>Being a programmer working on an already critical (or least, important) task, should not let yourself deviate by trying to develop something that is already available in the market (open source or commercial).</p>\n\n<p>You will now try to create a bug tracking system to keep track of the bug tracking system that you use to track bugs in your core development.</p>\n\n<p>First:\n1. Choose the platform your bug system would run on (Java, PHP, Windows, Linux etc.)\n2. Try finding open source tools that are available (by open source, I mean both commercial and free tools) on the platform you chose\n3. Spend minimum time to try to customize to your need. If possible, don't waste time in customising at all</p>\n\n<p>For an enterprise development team, we started using <a href=\"http://en.wikipedia.org/wiki/JIRA\" rel=\"nofollow noreferrer\">JIRA</a>. We wanted some extra reports, SSO login, etc. JIRA was capable of it, and we could extend it using the already available plugin. Since the code was given part of paid-support, we only spent minimal time on writing the custom plugin for login.</p>\n" }, { "answer_id": 62210, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 3, "selected": false, "text": "<p>A bug tracking system can be a great project to start junior developers on. It's a fairly simple system that you can use to train them in your coding conventions and so forth. Getting junior developers to build such a system is relatively cheap and they can make their mistakes on something a customer will not see. </p>\n\n<p>If it's junk you can just throw it away but you can give them a feeling of there work already being important to the company if it is used. You can't put a cost on a junior developer being able to experience the full life cycle and all the opportunities for knowledge transfer that such a project will bring.</p>\n" }, { "answer_id": 62229, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 1, "selected": false, "text": "<p>Every software developer wants to build their own bug tracking system. It's because we can <em>obviously</em> improve on what's already out there since we are domain experts.</p>\n\n<p>It's almost certainly not worth the cost (in terms of developer hours). Just buy <a href=\"http://www.atlassian.com/software/jira/\" rel=\"nofollow noreferrer\">JIRA</a>.</p>\n\n<p>If you need extra reports for your bug tracking system, you can add these, even if you have to do it by accessing the underlying database directly.</p>\n" }, { "answer_id": 62254, "author": "fuzzbone", "author_id": 5027, "author_profile": "https://Stackoverflow.com/users/5027", "pm_score": 1, "selected": false, "text": "<p>The quesion is what is your company paying you to do? Is it to write software that only you will use? Obviously not. So the only way you can justify the time and expense to build a bug tracking system is if it costs less than the costs associated with using even a free bug tracking system.</p>\n\n<p>There well may be cases where this makes sense. Do you need to integrate with an existing system? (Time tracking, estimation, requirements, QA, automated testing)? Do you have some unique requirements in your organization related to say SOX Compliance that requires specific data elements that would be difficult to capture?</p>\n\n<p>Are you in an extremely beauracratic environment that leads to significant \"down-time\" between projects?</p>\n\n<p>If the answer is yes to these types of questions - then by all means the \"buy\" vs build arguement would say build. </p>\n" }, { "answer_id": 62282, "author": "dcraggs", "author_id": 4382, "author_profile": "https://Stackoverflow.com/users/4382", "pm_score": 3, "selected": false, "text": "<p>We have done this here. We wrote our first one over 10 years ago. We then upgraded it to use web services, more as a way to learn the technology. The main reason we did this originally was that we wanted a bug tracking system that also produced version history reports and a few other features that we could not find in commercial products.</p>\n\n<p>We are now looking at bug tracking systems again and are seriously considering migrating to Mantis and using Mantis Connect to add additional custom features of our own. The amount of effort in rolling our own system is just too great.</p>\n\n<p>I guess we should also be looking at FogBugz :-)</p>\n" }, { "answer_id": 62283, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 4, "selected": false, "text": "<p>There is a third option, neither buy nor build. There are piles of good free ones out there. \nFor example: </p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Bugzilla\" rel=\"nofollow noreferrer\">Bugzilla</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Trac\" rel=\"nofollow noreferrer\">Trac</a></li>\n</ul>\n\n<p>Rolling your own bug tracker for any use other than learning is not a good use of time.</p>\n\n<p>Other links:</p>\n\n<ul>\n<li><em><a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1049951.html\" rel=\"nofollow noreferrer\">Three free bug-tracking tools</a></em></li>\n<li><em><a href=\"http://en.wikipedia.org/wiki/Comparison_of_issue_tracking_systems\" rel=\"nofollow noreferrer\">Comparison of issue tracking systems</a></em></li>\n</ul>\n" }, { "answer_id": 62290, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 2, "selected": false, "text": "<p>Building on what other people have said, rather than just download a free / open source one. How about download it, then modify it entirely for your own needs? I know I've been required to do that in the past. I took an installation of Bugzilla and then modified it to support regression testing and test reporting (this was many years ago).</p>\n\n<p>Don't reinvent the wheel unless you're convinced you can build a rounder wheel.</p>\n" }, { "answer_id": 62297, "author": "Marc Gear", "author_id": 6563, "author_profile": "https://Stackoverflow.com/users/6563", "pm_score": 1, "selected": false, "text": "<p>Because <a href=\"http://en.wikipedia.org/wiki/Trac\" rel=\"nofollow noreferrer\">Trac</a> exists. </p>\n\n<p>And because you'll have to train new staff on your bespoke software when they'll likely have experience in other systems which you can build on rather than throw away.</p>\n" }, { "answer_id": 62374, "author": "pro", "author_id": 352728, "author_profile": "https://Stackoverflow.com/users/352728", "pm_score": 1, "selected": false, "text": "<p>Because it's not billable time or even very useful unless you are going to sell it.</p>\n\n<p>There are perfectly good bug tracking systems available, for example, <a href=\"http://en.wikipedia.org/wiki/FogBugz\" rel=\"nofollow noreferrer\">FogBugz</a>.</p>\n" }, { "answer_id": 62386, "author": "quadri", "author_id": 6712, "author_profile": "https://Stackoverflow.com/users/6712", "pm_score": 0, "selected": false, "text": "<p>I agree with most of the people here. It is no use to rebuild something when there are many tools (even free) available.\nIf you want to customize anything, most of the free tools give you the code, play with it.</p>\n\n<p>If you do new development, you should not be doing it for yourself only.</p>\n" }, { "answer_id": 62469, "author": "Kinjal Dixit", "author_id": 6629, "author_profile": "https://Stackoverflow.com/users/6629", "pm_score": 1, "selected": false, "text": "<p>If \"Needing some highly specialised report, or the ability to tweak some feature in some allegedly unique way\", the best and cheapest way to do that is to talk to the developers of existing bug tracking systems. Pay them to put that feature in their application, make it available to the world. Instead of reinventing the wheel, just pay the wheel manufacturers to put in spokes shaped like springs.</p>\n\n<p>Otherwise, if trying to showcase a framework, its all good. Just make sure to put in the relevant disclaimers.</p>\n\n<p>To the people who believe bug tracking system are not difficult to build, follow the waterfall SDLC strictly. Get all the requirements down up front. That will surely help them understand the complexity. These are typically the same people who say that a search engine isn't that difficult to build. Just a text box, a \"search\" button and a \"i'm feeling lucky\" button, and the \"i'm feeling lucky\" button can be done in phase 2.</p>\n" }, { "answer_id": 62854, "author": "LepardUK", "author_id": 44247, "author_profile": "https://Stackoverflow.com/users/44247", "pm_score": 2, "selected": false, "text": "<p>Most developers think that they have some unique powers that no one else has and therefore they can create a system that is unique in some way.</p>\n\n<p>99% of them are wrong.</p>\n\n<p>What are the chances that your company has employees in the 1%?</p>\n" }, { "answer_id": 62901, "author": "Rangachari Anand", "author_id": 7222, "author_profile": "https://Stackoverflow.com/users/7222", "pm_score": 1, "selected": false, "text": "<p>I worked in a startup for several years where we started with <a href=\"http://en.wikipedia.org/wiki/GNATS\" rel=\"nofollow noreferrer\">GNATS</a>, an open source tool, and essentially built our own elaborate bug tracking system on top of it. The argument was that we would avoid spending a lot of money on a commercial system, and we would get a bug tracking system exactly fitted to our needs. </p>\n\n<p>Of course, it turned out to be much harder than expected and was a big distraction for the developers - who also had to maintain the bug tracking system in addition to our code. This was one of the contributing factors to the demise of our company.</p>\n" }, { "answer_id": 62905, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p><strong>Use some open source software as is</strong>.\nFor sure there are bugs, and you will need what is not yet there or is pending a bug fix. It happens all of the time. :)</p>\n\n<p>If you extend/customize an open source version then you must maintain it. Now the application that is suppose to help you with testing <strong>money making applications</strong> will become a burden to support.</p>\n" }, { "answer_id": 143000, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 3, "selected": false, "text": "<p>First, against the arguments in favor of building your own:</p>\n\n<blockquote>\n <p>Wanting to 'eat our own dog food' in terms of some internally built web framework</p>\n</blockquote>\n\n<p>That of course raises the question why build your own web framework. Just like there are many worthy free bug trackers out there, there are many worthy frameworks too. I wonder whether your developers have their priorities straight? Who's doing the work that makes your company actual money? </p>\n\n<p>OK, if they must build a framework, let it evolve organically from the process of building the actual software your business uses to make money.</p>\n\n<blockquote>\n <p>Needing some highly specialised report, or the ability to tweak some feature in some allegedly unique way</p>\n</blockquote>\n\n<p>As others have said, grab one of the many fine open source trackers and tweak it.</p>\n\n<blockquote>\n <p>Believing that it isn't difficult to build a bug tracking system</p>\n</blockquote>\n\n<p>Well, I wrote the first version of my <a href=\"http://ifdefined.com/bugtrackernet.html\" rel=\"nofollow noreferrer\">BugTracker.NET</a> in just a couple of weeks, starting with no prior C# knowledge. But now, 6 years and a couple thousand hours later, there's still a big list of undone feature requests, so it all depends on what you want a bug tracking system to do. How much email integration, source control integration, permissions, workflow, time tracking, schedule estimation, etc. A bug tracker can be a major, major application.</p>\n\n<blockquote>\n <p>What arguments might you use to support buying an existing bug tracking system?</p>\n</blockquote>\n\n<p>Don't need to buy.Too many good open source ones: <a href=\"http://en.wikipedia.org/wiki/Trac\" rel=\"nofollow noreferrer\">Trac</a>, <a href=\"http://en.wikipedia.org/wiki/Mantis_Bug_Tracker\" rel=\"nofollow noreferrer\">Mantis_Bug_Tracker</a>, my own BugTracker.NET, to name a few.</p>\n\n<blockquote>\n <p>In particular, what features sound easy but turn out hard to implement, or are difficult and important but often overlooked?</p>\n</blockquote>\n\n<p>If you are creating it just for yourselves, then you can take a lot of shortcuts, because you can hard-wire things. If you are building it for lots of different users, in lots of different scenarios, then it's the support for configurability that is hard. Configurable workflow, custom fields, and permissions.</p>\n\n<p>I think two features that a <em>good</em> bug tracker must have, that both <a href=\"http://en.wikipedia.org/wiki/FogBugz\" rel=\"nofollow noreferrer\">FogBugz</a> and BugTracker.NET have, are 1) integration of both incoming and outgoing email, so that the entire conversation about a bug lives with the bug and not in a separate email thread, and 2) a utility for turning a screenshot into a bug post with a just a couple of clicks. </p>\n" }, { "answer_id": 180008, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 7, "selected": true, "text": "<p>First, look at these <a href=\"http://ohloh.net\" rel=\"noreferrer\">Ohloh</a> metrics:</p>\n\n<pre><code> Trac: 44 KLoC, 10 Person Years, $577,003\nBugzilla: 54 KLoC, 13 Person Years, $714,437\n Redmine: 171 KLoC, 44 Person Years, $2,400,723\n Mantis: 182 KLoC, 47 Person Years, $2,562,978\n</code></pre>\n\n<p>What do we learn from these numbers? We learn that building Yet Another Bug Tracker is a great way to waste resources!</p>\n\n<p>So here are my reasons to build your own internal bug tracking system:</p>\n\n<ol>\n<li>You need to neutralize all the bozocoders for a decade or two.</li>\n<li>You need to flush some money to avoid budget reduction next year.</li>\n</ol>\n\n<p>Otherwise don't.</p>\n" }, { "answer_id": 180071, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>Suppose, tomorrow (next year), if they decided to bring in a popular open source/commercial tool for ALL bug tracking system in the company, how will this tool be able to export all its bug tickets to the other tool?</p>\n\n<p>As long as there is a real need for a custom bug tracking system, and such questions are answered, I would NOT bother too much.</p>\n" }, { "answer_id": 180111, "author": "Miles", "author_id": 21828, "author_profile": "https://Stackoverflow.com/users/21828", "pm_score": 0, "selected": false, "text": "<p>There's so many great ones out there already, why waste the time to re-invent the wheel?</p>\n\n<p>Just use <a href=\"http://en.wikipedia.org/wiki/FogBugz\" rel=\"nofollow noreferrer\">FogBugz</a>.</p>\n" }, { "answer_id": 182341, "author": "Jonathan Beerhalter", "author_id": 18927, "author_profile": "https://Stackoverflow.com/users/18927", "pm_score": 2, "selected": false, "text": "<p>I have been on both sides of this debate so let me be a little two faced here.</p>\n\n<p>When I was younger, I pushed to build our own bug tracking system. I just highlighted all of the things that the off the shelf stuff couldn't do, and I got management to go for it. Who did they pick to lead the team? Me! It was going to be my first chance to be a team lead and have a voice in everything from design to tools to personnel. I was thrilled. So my recommendation would be to check to the motivations of the people pushing this project. </p>\n\n<p>Now that I'm older and faced with the same question again, I just decided to go with FogBugz. It does 99% of what we need and the costs are basically 0. Plus, Joel will send you personal emails making you feel special. And in the end, isn't that the problem, your developers think this will make them special? </p>\n" }, { "answer_id": 228387, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 0, "selected": false, "text": "<p>Don't write your own software just so you can \"eat your own dog food\". You're just creating more work, when you could probably purchase software that does the same thing (and better) for less time and money spent.</p>\n" }, { "answer_id": 249805, "author": "Sarat", "author_id": 18937, "author_profile": "https://Stackoverflow.com/users/18937", "pm_score": 1, "selected": false, "text": "<p>I think the reason people write their own bug tracking systems (in my experience) are,</p>\n\n<ol>\n<li>They don't want to pay for a system they see as being relatively easy to build.</li>\n<li>Programmer ego</li>\n<li>General dissatisfaction with the experience and solution delivered by existing systems.</li>\n<li>They sell it as a product :)</li>\n</ol>\n\n<p>To me, the biggest reason why most bug trackers failed was that they did not deliver an optimum user experience and it can be very painful working with a system that you use a LOT, when it is not optimised for usability.</p>\n\n<p>I think the other reason is the same as why almost every one of us (programmers) have built their own custom CMS or CMS framework at sometime (guilty as charged). Just because you can!</p>\n" }, { "answer_id": 249859, "author": "t3mujin", "author_id": 15968, "author_profile": "https://Stackoverflow.com/users/15968", "pm_score": 0, "selected": false, "text": "<p>I don't think building an in-house tracking system is relatively easy to build, and certainly it won't match a paid or open source solution. Most of the times I would go for \"programmer ego\" or just having an IT department that really can't use third-party software and has to build literally every piece of software used. </p>\n\n<p>Once I worked on a telecommunications company that had their <strong>own in-house version control system</strong>, and it was pretty crappy, but it kept a whole team busy...</p>\n" }, { "answer_id": 309346, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I agree with all the reasons NOT to. We tried for some time to use what's out there, and wound up writing our own anyway. Why? Mainly because most of them are too cumbersome to engage anyone but the technical people. We even tried basecamp (which, of course, isn't designed for this and failed in that regard).</p>\n\n<p>We also came up with some unique functionality that worked great with our clients: a \"report a bug\" button that we scripted into code with one line of javascript. It allows our clients to open a small window, jot info in quickly and submit to the database.</p>\n\n<p>But, it certainly took many hours to code; became a BIG pet project; lots of weekend time.</p>\n\n<p>If you want to check it out: <a href=\"http://www.archerfishonline.com\" rel=\"nofollow noreferrer\">http://www.archerfishonline.com</a></p>\n\n<p>Would love some feedback.</p>\n" }, { "answer_id": 408259, "author": "jjriv", "author_id": 50996, "author_profile": "https://Stackoverflow.com/users/50996", "pm_score": 1, "selected": false, "text": "<p>We've done this... a few times. The only reason we built our own is because it was five years ago and there weren't very many good alternatives. but now there are tons of alternatives. The main thing we learned in building our own tool is that you will spend a lot of time working on it. And that is time you could be billing for your time. It makes a lot more sense, as a small business, to pay the monthly fee which you can easily recoup with one or two billable hours, than to spend all that time rolling your own. Sure, you'll have to make some concessions, but you'll be far better off in the long run.</p>\n\n<p>As for us, we decided to make our application available for other developers. Check it out at <a href=\"http://www.myintervals.com\" rel=\"nofollow noreferrer\">http://www.myintervals.com</a></p>\n" }, { "answer_id": 664792, "author": "Andy Dent", "author_id": 53870, "author_profile": "https://Stackoverflow.com/users/53870", "pm_score": 0, "selected": false, "text": "<p>Tell them, <em>that's great, the company could do with saving some money for a while and will be happy to contribute the development tools whilst you work on this unpaid sabbatical. Anyone who wishes to take their annual leave instead to work on the project is free to do so.</em></p>\n" }, { "answer_id": 2979169, "author": "louism", "author_id": 24702, "author_profile": "https://Stackoverflow.com/users/24702", "pm_score": 0, "selected": false, "text": "<p>I've built my own bug tracking systems. I too thought: \"how hard could it be, it's just a bug tracking system\" <strong>ERR - WRONG*</strong> - it took six months to code it.</p>\n\n<p>The main reason I baked my own was to get it exactly how I wanted it. The other reason was as a hobby project.</p>\n\n<p>I'd say that's about the only time it is justified to build your own is if it's as a hobby project. No company should be spending its time doing it.</p>\n\n<p>My software is called <a href=\"http://www.bugweb.com.au\" rel=\"nofollow noreferrer\">Bugweb</a> by the way.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
Several times now I've been faced with plans from a team that wants to build their own bug tracking system - Not as a product, but as an internal tool. The arguments I've heard in favous are usually along the lines of : * Wanting to 'eat our own dog food' in terms of some internally built web framework * Needing some highly specialised report, or the ability to tweak some feature in some allegedly unique way * Believing that it isn't difficult to build a bug tracking system What arguments might you use to support buying an existing bug tracking system? In particular, what features sound easy but turn out hard to implement, or are difficult and important but often overlooked?
First, look at these [Ohloh](http://ohloh.net) metrics: ``` Trac: 44 KLoC, 10 Person Years, $577,003 Bugzilla: 54 KLoC, 13 Person Years, $714,437 Redmine: 171 KLoC, 44 Person Years, $2,400,723 Mantis: 182 KLoC, 47 Person Years, $2,562,978 ``` What do we learn from these numbers? We learn that building Yet Another Bug Tracker is a great way to waste resources! So here are my reasons to build your own internal bug tracking system: 1. You need to neutralize all the bozocoders for a decade or two. 2. You need to flush some money to avoid budget reduction next year. Otherwise don't.
62,188
<p>To commemorate the public launch of Stack Overflow, what's the shortest code to cause a stack overflow? Any language welcome.</p> <p>ETA: Just to be clear on this question, seeing as I'm an occasional Scheme user: tail-call "recursion" is really iteration, and any solution which can be converted to an iterative solution relatively trivially by a decent compiler won't be counted. :-P</p> <p>ETA2: I've now selected a “best answer”; see <a href="https://stackoverflow.com/questions/62188/stack-overflow-code-golf/71833#71833">this post</a> for rationale. Thanks to everyone who contributed! :-)</p>
[ { "answer_id": 62189, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 7, "selected": false, "text": "<p>My current best (in x86 assembly) is:</p>\n\n<pre><code>push eax\njmp short $-1\n</code></pre>\n\n<p>which results in 3 bytes of object code (<code>50 EB FD</code>). For 16-bit code, this is also possible:</p>\n\n<pre><code>call $\n</code></pre>\n\n<p>which also results in 3 bytes (<code>E8 FD FF</code>).</p>\n" }, { "answer_id": 62191, "author": "Niyaz", "author_id": 184, "author_profile": "https://Stackoverflow.com/users/184", "pm_score": 0, "selected": false, "text": "<p><strong>C++</strong>:</p>\n\n<pre><code>int overflow(int n)\n{\n return overflow(1);\n}\n</code></pre>\n" }, { "answer_id": 62195, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 6, "selected": false, "text": "<p>C#: </p>\n\n<pre><code>public int Foo { get { return Foo; } }\n</code></pre>\n" }, { "answer_id": 62205, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 4, "selected": false, "text": "<p><strong>Python</strong>:</p>\n\n<pre><code>so=lambda:so();so()\n</code></pre>\n\n<p>Alternatively:</p>\n\n<pre><code>def so():so()\nso()\n</code></pre>\n\n<p>And if Python optimized tail calls...:</p>\n\n<pre><code>o=lambda:map(o,o());o()\n</code></pre>\n" }, { "answer_id": 62209, "author": "TK.", "author_id": 1816, "author_profile": "https://Stackoverflow.com/users/1816", "pm_score": 2, "selected": false, "text": "<p>PIC18:</p>\n\n<blockquote>\n <p>overflow</p>\n \n <blockquote>\n<pre><code> PUSH \n CALL overflow \n</code></pre>\n </blockquote>\n</blockquote>\n" }, { "answer_id": 62213, "author": "Agnel Kurian", "author_id": 45603, "author_profile": "https://Stackoverflow.com/users/45603", "pm_score": 0, "selected": false, "text": "<pre><code>int main(){\n int a = 20;\n return main();\n}\n</code></pre>\n" }, { "answer_id": 62215, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 0, "selected": false, "text": "<p><strong>JavaScript:</strong></p>\n\n<pre><code>function i(){ i(); }\ni();\n</code></pre>\n\n<p><hr>\n<strong>C++</strong>\nUsing a function-pointer:</p>\n\n<pre><code>int main(){\n int (*f)() = &amp;main;\n f();\n}\n</code></pre>\n" }, { "answer_id": 62217, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 5, "selected": false, "text": "<p>In english:</p>\n\n<pre><code>recursion = n. See recursion.\n</code></pre>\n" }, { "answer_id": 62221, "author": "Agnel Kurian", "author_id": 45603, "author_profile": "https://Stackoverflow.com/users/45603", "pm_score": 1, "selected": false, "text": "<pre><code>/* In C/C++ (second attempt) */\n\nint main(){\n int a = main() + 1;\n return a;\n}\n</code></pre>\n" }, { "answer_id": 62231, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "<p>Here's my C contribution, weighing in at 18 characters:</p>\n\n<pre><code>void o(){o();o();}\n</code></pre>\n\n<p>This is a <em>lot</em> harder to tail-call optimise! :-P</p>\n" }, { "answer_id": 62233, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>C#, done in 20 characters (exclusing whitespace):</p>\n\n<pre><code>int s(){\n return s();\n}\n</code></pre>\n" }, { "answer_id": 62243, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 2, "selected": false, "text": "<p><strong>CIL/MSIL</strong>:</p>\n\n<pre><code>loop: ldc.i4.0\nbr loop\n</code></pre>\n\n<p>Object code:</p>\n\n<pre><code>16 2B FD\n</code></pre>\n" }, { "answer_id": 62244, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 7, "selected": false, "text": "<p>You could also try this in C#.net</p>\n\n<pre><code>throw new StackOverflowException();\n</code></pre>\n" }, { "answer_id": 62318, "author": "stusmith", "author_id": 6604, "author_profile": "https://Stackoverflow.com/users/6604", "pm_score": 5, "selected": false, "text": "<p>How about the following in BASIC:</p>\n\n<pre><code>10 GOSUB 10\n</code></pre>\n\n<p>(I don't have a BASIC interpreter I'm afraid so that's a guess).</p>\n" }, { "answer_id": 62321, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 7, "selected": false, "text": "<p><strong>Nemerle</strong>:</p>\n\n<p>This <strong>crashes the compiler</strong> with a StackOverflowException:</p>\n\n<pre><code>def o(){[o()]}\n</code></pre>\n" }, { "answer_id": 62323, "author": "dr_bonzo", "author_id": 6657, "author_profile": "https://Stackoverflow.com/users/6657", "pm_score": 2, "selected": false, "text": "<p>Ruby:</p>\n\n<pre><code>def s() s() end; s()\n</code></pre>\n" }, { "answer_id": 62370, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": false, "text": "<p>I loved Cody's answer heaps, so here is my similar contribution, in C++:</p>\n\n<pre><code>template &lt;int i&gt;\nclass Overflow {\n typedef typename Overflow&lt;i + 1&gt;::type type;\n};\n\ntypedef Overflow&lt;0&gt;::type Kaboom;\n</code></pre>\n\n<p>Not a code golf entry by any means, but still, anything for a meta stack overflow! :-P</p>\n" }, { "answer_id": 62379, "author": "Ozgur Ozcitak", "author_id": 976, "author_profile": "https://Stackoverflow.com/users/976", "pm_score": 2, "selected": false, "text": "<p><strong>Lisp</strong></p>\n\n<pre><code>(defun x() (x)) (x)\n</code></pre>\n" }, { "answer_id": 62399, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 2, "selected": false, "text": "<pre><code>a{return a*a;};\n</code></pre>\n\n<p>Compile with:</p>\n\n<pre><code>gcc -D\"a=main()\" so.c\n</code></pre>\n\n<p>Expands to:</p>\n\n<pre><code>main() {\n return main()*main();\n}\n</code></pre>\n" }, { "answer_id": 62402, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "<p>c# again:</p>\n\n<pre><code>class Foo { public Foo() {new Foo(); } }\n</code></pre>\n" }, { "answer_id": 62407, "author": "asksol", "author_id": 5577, "author_profile": "https://Stackoverflow.com/users/5577", "pm_score": 4, "selected": false, "text": "<p>perl in 12 chars:</p>\n\n<pre><code>$_=sub{&amp;$_};&amp;$_\n</code></pre>\n\n<p>bash in 10 chars (the space in the function is important):</p>\n\n<pre><code>i(){ i;};i\n</code></pre>\n" }, { "answer_id": 62412, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 1, "selected": false, "text": "<p>Complete Delphi program.</p>\n\n<pre><code>program Project1;\n{$APPTYPE CONSOLE}\nuses SysUtils;\n\nbegin\n raise EStackOverflow.Create('Stack Overflow');\nend.\n</code></pre>\n" }, { "answer_id": 62420, "author": "Sean Cameron", "author_id": 6692, "author_profile": "https://Stackoverflow.com/users/6692", "pm_score": 0, "selected": false, "text": "<p>Clarion:</p>\n\n<pre><code>Poke(0)\n</code></pre>\n" }, { "answer_id": 62432, "author": "Manrico Corazzi", "author_id": 4690, "author_profile": "https://Stackoverflow.com/users/4690", "pm_score": 2, "selected": false, "text": "<p><strong>Java</strong> (embarassing):</p>\n\n<pre><code>public class SO \n{ \n private void killme()\n {\n killme();\n }\n\n public static void main(String[] args) \n { \n new SO().killme(); \n } \n}\n</code></pre>\n\n<p><strong>EDIT</strong>\nOf course it can be considerably shortened:</p>\n\n<pre><code>class SO\n{\n public static void main(String[] a)\n {\n main(null);\n }\n}\n</code></pre>\n" }, { "answer_id": 62468, "author": "Antti Kissaniemi", "author_id": 2948, "author_profile": "https://Stackoverflow.com/users/2948", "pm_score": 1, "selected": false, "text": "<p>so.c in <strong>15 characters</strong>:</p>\n\n<pre><code>main(){main();}\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>antti@blah:~$ gcc so.c -o so\nantti@blah:~$ ./so\nSegmentation fault (core dumped)\n</code></pre>\n\n<p><strong>Edit</strong>: Okay, it gives warnings with -Wall and does not cause a stack overflow with -O2. But it works!</p>\n" }, { "answer_id": 62568, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 0, "selected": false, "text": "<p>I tried to do it in Erlang:</p>\n\n<pre><code>c(N)-&gt;c(N+1)+c(N-1).\nc(0).\n</code></pre>\n\n<p>The double invocation of itself makes the memory usage go up <code>O(n^2)</code> rather than <code>O(n)</code>.</p>\n\n<p>However the Erlang interpreter doesn't appear to manage to crash.</p>\n" }, { "answer_id": 62596, "author": "Leo Lännenmäki", "author_id": 2451, "author_profile": "https://Stackoverflow.com/users/2451", "pm_score": 1, "selected": false, "text": "<p><strong>JavaSript:</strong></p>\n\n<p>Huppies answer to one line:</p>\n\n<pre><code>(function i(){ i(); })()\n</code></pre>\n\n<p>Same amount of characters, but no new line :)</p>\n" }, { "answer_id": 62609, "author": "Kinjal Dixit", "author_id": 6629, "author_profile": "https://Stackoverflow.com/users/6629", "pm_score": 0, "selected": false, "text": "<p>recursion is old hat. here is mutual recursion. kick off by calling either function.</p>\n\n<pre><code>a()\n{\n b();\n}\nb()\n{\n a();\n}\n</code></pre>\n\n<p>PS: but you were asking for shortest way.. not most creative way!</p>\n" }, { "answer_id": 62733, "author": "Michal", "author_id": 7135, "author_profile": "https://Stackoverflow.com/users/7135", "pm_score": 1, "selected": false, "text": "<p>Java (complete content of X.java):</p>\n\n<pre><code>class X {\npublic static void main(String[] args) {\n main(null);\n}}\n</code></pre>\n\n<p>Considering all the syntactic sugar, I am wondering if any shorter can be done in Java. Anyone?</p>\n\n<p><strong>EDIT:</strong> Oops, I missed there is already almost identical solution posted.</p>\n\n<p><strong>EDIT 2:</strong> I would say, that this one is (character wise) the shortest possible</p>\n\n<pre><code>class X{public static void main(String[]a){main(null);}}\n</code></pre>\n\n<p><strong>EDIT 3:</strong> Thanks to Anders for pointing out null is not optimal argument, so it's shorter to do:</p>\n\n<pre><code>class X{public static void main(String[]a){main(a);}}\n</code></pre>\n" }, { "answer_id": 62786, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>On the cell spus, there are no stack overflows, so theres no need for recursion, we can just wipe the stack pointer.</p>\n\n<p>asm(\"andi $1, $1, 0\" );</p>\n" }, { "answer_id": 62809, "author": "Anders Sandvig", "author_id": 1709, "author_profile": "https://Stackoverflow.com/users/1709", "pm_score": 3, "selected": false, "text": "<p>3 bytes:\n<code><pre>\nlabel:\n pusha\n jmp label\n</pre></code></p>\n\n<p><Strong>Update</strong></p>\n\n<p>According to <a href=\"http://www.penguin.cz/~literakl/intel/c.html#CALL\" rel=\"nofollow noreferrer\">the (old?) Intel(?) documentation</a>, this is also 3 bytes:</p>\n\n<p><code><pre>\nlabel:\n call label\n</pre></code></p>\n" }, { "answer_id": 62917, "author": "JWHEAT", "author_id": 7079, "author_profile": "https://Stackoverflow.com/users/7079", "pm_score": 0, "selected": false, "text": "<p><strong>PHP</strong> - recursion just for fun. I imagine needing a PHP interpreter takes it out of the running, but hey - it'll make the crash.</p>\n\n<pre><code>function a() { a(); } a();\n</code></pre>\n" }, { "answer_id": 62973, "author": "shelfoo", "author_id": 3444, "author_profile": "https://Stackoverflow.com/users/3444", "pm_score": 1, "selected": false, "text": "<p>There was a perl one already, but this is a couple characters shorter (9 vs 12) - and it doesn't recurse :)</p>\n\n<blockquote>\n <p>s//*_=0/e</p>\n</blockquote>\n" }, { "answer_id": 63020, "author": "Tim Ring", "author_id": 3685, "author_profile": "https://Stackoverflow.com/users/3685", "pm_score": 2, "selected": false, "text": "<p>GWBASIC output...</p>\n\n<pre><code>OK\n10 i=0\n20 print i;\n30 i=i+1\n40 gosub 20\nrun\n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21\n 22 23 24 25 26 27 28 29 30 31 32 33\nOut of memory in 30\nOk\n</code></pre>\n\n<p>Not much stack depth there :-)</p>\n" }, { "answer_id": 63025, "author": "bgee", "author_id": 7003, "author_profile": "https://Stackoverflow.com/users/7003", "pm_score": 0, "selected": false, "text": "<pre><code>//lang = C++... it's joke, of course\n//Pay attention how \nvoid StackOverflow(){printf(\"StackOverflow!\");}\nint main()\n{\n StackOverflow(); //called StackOverflow, right?\n}\n</code></pre>\n" }, { "answer_id": 63061, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>F#</p>\n\n<p>People keep asking \"What is F# useful for?\" </p>\n\n<pre><code>let rec f n =\n f (n)\n</code></pre>\n\n<p>performance optimized version (will fail faster :) )</p>\n\n<pre><code>let rec f n =\n f (f(n))\n</code></pre>\n" }, { "answer_id": 63116, "author": "Jesse Millikan", "author_id": 7526, "author_profile": "https://Stackoverflow.com/users/7526", "pm_score": 1, "selected": false, "text": "<p>I have a list of these at <a href=\"http://www.everything2.com/index.pl?node_id=1904026\" rel=\"nofollow noreferrer\">Infinite Loop</a> on E2 - see just the ones indicated as \"Stack Overflow\" in the title.</p>\n\n<p>I think the shortest there is</p>\n\n<pre><code>[dx]dx\n</code></pre>\n\n<p>in <a href=\"http://c2.com/cgi/wiki?DeeCee\" rel=\"nofollow noreferrer\">dc</a>. There may be a shorter solution in <a href=\"http://c2.com/cgi/wiki?FalseLanguage\" rel=\"nofollow noreferrer\">False</a>.</p>\n\n<p>EDIT: Apparently this doesn't work... At least on GNU dc. Maybe it was on a BSD version.</p>\n" }, { "answer_id": 63137, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Ruby:</p>\n\n<pre><code>def i()i()end;i()\n</code></pre>\n\n<p>(17 chars)</p>\n" }, { "answer_id": 63269, "author": "Evan DeMond", "author_id": 7695, "author_profile": "https://Stackoverflow.com/users/7695", "pm_score": 2, "selected": false, "text": "<p>In Lua:</p>\n\n<pre><code>function f()return 1+f()end f()\n</code></pre>\n\n<p>You've got to do something to the result of the recursive call, or else tail call optimization will allow it to loop forever. Weak for code golf, but nice to have!</p>\n\n<p>I guess that and the lengthy keywords mean Lua won't be winning the code golf anytime soon.</p>\n" }, { "answer_id": 63290, "author": "tomdemuyt", "author_id": 7602, "author_profile": "https://Stackoverflow.com/users/7602", "pm_score": 2, "selected": false, "text": "<p>batch program called call.cmd;</p>\n\n<p>call call.cmd</p>\n\n<pre><code>****** B A T C H R E C U R S I O N exceeds STACK limits ******\nRecursion Count=1240, Stack Usage=90 percent\n****** B A T C H PROCESSING IS A B O R T E D ******\n</code></pre>\n" }, { "answer_id": 63353, "author": "davidnicol", "author_id": 7420, "author_profile": "https://Stackoverflow.com/users/7420", "pm_score": 0, "selected": false, "text": "<p><strong>Perl</strong> in 10 chars</p>\n\n<pre><code>sub x{&amp;x}x\n</code></pre>\n\n<p>Eventually uses up all available memory.</p>\n" }, { "answer_id": 63400, "author": "davidnicol", "author_id": 7420, "author_profile": "https://Stackoverflow.com/users/7420", "pm_score": 0, "selected": false, "text": "<p><strong>MS-DOS batch:</strong></p>\n\n<pre><code>copy CON so.bat\nso.bat\n^Z\nso.bat\n</code></pre>\n" }, { "answer_id": 63519, "author": "Misha", "author_id": 7557, "author_profile": "https://Stackoverflow.com/users/7557", "pm_score": 3, "selected": false, "text": "<p>Java</p>\n\n<p>Slightly shorter version of the Java solution.</p>\n\n<pre><code>class X{public static void main(String[]a){main(a);}}\n</code></pre>\n" }, { "answer_id": 63529, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 2, "selected": false, "text": "<p>In Scheme, this will cause the interpreter to run out of memory:</p>\n\n<pre><code>(define (x)\n ((x)))\n\n(x)\n</code></pre>\n" }, { "answer_id": 63534, "author": "Antti Kissaniemi", "author_id": 2948, "author_profile": "https://Stackoverflow.com/users/2948", "pm_score": 1, "selected": false, "text": "<p>Shell script solution in <strong>10 characters</strong> including newlines:</p>\n\n<p>Well, technically not stack overflow but logically so, if you consider spawning a new process as constructing a new stack frame.</p>\n\n<pre><code>#!sh\n./so\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>antti@blah:~$ ./so\n[disconnected]\n</code></pre>\n\n<p>Whoops. Note: <strong>don't try this at home</strong></p>\n" }, { "answer_id": 63613, "author": "Robert S.", "author_id": 7565, "author_profile": "https://Stackoverflow.com/users/7565", "pm_score": 2, "selected": false, "text": "<p>In Whitespace, I think:</p>\n\n<p>It probably won't show up. :/</p>\n" }, { "answer_id": 63812, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 4, "selected": false, "text": "<p><strong>C</strong> - It's not the shortest, but it's recursion-free. It's also not portable: it crashes on Solaris, but some alloca() implementations might return an error here (or call malloc()). The call to printf() is necessary.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;alloca.h&gt;\n#include &lt;sys/resource.h&gt;\nint main(int argc, char *argv[]) {\n struct rlimit rl = {0};\n getrlimit(RLIMIT_STACK, &amp;rl);\n (void) alloca(rl.rlim_cur);\n printf(\"Goodbye, world\\n\");\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 63848, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "<p>C# with 27 non-whitespace characters - includes the call.</p>\n\n<pre><code>Action a = null;\na = () =&gt; a();\na();\n</code></pre>\n" }, { "answer_id": 63873, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>xor esp, esp\nret\n</code></pre>\n" }, { "answer_id": 64017, "author": "x0n", "author_id": 6920, "author_profile": "https://Stackoverflow.com/users/6920", "pm_score": 1, "selected": false, "text": "<p><strong>PowerShell</strong></p>\n\n<blockquote>\n <p>$f={&amp;$f};&amp;$f</p>\n</blockquote>\n\n<p>\"The script failed due to call depth overflow. The call depth reached 1001 and the maximum is 1000.\"</p>\n" }, { "answer_id": 64252, "author": "jrudolph", "author_id": 7647, "author_profile": "https://Stackoverflow.com/users/7647", "pm_score": 8, "selected": false, "text": "<p>Read this line, and do what it says <strong>twice</strong>.</p>\n" }, { "answer_id": 64290, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p><strong>bash:</strong> Only one process</p>\n\n<pre><code>\\#!/bin/bash\nof() { of; }\nof\n</code></pre>\n" }, { "answer_id": 64331, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Ruby, shorter than the other ones so far:</p>\n\n<pre><code>def a;a;end;a\n</code></pre>\n\n<p>(13 chars)</p>\n" }, { "answer_id": 64346, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Pretty much any shell:</p>\n\n<pre><code>sh $0\n</code></pre>\n\n<p>(5 characters, only works if run from file)</p>\n" }, { "answer_id": 64352, "author": "user8456", "author_id": 8456, "author_profile": "https://Stackoverflow.com/users/8456", "pm_score": 4, "selected": false, "text": "<p>try and put more than 4 patties on a single burger. stack overflow.</p>\n" }, { "answer_id": 64395, "author": "Chris Broadfoot", "author_id": 3947, "author_profile": "https://Stackoverflow.com/users/3947", "pm_score": 4, "selected": false, "text": "<p>Groovy:</p>\n\n<pre><code>main()\n</code></pre>\n\n<p>$ groovy stack.groovy:</p>\n\n<pre><code>Caught: java.lang.StackOverflowError\n at stack.main(stack.groovy)\n at stack.run(stack.groovy:1)\n ...\n</code></pre>\n" }, { "answer_id": 64425, "author": "Jonas Engström", "author_id": 7634, "author_profile": "https://Stackoverflow.com/users/7634", "pm_score": 0, "selected": false, "text": "<p>Five bytes in 16-bit asm which will cause a stack overflow.</p>\n\n<pre><code>push cs\npush $-1\nret\n</code></pre>\n" }, { "answer_id": 64573, "author": "botismarius", "author_id": 4528, "author_profile": "https://Stackoverflow.com/users/4528", "pm_score": 1, "selected": false, "text": "<p>In assembly language (x86 processors, 16 or 32 bit mode):</p>\n\n<pre><code>\ncall $\n</code></pre>\n\n<p>which will generate:</p>\n\n<ul>\n<li><p>in 32 bit mode: 0xe8;0xfb;0xff;0xff;0xff</p></li>\n<li><p>in 16 bit mode: 0xe8;0xfd;0xff</p></li>\n</ul>\n\n<p>in C/C++:</p>\n\n<pre><code>\nint main( ) {\n return main( );\n}\n</code></pre>\n" }, { "answer_id": 64707, "author": "Dennis Munsie", "author_id": 8728, "author_profile": "https://Stackoverflow.com/users/8728", "pm_score": 5, "selected": false, "text": "<p>Z-80 assembler -- at memory location 0x0000:</p>\n\n<pre><code>rst 00\n</code></pre>\n\n<p>one byte -- 0xC7 -- endless loop of pushing the current PC to the stack and jumping to address 0x0000.</p>\n" }, { "answer_id": 64830, "author": "Travis Wilson", "author_id": 8735, "author_profile": "https://Stackoverflow.com/users/8735", "pm_score": 4, "selected": false, "text": "<p><strong>Javascript</strong></p>\n\n<p>To trim a few more characters, and to get ourselves kicked out of more software shops, let's go with:</p>\n\n<pre><code>eval(i='eval(i)');\n</code></pre>\n" }, { "answer_id": 65046, "author": "mattiast", "author_id": 8272, "author_profile": "https://Stackoverflow.com/users/8272", "pm_score": 2, "selected": false, "text": "<p>Haskell:</p>\n\n<pre><code>let x = x\nprint x\n</code></pre>\n" }, { "answer_id": 65224, "author": "Joshua Carmody", "author_id": 8409, "author_profile": "https://Stackoverflow.com/users/8409", "pm_score": 2, "selected": false, "text": "<p>Well, nobody's mentioned Coldfusion yet, so...</p>\n\n<pre><code>&lt;cfinclude template=\"#ListLast(CGI.SCRIPT_NAME, \"/\\\")#\"&gt;\n</code></pre>\n\n<p>That oughta do it.</p>\n" }, { "answer_id": 65317, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "<p>VB.Net</p>\n\n<pre><code>Function StackOverflow() As Integer\n Return StackOverflow()\nEnd Function\n</code></pre>\n" }, { "answer_id": 65628, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 1, "selected": false, "text": "<p>TCL:</p>\n\n<pre><code>proc a {} a\n</code></pre>\n\n<p>I don't have a tclsh interpreter that can do tail recursion, but this might fool such a thing:</p>\n\n<pre><code>proc a {} \"a;a\"\n</code></pre>\n" }, { "answer_id": 66095, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 2, "selected": false, "text": "<p>Forth:</p>\n\n<pre><code>: a 1 recurse ; a\n</code></pre>\n\n<p>Inside the <code>gforth</code> interpreter:</p>\n\n<pre><code>: a 1 recurse ; a \n*the terminal*:1: Return stack overflow\n: a 1 recurse ; a\n ^\nBacktrace:\n</code></pre>\n\n<p>On a Power Mac G4 at the Open Firmware prompt, this just hangs the machine. :)</p>\n" }, { "answer_id": 66370, "author": "Kemal", "author_id": 7506, "author_profile": "https://Stackoverflow.com/users/7506", "pm_score": 5, "selected": false, "text": "<p>Another PHP Example:</p>\n\n<pre><code>&lt;?\nrequire(__FILE__);\n</code></pre>\n" }, { "answer_id": 66392, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": 0, "selected": false, "text": "<p>For Fun I had to look up the Motorolla HC11 Assembly:</p>\n\n<pre><code> org $100\nLoop nop\n jsr Loop\n</code></pre>\n" }, { "answer_id": 66470, "author": "WaldWolf", "author_id": 9764, "author_profile": "https://Stackoverflow.com/users/9764", "pm_score": -1, "selected": false, "text": "<p><strong>Prolog</strong></p>\n\n<p>p:-p.</p>\n\n<p>= 5 characters</p>\n\n<p>then start it and query p</p>\n\n<p>i think that is quite small and runs out of stack in prolog.</p>\n\n<p>a query of just a variable in swi prolog produces:</p>\n\n<p>?- X.\n% ... 1,000,000 ............ 10,000,000 years later\n% \n% >> 42 &lt;&lt; (last release gives the question)</p>\n\n<p>and here is another bash fork bomb:\n:(){ :|:&amp; };:</p>\n" }, { "answer_id": 66483, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>as a local variable in a C function:</p>\n\n<pre><code>int x[100000000000];\n</code></pre>\n" }, { "answer_id": 66616, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 0, "selected": false, "text": "<p>Not very short, but effective! (JavaScript)</p>\n\n<pre><code>setTimeout(1, function() {while(1) a=1;});\n</code></pre>\n" }, { "answer_id": 66663, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": false, "text": "<p><strong>C#</strong> </p>\n\n<pre><code>class _{static void Main(){Main();}}\n</code></pre>\n\n<p>Note that mine is a compilable program, not just a single function. I also removed excess whitespace.</p>\n\n<p>For flair, I made the class name as small as I could.</p>\n" }, { "answer_id": 66744, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 9, "selected": true, "text": "<p>All these answers and no Befunge? I'd wager a fair amount it's shortest solution of them all:</p>\n\n<pre><code>1\n</code></pre>\n\n<p>Not kidding. Try it yourself: <a href=\"http://www.quirkster.com/iano/js/befunge.html\" rel=\"nofollow noreferrer\">http://www.quirkster.com/iano/js/befunge.html</a></p>\n\n<p>EDIT: I guess I need to explain this one. The 1 operand pushes a 1 onto Befunge's internal stack and the lack of anything else puts it in a loop under the rules of the language. </p>\n\n<p>Using the interpreter provided, you will eventually--and I mean <i>eventually</i>--hit a point where the Javascript array that represents the Befunge stack becomes too large for the browser to reallocate. If you had a simple Befunge interpreter with a smaller and bounded stack--as is the case with most of the languages below--this program would cause a more noticeable overflow faster.</p>\n" }, { "answer_id": 67634, "author": "clahey", "author_id": 8453, "author_profile": "https://Stackoverflow.com/users/8453", "pm_score": 2, "selected": false, "text": "<p>Unless there's a language where the empty program causes a stack overflow, the following should be the shortest possible.</p>\n\n<p>Befunge:</p>\n\n<pre><code>:\n</code></pre>\n\n<p>Duplicates the top stack value over and over again.</p>\n\n<p>edit:\n Patrick's is better. Filling the stack with 1s is better than filling the stack with 0s, since the interpreter could optimize pushing 0s onto an empty stack as a no-op.</p>\n" }, { "answer_id": 67749, "author": "Despatcher", "author_id": 10240, "author_profile": "https://Stackoverflow.com/users/10240", "pm_score": 0, "selected": false, "text": "<p>I think it's cheating I've never played before ;) but here goes</p>\n\n<p>8086 assembler:</p>\n\n<p>org Int3VectorAdrress ;is that cheating? </p>\n\n<p>int 3</p>\n\n<p>1 byte - or 5 characters that generate code, what say you? </p>\n" }, { "answer_id": 68055, "author": "user4010", "author_id": 4010, "author_profile": "https://Stackoverflow.com/users/4010", "pm_score": 2, "selected": false, "text": "<p>If you consider a call frame to be a process, and the stack to be your Unix machine, you could consider a fork bomb to be a <em>parallel</em> program to create a stack overflow condition. Try this 13-character bash number. No saving to a file is necessary.</p>\n\n<pre><code>:(){ :|:&amp; };:\n</code></pre>\n" }, { "answer_id": 68229, "author": "RFelix", "author_id": 10582, "author_profile": "https://Stackoverflow.com/users/10582", "pm_score": 0, "selected": false, "text": "<p>Ruby, albeit not that short:</p>\n\n<pre><code>class Overflow\n def initialize\n Overflow.new\n end\nend\n\nOverflow.new\n</code></pre>\n" }, { "answer_id": 68442, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 5, "selected": false, "text": "<p>TeX:</p>\n\n<pre><code>\\def~{~.}~\n</code></pre>\n\n<p>Results in:</p>\n\n<pre>! TeX capacity exceeded, sorry [input stack size=5000].\n~->~\n .\n~->~\n .\n~->~\n .\n~->~\n .\n~->~\n .\n~->~\n .\n...\n&lt;*> \\def~{~.}~</pre>\n\n<p>LaTeX:</p>\n\n<pre><code>\\end\\end\n</code></pre>\n\n<p>Results in:</p>\n\n<pre>! TeX capacity exceeded, sorry [input stack size=5000].\n\\end #1->\\csname end#1\n \\endcsname \\@checkend {#1}\\expandafter \\endgroup \\if@e...\n&lt;*> \\end\\end</pre>\n" }, { "answer_id": 68521, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": -1, "selected": false, "text": "<p>I think this will work in Java (untried):</p>\n\n<pre><code>enum A{B.values()}\nenum B{A.values()}\n</code></pre>\n\n<p>Should overflow in static initialization before it even gets the chance to fail due to a lack of main(String[]).</p>\n" }, { "answer_id": 68586, "author": "user10178", "author_id": 10178, "author_profile": "https://Stackoverflow.com/users/10178", "pm_score": 1, "selected": false, "text": "<p>won't be the shortest but I had to try something... C#</p>\n\n<p>string[] f = new string[0]; Main(f);</p>\n\n<p>bit shorter</p>\n\n<pre><code>static void Main(){Main();}\n</code></pre>\n" }, { "answer_id": 68960, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 4, "selected": false, "text": "<pre><code>Person JeffAtwood;\nPerson JoelSpolsky;\nJeffAtwood.TalkTo(JoelSpolsky);\n</code></pre>\n\n<p>Here's hoping for no tail recursion!</p>\n" }, { "answer_id": 69003, "author": "Jude Allred", "author_id": 1388, "author_profile": "https://Stackoverflow.com/users/1388", "pm_score": 4, "selected": false, "text": "<p>Using a Window's batch file named \"s.bat\":</p>\n\n<pre><code>call s\n</code></pre>\n" }, { "answer_id": 69369, "author": "user11039", "author_id": 11039, "author_profile": "https://Stackoverflow.com/users/11039", "pm_score": 0, "selected": false, "text": "<p>In <strong>C#</strong>, this would create a stackoverflow...</p>\n\n<pre><code>static void Main()\n{\n Main();\n}\n</code></pre>\n" }, { "answer_id": 69577, "author": "mike511", "author_id": 9593, "author_profile": "https://Stackoverflow.com/users/9593", "pm_score": 0, "selected": false, "text": "<p>why not</p>\n\n<pre><code>mov sp,0\n</code></pre>\n\n<p>(stack grows down)</p>\n" }, { "answer_id": 69626, "author": "Mark Nold", "author_id": 4134, "author_profile": "https://Stackoverflow.com/users/4134", "pm_score": 0, "selected": false, "text": "<p>In a <strong>PostScript</strong> file called so.ps will cause execstackoverflow</p>\n\n<pre><code>%!PS\n/increase {1 add} def\n1 increase\n(so.ps) run\n</code></pre>\n" }, { "answer_id": 70176, "author": "Wouter Coekaerts", "author_id": 3432, "author_profile": "https://Stackoverflow.com/users/3432", "pm_score": 2, "selected": false, "text": "<p>In Irssi (terminal based IRC client, not \"really\" a programming language), $L means the current command line. So you can cause a stack overflow (\"hit maximum recursion limit\") with:</p>\n\n<pre><code>/eval $L\n</code></pre>\n" }, { "answer_id": 70398, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": false, "text": "<p>Every task needs the right tool. Meet the <a href=\"http://page.mi.fu-berlin.de/krudolph/stuff/so/\" rel=\"nofollow noreferrer\">SO Overflow</a> language, optimized to produce stack overflows:</p>\n\n<pre><code>so\n</code></pre>\n" }, { "answer_id": 70950, "author": "RFelix", "author_id": 10582, "author_profile": "https://Stackoverflow.com/users/10582", "pm_score": 1, "selected": false, "text": "<p>Here's another Ruby answer, this one uses lambdas:</p>\n\n<pre><code>(a=lambda{a.call}).call\n</code></pre>\n" }, { "answer_id": 71833, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>I'm selecting the “best answer” after this post. But first, I'd like to acknowledge some very original contributions:</p>\n\n<ol>\n<li>aku's ones. Each one explores a new and original way of causing stack overflow. The idea of doing f(x) ⇒ f(f(x)) is one I'll explore in my next entry, below. :-)</li>\n<li>Cody's one that gave the Nemerle <em>compiler</em> a stack overflow.</li>\n<li>And (a bit grudgingly), GateKiller's one about throwing a stack overflow exception. :-P</li>\n</ol>\n\n<p>Much as I love the above, the challenge is about doing code golf, and to be fair to respondents, I have to award “best answer” to the shortest code, which is the Befunge entry; I don't believe anybody will be able to beat that (although Konrad has certainly tried), so congrats Patrick!</p>\n\n<p>Seeing the large number of stack-overflow-by-recursion solutions, I'm surprised that nobody has (as of current writing) brought up the Y combinator (see Dick Gabriel's essay, <a href=\"http://www.dreamsongs.com/Files/WhyOfY.pdf\" rel=\"nofollow noreferrer\">The Why of Y</a>, for a primer). I have a recursive solution that uses the Y combinator, as well as aku's f(f(x)) approach. :-)</p>\n\n<pre><code>((Y (lambda (f) (lambda (x) (f (f x))))) #f)\n</code></pre>\n" }, { "answer_id": 71964, "author": "Leo Lännenmäki", "author_id": 2451, "author_profile": "https://Stackoverflow.com/users/2451", "pm_score": 1, "selected": false, "text": "<p>Another one in <strong>JavaScript</strong>:</p>\n\n<pre><code>(function() { arguments.callee() })()\n</code></pre>\n" }, { "answer_id": 72993, "author": "Javier", "author_id": 12449, "author_profile": "https://Stackoverflow.com/users/12449", "pm_score": 1, "selected": false, "text": "<p>Vb6</p>\n\n<pre><code>\nPublic Property Let x(ByVal y As Long)\n x = y\nEnd Property\n\nPrivate Sub Class_Initialize()\n x = 0\nEnd Sub\n</code></pre>\n" }, { "answer_id": 75948, "author": "squadette", "author_id": 7754, "author_profile": "https://Stackoverflow.com/users/7754", "pm_score": 1, "selected": false, "text": "<p>Short solution in K&amp;R C, could be compiled:</p>\n\n<pre><code>main(){main()}\n</code></pre>\n\n<p>14 bytes</p>\n" }, { "answer_id": 75991, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "<p>Here's another interesting one from Scheme:</p>\n\n<pre>((lambda (x) (x x)) (lambda (x) (x x)))</pre>\n" }, { "answer_id": 76923, "author": "Ramin", "author_id": 8919, "author_profile": "https://Stackoverflow.com/users/8919", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.google.com/search?q=google.com\" rel=\"nofollow noreferrer\">http://www.google.com/search?q=google.com</a></p>\n" }, { "answer_id": 78084, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 0, "selected": false, "text": "<p>Actionscript 3: All done with arrays...</p>\n\n<pre><code>var i=[];\ni[i.push(i)]=i;\ntrace(i);\n</code></pre>\n\n<p>Maybe not the smallest but I think it's cute. Especially the push method returning the new array length!</p>\n" }, { "answer_id": 78911, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>In response to the Y combinator comment, i might as well through in the Y-combinator in the SKI calculus:</p>\n\n<pre><code>S (K (S I I)) (S (S (K S) K) (K (S I I)))\n</code></pre>\n\n<p>There aren't any SKI interpreters that i know of but i once wrote a graphical one in about an hour in actionscript. I would be willing to post if there is interest (though i never got the layout working very efficiently)</p>\n\n<p>read all about it here:\n<a href=\"http://en.wikipedia.org/wiki/SKI_combinator_calculus\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/SKI_combinator_calculus</a></p>\n" }, { "answer_id": 79016, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>In x86 assembly, place a divide by 0 instruction at the location in memory of the interrupt handler for divide by 0!</p>\n" }, { "answer_id": 80350, "author": "matyr", "author_id": 15066, "author_profile": "https://Stackoverflow.com/users/15066", "pm_score": 2, "selected": false, "text": "<p>Groovy (5B):</p>\n\n<pre><code>run()\n</code></pre>\n" }, { "answer_id": 90506, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 1, "selected": false, "text": "<p>in perl:</p>\n\n<pre><code>`$0`\n</code></pre>\n\n<p>As a matter of fact, this will work with any shell that supports the backquote-command syntax and stores its own name in <code>$0</code></p>\n" }, { "answer_id": 90986, "author": "Aardappel", "author_id": 17419, "author_profile": "https://Stackoverflow.com/users/17419", "pm_score": 1, "selected": false, "text": "<p>False:</p>\n\n<p>[1][1]#</p>\n\n<p>(False is a stack language: # is a while loop that takes 2 closures, a conditional and a body. The body is the one that causes the overflow).</p>\n" }, { "answer_id": 570789, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>CMD overflow in one line</p>\n\n<pre><code>echo @call b.cmd &gt; b.cmd &amp; b\n</code></pre>\n" }, { "answer_id": 583659, "author": "Kaarel", "author_id": 12547, "author_profile": "https://Stackoverflow.com/users/12547", "pm_score": 0, "selected": false, "text": "<p><strong>Prolog</strong></p>\n\n<p>This program crashes both SWI-Prolog and Sicstus Prolog when consulted.</p>\n\n<pre><code>p :- p, q.\n:- p.\n</code></pre>\n" }, { "answer_id": 597337, "author": "Oscar Cabrero", "author_id": 14440, "author_profile": "https://Stackoverflow.com/users/14440", "pm_score": -1, "selected": false, "text": "<pre><code>Redmond.Microsoft.Core.Windows.Start()\n</code></pre>\n" }, { "answer_id": 597372, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 7, "selected": false, "text": "<h2>PIC18</h2>\n\n<p>The <a href=\"https://stackoverflow.com/questions/62188/stack-overflow-code-golf/62209#62209\">PIC18 answer given by TK</a> results in the following instructions (binary):</p>\n\n<pre><code>overflow\n PUSH\n 0000 0000 0000 0101\n CALL overflow\n 1110 1100 0000 0000\n 0000 0000 0000 0000\n</code></pre>\n\n<p>However, CALL alone will perform a stack overflow:</p>\n\n<pre><code>CALL $\n1110 1100 0000 0000\n0000 0000 0000 0000\n</code></pre>\n\n<h2>Smaller, faster PIC18</h2>\n\n<p>But RCALL (relative call) is smaller still (not global memory, so no need for the extra 2 bytes):</p>\n\n<pre><code>RCALL $\n1101 1000 0000 0000\n</code></pre>\n\n<p>So the smallest on the PIC18 is a single instruction, 16 bits (two bytes). This would take 2 instruction cycles per loop. At 4 clock cycles per instruction cycle you've got 8 clock cycles. The PIC18 has a 31 level stack, so after the 32nd loop it will overflow the stack, in 256 clock cycles. At 64MHz, you would <strong>overflow the stack in 4 micro seconds and 2 bytes</strong>.</p>\n\n<h2>PIC16F5x (even smaller and faster)</h2>\n\n<p>However, the PIC16F5x series uses 12 bit instructions:</p>\n\n<pre><code>CALL $\n1001 0000 0000\n</code></pre>\n\n<p>Again, two instruction cycles per loop, 4 clocks per instruction so 8 clock cycles per loop.</p>\n\n<p>However, the PIC16F5x has a two level stack, so on the third loop it would overflow, in 24 instructions. At 20MHz, it would <strong>overflow in 1.2 micro seconds and 1.5 bytes</strong>.</p>\n\n<h2>Intel 4004</h2>\n\n<p>The <a href=\"http://download.intel.com/museum/archives/pdf/4004_datasheet.pdf\" rel=\"nofollow noreferrer\">Intel 4004</a> has an 8 bit call subroutine instruction:</p>\n\n<pre><code>CALL $\n0101 0000\n</code></pre>\n\n<p>For the curious that corresponds to an ascii 'P'. With a 3 level stack that takes 24 clock cycles for a total of <strong>32.4 micro seconds and one byte</strong>. (Unless you overclock your 4004 - come on, you know you want to.)</p>\n\n<p>Which is as small as the befunge answer, but much, much faster than the befunge code running in current interpreters.</p>\n" }, { "answer_id": 597461, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 0, "selected": false, "text": "<p>Tail call optimization can be sabotaged by not tail calling. In Common Lisp:</p>\n\n<pre>(defun f () (1+ (f)))</pre>\n" }, { "answer_id": 605938, "author": "Jonas Kölker", "author_id": 58668, "author_profile": "https://Stackoverflow.com/users/58668", "pm_score": 1, "selected": false, "text": "<p>In Haskell</p>\n\n<pre><code>fix (1+)\n</code></pre>\n\n<p>This tries to find the fix point of the (1+) function (<code>λ n → n + 1</code>) . The implementation of fix is</p>\n\n<pre><code>fix f = (let x = f(x) in x)\n</code></pre>\n\n<p>So</p>\n\n<pre><code>fix (1+)\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>(1+) ((1+) ((1+) ...))\n</code></pre>\n\n<p>Note that</p>\n\n<pre><code>fix (+1)\n</code></pre>\n\n<p>just loops.</p>\n" }, { "answer_id": 779109, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "<p>Meta problem in D:</p>\n\n<pre><code>class C(int i) { C!(i+1) c; }\nC!(1) c;\n</code></pre>\n\n<p>compile time stack overflow</p>\n" }, { "answer_id": 848505, "author": "Tolgahan Albayrak", "author_id": 104468, "author_profile": "https://Stackoverflow.com/users/104468", "pm_score": 0, "selected": false, "text": "<pre><code>_asm t: call t;\n</code></pre>\n" }, { "answer_id": 973947, "author": "RCIX", "author_id": 117069, "author_profile": "https://Stackoverflow.com/users/117069", "pm_score": 1, "selected": false, "text": "<p><strong>A better lua solution:</strong></p>\n\n<pre><code>function c()c()end;\n</code></pre>\n\n<p>Stick this into SciTE or an interactive command prompt and then call it. Boom!</p>\n" }, { "answer_id": 1028904, "author": "Greg", "author_id": 12601, "author_profile": "https://Stackoverflow.com/users/12601", "pm_score": 4, "selected": false, "text": "<p>Please tell me what the acronym \"<a href=\"http://en.wikipedia.org/wiki/GNU\" rel=\"nofollow noreferrer\">GNU</a>\" stands for.</p>\n" }, { "answer_id": 1735693, "author": "Graphics Noob", "author_id": 127669, "author_profile": "https://Stackoverflow.com/users/127669", "pm_score": 0, "selected": false, "text": "<p>OCaml</p>\n\n<pre><code>let rec f l = f l@l;;\n</code></pre>\n\n<p>This one is a little different. There's only one stack frame on the stack (since it's tail recursive), but it's input keeps growing until it overflows the stack. Just call <code>f</code> with a non empty list like so (at the interpreter prompt):</p>\n\n<pre><code># f [0];;\nStack overflow during evaluation (looping recursion?).\n</code></pre>\n" }, { "answer_id": 1738894, "author": "Graphics Noob", "author_id": 127669, "author_profile": "https://Stackoverflow.com/users/127669", "pm_score": 0, "selected": false, "text": "<p>Even though it doesn't really have a stack...</p>\n\n<p><strong>brainf*ck 5 char</strong></p>\n\n<pre><code>+[&gt;+]\n</code></pre>\n" }, { "answer_id": 1985750, "author": "Tim Ring", "author_id": 3685, "author_profile": "https://Stackoverflow.com/users/3685", "pm_score": 0, "selected": false, "text": "<p>Z80 assembly language...</p>\n\n<pre><code>.org 1000\nloop: call loop\n</code></pre>\n\n<p>this generates 3 bytes of code at location 1000....</p>\n\n<p>1000 CD 00 10</p>\n" }, { "answer_id": 2101846, "author": "danielschemmel", "author_id": 65678, "author_profile": "https://Stackoverflow.com/users/65678", "pm_score": 2, "selected": false, "text": "<p>C#</p>\n\n<pre><code>class Program\n{\n class StackOverflowExceptionOverflow : System.Exception\n {\n public StackOverflowExceptionOverflow()\n {\n throw new StackOverflowExceptionOverflow();\n }\n }\n\n static void Main(string[] args)\n {\n throw new StackOverflowExceptionOverflow();\n }\n}\n</code></pre>\n\n<p>I realize this is not the shortest (and even code golfed it would not come close to be anywhere near short), but I simply could not resist throwing an exception that while being thrown throws a stackoverflowexception, before it is able to terminate the runtime itself ^^</p>\n" }, { "answer_id": 2173039, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 0, "selected": false, "text": "<p>ruby (again):</p>\n\n<pre><code>def a(x);x.gsub(/./){a$0};end;a\"x\"\n</code></pre>\n\n<p>There are plenty of ruby solutions already but I thought I'd throw in a regexp for good measure.</p>\n" }, { "answer_id": 2216158, "author": "KirarinSnow", "author_id": 174376, "author_profile": "https://Stackoverflow.com/users/174376", "pm_score": 2, "selected": false, "text": "<h1>PostScript, 7 characters</h1>\n\n<pre><code>{/}loop\n</code></pre>\n\n<p>When run in GhostScript, throws this exception:</p>\n\n<pre><code>GS&gt;{/}loop\nError: /stackoverflow in --execute--\nOperand stack:\n --nostringval--\nExecution stack:\n %interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- %loop_continue 1753 2 3 %oparray_pop --nostringval-- --nostringval-- false 1 %stopped_push .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- %loop_continue\nDictionary stack:\n --dict:1150/1684(ro)(G)-- --dict:0/20(G)-- --dict:70/200(L)--\nCurrent allocation mode is local\nLast OS error: 11\nCurrent file position is 8\n</code></pre>\n\n<p>Here's the recursive version without using variables (51 chars):</p>\n\n<pre><code>[{/[aload 8 1 roll]cvx exec}aload 8 1 roll]cvx exec\n</code></pre>\n" }, { "answer_id": 2343769, "author": "Carlos Gutiérrez", "author_id": 237761, "author_profile": "https://Stackoverflow.com/users/237761", "pm_score": 0, "selected": false, "text": "<p>Another Windows Batch file:</p>\n\n<pre><code>:a\n@call :a\n</code></pre>\n" }, { "answer_id": 2344985, "author": "N 1.1", "author_id": 280730, "author_profile": "https://Stackoverflow.com/users/280730", "pm_score": 0, "selected": false, "text": "<pre><code>main(){\n main();\n}</code></pre>\n\n<p>Plain and nice C. Feels quite Intuitive to me.</p>\n" }, { "answer_id": 2348396, "author": "Brent Bradburn", "author_id": 86967, "author_profile": "https://Stackoverflow.com/users/86967", "pm_score": 1, "selected": false, "text": "<p>GNU make:</p>\n\n<p>Create a file called \"Makefile\" with the following contents:</p>\n\n<pre><code>a:\n make\n</code></pre>\n\n<p>Then run make:</p>\n\n<pre><code>$ make\n</code></pre>\n\n<p>Note that a tab character must be used to offset the word \"make\". This file is 9 characters, including the 2 end-of-line characters and the 1 tab character.</p>\n\n<p>I suppose you could do a similar thing with bash, but it's probably too easy to be interesting:</p>\n\n<p>Create a filename \"b\" and mark it as executable (chmod +x b):</p>\n\n<pre><code>b ## ties the winning entry with only one character (does not require end-of-line)\n</code></pre>\n\n<p>Now execute the file with</p>\n\n<pre><code>$ ( PATH=$PATH:. ; b )\n</code></pre>\n\n<p>It's hard to say whether this approach technically results in stack overflow, but it does build a stack which will grow until the machine runs out of resources. The cool thing about doing it with GNU make is that you can watch it output status information as it builds and destroys the stack (assuming you hit ^C at some point before the crash occurs).</p>\n" }, { "answer_id": 2348499, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 2, "selected": false, "text": "<p>Java:</p>\n\n<pre><code>class X{static{new X();}{new X();}}\n</code></pre>\n\n<p>Actually causes a stack overflow initializing the X class. Before main() is called, the JVM must load the class, and when it does so it triggers any anonymous static code blocks:</p>\n\n<pre><code>static {\n new X();\n}\n</code></pre>\n\n<p>Which as you can see, instantiates X using the default constructor. The JVM will call anonymous code blocks even before the constructor:</p>\n\n<pre><code>{\n new X();\n}\n</code></pre>\n\n<p>Which is the recursive part.</p>\n" }, { "answer_id": 2396631, "author": "F'x", "author_id": 143495, "author_profile": "https://Stackoverflow.com/users/143495", "pm_score": 0, "selected": false, "text": "<h2>Fortran, 13 and 20 chars</h2>\n\n<pre><code>real n(0)\nn(1)=0\nend\n</code></pre>\n\n<p>or</p>\n\n<pre><code>call main\nend\n</code></pre>\n\n<p>The second case is compiler-dependent; for GNU Fortran, it will need to be compiled with <code>-fno-underscoring</code>.</p>\n\n<p>(Both counts include required newlines)</p>\n" }, { "answer_id": 2679742, "author": "Juliet", "author_id": 40516, "author_profile": "https://Stackoverflow.com/users/40516", "pm_score": 6, "selected": false, "text": "<p>Hoot overflow!</p>\n\n<pre><code>// v___v\nlet rec f o = f(o);(o)\n// ['---']\n// -\"---\"-\n</code></pre>\n" }, { "answer_id": 2904167, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 0, "selected": false, "text": "<p>Haskell:</p>\n\n<pre><code>main = print $ x 1 where x y = x y + 1\n</code></pre>\n" }, { "answer_id": 3029226, "author": "wash", "author_id": 336878, "author_profile": "https://Stackoverflow.com/users/336878", "pm_score": 0, "selected": false, "text": "<p>Dyalog APL</p>\n\n<pre><code>fib←{\n ⍵∊0 1:⍵\n +/∇¨⍵-1 2\n}\n</code></pre>\n" }, { "answer_id": 3029262, "author": "Daniel Băluţă", "author_id": 328594, "author_profile": "https://Stackoverflow.com/users/328594", "pm_score": 0, "selected": false, "text": "<pre><code>int main(void) { return main(); }\n</code></pre>\n" }, { "answer_id": 3171602, "author": "Cyclone", "author_id": 113419, "author_profile": "https://Stackoverflow.com/users/113419", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Php\" rel=\"nofollow noreferrer\">PHP</a> is a recursive acronym</p>\n" }, { "answer_id": 3230616, "author": "Artur Gaspar", "author_id": 286655, "author_profile": "https://Stackoverflow.com/users/286655", "pm_score": 0, "selected": false, "text": "<p>Python:</p>\n\n<pre><code>import sys \nsys.setrecursionlimit(sys.maxint) \ndef so(): \n so() \nso()\n</code></pre>\n" }, { "answer_id": 3272869, "author": "Ming-Tang", "author_id": 303939, "author_profile": "https://Stackoverflow.com/users/303939", "pm_score": 2, "selected": false, "text": "<p><strong>Java: 35 characters</strong></p>\n\n<p>I think it's too late, but I will still post my idea:</p>\n\n<pre><code>class A{{new A();}static{new A();}}\n</code></pre>\n\n<p>Using the static initializer and instance initializer features.</p>\n\n<p>Here is the output on my computer (notice it showed two error messages):</p>\n\n<pre><code>Exception in thread \"main\" java.lang.StackOverflowError\n at A.&lt;init&gt;(A.java:1)\n ......\n at A.&lt;init&gt;(A.java:1)\nCould not find the main class: A. Program will exit.\n</code></pre>\n\n<p>See also: <a href=\"http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/java/javaOO/initial.html\" rel=\"nofollow noreferrer\">http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/java/javaOO/initial.html</a></p>\n" }, { "answer_id": 3343950, "author": "st0le", "author_id": 216517, "author_profile": "https://Stackoverflow.com/users/216517", "pm_score": 0, "selected": false, "text": "<h2>JavaScript (17 Bytes)</h2>\n\n<pre><code>eval(t=\"eval(t)\")\n</code></pre>\n\n<h2>VB Script (25 Bytes)</h2>\n\n<pre><code>t=\"Execute(t)\":Execute(t)\n</code></pre>\n" }, { "answer_id": 3605353, "author": "Ming-Tang", "author_id": 303939, "author_profile": "https://Stackoverflow.com/users/303939", "pm_score": 2, "selected": false, "text": "<h1>C++ Compiler Error Message</h1>\n<pre><code>template&lt;int n&gt;struct f{f&lt;n+1&gt;a;};f&lt;0&gt;::a;\n</code></pre>\n<p>output:</p>\n<pre><code>$ g++ test.cpp;\ntest.cpp:1: error: template instantiation depth exceeds maximum of 500 (use -ftemplate-depth-NN to increase the maximum) instantiating ‘struct f&lt;500&gt;’\ntest.cpp:1: instantiated from ‘f&lt;499&gt;’\ntest.cpp:1: instantiated from ‘f&lt;498&gt;’\n......\n</code></pre>\n<p>Even if the compiler went through the template, there will be the next error: missing <code>main</code>.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13/" ]
To commemorate the public launch of Stack Overflow, what's the shortest code to cause a stack overflow? Any language welcome. ETA: Just to be clear on this question, seeing as I'm an occasional Scheme user: tail-call "recursion" is really iteration, and any solution which can be converted to an iterative solution relatively trivially by a decent compiler won't be counted. :-P ETA2: I've now selected a “best answer”; see [this post](https://stackoverflow.com/questions/62188/stack-overflow-code-golf/71833#71833) for rationale. Thanks to everyone who contributed! :-)
All these answers and no Befunge? I'd wager a fair amount it's shortest solution of them all: ``` 1 ``` Not kidding. Try it yourself: <http://www.quirkster.com/iano/js/befunge.html> EDIT: I guess I need to explain this one. The 1 operand pushes a 1 onto Befunge's internal stack and the lack of anything else puts it in a loop under the rules of the language. Using the interpreter provided, you will eventually--and I mean *eventually*--hit a point where the Javascript array that represents the Befunge stack becomes too large for the browser to reallocate. If you had a simple Befunge interpreter with a smaller and bounded stack--as is the case with most of the languages below--this program would cause a more noticeable overflow faster.
62,226
<p>An instance of class A instantiates a couple of other objects, say for example from class B:</p> <pre><code>$foo = new B(); </code></pre> <p>I would like to access A's public class variables from methods within B.</p> <p>Unless I'm missing something, the only way to do this is to pass the current object to the instances of B:</p> <pre><code>$foo = new B($this); </code></pre> <p>Is this best practice or is there another way to do this?</p>
[ { "answer_id": 62242, "author": "Hanno Fietz", "author_id": 2077, "author_profile": "https://Stackoverflow.com/users/2077", "pm_score": 1, "selected": false, "text": "<p>I would first check if you are not using the wrong pattern: From your application logic, should B really know about A? If B needs to know about A, a parent-child relationship seems not quite adequate. For example, A could be the child, or part of A's logic could go into a third object that is \"below\" B in the hierarchy (i. e. doesn't know about B).</p>\n\n<p>That said, I would suggest you have a method in B to register A as a data source, or create a method in A to register B as an <a href=\"http://en.wikipedia.org/wiki/Observer_pattern\" rel=\"nofollow noreferrer\" title=\"Wikipedia: Observer pattern\">Observer</a> and a matching method in B that A uses to notify B of value changes.</p>\n" }, { "answer_id": 62249, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 3, "selected": true, "text": "<p>That looks fine to me, I tend to use a rule of thumb of \"would someone maintaining this understand it?\" and that's an easily understood solution.</p>\n\n<p>If there's only one \"A\", you could consider using the registry pattern, see for example <a href=\"http://www.phppatterns.com/docs/design/the_registry\" rel=\"nofollow noreferrer\">http://www.phppatterns.com/docs/design/the_registry</a></p>\n" }, { "answer_id": 76201, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "<p>Similar to what Paul said, if there's only one A, you can implement that as a singleton. You can then pass the instance of A as an argument to the constructor (aggregation), with a setter method (essentially aggregation again), or you can set this relationship directly in the constructor (composition).</p>\n\n<p>However, while singletons are powerful, be wary of implementing them with composition. It's nice to think that you can do it that way and get rid of a constructor argument, but it also makes it impossible to replace A with something else without a code rewrite. Peronsally, I'd stick with aggregation, even if using a singleton</p>\n\n<pre><code>$foo = new B( A::getInstance() );\n</code></pre>\n" }, { "answer_id": 883890, "author": "Jet", "author_id": 109480, "author_profile": "https://Stackoverflow.com/users/109480", "pm_score": 0, "selected": false, "text": "<pre><code>$foo = new B($this);\n</code></pre>\n\n<p>Code like this unfortunately does not match my needs. Is there any other way to access the parent object properties? </p>\n\n<p>I'll try to explain why. We write a game software and some classes have very \"unusual\" dependencies and influence each other in different ways. That's why code sometimes gets almost unsupportable without links to parents in every instance (sometimes even several parents from different contexts i.e. a Squad may belong to Battle and to User etc...).</p>\n\n<p>And now the reason why links don't satisfy me. When I generate an output for the client side, I use a kind of serializing objects in XML. It works very nice until it meets recursive references like those links to parents. I can make them protected, but then they loose their usage i.e. (dummy example)</p>\n\n<pre><code>$this-&gt;squad-&gt;battle-&gt;getTeam($tid)-&gt;getSquad($sqid)-&gt;damageCreature(...);\n</code></pre>\n\n<p>The other way - to implement serialization method in every serializable class and call it inside serializer like this:</p>\n\n<pre><code>$obj-&gt;toXML($node);\n$this-&gt;appendChild($node);\n</code></pre>\n\n<p>but that's a lot of stuff to write and to support! And sometimes i generate the objects for serializer dynamically (less traffic).</p>\n\n<p>I even think about a hack: to \"teach\" serializer to ignore some properties in certain classess )). Huh... bad idea...</p>\n\n<p>It's a long discussion, but believe me, that Registry and Observer don't fit. Are there any other ideas?</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6260/" ]
An instance of class A instantiates a couple of other objects, say for example from class B: ``` $foo = new B(); ``` I would like to access A's public class variables from methods within B. Unless I'm missing something, the only way to do this is to pass the current object to the instances of B: ``` $foo = new B($this); ``` Is this best practice or is there another way to do this?
That looks fine to me, I tend to use a rule of thumb of "would someone maintaining this understand it?" and that's an easily understood solution. If there's only one "A", you could consider using the registry pattern, see for example <http://www.phppatterns.com/docs/design/the_registry>
62,230
<p>How do I save a jpg image to database and then load it in Delphi using FIBplus and TImage?</p>
[ { "answer_id": 62271, "author": "Roger Ween", "author_id": 6143, "author_profile": "https://Stackoverflow.com/users/6143", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://delphi.about.com/od/database/l/aa030601a.htm\" rel=\"nofollow noreferrer\">Take a look here.</a>\nI think you have to convert it to a stream, store it and vice versa.</p>\n" }, { "answer_id": 65859, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.devrace.com/en/fibplus/articles/2161.php\" rel=\"nofollow noreferrer\">This page</a> explains it. Use SaveToStream and a TMemoryStream instead of SaveToFile if you don't want temporary files. TImage.Picture has a LoadFromStream which loads the image from the stream into the TImage for display.</p>\n" }, { "answer_id": 69243, "author": "Ali", "author_id": 10989, "author_profile": "https://Stackoverflow.com/users/10989", "pm_score": 2, "selected": false, "text": "<pre><code>var\n S : TMemoryStream;\nbegin\n S := TMemoryStream.Create;\n try\n TBlobField(AdoQuery1.FieldByName('ImageField')).SaveToStream(S);\n S.Position := 0;\n Image1.Picture.Graphic.LoadFromStream(S);\n finally\n S.Free;\n end;\nend;\n</code></pre>\n\n<p>if you are using JPEG images, add JPG unit to <strong>uses</strong> clause of your unit file.</p>\n" }, { "answer_id": 27692275, "author": "alper", "author_id": 4402765, "author_profile": "https://Stackoverflow.com/users/4402765", "pm_score": -1, "selected": false, "text": "<p>Delphi 7 paradox table</p>\n\n<p>insert dbimage to jpeg</p>\n\n<pre><code>var\n FileStream: TFileStream;\n BlobStream: TStream;\nbegin\n if openpicturedialog1.Execute then\n begin\n Sicil_frm.DBNavigator1.BtnClick(nbEdit);\n image1.Picture.LoadFromFile(openpicturedialog1.FileName);\n try\n BlobStream := dm.sicil.CreateBlobStream(dm.sicil.FieldByName('Resim'),bmWrite);\n FileStream := TFileStream.Create(openpicturedialog1.FileName,fmOpenRead or fmShareDenyNone);\n BlobStream.CopyFrom(FileStream,FileStream.Size);\n FileStream.Free;\n BlobStream.Free;\n Sicil_frm.DBNavigator1.BtnClick(nbPost);\n DM.SicilAfterScroll(dm.sicil);\n except\n dm.sicil.Cancel;\n end;\n end;\nend;\n</code></pre>\n\n<p>Error \"Bitmap image is nat valid\"</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6155/" ]
How do I save a jpg image to database and then load it in Delphi using FIBplus and TImage?
``` var S : TMemoryStream; begin S := TMemoryStream.Create; try TBlobField(AdoQuery1.FieldByName('ImageField')).SaveToStream(S); S.Position := 0; Image1.Picture.Graphic.LoadFromStream(S); finally S.Free; end; end; ``` if you are using JPEG images, add JPG unit to **uses** clause of your unit file.
62,245
<p>I am trying to refactor some code I have for software that collects current status of agents in a call queue. Currently, for each of the 6 or so events that I listen to, I check in a Mnesia table if an agent exists and change some values in the row depending on the event or add it as new if the agent doesn't exist. Currently I have this Mnesia transaction in each event and of course that is a bunch of repeated code for checking the existence of agents and so on. </p> <p>I'm trying to change it so that there is one function like <em>change_agent/2</em> that I call from the events that handles this for me. </p> <p>My problems are of course records.... I find no way of dynamically creating them or merging 2 of them together or anything. Preferably there would be a function I could call like:</p> <pre><code>change_agent("001", #agent(id = "001", name = "Steve")). change_agent("001", #agent(id = "001", paused = 0, talking_to = "None")). </code></pre>
[ { "answer_id": 62556, "author": "uwiger", "author_id": 6834, "author_profile": "https://Stackoverflow.com/users/6834", "pm_score": 2, "selected": false, "text": "<p>It is difficult to write generic access functions for records.\nOne workaround for this is the <a href=\"http://forum.trapexit.org/viewtopic.php?p=21790#21790\" rel=\"nofollow noreferrer\">'exprecs'</a> library, which\nwill generate code for low-level record access functions.</p>\n\n<p>The thing you need to do is to add the following lines to \na module:</p>\n\n<pre><code>-compile({parse_transform, exprecs}).\n-export_records([...]). % name the records that you want to 'export'\n</code></pre>\n\n<p>The naming convention for the access functions may look strange, but was inspired by a proposal from Richard O'Keefe. It is, at least, consistent, and unlikely to clash with existing functions. (:</p>\n" }, { "answer_id": 62898, "author": "Adam Lindberg", "author_id": 2457, "author_profile": "https://Stackoverflow.com/users/2457", "pm_score": 3, "selected": true, "text": "<p>I wrote some code a while ago that merges two records. Is not entirely dynamic, but whith macros you could easily use it for several records.</p>\n\n<p>It works like this: The merge/2 function takes two records and converts them to lists together with the empty record for reference (the record type is defined at compile time, and must be. This is the \"undynamic\" part). These are then run through the generic function merge/4 which works with lists and takes elements from A if they are defined, otherwise from B if they are defined, or lastly from Default (which is always defined).</p>\n\n<p>Here's the code (please excuse StackOverflow's poor Erlang syntax highlighting):</p>\n\n<pre><code>%%%----------------------------------------------------------------------------\n%%% @spec merge(RecordA, RecordB) -&gt; #my_record{}\n%%% RecordA = #my_record{}\n%%% RecordB = #my_record{}\n%%%\n%%% @doc Merges two #my_record{} instances. The first takes precedence.\n%%% @end\n%%%----------------------------------------------------------------------------\nmerge(RecordA, RecordB) when is_record(RecordA, my_record),\n is_record(RecordB, my_record) -&gt;\n list_to_tuple(\n lists:append([my_record],\n merge(tl(tuple_to_list(RecordA)),\n tl(tuple_to_list(RecordB)),\n tl(tuple_to_list(#my_record{})),\n []))).\n\n%%%----------------------------------------------------------------------------\n%%% @spec merge(A, B, Default, []) -&gt; [term()]\n%%% A = [term()]\n%%% B = [term()]\n%%% Default = [term()]\n%%%\n%%% @doc Merges the lists `A' and `B' into to a new list taking\n%%% default values from `Default'.\n%%%\n%%% Each element of `A' and `B' are compared against the elements in\n%%% `Default'. If they match the default, the default is used. If one\n%%% of them differs from the other and the default value, that element is\n%%% chosen. If both differs, the element from `A' is chosen.\n%%% @end\n%%%----------------------------------------------------------------------------\nmerge([D|ATail], [D|BTail], [D|DTail], To) -&gt;\n merge(ATail, BTail, DTail, [D|To]); % If default, take from D\nmerge([D|ATail], [B|BTail], [D|DTail], To) -&gt;\n merge(ATail, BTail, DTail, [B|To]); % If only A default, take from B\nmerge([A|ATail], [_|BTail], [_|DTail], To) -&gt;\n merge(ATail, BTail, DTail, [A|To]); % Otherwise take from A\nmerge([], [], [], To) -&gt;\n lists:reverse(To).\n</code></pre>\n\n<p>Feel free to use it in any way you want.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5601/" ]
I am trying to refactor some code I have for software that collects current status of agents in a call queue. Currently, for each of the 6 or so events that I listen to, I check in a Mnesia table if an agent exists and change some values in the row depending on the event or add it as new if the agent doesn't exist. Currently I have this Mnesia transaction in each event and of course that is a bunch of repeated code for checking the existence of agents and so on. I'm trying to change it so that there is one function like *change\_agent/2* that I call from the events that handles this for me. My problems are of course records.... I find no way of dynamically creating them or merging 2 of them together or anything. Preferably there would be a function I could call like: ``` change_agent("001", #agent(id = "001", name = "Steve")). change_agent("001", #agent(id = "001", paused = 0, talking_to = "None")). ```
I wrote some code a while ago that merges two records. Is not entirely dynamic, but whith macros you could easily use it for several records. It works like this: The merge/2 function takes two records and converts them to lists together with the empty record for reference (the record type is defined at compile time, and must be. This is the "undynamic" part). These are then run through the generic function merge/4 which works with lists and takes elements from A if they are defined, otherwise from B if they are defined, or lastly from Default (which is always defined). Here's the code (please excuse StackOverflow's poor Erlang syntax highlighting): ``` %%%---------------------------------------------------------------------------- %%% @spec merge(RecordA, RecordB) -> #my_record{} %%% RecordA = #my_record{} %%% RecordB = #my_record{} %%% %%% @doc Merges two #my_record{} instances. The first takes precedence. %%% @end %%%---------------------------------------------------------------------------- merge(RecordA, RecordB) when is_record(RecordA, my_record), is_record(RecordB, my_record) -> list_to_tuple( lists:append([my_record], merge(tl(tuple_to_list(RecordA)), tl(tuple_to_list(RecordB)), tl(tuple_to_list(#my_record{})), []))). %%%---------------------------------------------------------------------------- %%% @spec merge(A, B, Default, []) -> [term()] %%% A = [term()] %%% B = [term()] %%% Default = [term()] %%% %%% @doc Merges the lists `A' and `B' into to a new list taking %%% default values from `Default'. %%% %%% Each element of `A' and `B' are compared against the elements in %%% `Default'. If they match the default, the default is used. If one %%% of them differs from the other and the default value, that element is %%% chosen. If both differs, the element from `A' is chosen. %%% @end %%%---------------------------------------------------------------------------- merge([D|ATail], [D|BTail], [D|DTail], To) -> merge(ATail, BTail, DTail, [D|To]); % If default, take from D merge([D|ATail], [B|BTail], [D|DTail], To) -> merge(ATail, BTail, DTail, [B|To]); % If only A default, take from B merge([A|ATail], [_|BTail], [_|DTail], To) -> merge(ATail, BTail, DTail, [A|To]); % Otherwise take from A merge([], [], [], To) -> lists:reverse(To). ``` Feel free to use it in any way you want.
62,264
<p>I recently asked about <a href="https://stackoverflow.com/questions/39742/does-git-have-anything-like-svn-propset-svnkeywords-or-pre-post-commit-hooks">keyword expansion in Git</a> and I'm willing to accept the design not to really support this idea in Git. </p> <p>For better or worse, the project I'm working on at the moment requires SVN keyword expansion like this:</p> <pre><code>svn propset svn:keywords "Id" expl3.dtx </code></pre> <p>to keep this string up-to-date:</p> <pre><code>$Id: expl3.dtx 803 2008-09-11 14:01:58Z will $ </code></pre> <p>But I would quite like to use Git to do my version control. Unfortunately, git-svn doesn't support this, according to the docs:</p> <blockquote> <p>"We ignore all SVN properties except svn:executable"</p> </blockquote> <p>But it doesn't seem too tricky to have this keyword stuff emulated by a couple of pre/post commit hooks. Am I the first person to want this? Does anyone have some code to do this?</p>
[ { "answer_id": 62288, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 1, "selected": false, "text": "<p>You could set the ident attribute on your files, but that would produce strings like</p>\n\n<pre><code>$Id: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef$\n</code></pre>\n\n<p>where <code>deadbeef...</code> is the sha1 of the blob corresponding to that file. If you really need that keyword expansion, and you need it in the git repo (as opposed to an exported archive), I think you're going to have to go with the <code>ident</code> gitattribute with a custom script that does the expansion for you. The problem with just using a hook is then the file in the working tree wouldn't match the index, and git would think it's been modified.</p>\n" }, { "answer_id": 72874, "author": "emk", "author_id": 12089, "author_profile": "https://Stackoverflow.com/users/12089", "pm_score": 6, "selected": true, "text": "<p>What's going on here: Git is optimized to switch between branches as quickly as possible. In particular, <code>git checkout</code> is designed to not touch any files that are identical in both branches.</p>\n\n<p>Unfortunately, RCS keyword substitution breaks this. For example, using <code>$Date$</code> would require <code>git checkout</code> to touch every file in the tree when switching branches. For a repository the size of the Linux kernel, this would bring everything to a screeching halt.</p>\n\n<p>In general, your best bet is to tag at least one version:</p>\n\n<pre><code>$ git tag v0.5.whatever\n</code></pre>\n\n<p>...and then call the following command from your Makefile:</p>\n\n<pre><code>$ git describe --tags\nv0.5.15.1-6-g61cde1d\n</code></pre>\n\n<p>Here, git is telling me that I'm working on an anonymous version 6 commits past v0.5.15.1, with an SHA1 hash beginning with <code>g61cde1d</code>. If you stick the output of this command into a <code>*.h</code> file somewhere, you're in business, and will have no problem linking the released software back to the source code. This is the preferred way of doing things.</p>\n\n<p>If you can't possibly avoid using RCS keywords, you may want to start with this <a href=\"http://kerneltrap.org/mailarchive/git/2007/10/12/335953\" rel=\"noreferrer\">explanation by Lars Hjemli</a>. Basically, <code>$Id$</code> is pretty easy, and you if you're using <code>git archive</code>, you can also use <code>$Format$</code>.</p>\n\n<p>But, if you absolutely cannot avoid RCS keywords, the following should get you started:</p>\n\n<pre><code>git config filter.rcs-keyword.clean 'perl -pe \"s/\\\\\\$Date[^\\\\\\$]*\\\\\\$/\\\\\\$Date\\\\\\$/\"'\ngit config filter.rcs-keyword.smudge 'perl -pe \"s/\\\\\\$Date[^\\\\\\$]*\\\\\\$/\\\\\\$Date: `date`\\\\\\$/\"'\n\necho '$Date$' &gt; test.html\necho 'test.html filter=rcs-keyword' &gt;&gt; .gitattributes\ngit add test.html .gitattributes\ngit commit -m \"Experimental RCS keyword support for git\"\n\nrm test.html\ngit checkout test.html\ncat test.html\n</code></pre>\n\n<p>On my system, I get:</p>\n\n<pre><code>$Date: Tue Sep 16 10:15:02 EDT 2008$\n</code></pre>\n\n<p>If you have trouble getting the shell escapes in the <code>smudge</code> and <code>clean</code> commands to work, just write your own Perl scripts for expanding and removing RCS keywords, respectively, and use those scripts as your filter.</p>\n\n<p>Note that you <em>really</em> don't want to do this for more files than absolutely necessary, or git will lose most of its speed.</p>\n" }, { "answer_id": 1194313, "author": "Rhialto", "author_id": 146440, "author_profile": "https://Stackoverflow.com/users/146440", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>Unfortunately, RCS keyword\n substitution breaks this. For example,\n using $Date$ would require git\n checkout to touch every file in the\n tree when switching branches.</p>\n</blockquote>\n\n<p>That is not true. $Date$ etc. expand to the value which holds at checkin time. That is much more useful anyway. So it doesn't change on other revisions or branches, unless the file is actually re-checked-in.\nFrom the RCS manual:</p>\n\n<pre><code> $Date$ The date and time the revision was checked in. With -zzone a\n numeric time zone offset is appended; otherwise, the date is\n UTC.\n</code></pre>\n\n<p>This also means that the suggested answer above, with the rcs-keyword.smudge filter, is incorrect. It inserts the time/date of the checkout, or whatever it is that causes it to run.</p>\n" }, { "answer_id": 5633162, "author": "turon", "author_id": 322797, "author_profile": "https://Stackoverflow.com/users/322797", "pm_score": 3, "selected": false, "text": "<p>Here is a sample project containing the configuration and filter code needed for adding RCS keyword support to a git project:</p>\n\n<p><a href=\"https://github.com/turon/git-rcs-keywords\" rel=\"noreferrer\">https://github.com/turon/git-rcs-keywords</a></p>\n\n<p>It's not as simple to setup as one would like, but it seems to work. It uses a smudge/clean filter pair written in perl (similar to what emk's answer described), and yes, it will touch all files with the extensions set in .gitattributes, generally slowing things down a bit. </p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4161/" ]
I recently asked about [keyword expansion in Git](https://stackoverflow.com/questions/39742/does-git-have-anything-like-svn-propset-svnkeywords-or-pre-post-commit-hooks) and I'm willing to accept the design not to really support this idea in Git. For better or worse, the project I'm working on at the moment requires SVN keyword expansion like this: ``` svn propset svn:keywords "Id" expl3.dtx ``` to keep this string up-to-date: ``` $Id: expl3.dtx 803 2008-09-11 14:01:58Z will $ ``` But I would quite like to use Git to do my version control. Unfortunately, git-svn doesn't support this, according to the docs: > > "We ignore all SVN properties except svn:executable" > > > But it doesn't seem too tricky to have this keyword stuff emulated by a couple of pre/post commit hooks. Am I the first person to want this? Does anyone have some code to do this?
What's going on here: Git is optimized to switch between branches as quickly as possible. In particular, `git checkout` is designed to not touch any files that are identical in both branches. Unfortunately, RCS keyword substitution breaks this. For example, using `$Date$` would require `git checkout` to touch every file in the tree when switching branches. For a repository the size of the Linux kernel, this would bring everything to a screeching halt. In general, your best bet is to tag at least one version: ``` $ git tag v0.5.whatever ``` ...and then call the following command from your Makefile: ``` $ git describe --tags v0.5.15.1-6-g61cde1d ``` Here, git is telling me that I'm working on an anonymous version 6 commits past v0.5.15.1, with an SHA1 hash beginning with `g61cde1d`. If you stick the output of this command into a `*.h` file somewhere, you're in business, and will have no problem linking the released software back to the source code. This is the preferred way of doing things. If you can't possibly avoid using RCS keywords, you may want to start with this [explanation by Lars Hjemli](http://kerneltrap.org/mailarchive/git/2007/10/12/335953). Basically, `$Id$` is pretty easy, and you if you're using `git archive`, you can also use `$Format$`. But, if you absolutely cannot avoid RCS keywords, the following should get you started: ``` git config filter.rcs-keyword.clean 'perl -pe "s/\\\$Date[^\\\$]*\\\$/\\\$Date\\\$/"' git config filter.rcs-keyword.smudge 'perl -pe "s/\\\$Date[^\\\$]*\\\$/\\\$Date: `date`\\\$/"' echo '$Date$' > test.html echo 'test.html filter=rcs-keyword' >> .gitattributes git add test.html .gitattributes git commit -m "Experimental RCS keyword support for git" rm test.html git checkout test.html cat test.html ``` On my system, I get: ``` $Date: Tue Sep 16 10:15:02 EDT 2008$ ``` If you have trouble getting the shell escapes in the `smudge` and `clean` commands to work, just write your own Perl scripts for expanding and removing RCS keywords, respectively, and use those scripts as your filter. Note that you *really* don't want to do this for more files than absolutely necessary, or git will lose most of its speed.
62,289
<p>How is it possible to read/write to the Windows registry using Java?</p>
[ { "answer_id": 62291, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 4, "selected": false, "text": "<p>Yes, using the java.util.Preferences API, since the Windows implementation of it uses the Registry as a backend.</p>\n<p>In the end it depends on what you're wanting to do: storing preferences for your app is what the Preferences does just great. If you're wanting to actually change registry keys not having to do with your app, you'll need some JNI app, as described by Mark (shameless steal here):</p>\n<blockquote>\n<p>From a quick google:\nCheck the WinPack for JNIWrapper. It has full Windows Registry access support including Reading and Writing.</p>\n<p>The WinPack Demo has Registry Viewer implemented as an example.</p>\n<p>Check at <a href=\"http://www.teamdev.com/jniwrapper/winpack/#registry_access\" rel=\"noreferrer\">http://www.teamdev.com/jniwrapper/winpack/#registry_access</a></p>\n<p>And...</p>\n<p>There is also try JNIRegistry @ <a href=\"http://www.trustice.com/java/jnireg/\" rel=\"noreferrer\">http://www.trustice.com/java/jnireg/</a></p>\n<p>There is also the option of invoking an external app, which is responsible for reading / writing the registry.</p>\n</blockquote>\n" }, { "answer_id": 62299, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 4, "selected": false, "text": "<p>From a quick google:</p>\n\n<blockquote>\n <p>Check the WinPack for JNIWrapper. It\n has full Windows Registry access\n support including Reading and Writing.</p>\n \n <p>The WinPack Demo has Registry Viewer\n implemented as an example.</p>\n \n <p>Check at\n <a href=\"http://www.teamdev.com/jniwrapper/winpack/#registry_access\" rel=\"noreferrer\">http://www.teamdev.com/jniwrapper/winpack/#registry_access</a></p>\n</blockquote>\n\n<p>And...</p>\n\n<blockquote>\n <p>There is also try JNIRegistry @\n <a href=\"http://www.trustice.com/java/jnireg/\" rel=\"noreferrer\">http://www.trustice.com/java/jnireg/</a></p>\n</blockquote>\n\n<p>There is also the option of invoking an external app, which is responsible for reading / writing the registry.</p>\n" }, { "answer_id": 62312, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>The Preferences API approach does not give you access to all the branches of the registry. In fact, it only gives you access to where the Preferences API stores its, well, preferences. It's not a generic registry handling API, like .NET's</p>\n\n<p>To read/write every key I guess JNI or an external tool would be the approach to take, as Mark shows.</p>\n" }, { "answer_id": 62690, "author": "Ignat", "author_id": 119889, "author_profile": "https://Stackoverflow.com/users/119889", "pm_score": 3, "selected": false, "text": "<p>There are few JNDI service providers to work with windows registry.</p>\n\n<p>One could observe <a href=\"https://web.archive.org/web/20120801053337/http://java.sun.com/products/jndi/serviceproviders.html\" rel=\"nofollow noreferrer\">http://java.sun.com/products/jndi/serviceproviders.html</a>.</p>\n" }, { "answer_id": 63231, "author": "Alex Argo", "author_id": 5885, "author_profile": "https://Stackoverflow.com/users/5885", "pm_score": 5, "selected": false, "text": "<p>I've done this before using <a href=\"http://sourceforge.net/projects/jregistrykey/\" rel=\"noreferrer\" title=\"jRegistryKey\">jRegistryKey</a>. It is an LGPL Java/JNI library that can do what you need. Here's an example of how I used it to enabled Registry editing through regedit and also the \"Show Folder Options\" option for myself in Windows via the registry.</p>\n\n<pre><code>import java.io.File;\nimport ca.beq.util.win32.registry.RegistryKey;\nimport ca.beq.util.win32.registry.RegistryValue;\nimport ca.beq.util.win32.registry.RootKey;\nimport ca.beq.util.win32.registry.ValueType;\n\n\npublic class FixStuff {\n\nprivate static final String REGEDIT_KEY = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\System\";\nprivate static final String REGEDIT_VALUE = \"DisableRegistryTools\";\nprivate static final String REGISTRY_LIBRARY_PATH = \"\\\\lib\\\\jRegistryKey.dll\";\nprivate static final String FOLDER_OPTIONS_KEY = \"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\Explorer\";\nprivate static final String FOLDER_OPTIONS_VALUE = \"NoFolderOptions\";\n\npublic static void main(String[] args) {\n //Load JNI library\n RegistryKey.initialize( new File(\".\").getAbsolutePath()+REGISTRY_LIBRARY_PATH );\n\n enableRegistryEditing(true); \n enableShowFolderOptions(true);\n}\n\nprivate static void enableShowFolderOptions(boolean enable) {\n RegistryKey key = new RegistryKey(RootKey.HKEY_CURRENT_USER,FOLDER_OPTIONS_KEY);\n RegistryKey key2 = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE,FOLDER_OPTIONS_KEY);\n RegistryValue value = new RegistryValue();\n value.setName(FOLDER_OPTIONS_VALUE);\n value.setType(ValueType.REG_DWORD_LITTLE_ENDIAN);\n value.setData(enable?0:1);\n\n if(key.hasValue(FOLDER_OPTIONS_VALUE)) {\n key.setValue(value);\n }\n if(key2.hasValue(FOLDER_OPTIONS_VALUE)) {\n key2.setValue(value);\n } \n}\n\nprivate static void enableRegistryEditing(boolean enable) {\n RegistryKey key = new RegistryKey(RootKey.HKEY_CURRENT_USER,REGEDIT_KEY);\n RegistryValue value = new RegistryValue();\n value.setName(REGEDIT_VALUE);\n value.setType(ValueType.REG_DWORD_LITTLE_ENDIAN);\n value.setData(enable?0:1);\n\n if(key.hasValue(REGEDIT_VALUE)) {\n key.setValue(value);\n }\n}\n\n}\n</code></pre>\n" }, { "answer_id": 876862, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>The WinPack Demo has Registry Viewer\n implemented as an example.</p>\n \n <p>Check at\n <a href=\"http://www.jniwrapper.com/winpack_features.jsp#registry\" rel=\"nofollow noreferrer\">http://www.jniwrapper.com/winpack_features.jsp#registry</a></p>\n</blockquote>\n\n<p>BTW, WinPack has been moved to the following address:</p>\n\n<p><a href=\"http://www.teamdev.com/jniwrapper/winpack/\" rel=\"nofollow noreferrer\">http://www.teamdev.com/jniwrapper/winpack/</a></p>\n" }, { "answer_id": 878336, "author": "Peter Smith", "author_id": 103715, "author_profile": "https://Stackoverflow.com/users/103715", "pm_score": 2, "selected": false, "text": "<p>You could try <a href=\"http://winrun4j.sourceforge.net/\" rel=\"nofollow noreferrer\" title=\"WinRun4J\">WinRun4J</a>. This is a windows java launcher and service host but it also provides a library for accessing the registry.</p>\n\n<p>(btw I work on this project so let me know if you have any questions)</p>\n" }, { "answer_id": 1982033, "author": "Oleg Ryaboy", "author_id": 205711, "author_profile": "https://Stackoverflow.com/users/205711", "pm_score": 7, "selected": false, "text": "<p>You don't actually need a 3rd party package. Windows has a reg utility for all registry operations. To get the command format, go to the DOS propmt and type:</p>\n\n<pre><code>reg /?\n</code></pre>\n\n<p>You can invoke <em>reg</em> through the Runtime class:</p>\n\n<pre><code>Runtime.getRuntime().exec(\"reg &lt;your parameters here&gt;\");\n</code></pre>\n\n<p>Editing keys and adding new ones is straightforward using the command above. To read the registry, you need to get <em>reg</em>'s output, and it's a little tricky. Here's the code:</p>\n\n<pre><code>import java.io.IOException;\nimport java.io.InputStream;\nimport java.io.StringWriter;\n\n/**\n * @author Oleg Ryaboy, based on work by Miguel Enriquez \n */\npublic class WindowsReqistry {\n\n /**\n * \n * @param location path in the registry\n * @param key registry key\n * @return registry value or null if not found\n */\n public static final String readRegistry(String location, String key){\n try {\n // Run reg query, then read output with StreamReader (internal class)\n Process process = Runtime.getRuntime().exec(\"reg query \" + \n '\"'+ location + \"\\\" /v \" + key);\n\n StreamReader reader = new StreamReader(process.getInputStream());\n reader.start();\n process.waitFor();\n reader.join();\n String output = reader.getResult();\n\n // Output has the following format:\n // \\n&lt;Version information&gt;\\n\\n&lt;key&gt;\\t&lt;registry type&gt;\\t&lt;value&gt;\n if( ! output.contains(\"\\t\")){\n return null;\n }\n\n // Parse out the value\n String[] parsed = output.split(\"\\t\");\n return parsed[parsed.length-1];\n }\n catch (Exception e) {\n return null;\n }\n\n }\n\n static class StreamReader extends Thread {\n private InputStream is;\n private StringWriter sw= new StringWriter();\n\n public StreamReader(InputStream is) {\n this.is = is;\n }\n\n public void run() {\n try {\n int c;\n while ((c = is.read()) != -1)\n sw.write(c);\n }\n catch (IOException e) { \n }\n }\n\n public String getResult() {\n return sw.toString();\n }\n }\n public static void main(String[] args) {\n\n // Sample usage\n String value = WindowsReqistry.readRegistry(\"HKCU\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\\" \n + \"Explorer\\\\Shell Folders\", \"Personal\");\n System.out.println(value);\n }\n}\n</code></pre>\n\n<hr>\n" }, { "answer_id": 5841923, "author": "Tom Anderson", "author_id": 116639, "author_profile": "https://Stackoverflow.com/users/116639", "pm_score": 3, "selected": false, "text": "<p>As has been noted, the Preferences API uses the registry to store preferences, but cannot be used to access the whole registry.</p>\n\n<p>However, a pirate called David Croft has worked out that it's possible to use methods in Sun's implementation of the Preferences API for <a href=\"http://www.davidc.net/programming/java/reading-windows-registry-java-without-jni\" rel=\"nofollow\">reading the Windows registry from Java without JNI</a>. There are some dangers to that, but it is worth a look.</p>\n" }, { "answer_id": 5902131, "author": "gousli", "author_id": 740494, "author_profile": "https://Stackoverflow.com/users/740494", "pm_score": 3, "selected": false, "text": "<p>Here's a modified version of Oleg's solution. I noticed that on my system (Windows server 2003), the output of \"reg query\" is not separated by tabs ('\\t'), but by 4 spaces.</p>\n\n<p>I also simplified the solution, as a thread is not required.</p>\n\n<pre><code>public static final String readRegistry(String location, String key)\n{\n try\n {\n // Run reg query, then read output with StreamReader (internal class)\n Process process = Runtime.getRuntime().exec(\"reg query \" + \n '\"'+ location + \"\\\" /v \" + key);\n\n InputStream is = process.getInputStream();\n StringBuilder sw = new StringBuilder();\n\n try\n {\n int c;\n while ((c = is.read()) != -1)\n sw.append((char)c);\n }\n catch (IOException e)\n { \n }\n\n String output = sw.toString();\n\n // Output has the following format:\n // \\n&lt;Version information&gt;\\n\\n&lt;key&gt; &lt;registry type&gt; &lt;value&gt;\\r\\n\\r\\n\n int i = output.indexOf(\"REG_SZ\");\n if (i == -1)\n {\n return null;\n }\n\n sw = new StringBuilder();\n i += 6; // skip REG_SZ\n\n // skip spaces or tabs\n for (;;)\n {\n if (i &gt; output.length())\n break;\n char c = output.charAt(i);\n if (c != ' ' &amp;&amp; c != '\\t')\n break;\n ++i;\n }\n\n // take everything until end of line\n for (;;)\n {\n if (i &gt; output.length())\n break;\n char c = output.charAt(i);\n if (c == '\\r' || c == '\\n')\n break;\n sw.append(c);\n ++i;\n }\n\n return sw.toString();\n }\n catch (Exception e)\n {\n return null;\n }\n</code></pre>\n\n<p>}</p>\n" }, { "answer_id": 6028547, "author": "Vishal", "author_id": 390550, "author_profile": "https://Stackoverflow.com/users/390550", "pm_score": -1, "selected": false, "text": "<p>I prefer using <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/preferences/overview.html\" rel=\"nofollow\">java.util.prefs.Preferences</a> class.</p>\n\n<p>A simple example would be </p>\n\n<pre><code>// Write Operation\nPreferences p = Preferences.userRoot();\np.put(\"key\",\"value\"); \n// also there are various other methods such as putByteArray(), putDouble() etc.\np.flush();\n//Read Operation\nPreferences p = Preferences.userRoot();\nString value = p.get(\"key\");\n</code></pre>\n" }, { "answer_id": 6163701, "author": "David", "author_id": 656963, "author_profile": "https://Stackoverflow.com/users/656963", "pm_score": 8, "selected": false, "text": "<p>I know this question is old, but it is the first search result on google to \"java read/write to registry\". Recently I found this amazing piece of code which:</p>\n\n<ul>\n<li>Can read/write to ANY part of the registry. </li>\n<li>DOES NOT USE JNI.</li>\n<li>DOES NOT USE ANY 3rd PARTY/EXTERNAL APPLICATIONS TO WORK.</li>\n<li>DOES NOT USE THE WINDOWS API (directly)</li>\n</ul>\n\n<p>This is pure, Java code.</p>\n\n<p>It uses reflection to work, by actually accessing the private methods in the <code>java.util.prefs.Preferences</code> class. The internals of this class are complicated, but the class itself is very easy to use.</p>\n\n<p>For example, the following code obtains the exact windows distribution <strong>from the registry</strong>:</p>\n\n<pre><code>String value = WinRegistry.readString (\n WinRegistry.HKEY_LOCAL_MACHINE, //HKEY\n \"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\", //Key\n \"ProductName\"); //ValueName\n System.out.println(\"Windows Distribution = \" + value); \n</code></pre>\n\n<p>Here is the original class. Just copy paste it and it should work:</p>\n\n<pre><code>import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n public static final int HKEY_CURRENT_USER = 0x80000001;\n public static final int HKEY_LOCAL_MACHINE = 0x80000002;\n public static final int REG_SUCCESS = 0;\n public static final int REG_NOTFOUND = 2;\n public static final int REG_ACCESSDENIED = 5;\n\n private static final int KEY_ALL_ACCESS = 0xf003f;\n private static final int KEY_READ = 0x20019;\n private static final Preferences userRoot = Preferences.userRoot();\n private static final Preferences systemRoot = Preferences.systemRoot();\n private static final Class&lt;? extends Preferences&gt; userClass = userRoot.getClass();\n private static final Method regOpenKey;\n private static final Method regCloseKey;\n private static final Method regQueryValueEx;\n private static final Method regEnumValue;\n private static final Method regQueryInfoKey;\n private static final Method regEnumKeyEx;\n private static final Method regCreateKeyEx;\n private static final Method regSetValueEx;\n private static final Method regDeleteKey;\n private static final Method regDeleteValue;\n\n static {\n try {\n regOpenKey = userClass.getDeclaredMethod(\"WindowsRegOpenKey\",\n new Class[] { int.class, byte[].class, int.class });\n regOpenKey.setAccessible(true);\n regCloseKey = userClass.getDeclaredMethod(\"WindowsRegCloseKey\",\n new Class[] { int.class });\n regCloseKey.setAccessible(true);\n regQueryValueEx = userClass.getDeclaredMethod(\"WindowsRegQueryValueEx\",\n new Class[] { int.class, byte[].class });\n regQueryValueEx.setAccessible(true);\n regEnumValue = userClass.getDeclaredMethod(\"WindowsRegEnumValue\",\n new Class[] { int.class, int.class, int.class });\n regEnumValue.setAccessible(true);\n regQueryInfoKey = userClass.getDeclaredMethod(\"WindowsRegQueryInfoKey1\",\n new Class[] { int.class });\n regQueryInfoKey.setAccessible(true);\n regEnumKeyEx = userClass.getDeclaredMethod( \n \"WindowsRegEnumKeyEx\", new Class[] { int.class, int.class, \n int.class }); \n regEnumKeyEx.setAccessible(true);\n regCreateKeyEx = userClass.getDeclaredMethod( \n \"WindowsRegCreateKeyEx\", new Class[] { int.class, \n byte[].class }); \n regCreateKeyEx.setAccessible(true); \n regSetValueEx = userClass.getDeclaredMethod( \n \"WindowsRegSetValueEx\", new Class[] { int.class, \n byte[].class, byte[].class }); \n regSetValueEx.setAccessible(true); \n regDeleteValue = userClass.getDeclaredMethod( \n \"WindowsRegDeleteValue\", new Class[] { int.class, \n byte[].class }); \n regDeleteValue.setAccessible(true); \n regDeleteKey = userClass.getDeclaredMethod( \n \"WindowsRegDeleteKey\", new Class[] { int.class, \n byte[].class }); \n regDeleteKey.setAccessible(true); \n }\n catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n private WinRegistry() { }\n\n /**\n * Read a value from key and value name\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @param valueName\n * @return the value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static String readString(int hkey, String key, String valueName) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readString(systemRoot, hkey, key, valueName);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readString(userRoot, hkey, key, valueName);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read value(s) and value name(s) form given key \n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @return the value name(s) plus the value(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static Map&lt;String, String&gt; readStringValues(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readStringValues(systemRoot, hkey, key);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readStringValues(userRoot, hkey, key);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read the value name(s) from a given key\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @return the value name(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static List&lt;String&gt; readStringSubKeys(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readStringSubKeys(systemRoot, hkey, key);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readStringSubKeys(userRoot, hkey, key);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Create a key\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void createKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int [] ret;\n if (hkey == HKEY_LOCAL_MACHINE) {\n ret = createKey(systemRoot, hkey, key);\n regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });\n }\n else if (hkey == HKEY_CURRENT_USER) {\n ret = createKey(userRoot, hkey, key);\n regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n if (ret[1] != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + ret[1] + \" key=\" + key);\n }\n }\n\n /**\n * Write a value in a given key/value name\n * @param hkey\n * @param key\n * @param valueName\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void writeStringValue\n (int hkey, String key, String valueName, String value) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n writeStringValue(systemRoot, hkey, key, valueName, value);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n writeStringValue(userRoot, hkey, key, valueName, value);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Delete a given key\n * @param hkey\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE) {\n rc = deleteKey(systemRoot, hkey, key);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n rc = deleteKey(userRoot, hkey, key);\n }\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key);\n }\n }\n\n /**\n * delete a value from a given key/value name\n * @param hkey\n * @param key\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteValue(int hkey, String key, String value) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE) {\n rc = deleteValue(systemRoot, hkey, key, value);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n rc = deleteValue(userRoot, hkey, key, value);\n }\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key + \" value=\" + value);\n }\n }\n\n // =====================\n\n private static int deleteValue\n (Preferences root, int hkey, String key, String value)\n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });\n if (handles[1] != REG_SUCCESS) {\n return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED\n }\n int rc =((Integer) regDeleteValue.invoke(root, \n new Object[] { \n new Integer(handles[0]), toCstr(value) \n })).intValue();\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return rc;\n }\n\n private static int deleteKey(Preferences root, int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int rc =((Integer) regDeleteKey.invoke(root, \n new Object[] { new Integer(hkey), toCstr(key) })).intValue();\n return rc; // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n }\n\n private static String readString(Preferences root, int hkey, String key, String value)\n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ) });\n if (handles[1] != REG_SUCCESS) {\n return null; \n }\n byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {\n new Integer(handles[0]), toCstr(value) });\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return (valb != null ? new String(valb).trim() : null);\n }\n\n private static Map&lt;String,String&gt; readStringValues\n (Preferences root, int hkey, String key)\n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n HashMap&lt;String, String&gt; results = new HashMap&lt;String,String&gt;();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ) });\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root,\n new Object[] { new Integer(handles[0]) });\n\n int count = info[0]; // count \n int maxlen = info[3]; // value length max\n for(int index=0; index&lt;count; index++) {\n byte[] name = (byte[]) regEnumValue.invoke(root, new Object[] {\n new Integer\n (handles[0]), new Integer(index), new Integer(maxlen + 1)});\n String value = readString(hkey, key, new String(name));\n results.put(new String(name).trim(), value);\n }\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return results;\n }\n\n private static List&lt;String&gt; readStringSubKeys\n (Preferences root, int hkey, String key)\n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ) \n });\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root,\n new Object[] { new Integer(handles[0]) });\n\n int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio\n int maxlen = info[3]; // value length max\n for(int index=0; index&lt;count; index++) {\n byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[] {\n new Integer\n (handles[0]), new Integer(index), new Integer(maxlen + 1)\n });\n results.add(new String(name).trim());\n }\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return results;\n }\n\n private static int [] createKey(Preferences root, int hkey, String key)\n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n return (int[]) regCreateKeyEx.invoke(root,\n new Object[] { new Integer(hkey), toCstr(key) });\n }\n\n private static void writeStringValue \n (Preferences root, int hkey, String key, String valueName, String value) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });\n\n regSetValueEx.invoke(root, \n new Object[] { \n new Integer(handles[0]), toCstr(valueName), toCstr(value) \n }); \n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n }\n\n // utility\n private static byte[] toCstr(String str) {\n byte[] result = new byte[str.length() + 1];\n\n for (int i = 0; i &lt; str.length(); i++) {\n result[i] = (byte) str.charAt(i);\n }\n result[str.length()] = 0;\n return result;\n }\n}\n</code></pre>\n\n<p>Original Author: Apache.</p>\n\n<p>Library Source: <a href=\"https://github.com/apache/npanday/tree/trunk/components/dotnet-registry/src/main/java/npanday/registry\" rel=\"noreferrer\">https://github.com/apache/npanday/tree/trunk/components/dotnet-registry/src/main/java/npanday/registry</a></p>\n" }, { "answer_id": 6287763, "author": "John McCarthy", "author_id": 277307, "author_profile": "https://Stackoverflow.com/users/277307", "pm_score": 6, "selected": false, "text": "<p><a href=\"https://github.com/java-native-access/jna\" rel=\"noreferrer\" title=\"JNA Home\">Java Native Access (JNA)</a> is an excellent project for working with native libraries and has support for the Windows registry in the platform library (platform.jar) through <a href=\"https://java-native-access.github.io/jna/5.4.0/javadoc/com/sun/jna/platform/win32/Advapi32Util.html\" rel=\"noreferrer\" title=\"JNA Advapi32Util javadoc\">Advapi32Util</a> and <a href=\"https://java-native-access.github.io/jna/5.4.0/javadoc/com/sun/jna/platform/win32/Advapi32.html\" rel=\"noreferrer\" title=\"JNA Advapi32 javadoc\">Advapi32</a>.</p>\n\n<p><strong>Update:</strong> Here's a snippet with some examples of how easy it is to use JNA to work with the Windows registry using JNA 3.4.1,</p>\n\n<pre><code>import com.sun.jna.platform.win32.Advapi32Util;\nimport com.sun.jna.platform.win32.WinReg;\n\npublic class WindowsRegistrySnippet {\n public static void main(String[] args) {\n // Read a string\n String productName = Advapi32Util.registryGetStringValue(\n WinReg.HKEY_LOCAL_MACHINE, \"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\", \"ProductName\");\n System.out.printf(\"Product Name: %s\\n\", productName);\n\n // Read an int (&amp; 0xFFFFFFFFL for large unsigned int)\n int timeout = Advapi32Util.registryGetIntValue(\n WinReg.HKEY_LOCAL_MACHINE, \"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Windows\", \"ShutdownWarningDialogTimeout\");\n System.out.printf(\"Shutdown Warning Dialog Timeout: %d (%d as unsigned long)\\n\", timeout, timeout &amp; 0xFFFFFFFFL);\n\n // Create a key and write a string\n Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, \"SOFTWARE\\\\StackOverflow\");\n Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER, \"SOFTWARE\\\\StackOverflow\", \"url\", \"http://stackoverflow.com/a/6287763/277307\");\n\n // Delete a key\n Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, \"SOFTWARE\\\\StackOverflow\");\n }\n}\n</code></pre>\n" }, { "answer_id": 8955801, "author": "Johnydep", "author_id": 750965, "author_profile": "https://Stackoverflow.com/users/750965", "pm_score": 0, "selected": false, "text": "<p>Although this is pretty old, but i guess the better utility to use on windows platform would be <code>regini</code> :</p>\n\n<p>A single call to process: </p>\n\n<pre><code>Runtime.getRuntime().exec(\"regini &lt;your script file abs path here&gt;\");\n</code></pre>\n\n<p>will do all the magic. I have tried it, while making jar as windows service using servany.exe which requires changes to made in registry for adding javaw.exe arguments and it works perfectly. You might want to read this: <a href=\"http://support.microsoft.com/kb/264584\" rel=\"nofollow\">http://support.microsoft.com/kb/264584</a></p>\n" }, { "answer_id": 11854901, "author": "Petrucio", "author_id": 828681, "author_profile": "https://Stackoverflow.com/users/828681", "pm_score": 5, "selected": false, "text": "<p>I've incremented the Pure java code originally posted by David to allow acessing the 32-bits section of the registry from a 64-bit JVM, and vice-versa. I don't think any of the other answers address this.</p>\n\n<p>Here it is:</p>\n\n<pre><code>/**\n * Pure Java Windows Registry access.\n * Modified by petrucio@stackoverflow(828681) to add support for\n * reading (and writing but not creating/deleting keys) the 32-bits\n * registry view from a 64-bits JVM (KEY_WOW64_32KEY)\n * and 64-bits view from a 32-bits JVM (KEY_WOW64_64KEY).\n *****************************************************************************/\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n public static final int HKEY_CURRENT_USER = 0x80000001;\n public static final int HKEY_LOCAL_MACHINE = 0x80000002;\n public static final int REG_SUCCESS = 0;\n public static final int REG_NOTFOUND = 2;\n public static final int REG_ACCESSDENIED = 5;\n\n public static final int KEY_WOW64_32KEY = 0x0200;\n public static final int KEY_WOW64_64KEY = 0x0100;\n\n private static final int KEY_ALL_ACCESS = 0xf003f;\n private static final int KEY_READ = 0x20019;\n private static Preferences userRoot = Preferences.userRoot();\n private static Preferences systemRoot = Preferences.systemRoot();\n private static Class&lt;? extends Preferences&gt; userClass = userRoot.getClass();\n private static Method regOpenKey = null;\n private static Method regCloseKey = null;\n private static Method regQueryValueEx = null;\n private static Method regEnumValue = null;\n private static Method regQueryInfoKey = null;\n private static Method regEnumKeyEx = null;\n private static Method regCreateKeyEx = null;\n private static Method regSetValueEx = null;\n private static Method regDeleteKey = null;\n private static Method regDeleteValue = null;\n\n static {\n try {\n regOpenKey = userClass.getDeclaredMethod(\"WindowsRegOpenKey\", new Class[] { int.class, byte[].class, int.class });\n regOpenKey.setAccessible(true);\n regCloseKey = userClass.getDeclaredMethod(\"WindowsRegCloseKey\", new Class[] { int.class });\n regCloseKey.setAccessible(true);\n regQueryValueEx= userClass.getDeclaredMethod(\"WindowsRegQueryValueEx\",new Class[] { int.class, byte[].class });\n regQueryValueEx.setAccessible(true);\n regEnumValue = userClass.getDeclaredMethod(\"WindowsRegEnumValue\", new Class[] { int.class, int.class, int.class });\n regEnumValue.setAccessible(true);\n regQueryInfoKey=userClass.getDeclaredMethod(\"WindowsRegQueryInfoKey1\",new Class[] { int.class });\n regQueryInfoKey.setAccessible(true);\n regEnumKeyEx = userClass.getDeclaredMethod(\"WindowsRegEnumKeyEx\", new Class[] { int.class, int.class, int.class }); \n regEnumKeyEx.setAccessible(true);\n regCreateKeyEx = userClass.getDeclaredMethod(\"WindowsRegCreateKeyEx\", new Class[] { int.class, byte[].class });\n regCreateKeyEx.setAccessible(true); \n regSetValueEx = userClass.getDeclaredMethod(\"WindowsRegSetValueEx\", new Class[] { int.class, byte[].class, byte[].class }); \n regSetValueEx.setAccessible(true); \n regDeleteValue = userClass.getDeclaredMethod(\"WindowsRegDeleteValue\", new Class[] { int.class, byte[].class }); \n regDeleteValue.setAccessible(true); \n regDeleteKey = userClass.getDeclaredMethod(\"WindowsRegDeleteKey\", new Class[] { int.class, byte[].class }); \n regDeleteKey.setAccessible(true); \n }\n catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n private WinRegistry() { }\n\n /**\n * Read a value from key and value name\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @param valueName\n * @param wow64 0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n * or KEY_WOW64_32KEY to force access to 32-bit registry view,\n * or KEY_WOW64_64KEY to force access to 64-bit registry view\n * @return the value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static String readString(int hkey, String key, String valueName, int wow64) \n throws IllegalArgumentException, IllegalAccessException,\n InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readString(systemRoot, hkey, key, valueName, wow64);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readString(userRoot, hkey, key, valueName, wow64);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read value(s) and value name(s) form given key \n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @param wow64 0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n * or KEY_WOW64_32KEY to force access to 32-bit registry view,\n * or KEY_WOW64_64KEY to force access to 64-bit registry view\n * @return the value name(s) plus the value(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static Map&lt;String, String&gt; readStringValues(int hkey, String key, int wow64) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readStringValues(systemRoot, hkey, key, wow64);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readStringValues(userRoot, hkey, key, wow64);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read the value name(s) from a given key\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @param wow64 0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n * or KEY_WOW64_32KEY to force access to 32-bit registry view,\n * or KEY_WOW64_64KEY to force access to 64-bit registry view\n * @return the value name(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static List&lt;String&gt; readStringSubKeys(int hkey, String key, int wow64) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n return readStringSubKeys(systemRoot, hkey, key, wow64);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n return readStringSubKeys(userRoot, hkey, key, wow64);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Create a key\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void createKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int [] ret;\n if (hkey == HKEY_LOCAL_MACHINE) {\n ret = createKey(systemRoot, hkey, key);\n regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });\n }\n else if (hkey == HKEY_CURRENT_USER) {\n ret = createKey(userRoot, hkey, key);\n regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n if (ret[1] != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + ret[1] + \" key=\" + key);\n }\n }\n\n /**\n * Write a value in a given key/value name\n * @param hkey\n * @param key\n * @param valueName\n * @param value\n * @param wow64 0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n * or KEY_WOW64_32KEY to force access to 32-bit registry view,\n * or KEY_WOW64_64KEY to force access to 64-bit registry view\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void writeStringValue\n (int hkey, String key, String valueName, String value, int wow64) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n if (hkey == HKEY_LOCAL_MACHINE) {\n writeStringValue(systemRoot, hkey, key, valueName, value, wow64);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n writeStringValue(userRoot, hkey, key, valueName, value, wow64);\n }\n else {\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Delete a given key\n * @param hkey\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE) {\n rc = deleteKey(systemRoot, hkey, key);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n rc = deleteKey(userRoot, hkey, key);\n }\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key);\n }\n }\n\n /**\n * delete a value from a given key/value name\n * @param hkey\n * @param key\n * @param value\n * @param wow64 0 for standard registry access (32-bits for 32-bit app, 64-bits for 64-bits app)\n * or KEY_WOW64_32KEY to force access to 32-bit registry view,\n * or KEY_WOW64_64KEY to force access to 64-bit registry view\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteValue(int hkey, String key, String value, int wow64) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE) {\n rc = deleteValue(systemRoot, hkey, key, value, wow64);\n }\n else if (hkey == HKEY_CURRENT_USER) {\n rc = deleteValue(userRoot, hkey, key, value, wow64);\n }\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key + \" value=\" + value);\n }\n }\n\n //========================================================================\n private static int deleteValue(Preferences root, int hkey, String key, String value, int wow64)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS | wow64)\n });\n if (handles[1] != REG_SUCCESS) {\n return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED\n }\n int rc =((Integer) regDeleteValue.invoke(root, new Object[] { \n new Integer(handles[0]), toCstr(value) \n })).intValue();\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return rc;\n }\n\n //========================================================================\n private static int deleteKey(Preferences root, int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int rc =((Integer) regDeleteKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key)\n })).intValue();\n return rc; // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n }\n\n //========================================================================\n private static String readString(Preferences root, int hkey, String key, String value, int wow64)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ | wow64)\n });\n if (handles[1] != REG_SUCCESS) {\n return null; \n }\n byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {\n new Integer(handles[0]), toCstr(value)\n });\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return (valb != null ? new String(valb).trim() : null);\n }\n\n //========================================================================\n private static Map&lt;String,String&gt; readStringValues(Preferences root, int hkey, String key, int wow64)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n HashMap&lt;String, String&gt; results = new HashMap&lt;String,String&gt;();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ | wow64)\n });\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {\n new Integer(handles[0])\n });\n\n int count = info[2]; // count \n int maxlen = info[3]; // value length max\n for(int index=0; index&lt;count; index++) {\n byte[] name = (byte[]) regEnumValue.invoke(root, new Object[] {\n new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)\n });\n String value = readString(hkey, key, new String(name), wow64);\n results.put(new String(name).trim(), value);\n }\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return results;\n }\n\n //========================================================================\n private static List&lt;String&gt; readStringSubKeys(Preferences root, int hkey, String key, int wow64)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_READ | wow64) \n });\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {\n new Integer(handles[0])\n });\n\n int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio\n int maxlen = info[3]; // value length max\n for(int index=0; index&lt;count; index++) {\n byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[] {\n new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)\n });\n results.add(new String(name).trim());\n }\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n return results;\n }\n\n //========================================================================\n private static int [] createKey(Preferences root, int hkey, String key)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n return (int[]) regCreateKeyEx.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key)\n });\n }\n\n //========================================================================\n private static void writeStringValue(Preferences root, int hkey, String key, String valueName, String value, int wow64)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException \n {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {\n new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS | wow64)\n });\n regSetValueEx.invoke(root, new Object[] { \n new Integer(handles[0]), toCstr(valueName), toCstr(value) \n }); \n regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });\n }\n\n //========================================================================\n // utility\n private static byte[] toCstr(String str) {\n byte[] result = new byte[str.length() + 1];\n\n for (int i = 0; i &lt; str.length(); i++) {\n result[i] = (byte) str.charAt(i);\n }\n result[str.length()] = 0;\n return result;\n }\n}\n</code></pre>\n" }, { "answer_id": 15689078, "author": "Ryan", "author_id": 656193, "author_profile": "https://Stackoverflow.com/users/656193", "pm_score": 2, "selected": false, "text": "<p>Yet another library...</p>\n\n<p><a href=\"https://code.google.com/p/java-registry/\" rel=\"nofollow\">https://code.google.com/p/java-registry/</a></p>\n\n<p>This one launches reg.exe under the covers, reading/writing to temporary files. I didn't end up using it, but it looks like a pretty comprehensive implementation. If I did use it, I might dive in and add some better management of the child processes.</p>\n" }, { "answer_id": 17310303, "author": "kevinarpe", "author_id": 257299, "author_profile": "https://Stackoverflow.com/users/257299", "pm_score": 2, "selected": false, "text": "<p>My previous edit to @David's answer was rejected. Here is some useful information about it.</p>\n\n<p>This \"magic\" works because Sun implements the <code>Preferences</code> class for Windows as part of JDK, but it is <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html\" rel=\"nofollow\">package private</a>. Parts of the implementation use JNI.</p>\n\n<ul>\n<li>Package private class from JDK <code>java.util.prefs.WindowsPreferences</code>: <a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/prefs/WindowsPreferences.java\" rel=\"nofollow\">http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/prefs/WindowsPreferences.java</a></li>\n<li>JNI: <a href=\"http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/src/windows/native/java/util/WindowsPreferences.c\" rel=\"nofollow\">http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/src/windows/native/java/util/WindowsPreferences.c</a></li>\n</ul>\n\n<p>The implementation is selected at runtime using a factory method here: <a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/prefs/Preferences.java#Preferences.0factory\" rel=\"nofollow\">http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/prefs/Preferences.java#Preferences.0factory</a></p>\n\n<p>The real question: Why doesn't OpenJDK expose this API to public?</p>\n" }, { "answer_id": 18103763, "author": "TacB0sS", "author_id": 348189, "author_profile": "https://Stackoverflow.com/users/348189", "pm_score": 0, "selected": false, "text": "<p>This was crazy... I took the code from one of the posts here, failed to see there were 18 more comments in which one stated that it does not read a dword value...</p>\n\n<p>In any case, I've refactored the hell of that code into something with less ifs and methods... </p>\n\n<p>The Enum could be refined a bit, but as soon as I've fought my way to read a numeric value or byte array and failed, I've given up...</p>\n\n<p>So here it is:</p>\n\n<pre><code>package com.nu.art.software.utils;\n\n\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.prefs.Preferences;\n\n/**\n *\n * @author TacB0sS\n */\npublic class WinRegistry_TacB0sS {\n\n public static final class RegistryException\n extends Exception {\n\n private static final long serialVersionUID = -8799947496460994651L;\n\n public RegistryException(String message, Throwable e) {\n super(message, e);\n }\n\n public RegistryException(String message) {\n super(message);\n }\n\n\n }\n\n public static final int KEY_WOW64_32KEY = 0x0200;\n\n public static final int KEY_WOW64_64KEY = 0x0100;\n\n public static final int REG_SUCCESS = 0;\n\n public static final int REG_NOTFOUND = 2;\n\n public static final int REG_ACCESSDENIED = 5;\n\n private static final int KEY_ALL_ACCESS = 0xf003f;\n\n private static final int KEY_READ = 0x20019;\n\n public enum WinRegistryKey {\n User(Preferences.userRoot(), 0x80000001), ;\n\n // System(Preferences.systemRoot(), 0x80000002);\n\n private final Preferences preferencesRoot;\n\n private final Integer key;\n\n private WinRegistryKey(Preferences preferencesRoot, int key) {\n this.preferencesRoot = preferencesRoot;\n this.key = key;\n }\n }\n\n private enum WinRegistryMethod {\n OpenKey(\"WindowsRegOpenKey\", int.class, byte[].class, int.class) {\n\n @Override\n protected void verifyReturnValue(Object retValue)\n throws RegistryException {\n int[] retVal = (int[]) retValue;\n if (retVal[1] != REG_SUCCESS)\n throw new RegistryException(\"Action Failed, Return Code: \" + retVal[1]);\n }\n },\n CreateKeyEx(\"WindowsRegCreateKeyEx\", int.class, byte[].class) {\n\n @Override\n protected void verifyReturnValue(Object retValue)\n throws RegistryException {\n int[] retVal = (int[]) retValue;\n if (retVal[1] != REG_SUCCESS)\n throw new RegistryException(\"Action Failed, Return Code: \" + retVal[1]);\n }\n },\n DeleteKey(\"WindowsRegDeleteKey\", int.class, byte[].class) {\n\n @Override\n protected void verifyReturnValue(Object retValue)\n throws RegistryException {\n int retVal = ((Integer) retValue).intValue();\n if (retVal != REG_SUCCESS)\n throw new RegistryException(\"Action Failed, Return Code: \" + retVal);\n }\n },\n DeleteValue(\"WindowsRegDeleteValue\", int.class, byte[].class) {\n\n @Override\n protected void verifyReturnValue(Object retValue)\n throws RegistryException {\n int retVal = ((Integer) retValue).intValue();\n if (retVal != REG_SUCCESS)\n throw new RegistryException(\"Action Failed, Return Code: \" + retVal);\n }\n },\n CloseKey(\"WindowsRegCloseKey\", int.class),\n QueryValueEx(\"WindowsRegQueryValueEx\", int.class, byte[].class),\n EnumKeyEx(\"WindowsRegEnumKeyEx\", int.class, int.class, int.class),\n EnumValue(\"WindowsRegEnumValue\", int.class, int.class, int.class),\n QueryInfoKey(\"WindowsRegQueryInfoKey\", int.class),\n SetValueEx(\"WindowsRegSetValueEx\", int.class, byte[].class, byte[].class);\n\n private Method method;\n\n private WinRegistryMethod(String methodName, Class&lt;?&gt;... classes) {\n // WinRegistryKey.User.preferencesRoot.getClass().getMDeclaredMethods()\n try {\n method = WinRegistryKey.User.preferencesRoot.getClass().getDeclaredMethod(methodName, classes);\n } catch (Exception e) {\n System.err.println(\"Error\");\n System.err.println(e);\n }\n method.setAccessible(true);\n }\n\n public Object invoke(Preferences root, Object... objects)\n throws RegistryException {\n Object retValue;\n try {\n retValue = method.invoke(root, objects);\n verifyReturnValue(retValue);\n } catch (Throwable e) {\n String params = \"\";\n if (objects.length &gt; 0) {\n params = objects[0].toString();\n for (int i = 1; i &lt; objects.length; i++) {\n params += \", \" + objects[i];\n }\n }\n throw new RegistryException(\"Error invoking method: \" + method + \", with params: (\" + params + \")\", e);\n }\n return retValue;\n }\n\n protected void verifyReturnValue(Object retValue)\n throws RegistryException {}\n }\n\n private WinRegistry_TacB0sS() {}\n\n public static String readString(WinRegistryKey regKey, String key, String valueName)\n throws RegistryException {\n int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n new Integer(KEY_READ)))[0];\n\n byte[] retValue = (byte[]) WinRegistryMethod.QueryValueEx.invoke(regKey.preferencesRoot, retVal,\n toCstr(valueName));\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n\n /*\n * Should this return an Empty String.\n */\n return (retValue != null ? new String(retValue).trim() : null);\n }\n\n public static Map&lt;String, String&gt; readStringValues(WinRegistryKey regKey, String key)\n throws RegistryException {\n HashMap&lt;String, String&gt; results = new HashMap&lt;String, String&gt;();\n int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n new Integer(KEY_READ)))[0];\n\n int[] info = (int[]) WinRegistryMethod.QueryInfoKey.invoke(regKey.preferencesRoot, retVal);\n\n int count = info[2]; // count\n int maxlen = info[3]; // value length max\n for (int index = 0; index &lt; count; index++) {\n byte[] name = (byte[]) WinRegistryMethod.EnumValue.invoke(regKey.preferencesRoot, retVal,\n new Integer(index), new Integer(maxlen + 1));\n String value = readString(regKey, key, new String(name));\n results.put(new String(name).trim(), value);\n }\n\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n return results;\n }\n\n public static List&lt;String&gt; readStringSubKeys(WinRegistryKey regKey, String key)\n throws RegistryException {\n List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n new Integer(KEY_READ)))[0];\n\n int[] info = (int[]) WinRegistryMethod.QueryInfoKey.invoke(regKey.preferencesRoot, retVal);\n\n int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by\n // Petrucio\n int maxlen = info[3]; // value length max\n for (int index = 0; index &lt; count; index++) {\n byte[] name = (byte[]) WinRegistryMethod.EnumValue.invoke(regKey.preferencesRoot, retVal,\n new Integer(index), new Integer(maxlen + 1));\n results.add(new String(name).trim());\n }\n\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n return results;\n }\n\n public static void createKey(WinRegistryKey regKey, String key)\n throws RegistryException {\n int[] retVal = (int[]) WinRegistryMethod.CreateKeyEx.invoke(regKey.preferencesRoot, regKey.key, toCstr(key));\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal[0]);\n }\n\n public static void writeStringValue(WinRegistryKey regKey, String key, String valueName, String value)\n throws RegistryException {\n int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n new Integer(KEY_ALL_ACCESS)))[0];\n\n WinRegistryMethod.SetValueEx.invoke(regKey.preferencesRoot, retVal, toCstr(valueName), toCstr(value));\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n }\n\n public static void deleteKey(WinRegistryKey regKey, String key)\n throws RegistryException {\n WinRegistryMethod.DeleteKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key));\n }\n\n public static void deleteValue(WinRegistryKey regKey, String key, String value)\n throws RegistryException {\n int retVal = ((int[]) WinRegistryMethod.OpenKey.invoke(regKey.preferencesRoot, regKey.key, toCstr(key),\n new Integer(KEY_ALL_ACCESS)))[0];\n WinRegistryMethod.DeleteValue.invoke(regKey.preferencesRoot, retVal, toCstr(value));\n WinRegistryMethod.CloseKey.invoke(regKey.preferencesRoot, retVal);\n }\n\n // utility\n private static byte[] toCstr(String str) {\n byte[] result = new byte[str.length() + 1];\n\n for (int i = 0; i &lt; str.length(); i++) {\n result[i] = (byte) str.charAt(i);\n }\n result[str.length()] = '\\0';\n return result;\n }\n}\n</code></pre>\n\n<p><strong>NOTE: THIS DOES NOT READ ANYTHING ELSE BUT STRINGS!!!!!</strong></p>\n" }, { "answer_id": 22589715, "author": "Ernestas Gruodis", "author_id": 2111085, "author_profile": "https://Stackoverflow.com/users/2111085", "pm_score": -1, "selected": false, "text": "<p>In response to David <a href=\"https://stackoverflow.com/a/6163701/2111085\">answer</a> - I would do some enhancements:</p>\n\n<pre><code>import java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n\n public static final int HKEY_CURRENT_USER = 0x80000001,\n HKEY_LOCAL_MACHINE = 0x80000002,\n REG_SUCCESS = 0,\n REG_NOTFOUND = 2,\n REG_ACCESSDENIED = 5,\n KEY_ALL_ACCESS = 0xf003f,\n KEY_READ = 0x20019;\n private static final Preferences userRoot = Preferences.userRoot(),\n systemRoot = Preferences.systemRoot();\n private static final Class&lt;? extends Preferences&gt; userClass = userRoot.getClass();\n private static Method regOpenKey,\n regCloseKey,\n regQueryValueEx,\n regEnumValue,\n regQueryInfoKey,\n regEnumKeyEx,\n regCreateKeyEx,\n regSetValueEx,\n regDeleteKey,\n regDeleteValue;\n\n static {\n try {\n (regOpenKey = userClass.getDeclaredMethod(\"WindowsRegOpenKey\", new Class[]{int.class, byte[].class, int.class})).setAccessible(true);\n (regCloseKey = userClass.getDeclaredMethod(\"WindowsRegCloseKey\", new Class[]{int.class})).setAccessible(true);\n (regQueryValueEx = userClass.getDeclaredMethod(\"WindowsRegQueryValueEx\", new Class[]{int.class, byte[].class})).setAccessible(true);\n (regEnumValue = userClass.getDeclaredMethod(\"WindowsRegEnumValue\", new Class[]{int.class, int.class, int.class})).setAccessible(true);\n (regQueryInfoKey = userClass.getDeclaredMethod(\"WindowsRegQueryInfoKey1\", new Class[]{int.class})).setAccessible(true);\n (regEnumKeyEx = userClass.getDeclaredMethod(\"WindowsRegEnumKeyEx\", new Class[]{int.class, int.class, int.class})).setAccessible(true);\n (regCreateKeyEx = userClass.getDeclaredMethod(\"WindowsRegCreateKeyEx\", new Class[]{int.class, byte[].class})).setAccessible(true);\n (regSetValueEx = userClass.getDeclaredMethod(\"WindowsRegSetValueEx\", new Class[]{int.class, byte[].class, byte[].class})).setAccessible(true);\n (regDeleteValue = userClass.getDeclaredMethod(\"WindowsRegDeleteValue\", new Class[]{int.class, byte[].class})).setAccessible(true);\n (regDeleteKey = userClass.getDeclaredMethod(\"WindowsRegDeleteKey\", new Class[]{int.class, byte[].class})).setAccessible(true);\n } catch (NoSuchMethodException | SecurityException ex) {\n Logger.getLogger(WinRegistry.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n\n /**\n * Read a value from key and value name\n *\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @param valueName\n * @return the value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static String readString(int hkey, String key, String valueName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n return readString(systemRoot, hkey, key, valueName);\n case HKEY_CURRENT_USER:\n return readString(userRoot, hkey, key, valueName);\n default:\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read value(s) and value name(s) form given key\n *\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @return the value name(s) plus the value(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static Map&lt;String, String&gt; readStringValues(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n return readStringValues(systemRoot, hkey, key);\n case HKEY_CURRENT_USER:\n return readStringValues(userRoot, hkey, key);\n default:\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Read the value name(s) from a given key\n *\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @return the value name(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static List&lt;String&gt; readStringSubKeys(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n return readStringSubKeys(systemRoot, hkey, key);\n case HKEY_CURRENT_USER:\n return readStringSubKeys(userRoot, hkey, key);\n default:\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Create a key\n *\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void createKey(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int[] ret;\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n ret = createKey(systemRoot, hkey, key);\n regCloseKey.invoke(systemRoot, new Object[]{ret[0]});\n break;\n case HKEY_CURRENT_USER:\n ret = createKey(userRoot, hkey, key);\n regCloseKey.invoke(userRoot, new Object[]{ret[0]});\n break;\n default:\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n\n if (ret[1] != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + ret[1] + \" key=\" + key);\n }\n }\n\n /**\n * Write a value in a given key/value name\n *\n * @param hkey\n * @param key\n * @param valueName\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void writeStringValue(int hkey, String key, String valueName, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n writeStringValue(systemRoot, hkey, key, valueName, value);\n break;\n case HKEY_CURRENT_USER:\n writeStringValue(userRoot, hkey, key, valueName, value);\n break;\n default:\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n }\n\n /**\n * Delete a given key\n *\n * @param hkey\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteKey(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int rc = -1;\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n rc = deleteKey(systemRoot, hkey, key);\n break;\n case HKEY_CURRENT_USER:\n rc = deleteKey(userRoot, hkey, key);\n }\n\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key);\n }\n }\n\n /**\n * delete a value from a given key/value name\n *\n * @param hkey\n * @param key\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteValue(int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int rc = -1;\n switch (hkey) {\n case HKEY_LOCAL_MACHINE:\n rc = deleteValue(systemRoot, hkey, key, value);\n break;\n case HKEY_CURRENT_USER:\n rc = deleteValue(userRoot, hkey, key, value);\n }\n\n if (rc != REG_SUCCESS) {\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key + \" value=\" + value);\n }\n }\n\n private static int deleteValue(Preferences root, int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_ALL_ACCESS});\n if (handles[1] != REG_SUCCESS) {\n return handles[1];//Can be REG_NOTFOUND, REG_ACCESSDENIED\n }\n int rc = ((Integer) regDeleteValue.invoke(root, new Object[]{handles[0], toCstr(value)}));\n regCloseKey.invoke(root, new Object[]{handles[0]});\n return rc;\n }\n\n private static int deleteKey(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int rc = ((Integer) regDeleteKey.invoke(root, new Object[]{hkey, toCstr(key)}));\n return rc; //Can be REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n }\n\n private static String readString(Preferences root, int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_READ});\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[]{handles[0], toCstr(value)});\n regCloseKey.invoke(root, new Object[]{handles[0]});\n return (valb != null ? new String(valb).trim() : null);\n }\n\n private static Map&lt;String, String&gt; readStringValues(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n HashMap&lt;String, String&gt; results = new HashMap&lt;&gt;();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_READ});\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[]{handles[0]});\n\n int count = info[0]; //Count \n int maxlen = info[3]; //Max value length\n for (int index = 0; index &lt; count; index++) {\n byte[] name = (byte[]) regEnumValue.invoke(root, new Object[]{handles[0], index, maxlen + 1});\n String value = readString(hkey, key, new String(name));\n results.put(new String(name).trim(), value);\n }\n regCloseKey.invoke(root, new Object[]{handles[0]});\n return results;\n }\n\n private static List&lt;String&gt; readStringSubKeys(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n List&lt;String&gt; results = new ArrayList&lt;&gt;();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_READ});\n if (handles[1] != REG_SUCCESS) {\n return null;\n }\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[]{handles[0]});\n\n int count = info[0];//Count\n int maxlen = info[3]; //Max value length\n for (int index = 0; index &lt; count; index++) {\n byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[]{handles[0], index, maxlen + 1});\n results.add(new String(name).trim());\n }\n regCloseKey.invoke(root, new Object[]{handles[0]});\n return results;\n }\n\n private static int[] createKey(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n return (int[]) regCreateKeyEx.invoke(root, new Object[]{hkey, toCstr(key)});\n }\n\n private static void writeStringValue(Preferences root, int hkey, String key, String valueName, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[]{hkey, toCstr(key), KEY_ALL_ACCESS});\n regSetValueEx.invoke(root, new Object[]{handles[0], toCstr(valueName), toCstr(value)});\n regCloseKey.invoke(root, new Object[]{handles[0]});\n }\n\n private static byte[] toCstr(String str) {\n\n byte[] result = new byte[str.length() + 1];\n for (int i = 0; i &lt; str.length(); i++) {\n result[i] = (byte) str.charAt(i);\n }\n result[str.length()] = 0;\n return result;\n }\n}\n</code></pre>\n" }, { "answer_id": 24877559, "author": "Boann", "author_id": 964243, "author_profile": "https://Stackoverflow.com/users/964243", "pm_score": 0, "selected": false, "text": "<p>This uses the same Java internal APIs as in <a href=\"https://stackoverflow.com/a/6163701\">in David's answer</a>, but I've rewritten it completely. It's shorter now and nicer to use. I also added support for HKEY_CLASSES_ROOT and other hives. It still has some of the other limitations though (such as no DWORD support and no Unicode support) which are due to the underlying API and are sadly unavoidable with this approach. Still, if you only need basic string reading/writing and don't want to load a native DLL, it's handy.</p>\n\n<p>I'm sure you can figure out how to use it.</p>\n\n<p>Public domain. Have fun.</p>\n\n<pre><code>import java.util.*;\nimport java.lang.reflect.Method;\n\n/**\n * Simple registry access class implemented using some private APIs\n * in java.util.prefs. It has no other prerequisites.\n */\npublic final class WindowsRegistry {\n /**\n * Tells if the Windows registry functions are available.\n * (They will not be available when not running on Windows, for example.)\n */\n public static boolean isAvailable() {\n return initError == null;\n }\n\n\n\n /** Reads a string value from the given key and value name. */\n public static String readValue(String keyName, String valueName) {\n try (Key key = Key.open(keyName, KEY_READ)) {\n return fromByteArray(invoke(regQueryValueEx, key.handle, toByteArray(valueName)));\n }\n }\n\n\n\n /** Returns a map of all the name-value pairs in the given key. */\n public static Map&lt;String,String&gt; readValues(String keyName) {\n try (Key key = Key.open(keyName, KEY_READ)) {\n int[] info = invoke(regQueryInfoKey, key.handle);\n checkError(info[INFO_ERROR_CODE]);\n int count = info[INFO_COUNT_VALUES];\n int maxlen = info[INFO_MAX_VALUE_LENGTH] + 1;\n Map&lt;String,String&gt; values = new HashMap&lt;&gt;();\n for (int i = 0; i &lt; count; i++) {\n String valueName = fromByteArray(invoke(regEnumValue, key.handle, i, maxlen));\n values.put(valueName, readValue(keyName, valueName));\n }\n return values;\n }\n }\n\n\n\n /** Returns a list of the names of all the subkeys of a key. */\n public static List&lt;String&gt; readSubkeys(String keyName) {\n try (Key key = Key.open(keyName, KEY_READ)) {\n int[] info = invoke(regQueryInfoKey, key.handle);\n checkError(info[INFO_ERROR_CODE]);\n int count = info[INFO_COUNT_KEYS];\n int maxlen = info[INFO_MAX_KEY_LENGTH] + 1;\n List&lt;String&gt; subkeys = new ArrayList&lt;&gt;(count);\n for (int i = 0; i &lt; count; i++) {\n subkeys.add(fromByteArray(invoke(regEnumKeyEx, key.handle, i, maxlen)));\n }\n return subkeys;\n }\n }\n\n\n\n /** Writes a string value with a given key and value name. */\n public static void writeValue(String keyName, String valueName, String value) {\n try (Key key = Key.open(keyName, KEY_WRITE)) {\n checkError(invoke(regSetValueEx, key.handle, toByteArray(valueName), toByteArray(value)));\n }\n }\n\n\n\n /** Deletes a value within a key. */\n public static void deleteValue(String keyName, String valueName) {\n try (Key key = Key.open(keyName, KEY_WRITE)) {\n checkError(invoke(regDeleteValue, key.handle, toByteArray(valueName)));\n }\n }\n\n\n\n /**\n * Deletes a key and all values within it. If the key has subkeys, an\n * \"Access denied\" error will be thrown. Subkeys must be deleted separately.\n */\n public static void deleteKey(String keyName) {\n checkError(invoke(regDeleteKey, keyParts(keyName)));\n }\n\n\n\n /**\n * Creates a key. Parent keys in the path will also be created if necessary.\n * This method returns without error if the key already exists.\n */\n public static void createKey(String keyName) {\n int[] info = invoke(regCreateKeyEx, keyParts(keyName));\n checkError(info[INFO_ERROR_CODE]);\n invoke(regCloseKey, info[INFO_HANDLE]);\n }\n\n\n\n /**\n * The exception type that will be thrown if a registry operation fails.\n */\n public static class RegError extends RuntimeException {\n public RegError(String message, Throwable cause) {\n super(message, cause);\n }\n }\n\n\n\n\n\n // *************\n // PRIVATE STUFF\n // *************\n\n private WindowsRegistry() {}\n\n\n // Map of registry hive names to constants from winreg.h\n private static final Map&lt;String,Integer&gt; hives = new HashMap&lt;&gt;();\n static {\n hives.put(\"HKEY_CLASSES_ROOT\", 0x80000000); hives.put(\"HKCR\", 0x80000000);\n hives.put(\"HKEY_CURRENT_USER\", 0x80000001); hives.put(\"HKCU\", 0x80000001);\n hives.put(\"HKEY_LOCAL_MACHINE\", 0x80000002); hives.put(\"HKLM\", 0x80000002);\n hives.put(\"HKEY_USERS\", 0x80000003); hives.put(\"HKU\", 0x80000003);\n hives.put(\"HKEY_CURRENT_CONFIG\", 0x80000005); hives.put(\"HKCC\", 0x80000005);\n }\n\n\n // Splits a path such as HKEY_LOCAL_MACHINE\\Software\\Microsoft into a pair of\n // values used by the underlying API: An integer hive constant and a byte array\n // of the key path within that hive.\n private static Object[] keyParts(String fullKeyName) {\n int x = fullKeyName.indexOf('\\\\');\n String hiveName = x &gt;= 0 ? fullKeyName.substring(0, x) : fullKeyName;\n String keyName = x &gt;= 0 ? fullKeyName.substring(x + 1) : \"\";\n Integer hkey = hives.get(hiveName);\n if (hkey == null) throw new RegError(\"Unknown registry hive: \" + hiveName, null);\n return new Object[] { hkey, toByteArray(keyName) };\n }\n\n\n // Type encapsulating a native handle to a registry key\n private static class Key implements AutoCloseable {\n final int handle;\n\n private Key(int handle) {\n this.handle = handle;\n }\n\n static Key open(String keyName, int accessMode) {\n Object[] keyParts = keyParts(keyName);\n int[] ret = invoke(regOpenKey, keyParts[0], keyParts[1], accessMode);\n checkError(ret[INFO_ERROR_CODE]);\n return new Key(ret[INFO_HANDLE]);\n }\n\n @Override\n public void close() {\n invoke(regCloseKey, handle);\n }\n }\n\n\n // Array index constants for results of regOpenKey, regCreateKeyEx, and regQueryInfoKey\n private static final int\n INFO_HANDLE = 0,\n INFO_COUNT_KEYS = 0,\n INFO_ERROR_CODE = 1,\n INFO_COUNT_VALUES = 2,\n INFO_MAX_KEY_LENGTH = 3,\n INFO_MAX_VALUE_LENGTH = 4;\n\n\n // Registry access mode constants from winnt.h\n private static final int\n KEY_READ = 0x20019,\n KEY_WRITE = 0x20006;\n\n\n // Error constants from winerror.h\n private static final int\n ERROR_SUCCESS = 0,\n ERROR_FILE_NOT_FOUND = 2,\n ERROR_ACCESS_DENIED = 5;\n\n private static void checkError(int e) {\n if (e == ERROR_SUCCESS) return;\n throw new RegError(\n e == ERROR_FILE_NOT_FOUND ? \"Key not found\" :\n e == ERROR_ACCESS_DENIED ? \"Access denied\" :\n (\"Error number \" + e), null);\n }\n\n\n // Registry access methods in java.util.prefs.WindowsPreferences\n private static final Method\n regOpenKey = getMethod(\"WindowsRegOpenKey\", int.class, byte[].class, int.class),\n regCloseKey = getMethod(\"WindowsRegCloseKey\", int.class),\n regQueryValueEx = getMethod(\"WindowsRegQueryValueEx\", int.class, byte[].class),\n regQueryInfoKey = getMethod(\"WindowsRegQueryInfoKey\", int.class),\n regEnumValue = getMethod(\"WindowsRegEnumValue\", int.class, int.class, int.class),\n regEnumKeyEx = getMethod(\"WindowsRegEnumKeyEx\", int.class, int.class, int.class),\n regSetValueEx = getMethod(\"WindowsRegSetValueEx\", int.class, byte[].class, byte[].class),\n regDeleteValue = getMethod(\"WindowsRegDeleteValue\", int.class, byte[].class),\n regDeleteKey = getMethod(\"WindowsRegDeleteKey\", int.class, byte[].class),\n regCreateKeyEx = getMethod(\"WindowsRegCreateKeyEx\", int.class, byte[].class);\n\n private static Throwable initError;\n\n private static Method getMethod(String methodName, Class&lt;?&gt;... parameterTypes) {\n try {\n Method m = java.util.prefs.Preferences.systemRoot().getClass()\n .getDeclaredMethod(methodName, parameterTypes);\n m.setAccessible(true);\n return m;\n } catch (Throwable t) {\n initError = t;\n return null;\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private static &lt;T&gt; T invoke(Method method, Object... args) {\n if (initError != null)\n throw new RegError(\"Registry methods are not available\", initError);\n try {\n return (T)method.invoke(null, args);\n } catch (Exception e) {\n throw new RegError(null, e);\n }\n }\n\n\n // Conversion of strings to/from null-terminated byte arrays.\n // There is no support for Unicode; sorry, this is a limitation\n // of the underlying methods that Java makes available.\n private static byte[] toByteArray(String str) {\n byte[] bytes = new byte[str.length() + 1];\n for (int i = 0; i &lt; str.length(); i++)\n bytes[i] = (byte)str.charAt(i);\n return bytes;\n }\n\n private static String fromByteArray(byte[] bytes) {\n if (bytes == null) return null;\n char[] chars = new char[bytes.length - 1];\n for (int i = 0; i &lt; chars.length; i++)\n chars[i] = (char)((int)bytes[i] &amp; 0xFF);\n return new String(chars);\n }\n}\n</code></pre>\n\n<p>One day, Java will have a built-in <a href=\"http://openjdk.java.net/jeps/191\" rel=\"nofollow\">foreign function interface</a> for easy access to native APIs, and this sort of hack will be unnecessary.</p>\n" }, { "answer_id": 26097666, "author": "Vipul Paralikar", "author_id": 1677308, "author_profile": "https://Stackoverflow.com/users/1677308", "pm_score": 2, "selected": false, "text": "<p>The <code>java.util.prefs</code> package provides a way for applications to store and retrieve user and system preferences and data configuration. These preference data will be stored persistently in an implementation-dependent backing stored. For example in Windows operating system in will stored in Windows registry.</p>\n\n<p>To write and read these data we use the <code>java.util.prefs.Preferences</code> class. Below code shows how to read and write to the <code>HKCU</code> and <code>HKLM</code> in the registry.</p>\n\n<pre><code>import java.util.prefs.Preferences;\n\npublic class RegistryDemo {\n public static final String PREF_KEY = \"org.username\";\n public static void main(String[] args) {\n //\n // Write Preferences information to HKCU (HKEY_CURRENT_USER),\n // HKCU\\Software\\JavaSoft\\Prefs\\org.username\n //\n Preferences userPref = Preferences.userRoot();\n userPref.put(PREF_KEY, \"xyz\");\n\n //\n // Below we read back the value we've written in the code above.\n //\n System.out.println(\"Preferences = \"\n + userPref.get(PREF_KEY, PREF_KEY + \" was not found.\"));\n\n //\n // Write Preferences information to HKLM (HKEY_LOCAL_MACHINE),\n // HKLM\\Software\\JavaSoft\\Prefs\\org.username\n //\n Preferences systemPref = Preferences.systemRoot();\n systemPref.put(PREF_KEY, \"xyz\");\n\n //\n // Read back the value we've written in the code above.\n //\n System.out.println(\"Preferences = \"\n + systemPref.get(PREF_KEY, PREF_KEY + \" was not found.\"));\n }\n}\n</code></pre>\n" }, { "answer_id": 26106387, "author": "Palak Nagar", "author_id": 4092109, "author_profile": "https://Stackoverflow.com/users/4092109", "pm_score": -1, "selected": false, "text": "<p>You can execute these \"REG QUERY\" command using <strong>java</strong> code.</p>\n\n<p>Try to execute this from command prompt and execute command from java code.</p>\n\n<blockquote>\n <p>HKEY_LOCAL_MACHINE \"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\"</p>\n</blockquote>\n\n<p>To Search details like productname version etc.. use /v amd \"name\". </p>\n\n<blockquote>\n <p>HKEY_LOCAL_MACHINE \"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\" /v \"ProductName\"</p>\n</blockquote>\n" }, { "answer_id": 30019357, "author": "BullyWiiPlaza", "author_id": 3764804, "author_profile": "https://Stackoverflow.com/users/3764804", "pm_score": 3, "selected": false, "text": "<p>The best way to write to the register probably is using the <code>reg import</code> native Windows command and giving it the file path to the <code>.reg</code> file which has been generated by exporting something from the registry.</p>\n\n<p>Reading is done with the <code>reg query</code> command. Also see the documentation:\n<a href=\"https://technet.microsoft.com/en-us/library/cc742028.aspx\" rel=\"noreferrer\">https://technet.microsoft.com/en-us/library/cc742028.aspx</a></p>\n\n<p>Therefore the following code should be self-explanatory:</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class WindowsRegistry\n{\n public static void importSilently(String regFilePath) throws IOException,\n InterruptedException\n {\n if (!new File(regFilePath).exists())\n {\n throw new FileNotFoundException();\n }\n\n Process importer = Runtime.getRuntime().exec(\"reg import \" + regFilePath);\n\n importer.waitFor();\n }\n\n public static void overwriteValue(String keyPath, String keyName,\n String keyValue) throws IOException, InterruptedException\n {\n Process overwriter = Runtime.getRuntime().exec(\n \"reg add \" + keyPath + \" /t REG_SZ /v \\\"\" + keyName + \"\\\" /d \"\n + keyValue + \" /f\");\n\n overwriter.waitFor();\n }\n\n public static String getValue(String keyPath, String keyName)\n throws IOException, InterruptedException\n {\n Process keyReader = Runtime.getRuntime().exec(\n \"reg query \\\"\" + keyPath + \"\\\" /v \\\"\" + keyName + \"\\\"\");\n\n BufferedReader outputReader;\n String readLine;\n StringBuffer outputBuffer = new StringBuffer();\n\n outputReader = new BufferedReader(new InputStreamReader(\n keyReader.getInputStream()));\n\n while ((readLine = outputReader.readLine()) != null)\n {\n outputBuffer.append(readLine);\n }\n\n String[] outputComponents = outputBuffer.toString().split(\" \");\n\n keyReader.waitFor();\n\n return outputComponents[outputComponents.length - 1];\n }\n}\n</code></pre>\n" }, { "answer_id": 35532028, "author": "pratapvaibhav19", "author_id": 4585099, "author_profile": "https://Stackoverflow.com/users/4585099", "pm_score": 3, "selected": false, "text": "<p>Thanks to original post. I have reskinned this utility class and come up over the flaws which it had earlier, thought it might help others so posting here. I have also added some extra utility methods. Now it is able to read any file in windows registry(including REG_DWORD, REG_BINARY, REG_EXPAND_SZ etc.). All the methods work like a charm. Just copy and paste it and it should work. Here is the reskinned and modified class: </p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.StringTokenizer;\nimport java.util.prefs.Preferences;\n\npublic class WinRegistry {\n\n private static final int REG_SUCCESS = 0;\n private static final int REG_NOTFOUND = 2;\n private static final int KEY_READ = 0x20019;\n private static final int REG_ACCESSDENIED = 5;\n private static final int KEY_ALL_ACCESS = 0xf003f;\n public static final int HKEY_CLASSES_ROOT = 0x80000000;\n public static final int HKEY_CURRENT_USER = 0x80000001;\n public static final int HKEY_LOCAL_MACHINE = 0x80000002;\n private static final String CLASSES_ROOT = \"HKEY_CLASSES_ROOT\";\n private static final String CURRENT_USER = \"HKEY_CURRENT_USER\";\n private static final String LOCAL_MACHINE = \"HKEY_LOCAL_MACHINE\";\n private static Preferences userRoot = Preferences.userRoot();\n private static Preferences systemRoot = Preferences.systemRoot();\n private static Class&lt;? extends Preferences&gt; userClass = userRoot.getClass();\n private static Method regOpenKey = null;\n private static Method regCloseKey = null;\n private static Method regQueryValueEx = null;\n private static Method regEnumValue = null;\n private static Method regQueryInfoKey = null;\n private static Method regEnumKeyEx = null;\n private static Method regCreateKeyEx = null;\n private static Method regSetValueEx = null;\n private static Method regDeleteKey = null;\n private static Method regDeleteValue = null;\n\n static {\n try {\n regOpenKey = userClass.getDeclaredMethod(\"WindowsRegOpenKey\", new Class[] {int.class, byte[].class, int.class});\n regOpenKey.setAccessible(true);\n regCloseKey = userClass.getDeclaredMethod(\"WindowsRegCloseKey\", new Class[] {int.class});\n regCloseKey.setAccessible(true);\n regQueryValueEx = userClass.getDeclaredMethod(\"WindowsRegQueryValueEx\", new Class[] {int.class, byte[].class});\n regQueryValueEx.setAccessible(true);\n regEnumValue = userClass.getDeclaredMethod(\"WindowsRegEnumValue\", new Class[] {int.class, int.class, int.class});\n regEnumValue.setAccessible(true);\n regQueryInfoKey = userClass.getDeclaredMethod(\"WindowsRegQueryInfoKey1\", new Class[] {int.class});\n regQueryInfoKey.setAccessible(true);\n regEnumKeyEx = userClass.getDeclaredMethod(\"WindowsRegEnumKeyEx\", new Class[] {int.class, int.class, int.class}); \n regEnumKeyEx.setAccessible(true);\n regCreateKeyEx = userClass.getDeclaredMethod(\"WindowsRegCreateKeyEx\", new Class[] {int.class, byte[].class}); \n regCreateKeyEx.setAccessible(true);\n regSetValueEx = userClass.getDeclaredMethod(\"WindowsRegSetValueEx\", new Class[] {int.class, byte[].class, byte[].class}); \n regSetValueEx.setAccessible(true);\n regDeleteValue = userClass.getDeclaredMethod(\"WindowsRegDeleteValue\", new Class[] {int.class, byte[].class}); \n regDeleteValue.setAccessible(true);\n regDeleteKey = userClass.getDeclaredMethod(\"WindowsRegDeleteKey\", new Class[] {int.class, byte[].class}); \n regDeleteKey.setAccessible(true);\n }\n catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n /**\n * Reads value for the key from given path\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param path\n * @param key\n * @return the value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n * @throws IOException \n */\n public static String valueForKey(int hkey, String path, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n if (hkey == HKEY_LOCAL_MACHINE)\n return valueForKey(systemRoot, hkey, path, key);\n else if (hkey == HKEY_CURRENT_USER)\n return valueForKey(userRoot, hkey, path, key);\n else\n return valueForKey(null, hkey, path, key);\n }\n\n /**\n * Reads all key(s) and value(s) from given path\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param path\n * @return the map of key(s) and corresponding value(s)\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n * @throws IOException \n */\n public static Map&lt;String, String&gt; valuesForPath(int hkey, String path) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n if (hkey == HKEY_LOCAL_MACHINE)\n return valuesForPath(systemRoot, hkey, path);\n else if (hkey == HKEY_CURRENT_USER)\n return valuesForPath(userRoot, hkey, path);\n else\n return valuesForPath(null, hkey, path);\n }\n\n /**\n * Read all the subkey(s) from a given path\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param path\n * @return the subkey(s) list\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static List&lt;String&gt; subKeysForPath(int hkey, String path)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n if (hkey == HKEY_LOCAL_MACHINE)\n return subKeysForPath(systemRoot, hkey, path);\n else if (hkey == HKEY_CURRENT_USER)\n return subKeysForPath(userRoot, hkey, path);\n else\n return subKeysForPath(null, hkey, path);\n }\n\n /**\n * Create a key\n * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void createKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int [] ret;\n if (hkey == HKEY_LOCAL_MACHINE) {\n ret = createKey(systemRoot, hkey, key);\n regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });\n } else if (hkey == HKEY_CURRENT_USER) {\n ret = createKey(userRoot, hkey, key);\n regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });\n } else\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n if (ret[1] != REG_SUCCESS)\n throw new IllegalArgumentException(\"rc=\" + ret[1] + \" key=\" + key);\n }\n\n /**\n * Write a value in a given key/value name\n * @param hkey\n * @param key\n * @param valueName\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void writeStringValue(int hkey, String key, String valueName, String value) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n if (hkey == HKEY_LOCAL_MACHINE)\n writeStringValue(systemRoot, hkey, key, valueName, value);\n else if (hkey == HKEY_CURRENT_USER)\n writeStringValue(userRoot, hkey, key, valueName, value);\n else\n throw new IllegalArgumentException(\"hkey=\" + hkey);\n }\n\n /**\n * Delete a given key\n * @param hkey\n * @param key\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteKey(int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE)\n rc = deleteKey(systemRoot, hkey, key);\n else if (hkey == HKEY_CURRENT_USER)\n rc = deleteKey(userRoot, hkey, key);\n if (rc != REG_SUCCESS)\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key);\n }\n\n /**\n * delete a value from a given key/value name\n * @param hkey\n * @param key\n * @param value\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n public static void deleteValue(int hkey, String key, String value) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int rc = -1;\n if (hkey == HKEY_LOCAL_MACHINE)\n rc = deleteValue(systemRoot, hkey, key, value);\n else if (hkey == HKEY_CURRENT_USER)\n rc = deleteValue(userRoot, hkey, key, value);\n if (rc != REG_SUCCESS)\n throw new IllegalArgumentException(\"rc=\" + rc + \" key=\" + key + \" value=\" + value);\n }\n\n // =====================\n\n private static int deleteValue(Preferences root, int hkey, String key, String value)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS)});\n if (handles[1] != REG_SUCCESS)\n return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED\n int rc =((Integer) regDeleteValue.invoke(root, new Object[] {new Integer(handles[0]), toCstr(value)})).intValue();\n regCloseKey.invoke(root, new Object[] { new Integer(handles[0])});\n return rc;\n }\n\n private static int deleteKey(Preferences root, int hkey, String key) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int rc =((Integer) regDeleteKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key)})).intValue();\n return rc; // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS\n }\n\n private static String valueForKey(Preferences root, int hkey, String path, String key)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});\n if (handles[1] != REG_SUCCESS)\n throw new IllegalArgumentException(\"The system can not find the specified path: '\"+getParentKey(hkey)+\"\\\\\"+path+\"'\");\n byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {new Integer(handles[0]), toCstr(key)});\n regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n return (valb != null ? parseValue(valb) : queryValueForKey(hkey, path, key));\n }\n\n private static String queryValueForKey(int hkey, String path, String key) throws IOException {\n return queryValuesForPath(hkey, path).get(key);\n }\n\n private static Map&lt;String,String&gt; valuesForPath(Preferences root, int hkey, String path)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n HashMap&lt;String, String&gt; results = new HashMap&lt;String,String&gt;();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});\n if (handles[1] != REG_SUCCESS)\n throw new IllegalArgumentException(\"The system can not find the specified path: '\"+getParentKey(hkey)+\"\\\\\"+path+\"'\");\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {new Integer(handles[0])});\n int count = info[2]; // Fixed: info[0] was being used here\n int maxlen = info[4]; // while info[3] was being used here, causing wrong results\n for(int index=0; index&lt;count; index++) {\n byte[] valb = (byte[]) regEnumValue.invoke(root, new Object[] {new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)});\n String vald = parseValue(valb);\n if(valb == null || vald.isEmpty())\n return queryValuesForPath(hkey, path);\n results.put(vald, valueForKey(root, hkey, path, vald));\n }\n regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n return results;\n }\n\n /**\n * Searches recursively into the path to find the value for key. This method gives \n * only first occurrence value of the key. If required to get all values in the path \n * recursively for this key, then {@link #valuesForKeyPath(int hkey, String path, String key)} \n * should be used.\n * @param hkey\n * @param path\n * @param key\n * @param list\n * @return the value of given key obtained recursively\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n * @throws IOException\n */\n public static String valueForKeyPath(int hkey, String path, String key)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n String val;\n try {\n val = valuesForKeyPath(hkey, path, key).get(0);\n } catch(IndexOutOfBoundsException e) {\n throw new IllegalArgumentException(\"The system can not find the key: '\"+key+\"' after \"\n + \"searching the specified path: '\"+getParentKey(hkey)+\"\\\\\"+path+\"'\");\n }\n return val;\n }\n\n /**\n * Searches recursively into given path for particular key and stores obtained value in list\n * @param hkey\n * @param path\n * @param key\n * @param list\n * @return list containing values for given key obtained recursively\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n * @throws IOException\n */\n public static List&lt;String&gt; valuesForKeyPath(int hkey, String path, String key)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n List&lt;String&gt; list = new ArrayList&lt;String&gt;();\n if (hkey == HKEY_LOCAL_MACHINE)\n return valuesForKeyPath(systemRoot, hkey, path, key, list);\n else if (hkey == HKEY_CURRENT_USER)\n return valuesForKeyPath(userRoot, hkey, path, key, list);\n else\n return valuesForKeyPath(null, hkey, path, key, list);\n }\n\n private static List&lt;String&gt; valuesForKeyPath(Preferences root, int hkey, String path, String key, List&lt;String&gt; list)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n if(!isDirectory(root, hkey, path)) {\n takeValueInListForKey(hkey, path, key, list);\n } else {\n List&lt;String&gt; subKeys = subKeysForPath(root, hkey, path);\n for(String subkey: subKeys) {\n String newPath = path+\"\\\\\"+subkey;\n if(isDirectory(root, hkey, newPath))\n valuesForKeyPath(root, hkey, newPath, key, list);\n takeValueInListForKey(hkey, newPath, key, list);\n }\n }\n return list;\n }\n\n /**\n * Takes value for key in list\n * @param hkey\n * @param path\n * @param key\n * @param list\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n * @throws IOException\n */\n private static void takeValueInListForKey(int hkey, String path, String key, List&lt;String&gt; list)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException {\n String value = valueForKey(hkey, path, key);\n if(value != null)\n list.add(value);\n }\n\n /**\n * Checks if the path has more subkeys or not\n * @param root\n * @param hkey\n * @param path\n * @return true if path has subkeys otherwise false\n * @throws IllegalArgumentException\n * @throws IllegalAccessException\n * @throws InvocationTargetException\n */\n private static boolean isDirectory(Preferences root, int hkey, String path)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n return !subKeysForPath(root, hkey, path).isEmpty();\n }\n\n private static List&lt;String&gt; subKeysForPath(Preferences root, int hkey, String path)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n List&lt;String&gt; results = new ArrayList&lt;String&gt;();\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(path), new Integer(KEY_READ)});\n if (handles[1] != REG_SUCCESS)\n throw new IllegalArgumentException(\"The system can not find the specified path: '\"+getParentKey(hkey)+\"\\\\\"+path+\"'\");\n int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] {new Integer(handles[0])});\n int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio\n int maxlen = info[3]; // value length max\n for(int index=0; index&lt;count; index++) {\n byte[] valb = (byte[]) regEnumKeyEx.invoke(root, new Object[] {new Integer(handles[0]), new Integer(index), new Integer(maxlen + 1)});\n results.add(parseValue(valb));\n }\n regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n return results;\n }\n\n private static int [] createKey(Preferences root, int hkey, String key)\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n return (int[]) regCreateKeyEx.invoke(root, new Object[] {new Integer(hkey), toCstr(key)});\n }\n\n private static void writeStringValue(Preferences root, int hkey, String key, String valueName, String value) \n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS)});\n regSetValueEx.invoke(root, new Object[] {new Integer(handles[0]), toCstr(valueName), toCstr(value)}); \n regCloseKey.invoke(root, new Object[] {new Integer(handles[0])});\n }\n\n /**\n * Makes cmd query for the given hkey and path then executes the query\n * @param hkey\n * @param path\n * @return the map containing all results in form of key(s) and value(s) obtained by executing query\n * @throws IOException\n */\n private static Map&lt;String, String&gt; queryValuesForPath(int hkey, String path) throws IOException {\n String line;\n StringBuilder builder = new StringBuilder();\n Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();\n Process process = Runtime.getRuntime().exec(\"reg query \\\"\"+getParentKey(hkey)+\"\\\\\" + path + \"\\\"\");\n BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));\n while((line = reader.readLine()) != null) {\n if(!line.contains(\"REG_\"))\n continue;\n StringTokenizer tokenizer = new StringTokenizer(line, \" \\t\");\n while(tokenizer.hasMoreTokens()) {\n String token = tokenizer.nextToken();\n if(token.startsWith(\"REG_\"))\n builder.append(\"\\t \");\n else\n builder.append(token).append(\" \");\n }\n String[] arr = builder.toString().split(\"\\t\");\n map.put(arr[0].trim(), arr[1].trim());\n builder.setLength(0);\n }\n return map;\n }\n\n /**\n * Determines the string equivalent of hkey\n * @param hkey\n * @return string equivalent of hkey\n */\n private static String getParentKey(int hkey) {\n if(hkey == HKEY_CLASSES_ROOT)\n return CLASSES_ROOT;\n else if(hkey == HKEY_CURRENT_USER)\n return CURRENT_USER;\n else if(hkey == HKEY_LOCAL_MACHINE)\n return LOCAL_MACHINE;\n return null;\n }\n\n /**\n *Intern method which adds the trailing \\0 for the handle with java.dll\n * @param str String\n * @return byte[] \n */\n private static byte[] toCstr(String str) {\n if(str == null)\n str = \"\";\n return (str += \"\\0\").getBytes();\n }\n\n /**\n * Method removes the trailing \\0 which is returned from the java.dll (just if the last sign is a \\0)\n * @param buf the byte[] buffer which every read method returns\n * @return String a parsed string without the trailing \\0\n */\n private static String parseValue(byte buf[]) {\n if(buf == null)\n return null;\n String ret = new String(buf);\n if(ret.charAt(ret.length()-1) == '\\0')\n return ret.substring(0, ret.length()-1);\n return ret;\n }\n} \n</code></pre>\n\n<p><strong>Sample of using the methods is as follows:</strong> </p>\n\n<p>Below method retrieves the value of the key from the given path: </p>\n\n<pre><code>String hex = WinRegistry.valueForKey(WinRegistry.HKEY_LOCAL_MACHINE, \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\WindowsUpdate\\\\Auto Update\", \"AUOptions\");\n</code></pre>\n\n<p>This method retrieves all data for the specified path(in form of keys and values) : </p>\n\n<pre><code>Map&lt;String, String&gt; map = WinRegistry.valuesForPath(WinRegistry.HKEY_LOCAL_MACHINE, \"SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\WSMAN\");\n</code></pre>\n\n<p>This method retrieves value recursively for the key from the given path: </p>\n\n<pre><code>String val = WinRegistry.valueForKeyPath(WinRegistry.HKEY_LOCAL_MACHINE, \"System\", \"TypeID\");\n</code></pre>\n\n<p>and this one retrieves all values recursively for a key from the given path: </p>\n\n<pre><code>List&lt;String&gt; list = WinRegistry.valuesForKeyPath(\n WinRegistry.HKEY_LOCAL_MACHINE, //HKEY \"SOFTWARE\\\\Wow6432Node\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\", //path \"DisplayName\" //Key\n );\n</code></pre>\n\n<p>Here in above code I retrieved all installed software names in windows system.<br>\n<strong>Note: See the documentation of these methods</strong> </p>\n\n<p>And this one retrieves all subkeys of the given path: </p>\n\n<pre><code>List&lt;String&gt; list3 = WinRegistry.subKeysForPath(WinRegistry.HKEY_CURRENT_USER, \"Software\");\n</code></pre>\n\n<p><strong>Important Note: I have modified only reading purpose methods in this process, not the writing purpose methods like createKey, deleteKey etc. They still are same as I recieved them.</strong> </p>\n" }, { "answer_id": 73575038, "author": "Gon Juarez", "author_id": 9296473, "author_profile": "https://Stackoverflow.com/users/9296473", "pm_score": 0, "selected": false, "text": "<p>I make my own code using enum.</p>\n<pre><code> public class Registry {\n\n public static enum key {\n HKEY_CURRENT_USER, HKEY_USERS, HKEY_LOCAL_MACHINE, HKEY_CURRENT_CONFIG;\n };\n\n public static enum dataType {\n REG_BINARY, REG_DWORD, REG_EXPAND_SZ, REG_MULTI_SZ, REG_SZ, REG_RESOURCE_LIST, REG_RESOURCE_REQUIREMENTS_LIST, REG_FULL_RESOURCE_DESCRIPTOR, REG_NONE, REG_LINK, REG_QWORD;\n }\n\n public static enum userKey {\n AppEvents, Console, Control_Panel, Enviroment, EUDC, Keyboard_Layout, Microsoft, Network, Printers, Software, System, Uninstall, Volatile_Enviroment;\n }\n\n public static void overWriteSoftwareInt(String key, String userKey, String path, String valueKey, String datatype, int value) {\n try {\n Process process = Runtime.getRuntime().exec(&quot;reg add &quot; + key + &quot;\\\\&quot; + userKey + &quot;\\\\&quot; + path + &quot; /t &quot; + datatype + &quot; /v \\&quot;&quot; + valueKey + &quot;\\&quot; /d &quot; + value);\n process.waitFor();\n } catch (IOException ex) {\n // Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n } catch (InterruptedException ex) {\n Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n \n public static void overWriteSoftwareString(String key, String userKey, String path, String valueKey, String datatype, int value) {\n try {\n Process process = Runtime.getRuntime().exec(&quot;reg add &quot; + key + &quot;\\\\&quot; + userKey + &quot;\\\\&quot; + path + &quot; /t &quot; + datatype + &quot; /v \\&quot;&quot; + valueKey + &quot;\\&quot; /d \\&quot;&quot; + value+&quot;\\&quot;&quot;);\n process.waitFor();\n } catch (IOException ex) {\n // Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n } catch (InterruptedException ex) {\n Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n\n public static void deleteValue(String key, String userKey, String path, String valueKey) {\n try {\n Process process = Runtime.getRuntime().exec(&quot;reg delete &quot; + key + &quot;\\\\&quot; + userKey + &quot;\\\\&quot; + path + &quot; /v \\&quot;&quot; + valueKey + &quot;\\&quot; /f&quot;);\n process.waitFor();\n } catch (IOException ex) {\n // Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n } catch (InterruptedException ex) {\n Logger.getLogger(Registry.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n}\n</code></pre>\n<p>You can use this class following this example.</p>\n<pre><code> Registry.deleteValue(Registry.key.HKEY_CURRENT_USER.name(), Registry.userKey.Software.name(), &quot;path&quot;, &quot;valueName&quot;);\n Registry.overWriteSoftwareInt(Registry.key.HKEY_CURRENT_USER.name(), Registry.userKey.Software.name(), &quot;path&quot;, &quot;valueName&quot;, Registry.dataType.REG_DWORD.name(), 0);\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How is it possible to read/write to the Windows registry using Java?
I know this question is old, but it is the first search result on google to "java read/write to registry". Recently I found this amazing piece of code which: * Can read/write to ANY part of the registry. * DOES NOT USE JNI. * DOES NOT USE ANY 3rd PARTY/EXTERNAL APPLICATIONS TO WORK. * DOES NOT USE THE WINDOWS API (directly) This is pure, Java code. It uses reflection to work, by actually accessing the private methods in the `java.util.prefs.Preferences` class. The internals of this class are complicated, but the class itself is very easy to use. For example, the following code obtains the exact windows distribution **from the registry**: ``` String value = WinRegistry.readString ( WinRegistry.HKEY_LOCAL_MACHINE, //HKEY "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", //Key "ProductName"); //ValueName System.out.println("Windows Distribution = " + value); ``` Here is the original class. Just copy paste it and it should work: ``` import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.List; import java.util.prefs.Preferences; public class WinRegistry { public static final int HKEY_CURRENT_USER = 0x80000001; public static final int HKEY_LOCAL_MACHINE = 0x80000002; public static final int REG_SUCCESS = 0; public static final int REG_NOTFOUND = 2; public static final int REG_ACCESSDENIED = 5; private static final int KEY_ALL_ACCESS = 0xf003f; private static final int KEY_READ = 0x20019; private static final Preferences userRoot = Preferences.userRoot(); private static final Preferences systemRoot = Preferences.systemRoot(); private static final Class<? extends Preferences> userClass = userRoot.getClass(); private static final Method regOpenKey; private static final Method regCloseKey; private static final Method regQueryValueEx; private static final Method regEnumValue; private static final Method regQueryInfoKey; private static final Method regEnumKeyEx; private static final Method regCreateKeyEx; private static final Method regSetValueEx; private static final Method regDeleteKey; private static final Method regDeleteValue; static { try { regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey", new Class[] { int.class, byte[].class, int.class }); regOpenKey.setAccessible(true); regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey", new Class[] { int.class }); regCloseKey.setAccessible(true); regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx", new Class[] { int.class, byte[].class }); regQueryValueEx.setAccessible(true); regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue", new Class[] { int.class, int.class, int.class }); regEnumValue.setAccessible(true); regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1", new Class[] { int.class }); regQueryInfoKey.setAccessible(true); regEnumKeyEx = userClass.getDeclaredMethod( "WindowsRegEnumKeyEx", new Class[] { int.class, int.class, int.class }); regEnumKeyEx.setAccessible(true); regCreateKeyEx = userClass.getDeclaredMethod( "WindowsRegCreateKeyEx", new Class[] { int.class, byte[].class }); regCreateKeyEx.setAccessible(true); regSetValueEx = userClass.getDeclaredMethod( "WindowsRegSetValueEx", new Class[] { int.class, byte[].class, byte[].class }); regSetValueEx.setAccessible(true); regDeleteValue = userClass.getDeclaredMethod( "WindowsRegDeleteValue", new Class[] { int.class, byte[].class }); regDeleteValue.setAccessible(true); regDeleteKey = userClass.getDeclaredMethod( "WindowsRegDeleteKey", new Class[] { int.class, byte[].class }); regDeleteKey.setAccessible(true); } catch (Exception e) { throw new RuntimeException(e); } } private WinRegistry() { } /** * Read a value from key and value name * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE * @param key * @param valueName * @return the value * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ public static String readString(int hkey, String key, String valueName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (hkey == HKEY_LOCAL_MACHINE) { return readString(systemRoot, hkey, key, valueName); } else if (hkey == HKEY_CURRENT_USER) { return readString(userRoot, hkey, key, valueName); } else { throw new IllegalArgumentException("hkey=" + hkey); } } /** * Read value(s) and value name(s) form given key * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE * @param key * @return the value name(s) plus the value(s) * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ public static Map<String, String> readStringValues(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (hkey == HKEY_LOCAL_MACHINE) { return readStringValues(systemRoot, hkey, key); } else if (hkey == HKEY_CURRENT_USER) { return readStringValues(userRoot, hkey, key); } else { throw new IllegalArgumentException("hkey=" + hkey); } } /** * Read the value name(s) from a given key * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE * @param key * @return the value name(s) * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ public static List<String> readStringSubKeys(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (hkey == HKEY_LOCAL_MACHINE) { return readStringSubKeys(systemRoot, hkey, key); } else if (hkey == HKEY_CURRENT_USER) { return readStringSubKeys(userRoot, hkey, key); } else { throw new IllegalArgumentException("hkey=" + hkey); } } /** * Create a key * @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE * @param key * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ public static void createKey(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { int [] ret; if (hkey == HKEY_LOCAL_MACHINE) { ret = createKey(systemRoot, hkey, key); regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) }); } else if (hkey == HKEY_CURRENT_USER) { ret = createKey(userRoot, hkey, key); regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) }); } else { throw new IllegalArgumentException("hkey=" + hkey); } if (ret[1] != REG_SUCCESS) { throw new IllegalArgumentException("rc=" + ret[1] + " key=" + key); } } /** * Write a value in a given key/value name * @param hkey * @param key * @param valueName * @param value * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ public static void writeStringValue (int hkey, String key, String valueName, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { if (hkey == HKEY_LOCAL_MACHINE) { writeStringValue(systemRoot, hkey, key, valueName, value); } else if (hkey == HKEY_CURRENT_USER) { writeStringValue(userRoot, hkey, key, valueName, value); } else { throw new IllegalArgumentException("hkey=" + hkey); } } /** * Delete a given key * @param hkey * @param key * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ public static void deleteKey(int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { int rc = -1; if (hkey == HKEY_LOCAL_MACHINE) { rc = deleteKey(systemRoot, hkey, key); } else if (hkey == HKEY_CURRENT_USER) { rc = deleteKey(userRoot, hkey, key); } if (rc != REG_SUCCESS) { throw new IllegalArgumentException("rc=" + rc + " key=" + key); } } /** * delete a value from a given key/value name * @param hkey * @param key * @param value * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ public static void deleteValue(int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { int rc = -1; if (hkey == HKEY_LOCAL_MACHINE) { rc = deleteValue(systemRoot, hkey, key, value); } else if (hkey == HKEY_CURRENT_USER) { rc = deleteValue(userRoot, hkey, key, value); } if (rc != REG_SUCCESS) { throw new IllegalArgumentException("rc=" + rc + " key=" + key + " value=" + value); } } // ===================== private static int deleteValue (Preferences root, int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { int[] handles = (int[]) regOpenKey.invoke(root, new Object[] { new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) }); if (handles[1] != REG_SUCCESS) { return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED } int rc =((Integer) regDeleteValue.invoke(root, new Object[] { new Integer(handles[0]), toCstr(value) })).intValue(); regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) }); return rc; } private static int deleteKey(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { int rc =((Integer) regDeleteKey.invoke(root, new Object[] { new Integer(hkey), toCstr(key) })).intValue(); return rc; // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS } private static String readString(Preferences root, int hkey, String key, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { int[] handles = (int[]) regOpenKey.invoke(root, new Object[] { new Integer(hkey), toCstr(key), new Integer(KEY_READ) }); if (handles[1] != REG_SUCCESS) { return null; } byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] { new Integer(handles[0]), toCstr(value) }); regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) }); return (valb != null ? new String(valb).trim() : null); } private static Map<String,String> readStringValues (Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { HashMap<String, String> results = new HashMap<String,String>(); int[] handles = (int[]) regOpenKey.invoke(root, new Object[] { new Integer(hkey), toCstr(key), new Integer(KEY_READ) }); if (handles[1] != REG_SUCCESS) { return null; } int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] { new Integer(handles[0]) }); int count = info[0]; // count int maxlen = info[3]; // value length max for(int index=0; index<count; index++) { byte[] name = (byte[]) regEnumValue.invoke(root, new Object[] { new Integer (handles[0]), new Integer(index), new Integer(maxlen + 1)}); String value = readString(hkey, key, new String(name)); results.put(new String(name).trim(), value); } regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) }); return results; } private static List<String> readStringSubKeys (Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { List<String> results = new ArrayList<String>(); int[] handles = (int[]) regOpenKey.invoke(root, new Object[] { new Integer(hkey), toCstr(key), new Integer(KEY_READ) }); if (handles[1] != REG_SUCCESS) { return null; } int[] info = (int[]) regQueryInfoKey.invoke(root, new Object[] { new Integer(handles[0]) }); int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio int maxlen = info[3]; // value length max for(int index=0; index<count; index++) { byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[] { new Integer (handles[0]), new Integer(index), new Integer(maxlen + 1) }); results.add(new String(name).trim()); } regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) }); return results; } private static int [] createKey(Preferences root, int hkey, String key) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { return (int[]) regCreateKeyEx.invoke(root, new Object[] { new Integer(hkey), toCstr(key) }); } private static void writeStringValue (Preferences root, int hkey, String key, String valueName, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { int[] handles = (int[]) regOpenKey.invoke(root, new Object[] { new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) }); regSetValueEx.invoke(root, new Object[] { new Integer(handles[0]), toCstr(valueName), toCstr(value) }); regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) }); } // utility private static byte[] toCstr(String str) { byte[] result = new byte[str.length() + 1]; for (int i = 0; i < str.length(); i++) { result[i] = (byte) str.charAt(i); } result[str.length()] = 0; return result; } } ``` Original Author: Apache. Library Source: <https://github.com/apache/npanday/tree/trunk/components/dotnet-registry/src/main/java/npanday/registry>
62,317
<p>In PHP, how can I replicate the expand/contract feature for Tinyurls as on search.twitter.com?</p>
[ { "answer_id": 62367, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 4, "selected": true, "text": "<p>If you want to find out where a tinyurl is going, use fsockopen to get a connection to tinyurl.com on port 80, and send it an HTTP request like this</p>\n\n<pre><code>GET /dmsfm HTTP/1.0\nHost: tinyurl.com\n</code></pre>\n\n<p>The response you get back will look like</p>\n\n<pre><code>HTTP/1.0 301 Moved Permanently\nConnection: close\nX-Powered-By: PHP/5.2.6\nLocation: http://en.wikipedia.org/wiki/TinyURL\nContent-type: text/html\nContent-Length: 0\nDate: Mon, 15 Sep 2008 12:29:04 GMT\nServer: TinyURL/1.6\n</code></pre>\n\n<p>example code...</p>\n\n<pre><code>&lt;?php\n$tinyurl=\"dmsfm\";\n\n$fp = fsockopen(\"tinyurl.com\", 80, $errno, $errstr, 30);\nif (!$fp) {\n echo \"$errstr ($errno)&lt;br /&gt;\\n\";\n} else {\n $out = \"GET /$tinyurl HTTP/1.0\\r\\n\";\n $out .= \"Host: tinyurl.com\\r\\n\";\n $out .= \"Connection: Close\\r\\n\\r\\n\";\n\n $response=\"\";\n\n fwrite($fp, $out);\n while (!feof($fp)) {\n $response.=fgets($fp, 128);\n }\n fclose($fp);\n\n //now parse the Location: header out of the response\n\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 62597, "author": "Udo", "author_id": 6907, "author_profile": "https://Stackoverflow.com/users/6907", "pm_score": 2, "selected": false, "text": "<p>And here is how to <em>contract</em> an arbitrary URL using the TinyURL API. The general call pattern goes like this, it's a simple HTTP request with parameters:</p>\n\n<p><a href=\"http://tinyurl.com/api-create.php?url=http://insertyourstuffhere.com\" rel=\"nofollow noreferrer\">http://tinyurl.com/api-create.php?url=http://insertyourstuffhere.com</a></p>\n\n<p>This will return the corresponding TinyURL for <a href=\"http://insertyourstuffhere.com\" rel=\"nofollow noreferrer\">http://insertyourstuffhere.com</a>. In PHP, you can wrap this in an fsockopen() call or, for convenience, just use the file() function to retrieve it:</p>\n\n<pre><code>function make_tinyurl($longurl)\n{\n return(implode('', file(\n 'http://tinyurl.com/api-create.php?url='.urlencode($longurl))));\n}\n\n// make an example call\nprint(make_tinyurl('http://www.joelonsoftware.com/items/2008/09/15.html'));\n</code></pre>\n" }, { "answer_id": 63072, "author": "barredo", "author_id": 7398, "author_profile": "https://Stackoverflow.com/users/7398", "pm_score": 0, "selected": false, "text": "<p>Another simple and easy way:</p>\n\n<pre><code>&lt;?php\nfunction getTinyUrl($url) {\nreturn file_get_contents('http://tinyurl.com/api-create.php?url='.$url);\n}\n?&gt;\n</code></pre>\n" }, { "answer_id": 63091, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "<p>As people have answered programatically how to create and resolve tinyurl.com redirects, I'd like to (strongly) suggest something: caching.</p>\n\n<p>In the twitter example, if every time you clicked the \"expand\" button, it did an XmlHTTPRequest to, say, <code>/api/resolve_tinyurl/http://tinyurl.com/abcd</code>, then the server created a HTTP connection to tinyurl.com, and inspected the header - it would destroy both twitter and tinyurl's servers..</p>\n\n<p>An infinitely more sensible method would be to do something like this Python'y pseudo-code..</p>\n\n<pre><code>def resolve_tinyurl(url):\n key = md5( url.lower_case() )\n if cache.has_key(key)\n return cache[md5]\n else:\n resolved = query_tinyurl(url)\n cache[key] = resolved\n return resolved\n</code></pre>\n\n<p>Where <code>cache</code>'s items magically get backed up into memory, and/or a file, and query_tinyurl() works as Paul Dixon's answer does.</p>\n" }, { "answer_id": 1735913, "author": "GZipp", "author_id": 153350, "author_profile": "https://Stackoverflow.com/users/153350", "pm_score": 0, "selected": false, "text": "<p>If you just want the location, then do a HEAD request instead of GET.</p>\n\n<pre><code>$tinyurl = 'http://tinyurl.com/3fvbx8';\n$context = stream_context_create(array('http' =&gt; array('method' =&gt; 'HEAD')));\n$response = file_get_contents($tinyurl, null, $context);\n\n$location = '';\nforeach ($http_response_header as $header) {\n if (strpos($header, 'Location:') === 0) {\n $location = trim(strrchr($header, ' '));\n break;\n }\n}\necho $location;\n// http://www.pingdom.com/reports/vb1395a6sww3/check_overview/?name=twitter.com%2Fhome\n</code></pre>\n" }, { "answer_id": 1975639, "author": "Pons", "author_id": 231676, "author_profile": "https://Stackoverflow.com/users/231676", "pm_score": 1, "selected": false, "text": "<p>Here is another way to decode short urls via CURL library:</p>\n\n<pre><code>function doShortURLDecode($url) {\n $ch = @curl_init($url);\n @curl_setopt($ch, CURLOPT_HEADER, TRUE);\n @curl_setopt($ch, CURLOPT_NOBODY, TRUE);\n @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);\n @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);\n $response = @curl_exec($ch);\n preg_match('/Location: (.*)\\n/', $response, $a);\n if (!isset($a[1])) return $url;\n return $a[1];\n}\n</code></pre>\n\n<p>It's described <a href=\"http://www.barattalo.it/2009/12/29/tiny-url-encode-and-decode-with-php/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 2021778, "author": "Pons", "author_id": 231676, "author_profile": "https://Stackoverflow.com/users/231676", "pm_score": 0, "selected": false, "text": "<p>In PHP there is also a <a href=\"http://php.net/manual/en/function.get-headers.php\" rel=\"nofollow noreferrer\">get_headers</a> function that can be used to decode tiny urls.</p>\n" }, { "answer_id": 57036749, "author": "rubo77", "author_id": 1069083, "author_profile": "https://Stackoverflow.com/users/1069083", "pm_score": 0, "selected": false, "text": "<p>The Solution <a href=\"https://www.barattalo.it/coding/tiny-url-encode-and-decode-with-php/\" rel=\"nofollow noreferrer\">here</a> from @Pons solution, didn't work alone on my php7.3 server reslolving stackexchange URLs like <code>https://stackoverflow.com/q/62317</code></p>\n\n<p>This solved it:</p>\n\n<pre><code>public function doShortURLDecode($url) {\n $ch = @curl_init($url);\n @curl_setopt($ch, CURLOPT_HEADER, TRUE);\n @curl_setopt($ch, CURLOPT_NOBODY, TRUE);\n @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);\n @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);\n $response = @curl_exec($ch);\n $cleanresponse= preg_replace('/[^A-Za-z0-9\\- _,.:\\n\\/]/', '', $response);\n preg_match('/Location: (.*)[\\n\\r]/', $cleanresponse, $a);\n if (!isset($a[1])) return $url;\n return parse_url($url, PHP_URL_SCHEME).'://'.parse_url($url, PHP_URL_HOST).$a[1];\n}\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In PHP, how can I replicate the expand/contract feature for Tinyurls as on search.twitter.com?
If you want to find out where a tinyurl is going, use fsockopen to get a connection to tinyurl.com on port 80, and send it an HTTP request like this ``` GET /dmsfm HTTP/1.0 Host: tinyurl.com ``` The response you get back will look like ``` HTTP/1.0 301 Moved Permanently Connection: close X-Powered-By: PHP/5.2.6 Location: http://en.wikipedia.org/wiki/TinyURL Content-type: text/html Content-Length: 0 Date: Mon, 15 Sep 2008 12:29:04 GMT Server: TinyURL/1.6 ``` example code... ``` <?php $tinyurl="dmsfm"; $fp = fsockopen("tinyurl.com", 80, $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)<br />\n"; } else { $out = "GET /$tinyurl HTTP/1.0\r\n"; $out .= "Host: tinyurl.com\r\n"; $out .= "Connection: Close\r\n\r\n"; $response=""; fwrite($fp, $out); while (!feof($fp)) { $response.=fgets($fp, 128); } fclose($fp); //now parse the Location: header out of the response } ?> ```
62,340
<pre><code>std::vector&lt;int&gt; ints; // ... fill ints with random values for(std::vector&lt;int&gt;::iterator it = ints.begin(); it != ints.end(); ) { if(*it &lt; 10) { *it = ints.back(); ints.pop_back(); continue; } it++; } </code></pre> <p>This code is not working because when <code>pop_back()</code> is called, <code>it</code> is invalidated. But I don't find any doc talking about invalidation of iterators in <code>std::vector::pop_back()</code>.</p> <p>Do you have some links about that?</p>
[ { "answer_id": 62368, "author": "David Joyner", "author_id": 1146, "author_profile": "https://Stackoverflow.com/users/1146", "pm_score": 1, "selected": false, "text": "<p>Iterators are only invalidated on reallocation of storage. Google is your friend: <a href=\"http://www.sgi.com/tech/stl/Vector.html\" rel=\"nofollow noreferrer\">see footnote 5</a>.</p>\n\n<p>Your code is not working for other reasons.</p>\n" }, { "answer_id": 62417, "author": "jvasak", "author_id": 5840, "author_profile": "https://Stackoverflow.com/users/5840", "pm_score": -1, "selected": false, "text": "<p>Check out the information <a href=\"http://www.cplusplus.com/reference/stl/vector/pop_back.html\" rel=\"nofollow noreferrer\">here (cplusplus.com)</a>:</p>\n\n<blockquote>\n <p><strong>Delete last element</strong></p>\n \n <p>Removes the last element in the vector, effectively reducing the vector size by one and invalidating all iterators and references to it.</p>\n</blockquote>\n" }, { "answer_id": 62485, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Error is that when \"it\" points to the last element of vector and if this element is less than 10, this last element is removed. And now \"it\" points to ints.end(), next \"it++\" moves pointer to ints.end()+1, so now \"it\" running away from ints.end(), and you got infinite loop scanning all your memory :).</p>\n" }, { "answer_id": 62522, "author": "Ben", "author_id": 6930, "author_profile": "https://Stackoverflow.com/users/6930", "pm_score": 5, "selected": true, "text": "<p>The call to <a href=\"http://en.cppreference.com/w/cpp/container/vector/pop_back\" rel=\"noreferrer\"><code>pop_back()</code></a> removes the last element in the vector and so the iterator to that element is invalidated. The <code>pop_back()</code> call does <em>not</em> invalidate iterators to items before the last element, only reallocation will do that. From Josuttis' \"C++ Standard Library Reference\":</p>\n\n<blockquote>\n <p>Inserting or removing elements\n invalidates references, pointers, and\n iterators that refer to the following\n element. If an insertion causes\n reallocation, it invalidates all\n references, iterators, and pointers.</p>\n</blockquote>\n" }, { "answer_id": 62730, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here is a quote from SGI's STL documentation (<a href=\"http://www.sgi.com/tech/stl/Vector.html\" rel=\"nofollow noreferrer\">http://www.sgi.com/tech/stl/Vector.html</a>):</p>\n\n<p>[5] A vector's iterators are invalidated when its memory is reallocated. Additionally, inserting or deleting an element in the middle of a vector invalidates all iterators that point to elements following the insertion or deletion point. It follows that you can prevent a vector's iterators from being invalidated if you use reserve() to preallocate as much memory as the vector will ever use, and if all insertions and deletions are at the vector's end. </p>\n\n<p>I think it follows that pop_back only invalidates the iterator pointing at the last element and the end() iterator. We really need to see the data for which the code fails, as well as the manner in which it fails to decide what's going on. As far as I can tell, the code should work - the usual problem in such code is that removal of element and ++ on iterator happen in the same iteration, the way @mikhaild points out. However, in this code it's not the case: it++ does not happen when pop_back is called.</p>\n\n<p>Something bad may still happen when it is pointing to the last element, and the last element is less than 10. We're now comparing an <em>invalidated</em> it and end(). It may still work, but no guarantees can be made.</p>\n" }, { "answer_id": 62799, "author": "swmc", "author_id": 7016, "author_profile": "https://Stackoverflow.com/users/7016", "pm_score": 0, "selected": false, "text": "<p>The \"official specification\" is the C++ Standard. If you don't have access to a copy of C++03, you can get the latest draft of C++0x from the Committee's website: <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2723.pdf\" rel=\"nofollow noreferrer\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2723.pdf</a></p>\n\n<p>The \"Operational Semantics\" section of container requirements specifies that pop_back() is equivalent to { iterator i = end(); --i; erase(i); }. the [vector.modifiers] section for erase says \"Effects: Invalidates iterators and references at or after the point of the erase.\"</p>\n\n<p>If you want the intuition argument, pop_back is no-fail (since destruction of value_types in standard containers are not allowed to throw exceptions), so it cannot do any copy or allocation (since they can throw), which means that you can guess that the iterator to the erased element and the end iterator are invalidated, but the remainder are not.</p>\n" }, { "answer_id": 62840, "author": "jlehrer", "author_id": 7013, "author_profile": "https://Stackoverflow.com/users/7013", "pm_score": 4, "selected": false, "text": "<p>Here is your answer, directly from The Holy Standard:</p>\n\n<blockquote>\n23.2.4.2 A vector satisfies all of the requirements of a container and of a reversible container (given in two tables in 23.1) and of a sequence, including most of the optional sequence requirements (23.1.1).\n</blockquote>\n\n<blockquote>\n23.1.1.12 Table 68\n\n\nexpressiona.pop_back()\nreturn typevoid\noperational semantics<strong>a.erase(--a.end())</strong>\ncontainervector, list, deque\n\n</blockquote>\n\n<p>Notice that a.pop_back is equivalent to a.erase(--a.end()). Looking at vector's specifics on erase:</p>\n\n<blockquote>\n23.2.4.3.3 - iterator erase(iterator position) - effects - <strong>Invalidates all the iterators and references after the point of the erase</strong>\n</blockquote>\n\n<p>Therefore, once you call pop_back, any iterators to the previously final element (which now no longer exists) are invalidated.</p>\n\n<p>Looking at your code, the problem is that when you remove the final element and the list becomes empty, you still increment it and walk off the end of the list.</p>\n" }, { "answer_id": 62878, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 3, "selected": false, "text": "<p>(I use the numbering scheme as used in the C++0x working draft, <a href=\"http://www.justsoftwaresolutions.co.uk/cplusplus/new-cplusplus-draft-and-concurrency-papers.html\" rel=\"noreferrer\">obtainable here</a></p>\n\n<p>Table 94 at page 732 says that pop_back (if it exists in a sequence container) has the following effect:</p>\n\n<pre><code>{ iterator tmp = a.end(); \n--tmp; \na.erase(tmp); } \n</code></pre>\n\n<p>23.1.1, point 12 states that:</p>\n\n<blockquote>\n <p>Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container \n member function or passing a container as an argument to a library function shall not invalidate iterators to, or change \n the values of, objects within that container.</p>\n</blockquote>\n\n<p>Both accessing end() as applying prefix-- have no such effect, erase() however:</p>\n\n<p>23.2.6.4 (concerning vector.erase() point 4):</p>\n\n<blockquote>\n <p>Effects: Invalidates iterators and references at or after the point of the erase. </p>\n</blockquote>\n\n<p>So in conclusion: pop_back() will only invalidate an iterator to the last element, per the standard.</p>\n" }, { "answer_id": 62988, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>pop_back() will only invalidate <strong>it</strong> if <strong>it</strong> was pointing to the last item in the vector. Your code will therefore fail whenever the last int in the vector is less than 10, as follows:</p>\n\n<p>*it = ints.back(); // Set *it to the value it already has<br>\n ints.pop_back(); // Invalidate the iterator<br>\n continue; // Loop round and access the invalid iterator </p>\n" }, { "answer_id": 63135, "author": "NeARAZ", "author_id": 6799, "author_profile": "https://Stackoverflow.com/users/6799", "pm_score": 1, "selected": false, "text": "<p><code>pop_back()</code> invalidates only iterators that point to the last element. From C++ Standard Library Reference:</p>\n\n<blockquote>\n <p>Inserting or removing elements\n invalidates references, pointers, and\n iterators that refer to the following\n element. If an insertion causes\n reallocation, it invalidates all\n references, iterators, and pointers.</p>\n</blockquote>\n\n<p>So to answer your question, no it does not invalidate <em>all</em> iterators.</p>\n\n<p>However, in your code example, it can invalidate <strong><code>it</code></strong> when it is pointing to the last element and the value is below 10. In which case Visual Studio debug STL will mark iterator as invalidated, and further check for it not being equal to end() will show an assert.</p>\n\n<p>If iterators are implemented as pure pointers (as they would in probably all non-debug STL vector cases), your code should just work. If iterators are more than pointers, then your code does not handle this case of removing the last element correctly.</p>\n" }, { "answer_id": 415847, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 0, "selected": false, "text": "<p>You might want to consider using the return value of erase instead of swapping the back element to the deleted position an popping back. For sequences erase returns an iterator pointing the the element one beyond the element being deleted. Note that this method may cause more copying than your original algorithm.</p>\n\n<pre><code>for(std::vector&lt;int&gt;::iterator it = ints.begin(); it != ints.end(); )\n{\n if(*it &lt; 10)\n it = ints.erase( it );\n else\n ++it;\n}\n</code></pre>\n\n<p><code>std::remove_if</code> could also be an alternative solution.</p>\n\n<pre><code>struct LessThanTen { bool operator()( int n ) { return n &lt; 10; } };\n\nints.erase( std::remove_if( ints.begin(), ints.end(), LessThanTen() ), ints.end() );\n</code></pre>\n\n<p><code>std::remove_if</code> is (like my first algorithm) stable, so it may not be the most efficient way of doing this, but it is succinct.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6605/" ]
``` std::vector<int> ints; // ... fill ints with random values for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); ) { if(*it < 10) { *it = ints.back(); ints.pop_back(); continue; } it++; } ``` This code is not working because when `pop_back()` is called, `it` is invalidated. But I don't find any doc talking about invalidation of iterators in `std::vector::pop_back()`. Do you have some links about that?
The call to [`pop_back()`](http://en.cppreference.com/w/cpp/container/vector/pop_back) removes the last element in the vector and so the iterator to that element is invalidated. The `pop_back()` call does *not* invalidate iterators to items before the last element, only reallocation will do that. From Josuttis' "C++ Standard Library Reference": > > Inserting or removing elements > invalidates references, pointers, and > iterators that refer to the following > element. If an insertion causes > reallocation, it invalidates all > references, iterators, and pointers. > > >
62,353
<p>I have a solution with multiple project. I am trying to optimize AssemblyInfo.cs files by linking one solution wide assembly info file. What are the best practices for doing this? Which attributes should be in solution wide file and which are project/assembly specific?</p> <hr> <p><em>Edit: If you are interested there is a follow up question <a href="https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin">What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?</a></em></p>
[ { "answer_id": 62631, "author": "SaguiItay", "author_id": 6980, "author_profile": "https://Stackoverflow.com/users/6980", "pm_score": 0, "selected": false, "text": "<p>Using a single AseemblyInfo.cs file for multiple projects is not recommended.\nThe AssemblyInfo file includes information that might be relevant only for that specific assembly. The two most obvious pieces of information are the <code>AssemblyTitle</code> and <code>AssemblyVersion</code>.</p>\n\n<p>A better solution might be to use <code>targets</code> file, which are handled by the MSBuild, in order to \"inject\" assembly attributes to more than one project.</p>\n" }, { "answer_id": 62637, "author": "JRoppert", "author_id": 6777, "author_profile": "https://Stackoverflow.com/users/6777", "pm_score": 9, "selected": true, "text": "<p>We're using a global file called GlobalAssemblyInfo.cs and a local one called AssemblyInfo.cs. The global file contains the following attributes:</p>\n\n<pre><code> [assembly: AssemblyProduct(\"Your Product Name\")]\n\n [assembly: AssemblyCompany(\"Your Company\")]\n [assembly: AssemblyCopyright(\"Copyright © 2008 ...\")]\n [assembly: AssemblyTrademark(\"Your Trademark - if applicable\")]\n\n #if DEBUG\n [assembly: AssemblyConfiguration(\"Debug\")]\n #else\n [assembly: AssemblyConfiguration(\"Release\")]\n #endif\n\n [assembly: AssemblyVersion(\"This is set by build process\")]\n [assembly: AssemblyFileVersion(\"This is set by build process\")]\n</code></pre>\n\n<p>The local AssemblyInfo.cs contains the following attributes:</p>\n\n<pre><code> [assembly: AssemblyTitle(\"Your assembly title\")]\n [assembly: AssemblyDescription(\"Your assembly description\")]\n [assembly: AssemblyCulture(\"The culture - if not neutral\")]\n\n [assembly: ComVisible(true/false)]\n\n // unique id per assembly\n [assembly: Guid(\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\")]\n</code></pre>\n\n<p>You can add the GlobalAssemblyInfo.cs using the following procedure:</p>\n\n<ul>\n<li>Select <strong>Add/Existing Item...</strong> in the context menu of the project</li>\n<li>Select GlobalAssemblyInfo.cs</li>\n<li>Expand the Add-Button by clicking on that little down-arrow on the right hand</li>\n<li>Select \"Add As Link\" in the buttons drop down list</li>\n</ul>\n" }, { "answer_id": 62703, "author": "Cameron MacFarland", "author_id": 3820, "author_profile": "https://Stackoverflow.com/users/3820", "pm_score": 2, "selected": false, "text": "<p>To share a file between multiple projects you can add an existing file as a link.</p>\n\n<p>To do this, add an existing file, and click on \"Add as Link\" in the file selector.<a href=\"http://laurent.etiemble.free.fr/dotclear/images/AddLinkedFile03.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/w4Ka4.png\" alt=\"Add As Link\"></a><br>\n<sub>(source: <a href=\"http://laurent.etiemble.free.fr/dotclear/images/AddLinkedFile03_tn.png\" rel=\"nofollow noreferrer\">free.fr</a>)</sub> </p>\n\n<p>As for what to put in the shared file, I would suggest putting things that would be shared across assemblies. Things like copyright, company, perhaps version.</p>\n" }, { "answer_id": 62739, "author": "Krishna", "author_id": 6995, "author_profile": "https://Stackoverflow.com/users/6995", "pm_score": 4, "selected": false, "text": "<p>In my case, we're building a product for which we have a Visual Studio solution, with various components in their own projects. The common attributes go. In the solution, there are about 35 projects, and a common assembly info (CommonAssemblyInfo.cs), which has the following attributes:</p>\n\n<pre><code>[assembly: AssemblyCompany(\"Company\")]\n[assembly: AssemblyProduct(\"Product Name\")]\n[assembly: AssemblyCopyright(\"Copyright © 2007 Company\")]\n[assembly: AssemblyTrademark(\"Company\")]\n\n//This shows up as Product Version in Windows Explorer\n//We make this the same for all files in a particular product version. And increment it globally for all projects.\n//We then use this as the Product Version in installers as well (for example built using Wix).\n[assembly: AssemblyInformationalVersion(\"0.9.2.0\")]\n</code></pre>\n\n<p>The other attributes such as AssemblyTitle, AssemblyVersion etc, we supply on a per-assembly basis. When building an assembly both AssemblyInfo.cs and CommonAssemblyInfo.cs are built into each assembly. This gives us the best of both worlds where you may want to have some common attributes for all projects and specific values for some others.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 63000, "author": "jlew", "author_id": 7450, "author_profile": "https://Stackoverflow.com/users/7450", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://github.com/loresoft/msbuildtasks\" rel=\"nofollow noreferrer\">MSBuild Community Tasks</a> contains a custom task called AssemblyInfo which you can use to generate your assemblyinfo.cs. It requires a little hand-editing of your csproj files to use, but is worthwhile. </p>\n" }, { "answer_id": 63132, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 4, "selected": false, "text": "<p>The solution presented by @JRoppert is almost the same as what I do. The only difference is that I put the following lines in the local AssemblyInfo.cs file as they can vary with each assembly:</p>\n\n<pre><code>#if DEBUG\n[assembly: AssemblyConfiguration(\"Debug\")]\n#else\n[assembly: AssemblyConfiguration(\"Release\")]\n#endif\n[assembly: AssemblyVersion(\"This is set by build process\")]\n[assembly: AssemblyFileVersion(\"This is set by build process\")]\n[assembly: CLSCompliant(true)]\n</code></pre>\n\n<p>I also (generally) use one common assembly info per solution, with the assumption that one solution is a single product line/releasable product. The common assembly info file also has:</p>\n\n<pre><code>[assembly: AssemblyInformationalVersion(\"0.9.2.0\")]\n</code></pre>\n\n<p>Which will set the \"ProductVersion\" value displayed by Windows Explorer.</p>\n" }, { "answer_id": 25117433, "author": "Jack Ukleja", "author_id": 61714, "author_profile": "https://Stackoverflow.com/users/61714", "pm_score": 3, "selected": false, "text": "<p>In my opinion using a GlobalAssemblyInfo.cs is more trouble than it's worth, because you need to modify every project file and remember to modify every new project, whereas you get an AssemblyInfo.cs by default.</p>\n\n<p>For changes to global values (i.e. Company, Product etc) the changes are usually so infrequent and simple to manage I don't think <a href=\"http://en.wikipedia.org/wiki/Don&#39;t_repeat_yourself\" rel=\"noreferrer\">DRY</a> should be a consideration. Just run the following MSBuild script (dependent on the <a href=\"http://mikefourie.github.io/MSBuildExtensionPack/\" rel=\"noreferrer\">MSBuild Extension Pack</a>) when you want to manually change the values in all projects as a one-off:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;Project ToolsVersion=\"4.0\" DefaultTargets=\"UpdateAssemblyInfo\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"&gt;\n\n &lt;ItemGroup&gt;\n &lt;AllAssemblyInfoFiles Include=\"..\\**\\AssemblyInfo.cs\" /&gt;\n &lt;/ItemGroup&gt;\n\n &lt;Import Project=\"MSBuild.ExtensionPack.tasks\" /&gt;\n\n &lt;Target Name=\"UpdateAssemblyInfo\"&gt;\n &lt;Message Text=\"%(AllAssemblyInfoFiles.FullPath)\" /&gt;\n &lt;MSBuild.ExtensionPack.Framework.AssemblyInfo \n AssemblyInfoFiles=\"@(AllAssemblyInfoFiles)\"\n AssemblyCompany=\"Company\"\n AssemblyProduct=\"Product\"\n AssemblyCopyright=\"Copyright\"\n ... etc ...\n /&gt;\n &lt;/Target&gt;\n\n&lt;/Project&gt;\n</code></pre>\n" }, { "answer_id": 39352322, "author": "John Denniston", "author_id": 4511145, "author_profile": "https://Stackoverflow.com/users/4511145", "pm_score": 1, "selected": false, "text": "<p>One thing I have found useful is to generate the AssemblyVersion elements (etc) by applying token-substitution in the pre-build phase.</p>\n\n<p>I use TortoiseSvn, and it is easy to use its <code>SubWCRev.exe</code> to turn a template <code>AssemblyInfo.wcrev</code> into <code>AssemblyInfo.cs</code>. The relevant line in the template might look something like this:</p>\n\n<pre><code>[assembly: AssemblyVersion(\"2.3.$WCREV$.$WCMODS?1:0$$WCUNVER?1:0$\")]\n</code></pre>\n\n<p>The third element is then the revision number. I use the fourth element to check I haven't forgotten to commit any new or changed files (the fourth element is 00 if it is all OK).</p>\n\n<p>By the way, add <code>AssemblyInfo.wcrev</code> to your version control and <strong>ignore</strong> <code>AssemblyInfo.cs</code> if you use this.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361/" ]
I have a solution with multiple project. I am trying to optimize AssemblyInfo.cs files by linking one solution wide assembly info file. What are the best practices for doing this? Which attributes should be in solution wide file and which are project/assembly specific? --- *Edit: If you are interested there is a follow up question [What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?](https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin)*
We're using a global file called GlobalAssemblyInfo.cs and a local one called AssemblyInfo.cs. The global file contains the following attributes: ``` [assembly: AssemblyProduct("Your Product Name")] [assembly: AssemblyCompany("Your Company")] [assembly: AssemblyCopyright("Copyright © 2008 ...")] [assembly: AssemblyTrademark("Your Trademark - if applicable")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyVersion("This is set by build process")] [assembly: AssemblyFileVersion("This is set by build process")] ``` The local AssemblyInfo.cs contains the following attributes: ``` [assembly: AssemblyTitle("Your assembly title")] [assembly: AssemblyDescription("Your assembly description")] [assembly: AssemblyCulture("The culture - if not neutral")] [assembly: ComVisible(true/false)] // unique id per assembly [assembly: Guid("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")] ``` You can add the GlobalAssemblyInfo.cs using the following procedure: * Select **Add/Existing Item...** in the context menu of the project * Select GlobalAssemblyInfo.cs * Expand the Add-Button by clicking on that little down-arrow on the right hand * Select "Add As Link" in the buttons drop down list
62,365
<p>Say I have an ASMX web service, MyService. The service has a method, MyMethod. I could execute MyMethod on the server side as follows:</p> <pre><code>MyService service = new MyService(); service.MyMethod(); </code></pre> <p>I need to do similar, with service and method not known until runtime. </p> <p>I'm assuming that reflection is the way to go about that. Unfortunately, I'm having a hard time making it work. When I execute this code:</p> <pre><code>Type.GetType("MyService", true); </code></pre> <p>It throws this error:</p> <blockquote> <p>Could not load type 'MyService' from assembly 'App_Web__ktsp_r0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.</p> </blockquote> <p>Any guidance would be appreciated.</p>
[ { "answer_id": 62381, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 3, "selected": true, "text": "<p>I'm not sure if this would be the best way to go about it. The most obvious way to me, would be to make an HTTP Request, and call the webservice using an actual HTTP GET or POST. Using your method, I'm not entirely sure how you'd set up the data you are sending to the web service. I've added some sample code in VB.Net</p>\n\n<pre><code>Dim HTTPRequest As HttpWebRequest\nDim HTTPResponse As HttpWebResponse\nDim ResponseReader As StreamReader\nDim URL AS String\nDim ResponseText As String\n\nURL = \"http://www.example.com/MyWebSerivce/MyMethod?arg1=A&amp;arg2=B\"\n\nHTTPRequest = HttpWebRequest.Create(URL)\nHTTPRequest.Method = \"GET\"\n\nHTTPResponse = HTTPRequest.GetResponse()\n\nResponseReader = New StreamReader(HTTPResponse.GetResponseStream())\nResponseText = ResponseReader.ReadToEnd()\n</code></pre>\n" }, { "answer_id": 62461, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 1, "selected": false, "text": "<p>Although I don't know why Reflection is not working for you there (I assume the compiler might be creating a new class from your <code>[WebService]</code> annotations), here is some advice that might solve your problem:</p>\n\n<p><strong>Keep your WebService simple, shallow, in short: An implementation of the Facade Pattern</strong>.</p>\n\n<p>Make your service delegate computation to an implementation class, which should easily be callable through Reflection. This way, your WebService class is just a front for your system - you can even add an email handler, XML-RPC frontend etc., since your logic is not coupled to the WebService, but to an actual business layer object.</p>\n\n<p>Think of WebService classes as UI layer objects in your Architecture.</p>\n" }, { "answer_id": 62587, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 0, "selected": false, "text": "<p>@Kibbee: I need to avoid the HTTP performance hit. It won't be a remote call, so all of that added overhead <em>should</em> be unnecessary.</p>\n\n<p>@Daren: I definitely agree with that design philosophy. The issue here is that I'm not going to be in control of the service or its underlying business logic.</p>\n\n<p>This is for <a href=\"http://codeplex.com/UsernameAvailability\" rel=\"nofollow noreferrer\">a server control</a> that will need to execute against an arbitrary service/method, orthogonally to how the web service itself is implemented.</p>\n" }, { "answer_id": 62687, "author": "Radu094", "author_id": 3263, "author_profile": "https://Stackoverflow.com/users/3263", "pm_score": 0, "selected": false, "text": "<p>Although I cannot tell from your post:</p>\n\n<p>One thing to keep in mind is that if you use reflection, you need to create an instance of the autogenerated webservice class(the one created from your webservice's WSDL). Do not create the class that is responsbile for the server-side of the service.</p>\n\n<p>So if you have a webservice </p>\n\n<pre><code> [WebService(Namespace = \"http://tempuri.org/\")]\n [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\n [ToolboxItem(false)]\n public class WebService1 : System.Web.Services.WebService\n {\n ...\n }\n</code></pre>\n\n<p>you cannot reference that assembly in your client and do something like:</p>\n\n<pre><code>WebService1 ws = new WebService1 ();\nws.SomeMethod();\n</code></pre>\n" }, { "answer_id": 62774, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 0, "selected": false, "text": "<p>@Radu: I'm able to create an instance and call the method exactly like that. For example, if I have this ASMX:</p>\n\n<pre>[WebService(Namespace = \"http://tempuri.org/\")]\n[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\n[ScriptService]\npublic class MyService : System.Web.Services.WebService\n{\n [WebMethod]\n public string HelloWorld()\n {\n return \"Hello World\";\n }\n}</pre>\n\n<p>I'm able to call it from an ASPX page's codebehind like this:</p>\n\n<pre>MyService service = new MyService();\nResponse.Write(service.HelloWorld());</pre>\n\n<p>Are you saying that shouldn't work?</p>\n" }, { "answer_id": 62794, "author": "Steve Eisner", "author_id": 7104, "author_profile": "https://Stackoverflow.com/users/7104", "pm_score": 1, "selected": false, "text": "<p>Here's a quick answer someone can probably expand on.</p>\n\n<p>When you use the WSDL templating app (WSDL.exe) to genereate service wrappers, it builds a class of type SoapHttpClientProtocol. You can do it manually, too:</p>\n\n<pre><code>public class MyService : SoapHttpClientProtocol\n{\n public MyService(string url)\n {\n this.Url = url;\n // plus set credentials, etc.\n }\n\n [SoapDocumentMethod(\"{service url}\", RequestNamespace=\"{namespace}\", ResponseNamespace=\"{namespace}\", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]\n public int MyMethod(string arg1)\n {\n object[] results = this.Invoke(\"MyMethod\", new object[] { arg1 });\n return ((int)(results[0]));\n }\n}\n</code></pre>\n\n<p>I haven't tested this code but I imagine it should work stand-alone without having to run the WSDL tool.</p>\n\n<p>The code I've provided is the caller code which hooks up to the web service via a remote call (even if for whatever reason, you don't actually want it to be remote.) The Invoke method takes care of packaging it as a Soap call. @Dave Ward's code is correct if you want to bypass the web service call via HTTP - as long as you are actually able to reference the class. Perhaps the internal type is not \"MyService\" - you'd have to inspect the control's code to know for sure.</p>\n" }, { "answer_id": 87636, "author": "Steve Eisner", "author_id": 7104, "author_profile": "https://Stackoverflow.com/users/7104", "pm_score": 0, "selected": false, "text": "<p>I looked back at this question and I think what you're facing is that the ASMX code will be built into a DLL with a random name as part of the dynamic compilation of your site. Your code to look up the type will, by default, only search its own assembly (another App_Code DLL, by the looks of the error you received) and core libraries. You could provide a specific assembly reference \"TypeName, AssemblyName\" to GetType() but that's not possible in the case of the automatically generated assemblies, which have new names after each recompile.</p>\n\n<p>Solution.... I haven't done this myself before but I believe that you should be able to use something like this:</p>\n\n<pre><code>System.Web.Compilation.BuildManager.GetType(\"MyService\", true)\n</code></pre>\n\n<p>as the BuildManager is aware of the DLLs it has created and knows where to look.</p>\n\n<p>I guess this really doesn't have to do with Web Services but if it were your own code, Daren's right about Facade patterns.</p>\n" }, { "answer_id": 730158, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>// Try this -></p>\n\n<pre><code> Type t = System.Web.Compilation.BuildManager.GetType(\"MyServiceClass\", true);\n object act = Activator.CreateInstance(t); \n object o = t.GetMethod(\"hello\").Invoke(act, null);\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60/" ]
Say I have an ASMX web service, MyService. The service has a method, MyMethod. I could execute MyMethod on the server side as follows: ``` MyService service = new MyService(); service.MyMethod(); ``` I need to do similar, with service and method not known until runtime. I'm assuming that reflection is the way to go about that. Unfortunately, I'm having a hard time making it work. When I execute this code: ``` Type.GetType("MyService", true); ``` It throws this error: > > Could not load type 'MyService' from assembly 'App\_Web\_\_ktsp\_r0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. > > > Any guidance would be appreciated.
I'm not sure if this would be the best way to go about it. The most obvious way to me, would be to make an HTTP Request, and call the webservice using an actual HTTP GET or POST. Using your method, I'm not entirely sure how you'd set up the data you are sending to the web service. I've added some sample code in VB.Net ``` Dim HTTPRequest As HttpWebRequest Dim HTTPResponse As HttpWebResponse Dim ResponseReader As StreamReader Dim URL AS String Dim ResponseText As String URL = "http://www.example.com/MyWebSerivce/MyMethod?arg1=A&arg2=B" HTTPRequest = HttpWebRequest.Create(URL) HTTPRequest.Method = "GET" HTTPResponse = HTTPRequest.GetResponse() ResponseReader = New StreamReader(HTTPResponse.GetResponseStream()) ResponseText = ResponseReader.ReadToEnd() ```
62,382
<p>I might be missing something really obvious. I'm trying to write a custom Panel where the contents are laid out according to a couple of dependency properties (I'm assuming they <em>have</em> to be DPs because I want to be able to animate them.)</p> <p>However, when I try to run a storyboard to animate both of these properties, Silverlight throws a Catastophic Error. But if I try to animate just one of them, it works fine. And if I try to animate one of my properties and a 'built-in' property (like Opacity) it also works. But if I try to animate both my custom properties I get the Catastrophic error.</p> <p>Anyone else come across this?</p> <p>edit:</p> <p>The two DPs are ScaleX and ScaleY - both doubles. They scale the X and Y position of children in the panel. Here's how one of them is defined:</p> <pre><code> public double ScaleX { get { return (double)GetValue(ScaleXProperty); } set { SetValue(ScaleXProperty, value); } } /// &lt;summary&gt; /// Identifies the ScaleX dependency property. /// &lt;/summary&gt; public static readonly DependencyProperty ScaleXProperty = DependencyProperty.Register( "ScaleX", typeof(double), typeof(MyPanel), new PropertyMetadata(OnScaleXPropertyChanged)); /// &lt;summary&gt; /// ScaleXProperty property changed handler. /// &lt;/summary&gt; /// &lt;param name="d"&gt;MyPanel that changed its ScaleX.&lt;/param&gt; /// &lt;param name="e"&gt;DependencyPropertyChangedEventArgs.&lt;/param&gt; private static void OnScaleXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MyPanel _MyPanel = d as MyPanel; if (_MyPanel != null) { _MyPanel.InvalidateArrange(); } } public static void SetScaleX(DependencyObject obj, double val) { obj.SetValue(ScaleXProperty, val); } public static double GetScaleX(DependencyObject obj) { return (double)obj.GetValue(ScaleXProperty); } </code></pre> <p>Edit: I've tried it with and without the call to InvalidateArrange (which is absolutely necessary in any case) and the result is the same. The event handler doesn't even get called before the Catastrophic error kicks off.</p>
[ { "answer_id": 72058, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I would try commenting out the InvalidateArrange in the OnPropertyChanged and see what happens.</p>\n" }, { "answer_id": 86917, "author": "Arun", "author_id": 16671, "author_profile": "https://Stackoverflow.com/users/16671", "pm_score": 2, "selected": true, "text": "<p>It's a documented bug with Silverlight 2 Beta 2. You can't animate two custom dependancy properties on the same object.</p>\n" }, { "answer_id": 140824, "author": "Jim Lynn", "author_id": 6483, "author_profile": "https://Stackoverflow.com/users/6483", "pm_score": 0, "selected": false, "text": "<p>I hope it's not bad form to answer my own question.</p>\n\n<p>Silverlight 2 Release Candidate 0 was released today, I've tested this problem on it, and it appears to have been fixed. Both Custom DPs in my test panel can now be animated properly, so the app is behaving as expected. Which is nice.</p>\n\n<p>Note that this RC is only a developer-based RC so the standard build of Silverlight hasn't been updated. I'd expect it to be fully released in the next month, though.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6483/" ]
I might be missing something really obvious. I'm trying to write a custom Panel where the contents are laid out according to a couple of dependency properties (I'm assuming they *have* to be DPs because I want to be able to animate them.) However, when I try to run a storyboard to animate both of these properties, Silverlight throws a Catastophic Error. But if I try to animate just one of them, it works fine. And if I try to animate one of my properties and a 'built-in' property (like Opacity) it also works. But if I try to animate both my custom properties I get the Catastrophic error. Anyone else come across this? edit: The two DPs are ScaleX and ScaleY - both doubles. They scale the X and Y position of children in the panel. Here's how one of them is defined: ``` public double ScaleX { get { return (double)GetValue(ScaleXProperty); } set { SetValue(ScaleXProperty, value); } } /// <summary> /// Identifies the ScaleX dependency property. /// </summary> public static readonly DependencyProperty ScaleXProperty = DependencyProperty.Register( "ScaleX", typeof(double), typeof(MyPanel), new PropertyMetadata(OnScaleXPropertyChanged)); /// <summary> /// ScaleXProperty property changed handler. /// </summary> /// <param name="d">MyPanel that changed its ScaleX.</param> /// <param name="e">DependencyPropertyChangedEventArgs.</param> private static void OnScaleXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MyPanel _MyPanel = d as MyPanel; if (_MyPanel != null) { _MyPanel.InvalidateArrange(); } } public static void SetScaleX(DependencyObject obj, double val) { obj.SetValue(ScaleXProperty, val); } public static double GetScaleX(DependencyObject obj) { return (double)obj.GetValue(ScaleXProperty); } ``` Edit: I've tried it with and without the call to InvalidateArrange (which is absolutely necessary in any case) and the result is the same. The event handler doesn't even get called before the Catastrophic error kicks off.
It's a documented bug with Silverlight 2 Beta 2. You can't animate two custom dependancy properties on the same object.
62,430
<p>Is is possible to construct a regular expression that rejects all input strings?</p>
[ { "answer_id": 62438, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "<p>EDIT:\n [^\\n\\r\\w\\s]</p>\n" }, { "answer_id": 62473, "author": "Jan Hančič", "author_id": 185527, "author_profile": "https://Stackoverflow.com/users/185527", "pm_score": 1, "selected": false, "text": "<p>Why would you even want that? Wouldn't a simple if statment do the trick? Something along the lines of:</p>\n\n<pre><code>if ( inputString != \"\" )\n doSomething ()\n</code></pre>\n" }, { "answer_id": 62475, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": true, "text": "<p>Probably this:</p>\n\n<pre><code>[^\\w\\W]\n</code></pre>\n\n<p>\\w - word character (letter, digit, etc)<br>\n\\W - opposite of \\w</p>\n\n<p>[^\\w\\W] - should always fail, because any character should belong to one of the character classes - \\w or \\W</p>\n\n<p>Another snippets:</p>\n\n<pre><code>$.^\n</code></pre>\n\n<p>$ - assert position at the end of the string<br>\n^ - assert position at the start of the line<br>\n. - any char </p>\n\n<pre><code>(?#it's just a comment inside of empty regex)\n</code></pre>\n\n<p>Empty lookahead/behind should work:</p>\n\n<pre><code>(?&lt;!)\n</code></pre>\n" }, { "answer_id": 62497, "author": "Erik", "author_id": 6733, "author_profile": "https://Stackoverflow.com/users/6733", "pm_score": 0, "selected": false, "text": "<p>[^\\x00-\\xFF]</p>\n" }, { "answer_id": 62508, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": -1, "selected": false, "text": "<p>Well,</p>\n\n<p>I am not sure if I understood, since I always thought of regular expression of a way to match strings. I would say the best shot you have is not using regex.</p>\n\n<p>But, you can also use regexp that matches empty lines like <code>^$</code> or a regexp that do not match words/spaces like <code>[^\\w\\s]</code> ...</p>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 62561, "author": "Henrik N", "author_id": 6962, "author_profile": "https://Stackoverflow.com/users/6962", "pm_score": 2, "selected": false, "text": "<pre><code>(?=not)possible\n</code></pre>\n\n<p>?= is a positive lookahead. They're not supported in all regexp flavors, but in many.</p>\n\n<p>The expression will look for \"not\", then look for \"possible\" starting at the same position (since lookaheads don't move forward in the string).</p>\n" }, { "answer_id": 62758, "author": "asksol", "author_id": 5577, "author_profile": "https://Stackoverflow.com/users/5577", "pm_score": 1, "selected": false, "text": "<p>To me it sounds like you're attacking a problem the wrong way, what exactly\nare you trying to solve?</p>\n\n<p>You could do a regular expression that catches everything and negate the result.</p>\n\n<p>e.g in javascript:</p>\n\n<pre><code>if (! str.match( /./ ))\n</code></pre>\n\n<p>but then you could just do</p>\n\n<pre><code>if (!foo)\n</code></pre>\n\n<p>instead, as @[jan-hani] said.</p>\n\n<p>If you're looking to embed such a regex in another regex, you\nmight be looking for <em>$</em> or <em>^</em> instead, or use lookaheads like @[henrik-n] mentioned.</p>\n\n<p>But as I said, this looks like a \"I think I need x, but what I really need is y\" problem.</p>\n" }, { "answer_id": 62896, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It depends on what you mean by \"regular expression\". Do you mean regexps in a particular programming language or library? In that case the answer is probably yes, and you can refer to any of the above replies. </p>\n\n<p>If you mean the regular expressions as taught in computer science classes, then the answer is no. Every regular expression matches some string. It could be the empty string, but it always matches <em>something</em>.</p>\n\n<p>In any case, I suggest you edit the title of your question to narrow down what kinds of regular expressions you mean.</p>\n" }, { "answer_id": 63905, "author": "squadette", "author_id": 7754, "author_profile": "https://Stackoverflow.com/users/7754", "pm_score": 2, "selected": false, "text": "<p>One example of why such thing could possibly be needed is when you want to filter some input with regexes and you pass regex as an argument to a function.</p>\n\n<p>In spirit of functional programming, for algebraic completeness, you may want some trivial primary regexes like \"everything is allowed\" and \"nothing is allowed\".</p>\n" }, { "answer_id": 70015, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 0, "selected": false, "text": "<p><code>[^]+</code> should do it.</p>\n\n<p>In answer to aku's comment attached to this, I tested it with an online regex tester (<a href=\"http://www.regextester.com/\" rel=\"nofollow noreferrer\">http://www.regextester.com/</a>), and so assume it works with JavaScript. I have to confess to not testing it in \"real\" code. ;)</p>\n" }, { "answer_id": 79286, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 3, "selected": false, "text": "<p>The <em>best</em> standard regexs (i.e., no lookahead or back-references) that reject all inputs are (after @aku above)</p>\n\n<pre><code>.^\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$.\n</code></pre>\n\n<p>These are flat contradictions: \"a string with a character before its beginning\" and \"a string with a character after its end.\"</p>\n\n<p>NOTE: It's possible that some regex implementations would reject these patterns as ill-formed (it's pretty easy to check that <code>^</code> comes at the beginning of a pattern and <code>$</code> at the end... with a regular expression), but the few I've checked do accept them. These also won't work in implementations that allow <code>^</code> and <code>$</code> to match newlines.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4984/" ]
Is is possible to construct a regular expression that rejects all input strings?
Probably this: ``` [^\w\W] ``` \w - word character (letter, digit, etc) \W - opposite of \w [^\w\W] - should always fail, because any character should belong to one of the character classes - \w or \W Another snippets: ``` $.^ ``` $ - assert position at the end of the string ^ - assert position at the start of the line . - any char ``` (?#it's just a comment inside of empty regex) ``` Empty lookahead/behind should work: ``` (?<!) ```
62,436
<p>I am having a problem with the speed of accessing an association property with a large number of records.</p> <p>I have an XAF app with a parent class called <code>MyParent</code>.</p> <p>There are 230 records in <code>MyParent</code>.</p> <p><code>MyParent</code> has a child class called <code>MyChild</code>.</p> <p>There are 49,000 records in <code>MyChild</code>.</p> <p>I have an association defined between <code>MyParent</code> and <code>MyChild</code> in the standard way:</p> <p>In <code>MyChild</code>:</p> <pre><code>// MyChild (many) and MyParent (one) [Association("MyChild-MyParent")] public MyParent MyParent; </code></pre> <p>And in <code>MyParent</code>:</p> <pre><code>[Association("MyChild-MyParent", typeof(MyChild))] public XPCollection&lt;MyCHild&gt; MyCHildren { get { return GetCollection&lt;MyCHild&gt;("MyCHildren"); } } </code></pre> <p>There's a specific <code>MyParent</code> record called <code>MyParent1</code>.</p> <p>For <code>MyParent1</code>, there are 630 <code>MyChild</code> records.</p> <p>I have a DetailView for a class called <code>MyUI</code>.</p> <p>The user chooses an item in one drop-down in the <code>MyUI</code> DetailView, and my code has to fill another drop-down with <code>MyChild</code> objects.</p> <p>The user chooses <code>MyParent1</code> in the first drop-down.</p> <p>I created a property in <code>MyUI</code> to return the collection of <code>MyChild</code> objects for the selected value in the first drop-down.</p> <p>Here is the code for the property:</p> <pre><code>[NonPersistent] public XPCollection&lt;MyChild&gt; DisplayedValues { get { Session theSession; MyParent theParentValue; XPCollection&lt;MyCHild&gt; theChildren; theParentValue = this.DropDownOne; // get the parent value if theValue == null) { // if none return null; // return null } theChildren = theParentValue.MyChildren; // get the child values for the parent return theChildren; // return it } </code></pre> <p>I marked the <code>DisplayedValues</code> property as <code>NonPersistent</code> because it is only needed for the UI of the DetailVIew. I don't think that persisting it will speed up the creation of the collection the first time, and after it's used to fill the drop-down, I don't need it, so I don't want to spend time storing it.</p> <p>The problem is that it takes 45 seconds to call <code>theParentValue = this.DropDownOne</code>.</p> <p>Specs:</p> <ul> <li>Vista Business</li> <li>8 GB of RAM</li> <li>2.33 GHz E6550 processor</li> <li>SQL Server Express 2005</li> </ul> <p>This is too long for users to wait for one of many drop-downs in the DetailView.</p> <p>I took the time to sketch out the business case because I have two questions:</p> <ol> <li><p>How can I make the associated values load faster?</p></li> <li><p>Is there another (simple) way to program the drop-downs and DetailView that runs much faster?</p></li> </ol> <p>Yes, you can say that 630 is too many items to display in a drop-down, but this code is taking so long I suspect that the speed is proportional to the 49,000 and not to the 630. 100 items in the drop-down would not be too many for my app.</p> <p>I need quite a few of these drop-downs in my app, so it's not appropriate to force the user to enter more complicated filtering criteria for each one. The user needs to pick one value and see the related values.</p> <p>I would understand if finding a large number of records was slow, but finding a few hundred shouldn't take that long.</p>
[ { "answer_id": 78123, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 3, "selected": true, "text": "<p>Firstly you are right to be sceptical that this operation should take this long, XPO on read operations should add only between 30 - 70% overhead, and on this tiny amount of data we should be talking milli-seconds not seconds.</p>\n\n<p>Some general perf tips are available in the DevExpress forums, and centre around object caching, lazy vs deep loads etc, but I think in your case the issue is something else, unfortunately its very hard to second guess whats going on from your question, only to say, its highly unlikely to be a problem with XPO much more likely to be something else, I would be inclined to look at your session creation (this also creates your object cache) and SQL connection code (the IDataStore stuff), Connections are often slow if hosts cannot not be resolved cleanly and if you are not pooling / re-using connections this problem can be exacerbated.</p>\n" }, { "answer_id": 91582, "author": "MindModel", "author_id": 6783, "author_profile": "https://Stackoverflow.com/users/6783", "pm_score": 0, "selected": false, "text": "<p>Thanks for the answer. I created a separate solution and was able to get good performance, as you suggest.</p>\n\n<p>My SQL connection is OK and works with other features in the app.</p>\n\n<p>Given that I'm using XAF and not doing anything extra/fancy, aren't my sessions managed by XAF?</p>\n\n<p>The session I use is read from the DetailView.</p>\n" }, { "answer_id": 1169654, "author": "Steven Evers", "author_id": 48553, "author_profile": "https://Stackoverflow.com/users/48553", "pm_score": 1, "selected": false, "text": "<p>I'm unsure why you would be doing it the way you are. If you've created an association like this:</p>\n\n<pre><code>public class A : XPObject\n{\n [Association(\"a&lt;b\", typeof(b))]\n public XPCollection&lt;b&gt; bs { get { GetCollection(\"bs\"); } }\n}\n\npublic class B : XPObject\n{\n [Association(\"a&lt;b\") Persistent(\"Aid\")]\n public A a { get; set; }\n}\n</code></pre>\n\n<p>then when you want to populate a dropdown (like a lookupEdit control)</p>\n\n<pre><code>A myA = GetSomeParticularA();\nlupAsBs.Properties.DataSource = myA.Bs;\nlupAsBs.Properties.DisplayMember = \"WhateverPropertyName\";\n</code></pre>\n\n<p>You don't have to load A's children, XPO will load them as they're needed, and there's no session management necessary for this at all.</p>\n" }, { "answer_id": 3474668, "author": "Tien Do", "author_id": 108616, "author_profile": "https://Stackoverflow.com/users/108616", "pm_score": 0, "selected": false, "text": "<p>I'm not sure about your case, just want to share some my experiences with XAF.</p>\n\n<p>The first time you click on a dropdown (lookup list) control (in a detail view), there will be two queries sent to the database to populate the list. In my tests, sometimes entire object is loaded into the source collection, not just ID and Name properties as we thought so depends on your objects you may want to use lighter ones for lists. You can also turn on Server Mode of the list then only 128 objects are loaded each time.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6783/" ]
I am having a problem with the speed of accessing an association property with a large number of records. I have an XAF app with a parent class called `MyParent`. There are 230 records in `MyParent`. `MyParent` has a child class called `MyChild`. There are 49,000 records in `MyChild`. I have an association defined between `MyParent` and `MyChild` in the standard way: In `MyChild`: ``` // MyChild (many) and MyParent (one) [Association("MyChild-MyParent")] public MyParent MyParent; ``` And in `MyParent`: ``` [Association("MyChild-MyParent", typeof(MyChild))] public XPCollection<MyCHild> MyCHildren { get { return GetCollection<MyCHild>("MyCHildren"); } } ``` There's a specific `MyParent` record called `MyParent1`. For `MyParent1`, there are 630 `MyChild` records. I have a DetailView for a class called `MyUI`. The user chooses an item in one drop-down in the `MyUI` DetailView, and my code has to fill another drop-down with `MyChild` objects. The user chooses `MyParent1` in the first drop-down. I created a property in `MyUI` to return the collection of `MyChild` objects for the selected value in the first drop-down. Here is the code for the property: ``` [NonPersistent] public XPCollection<MyChild> DisplayedValues { get { Session theSession; MyParent theParentValue; XPCollection<MyCHild> theChildren; theParentValue = this.DropDownOne; // get the parent value if theValue == null) { // if none return null; // return null } theChildren = theParentValue.MyChildren; // get the child values for the parent return theChildren; // return it } ``` I marked the `DisplayedValues` property as `NonPersistent` because it is only needed for the UI of the DetailVIew. I don't think that persisting it will speed up the creation of the collection the first time, and after it's used to fill the drop-down, I don't need it, so I don't want to spend time storing it. The problem is that it takes 45 seconds to call `theParentValue = this.DropDownOne`. Specs: * Vista Business * 8 GB of RAM * 2.33 GHz E6550 processor * SQL Server Express 2005 This is too long for users to wait for one of many drop-downs in the DetailView. I took the time to sketch out the business case because I have two questions: 1. How can I make the associated values load faster? 2. Is there another (simple) way to program the drop-downs and DetailView that runs much faster? Yes, you can say that 630 is too many items to display in a drop-down, but this code is taking so long I suspect that the speed is proportional to the 49,000 and not to the 630. 100 items in the drop-down would not be too many for my app. I need quite a few of these drop-downs in my app, so it's not appropriate to force the user to enter more complicated filtering criteria for each one. The user needs to pick one value and see the related values. I would understand if finding a large number of records was slow, but finding a few hundred shouldn't take that long.
Firstly you are right to be sceptical that this operation should take this long, XPO on read operations should add only between 30 - 70% overhead, and on this tiny amount of data we should be talking milli-seconds not seconds. Some general perf tips are available in the DevExpress forums, and centre around object caching, lazy vs deep loads etc, but I think in your case the issue is something else, unfortunately its very hard to second guess whats going on from your question, only to say, its highly unlikely to be a problem with XPO much more likely to be something else, I would be inclined to look at your session creation (this also creates your object cache) and SQL connection code (the IDataStore stuff), Connections are often slow if hosts cannot not be resolved cleanly and if you are not pooling / re-using connections this problem can be exacerbated.
62,437
<p>I load some XML from a servlet from my Flex application like this:</p> <pre><code>_loader = new URLLoader(); _loader.load(new URLRequest(_servletURL+"?do=load&amp;id="+_id)); </code></pre> <p>As you can imagine <code>_servletURL</code> is something like <a href="http://foo.bar/path/to/servlet" rel="nofollow noreferrer">http://foo.bar/path/to/servlet</a></p> <p>In some cases, this URL contains accented characters (long story). I pass the <code>unescaped</code> string to <code>URLRequest</code>, but it seems that flash escapes it and calls the escaped URL, which is invalid. Ideas?</p>
[ { "answer_id": 62519, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 2, "selected": false, "text": "<p>I'm not sure if this will be any different, but this is a cleaner way of achieving the same URLRequest:</p>\n\n<pre><code>var request:URLRequest = new URLRequest(_servletURL)\nrequest.method = URLRequestMethod.GET;\nvar reqData:Object = new Object();\n\nreqData.do = \"load\";\nreqData.id = _id;\nrequest.data = reqData;\n\n_loader = new URLLoader(request); \n</code></pre>\n" }, { "answer_id": 62994, "author": "Ryan Guill", "author_id": 7186, "author_profile": "https://Stackoverflow.com/users/7186", "pm_score": 0, "selected": false, "text": "<p>From the livedocs: <a href=\"http://livedocs.adobe.com/flex/3/langref/flash/net/URLRequest.html\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flex/3/langref/flash/net/URLRequest.html</a></p>\n\n<blockquote>\n <p>Creates a URLRequest object. If System.useCodePage is true, the request is encoded using the system code page, rather than Unicode. If System.useCodePage is false, the request is encoded using Unicode, rather than the system code page.</p>\n</blockquote>\n\n<p>This page has more information: <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=18_Client_System_Environment_3.html\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flex/3/html/help.html?content=18_Client_System_Environment_3.html</a></p>\n\n<p>but basically you just need to add this to a function that will be run before the URLRequest (I would probably put it in a creationComplete event)</p>\n\n<p><code>System.useCodePage = false</code>;</p>\n" }, { "answer_id": 87530, "author": "Peldi Guilizzoni", "author_id": 1199623, "author_profile": "https://Stackoverflow.com/users/1199623", "pm_score": 3, "selected": false, "text": "<p>My friend Luis figured it out:</p>\n\n<p>You should use encodeURI does the UTF8URL encoding\n<a href=\"http://livedocs.adobe.com/flex/3/langref/package.html#encodeURI()\" rel=\"noreferrer\">http://livedocs.adobe.com/flex/3/langref/package.html#encodeURI()</a></p>\n\n<p>but not unescape because it unescapes to ASCII see\n<a href=\"http://livedocs.adobe.com/flex/3/langref/package.html#unescape()\" rel=\"noreferrer\">http://livedocs.adobe.com/flex/3/langref/package.html#unescape()</a></p>\n\n<p>I think that is where we are getting a %E9 in the URL instead of the expected %C3%A9.</p>\n\n<p><a href=\"http://www.w3schools.com/TAGS/ref_urlencode.asp\" rel=\"noreferrer\">http://www.w3schools.com/TAGS/ref_urlencode.asp</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199623/" ]
I load some XML from a servlet from my Flex application like this: ``` _loader = new URLLoader(); _loader.load(new URLRequest(_servletURL+"?do=load&id="+_id)); ``` As you can imagine `_servletURL` is something like <http://foo.bar/path/to/servlet> In some cases, this URL contains accented characters (long story). I pass the `unescaped` string to `URLRequest`, but it seems that flash escapes it and calls the escaped URL, which is invalid. Ideas?
My friend Luis figured it out: You should use encodeURI does the UTF8URL encoding <http://livedocs.adobe.com/flex/3/langref/package.html#encodeURI()> but not unescape because it unescapes to ASCII see <http://livedocs.adobe.com/flex/3/langref/package.html#unescape()> I think that is where we are getting a %E9 in the URL instead of the expected %C3%A9. <http://www.w3schools.com/TAGS/ref_urlencode.asp>
62,447
<p>Tomcat fails to start even if i remove all my applications from the WEBAPPS directory leaving everything just like after the OS installation.</p> <p>The log (catalina.out) says:</p> <pre><code>Using CATALINA_BASE: /usr/share/tomcat5 Using CATALINA_HOME: /usr/share/tomcat5 Using CATALINA_TMPDIR: /usr/share/tomcat5/temp Using JRE_HOME: Created MBeanServer with ID: -dpv07y:fl4s82vl.0:hydrogenium.timberlinecolorado.com:1 java.lang.NoClassDefFoundError: org.apache.catalina.core.StandardService at java.lang.Class.initializeClass(libgcj.so.7rh) at java.lang.Class.initializeClass(libgcj.so.7rh) at java.lang.Class.initializeClass(libgcj.so.7rh) at java.lang.Class.newInstance(libgcj.so.7rh) at org.apache.catalina.startup.Bootstrap.init(bootstrap.jar.so) at org.apache.catalina.startup.Bootstrap.main(bootstrap.jar.so) Caused by: java.lang.ClassNotFoundException: org.apache.commons.modeler.Registry not found in org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/server/classes/,file:/usr/share/java/tomcat5/catalina-cluster-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-storeconfig-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-optional-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-coyote-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-jkstatus-ant-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-ajp-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-default-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-invoker-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-ant-jmx-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-http-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-util-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-apr-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/servlets-webdav-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-5.5.23.jar], parent=org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/common/classes/,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-ja.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-fr.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-en.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-es.jar,file:/usr/share/java/tomcat5/naming-resources-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/naming-factory-5.5.23.jar], parent=gnu.gcj.runtime.SystemClassLoader{urls=[file:/usr/lib/jvm/java/lib/tools.jar,file:/usr/share/tomcat5/bin/bootstrap.jar,file:/usr/share/tomcat5/bin/commons-logging-api.jar,file:/usr/share/java/mx4j/mx4j-impl.jar,file:/usr/share/java/mx4j/mx4j-jmx.jar], parent=gnu.gcj.runtime.ExtensionClassLoader{urls=[], parent=null}}}} at java.net.URLClassLoader.findClass(libgcj.so.7rh) at java.lang.ClassLoader.loadClass(libgcj.so.7rh) at java.lang.ClassLoader.loadClass(libgcj.so.7rh) at java.lang.Class.initializeClass(libgcj.so.7rh) ...5 more </code></pre>
[ { "answer_id": 62488, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 0, "selected": false, "text": "<p>This screams class path issue, to me. Where exactly is your tomcat installed? (Give us command line printouts of where the home directory is.) Also, how are you starting it?</p>\n" }, { "answer_id": 62559, "author": "tbond", "author_id": 6197, "author_profile": "https://Stackoverflow.com/users/6197", "pm_score": 0, "selected": false, "text": "<p>Check your <code>JAVA_HOME/JRE_HOME</code> setting. You might want to use a different JVM rather than the one that is installed with the OS</p>\n" }, { "answer_id": 64862, "author": "Alexandre Brasil", "author_id": 8841, "author_profile": "https://Stackoverflow.com/users/8841", "pm_score": 1, "selected": false, "text": "<p>Seems like you've implemented a JMX service and tried to install it on your server.xml file but forgot to add the apache commons modeler jar to the server/lib directory (therefore the <code>ClassNotFoundException</code> for <code>org.apache.commons.modeler.Registry</code>). Check your server.xml file for anything you might have added, and try to add the proper jar file to your server classpath.</p>\n" }, { "answer_id": 358763, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Seems like you need to have the jar for commons-modeler into <code>$CATALINA_HOME/common/lib</code>. You get the same kind of error when trying to setup JDBC datasources if you didn't put the driver's jar file into tomcat's server classpath.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Tomcat fails to start even if i remove all my applications from the WEBAPPS directory leaving everything just like after the OS installation. The log (catalina.out) says: ``` Using CATALINA_BASE: /usr/share/tomcat5 Using CATALINA_HOME: /usr/share/tomcat5 Using CATALINA_TMPDIR: /usr/share/tomcat5/temp Using JRE_HOME: Created MBeanServer with ID: -dpv07y:fl4s82vl.0:hydrogenium.timberlinecolorado.com:1 java.lang.NoClassDefFoundError: org.apache.catalina.core.StandardService at java.lang.Class.initializeClass(libgcj.so.7rh) at java.lang.Class.initializeClass(libgcj.so.7rh) at java.lang.Class.initializeClass(libgcj.so.7rh) at java.lang.Class.newInstance(libgcj.so.7rh) at org.apache.catalina.startup.Bootstrap.init(bootstrap.jar.so) at org.apache.catalina.startup.Bootstrap.main(bootstrap.jar.so) Caused by: java.lang.ClassNotFoundException: org.apache.commons.modeler.Registry not found in org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/server/classes/,file:/usr/share/java/tomcat5/catalina-cluster-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-storeconfig-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-optional-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-coyote-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-jkstatus-ant-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-ajp-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-default-5.5.23.jar,file:/usr/share/java/tomcat5/servlets-invoker-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-ant-jmx-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-http-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-util-5.5.23.jar,file:/usr/share/java/tomcat5/tomcat-apr-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/servlets-webdav-5.5.23.jar,file:/usr/share/java/tomcat5/catalina-5.5.23.jar], parent=org.apache.catalina.loader.StandardClassLoader{urls=[file:/var/lib/tomcat5/common/classes/,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-ja.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-fr.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-en.jar,file:/var/lib/tomcat5/common/i18n/tomcat-i18n-es.jar,file:/usr/share/java/tomcat5/naming-resources-5.5.23.jar,file:/usr/share/eclipse/plugins/org.eclipse.jdt.core_3.2.1.v_677_R32x.jar,file:/usr/share/java/tomcat5/naming-factory-5.5.23.jar], parent=gnu.gcj.runtime.SystemClassLoader{urls=[file:/usr/lib/jvm/java/lib/tools.jar,file:/usr/share/tomcat5/bin/bootstrap.jar,file:/usr/share/tomcat5/bin/commons-logging-api.jar,file:/usr/share/java/mx4j/mx4j-impl.jar,file:/usr/share/java/mx4j/mx4j-jmx.jar], parent=gnu.gcj.runtime.ExtensionClassLoader{urls=[], parent=null}}}} at java.net.URLClassLoader.findClass(libgcj.so.7rh) at java.lang.ClassLoader.loadClass(libgcj.so.7rh) at java.lang.ClassLoader.loadClass(libgcj.so.7rh) at java.lang.Class.initializeClass(libgcj.so.7rh) ...5 more ```
Seems like you've implemented a JMX service and tried to install it on your server.xml file but forgot to add the apache commons modeler jar to the server/lib directory (therefore the `ClassNotFoundException` for `org.apache.commons.modeler.Registry`). Check your server.xml file for anything you might have added, and try to add the proper jar file to your server classpath.
62,449
<p>When using the Net.Sockets.TcpListener, what is the best way to handle incoming connections (.AcceptSocket) in seperate threads?</p> <p>The idea is to start a new thread when a new incoming connection is accepted, while the tcplistener then stays available for further incoming connections (and for every new incoming connection a new thread is created). All communication and termination with the client that originated the connection will be handled in the thread.</p> <p>Example C# of VB.NET code is appreciated.</p>
[ { "answer_id": 62481, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 0, "selected": false, "text": "<p>I would use a threadpool, this way you won't have to start a new thread every time (since this is kinda expensive). I would also not wait indefinetely for furhter connections, since clients may not close their connections. How do you plan to route the client to the same thread each time?</p>\n\n<p>Sorry, don't have sample.</p>\n" }, { "answer_id": 62547, "author": "x0n", "author_id": 6920, "author_profile": "https://Stackoverflow.com/users/6920", "pm_score": 1, "selected": false, "text": "<p>There's a great example in the O'Reilly C# 3.0 Cookbook. You can download the accompanying source from <a href=\"http://examples.oreilly.com/9780596516109/CSharp3_0CookbookCodeRTM.zip\" rel=\"nofollow noreferrer\"><code>http://examples.oreilly.com/9780596516109/CSharp3_0CookbookCodeRTM.zip</code></a></p>\n" }, { "answer_id": 62803, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "<p>I believe you do it in the same way as any other asynchronous operation in .NET: you call the BeginXxx version of the method, in this case BeginAcceptSocket. Your callback will execute on the thread pool.</p>\n\n<p>Pooled threads generally scale much better than thread-per-connection: once you get over a few tens of connections, the system works much harder in switching between threads than on getting actual work done. In addition, each thread has its own stack which is typically 1MB in size (though it depends on link flags) which has to be found in the 2GB virtual address space (on 32-bit systems); in practice this limits you to fewer than 1000 threads.</p>\n\n<p>I'm not sure whether .NET's threadpool currently uses it, but Windows has a kernel object called the I/O Completion Port which assists in scalable I/O. You can associate threads with this object, and I/O requests (including accepting incoming connections) can be associated with it. When an I/O completes (e.g. a connection arrives) Windows will release a waiting thread, but only if the number of currently runnable threads (not blocked for some other reason) is less than the configured scalability limit for the completion port. Typically you'd set this to a small multiple of the number of cores.</p>\n" }, { "answer_id": 108766, "author": "Dror Helper", "author_id": 11361, "author_profile": "https://Stackoverflow.com/users/11361", "pm_score": 2, "selected": false, "text": "<p>I'd like to suggest a diffrent approach: \nMy suggestion uses only two threads.\n * one thread checks for incomming connections.\n * When a new connection opened this info is written to a shared data structure that holds all of the current open connections.\n * The 2nd thread enumerate that data structure and for each open connection recieve data sent and send replys.</p>\n\n<p>This solution is more scaleable thread-wise and if implemented currectly should have better performance then opening a new thread per opened connection.</p>\n" }, { "answer_id": 247108, "author": "Anton", "author_id": 341413, "author_profile": "https://Stackoverflow.com/users/341413", "pm_score": 5, "selected": true, "text": "<p>The code that I've been using looks like this:</p>\n\n<pre><code>class Server\n{\n private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);\n\n public void Start()\n {\n TcpListener listener = new TcpListener(IPAddress.Any, 5555);\n listener.Start();\n\n while(true)\n {\n IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener);\n connectionWaitHandle.WaitOne(); // Wait until a client has begun handling an event\n connectionWaitHandle.Reset(); // Reset wait handle or the loop goes as fast as it can (after first request)\n }\n }\n\n\n private void HandleAsyncConnection(IAsyncResult result)\n {\n TcpListener listener = (TcpListener)result.AsyncState;\n TcpClient client = listener.EndAcceptTcpClient(result);\n connectionWaitHandle.Set(); //Inform the main thread this connection is now handled\n\n //... Use your TcpClient here\n\n client.Close();\n }\n}\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1271/" ]
When using the Net.Sockets.TcpListener, what is the best way to handle incoming connections (.AcceptSocket) in seperate threads? The idea is to start a new thread when a new incoming connection is accepted, while the tcplistener then stays available for further incoming connections (and for every new incoming connection a new thread is created). All communication and termination with the client that originated the connection will be handled in the thread. Example C# of VB.NET code is appreciated.
The code that I've been using looks like this: ``` class Server { private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false); public void Start() { TcpListener listener = new TcpListener(IPAddress.Any, 5555); listener.Start(); while(true) { IAsyncResult result = listener.BeginAcceptTcpClient(HandleAsyncConnection, listener); connectionWaitHandle.WaitOne(); // Wait until a client has begun handling an event connectionWaitHandle.Reset(); // Reset wait handle or the loop goes as fast as it can (after first request) } } private void HandleAsyncConnection(IAsyncResult result) { TcpListener listener = (TcpListener)result.AsyncState; TcpClient client = listener.EndAcceptTcpClient(result); connectionWaitHandle.Set(); //Inform the main thread this connection is now handled //... Use your TcpClient here client.Close(); } } ```
62,490
<p>I am receiving SOAP requests from a client that uses the Axis 1.4 libraries. The requests have the following form:</p> <pre><code>&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;soapenv:Body&gt; &lt;PlaceOrderRequest xmlns="http://example.com/schema/order/request"&gt; &lt;order&gt; &lt;ns1:requestParameter xmlns:ns1="http://example.com/schema/common/request"&gt; &lt;ns1:orderingSystemWithDomain&gt; &lt;ns1:orderingSystem&gt;Internet&lt;/ns1:orderingSystem&gt; &lt;ns1:domainSign&gt;2&lt;/ns1:domainSign&gt; &lt;/ns1:orderingSystemWithDomain&gt; &lt;/ns1:requestParameter&gt; &lt;ns2:directDeliveryAddress ns2:addressType="0" ns2:index="1" xmlns:ns2="http://example.com/schema/order/request"&gt; &lt;ns3:address xmlns:ns3="http://example.com/schema/common/request"&gt; &lt;ns4:zipcode xmlns:ns4="http://example.com/schema/common"&gt;12345&lt;/ns4:zipcode&gt; &lt;ns5:city xmlns:ns5="http://example.com/schema/common"&gt;City&lt;/ns5:city&gt; &lt;ns6:street xmlns:ns6="http://example.com/schema/common"&gt;Street&lt;/ns6:street&gt; &lt;ns7:houseNum xmlns:ns7="http://example.com/schema/common"&gt;1&lt;/ns7:houseNum&gt; &lt;ns8:country xmlns:ns8="http://example.com/schema/common"&gt;XX&lt;/ns8:country&gt; &lt;/ns3:address&gt; [...] </code></pre> <p>As you can see, several prefixes are defined for the same namespace, e.g. the namespace <a href="http://example.com/schema/common" rel="noreferrer">http://example.com/schema/common</a> has the prefixes ns4, ns5, ns6, ns7 and ns8. Some long requests define several hundred prefixes for the same namespace.</p> <p>This causes a problem with the <a href="http://saxon.sourceforge.net/" rel="noreferrer">Saxon</a> XSLT processor, that I use to transform the requests. Saxon limits the the number of different prefixes for the same namespace to 255 and throws an exception when you define more prefixes.</p> <p>Can Axis 1.4 be configured to define smarter prefixes, so that there is only one prefix for each namespace?</p>
[ { "answer_id": 179495, "author": "Ian McLaird", "author_id": 18796, "author_profile": "https://Stackoverflow.com/users/18796", "pm_score": 2, "selected": false, "text": "<p>I have the same issue. For the moment, I've worked around it by writing a BasicHandler extension, and then walking the SOAPPart myself and moving the namespace reference up to a parent node. I don't <em>like</em> this solution, but it does seem to work.</p>\n\n<p>I really hope somebody comes along and tells us what we have to do.</p>\n\n<p><strong><em>EDIT</em></strong></p>\n\n<p>This is way too complicated, and like I said, I don't like it at all, but here we go. I actually broke the functionality into a few classes (This wasn't the only manipulation that we needed to do in that project, so there were other implementations) I really hope that somebody can fix this soon. This uses dom4j to process the XML passing through the SOAP process, so you'll need dom4j to make it work.</p>\n\n<pre><code>public class XMLManipulationHandler extends BasicHandler {\n private static Log log = LogFactory.getLog(XMLManipulationHandler.class);\n private static List processingHandlers;\n\n public static void setProcessingHandlers(List handlers) {\n processingHandlers = handlers;\n }\n\n protected Document process(Document doc) {\n if (processingHandlers == null) {\n processingHandlers = new ArrayList();\n processingHandlers.add(new EmptyProcessingHandler());\n }\n log.trace(processingHandlers);\n treeWalk(doc.getRootElement());\n return doc;\n }\n\n protected void treeWalk(Element element) {\n for (int i = 0, size = element.nodeCount(); i &lt; size; i++) {\n Node node = element.node(i);\n for (int handlerIndex = 0; handlerIndex &lt; processingHandlers.size(); handlerIndex++) {\n ProcessingHandler handler = (ProcessingHandler) processingHandlers.get(handlerIndex);\n handler.process(node);\n }\n if (node instanceof Element) {\n treeWalk((Element) node);\n }\n }\n }\n\n public void invoke(MessageContext context) throws AxisFault {\n if (!context.getPastPivot()) {\n SOAPMessage message = context.getMessage();\n SOAPPart soapPart = message.getSOAPPart();\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n\n try {\n message.writeTo(baos);\n baos.flush();\n baos.close();\n\n ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());\n SAXReader saxReader = new SAXReader();\n Document doc = saxReader.read(bais);\n doc = process(doc);\n DocumentSource ds = new DocumentSource(doc);\n soapPart.setContent(ds);\n message.saveChanges();\n } catch (Exception e) {\n throw new AxisFault(\"Error Caught processing document in XMLManipulationHandler\", e);\n }\n }\n }\n}\n</code></pre>\n\n<pre><code>public interface ProcessingHandler {\n public Node process(Node node);\n}\n</code></pre>\n\n<pre><code>public class NamespaceRemovalHandler implements ProcessingHandler {\n private static Log log = LogFactory.getLog(NamespaceRemovalHandler.class);\n private Namespace namespace;\n private String targetElement;\n private Set ignoreElements;\n\n public NamespaceRemovalHandler() {\n ignoreElements = new HashSet();\n }\n\n public Node process(Node node) {\n if (node instanceof Element) {\n Element element = (Element) node;\n if (element.isRootElement()) {\n // Evidently, we never actually see the root node when we're called from\n // SOAP...\n } else {\n if (element.getName().equals(targetElement)) {\n log.trace(\"Found the target Element. Adding requested namespace\");\n Namespace already = element.getNamespaceForURI(namespace.getURI());\n if (already == null) {\n element.add(namespace);\n }\n } else if (!ignoreElements.contains(element.getName())) {\n Namespace target = element.getNamespaceForURI(namespace.getURI());\n if (target != null) {\n element.remove(target);\n element.setQName(new QName(element.getName(), namespace));\n }\n }\n\n Attribute type = element.attribute(\"type\");\n if (type != null) {\n log.trace(\"Replacing type information: \" + type.getText());\n String typeText = type.getText();\n typeText = typeText.replaceAll(\"ns[0-9]+\", namespace.getPrefix());\n type.setText(typeText);\n }\n }\n }\n\n return node;\n }\n\n public Namespace getNamespace() {\n return namespace;\n }\n\n public void setNamespace(Namespace namespace) {\n this.namespace = namespace;\n }\n\n /**\n * @return the targetElement\n */\n public String getTargetElement() {\n return targetElement;\n }\n\n /**\n * @param targetElement the targetElement to set\n */\n public void setTargetElement(String targetElement) {\n this.targetElement = targetElement;\n }\n\n /**\n * @return the ignoreElements\n */\n public Set getIgnoreElements() {\n return ignoreElements;\n }\n\n /**\n * @param ignoreElements the ignoreElements to set\n */\n public void setIgnoreElements(Set ignoreElements) {\n this.ignoreElements = ignoreElements;\n }\n\n public void addIgnoreElement(String element) {\n this.ignoreElements.add(element);\n }\n}\n</code></pre>\n\n<p>No warranty, etc, etc.</p>\n" }, { "answer_id": 185432, "author": "Stephen Denne", "author_id": 11721, "author_profile": "https://Stackoverflow.com/users/11721", "pm_score": 1, "selected": false, "text": "<p>Alter your client's wsdd to set <code>enableNamespacePrefixOptimization</code> to <code>true</code></p>\n\n<pre><code>&lt;globalConfiguration &gt;\n &lt;parameter name=\"enableNamespacePrefixOptimization\" value=\"true\"/&gt;\n</code></pre>\n" }, { "answer_id": 5649242, "author": "Pica Creations", "author_id": 706035, "author_profile": "https://Stackoverflow.com/users/706035", "pm_score": 2, "selected": false, "text": "<p>For the Request I use this to remove namespaces types:</p>\n\n<pre><code>String endpoint = \"http://localhost:5555/yourService\";\n\n// Parameter to be send\nInteger secuencial = new Integer(11); // 0011\n\n// Make the call\nService service = new Service();\n\nCall call = (Call) service.createCall();\n\n// Disable sending Multirefs\ncall.setOption( org.apache.axis.AxisEngine.PROP_DOMULTIREFS, new java.lang.Boolean( false) ); \n\n// Disable sending xsi:type\ncall.setOption(org.apache.axis.AxisEngine.PROP_SEND_XSI, new java.lang.Boolean( false)); \n\n// XML with new line\ncall.setOption(org.apache.axis.AxisEngine.PROP_DISABLE_PRETTY_XML, new java.lang.Boolean( false)); \n\n// Other Options. You will not need them\ncall.setOption(org.apache.axis.AxisEngine.PROP_ENABLE_NAMESPACE_PREFIX_OPTIMIZATION, new java.lang.Boolean( true)); \ncall.setOption(org.apache.axis.AxisEngine.PROP_DOTNET_SOAPENC_FIX, new java.lang.Boolean( true));\n\ncall.setTargetEndpointAddress(new java.net.URL(endpoint));\ncall.setSOAPActionURI(\"http://YourActionUrl\");//Optional\n\n// Opertion Name\n//call.setOperationName( \"YourMethod\" );\ncall.setOperationName(new javax.xml.namespace.QName(\"http://yourUrl\", \"YourMethod\")); \n\n// Do not send encoding style\ncall.setEncodingStyle(null);\n\n// Do not send xmlns in the xml nodes\ncall.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);\n\n/////// Configuration of namespaces\norg.apache.axis.description.OperationDesc oper;\norg.apache.axis.description.ParameterDesc param;\noper = new org.apache.axis.description.OperationDesc();\noper.setName(\"InsertaTran\");\nparam = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName(\"http://yourUrl\", \"secuencial\"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName(\"http://www.w3.org/2001/XMLSchema\", \"int\"), int.class, false, false);\noper.addParameter(param);\n\noper.setReturnType(new javax.xml.namespace.QName(\"http://www.w3.org/2001/XMLSchema\", \"int\"));\noper.setReturnClass(int.class);\noper.setReturnQName(new javax.xml.namespace.QName(\"http://yourUrl\", \"yourReturnMethod\"));\noper.setStyle(org.apache.axis.constants.Style.WRAPPED);\noper.setUse(org.apache.axis.constants.Use.LITERAL);\n\ncall.setOperation(oper);\n\nInteger ret = (Integer) call.invoke( new java.lang.Object [] \n { secuencial });\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5035/" ]
I am receiving SOAP requests from a client that uses the Axis 1.4 libraries. The requests have the following form: ``` <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <PlaceOrderRequest xmlns="http://example.com/schema/order/request"> <order> <ns1:requestParameter xmlns:ns1="http://example.com/schema/common/request"> <ns1:orderingSystemWithDomain> <ns1:orderingSystem>Internet</ns1:orderingSystem> <ns1:domainSign>2</ns1:domainSign> </ns1:orderingSystemWithDomain> </ns1:requestParameter> <ns2:directDeliveryAddress ns2:addressType="0" ns2:index="1" xmlns:ns2="http://example.com/schema/order/request"> <ns3:address xmlns:ns3="http://example.com/schema/common/request"> <ns4:zipcode xmlns:ns4="http://example.com/schema/common">12345</ns4:zipcode> <ns5:city xmlns:ns5="http://example.com/schema/common">City</ns5:city> <ns6:street xmlns:ns6="http://example.com/schema/common">Street</ns6:street> <ns7:houseNum xmlns:ns7="http://example.com/schema/common">1</ns7:houseNum> <ns8:country xmlns:ns8="http://example.com/schema/common">XX</ns8:country> </ns3:address> [...] ``` As you can see, several prefixes are defined for the same namespace, e.g. the namespace <http://example.com/schema/common> has the prefixes ns4, ns5, ns6, ns7 and ns8. Some long requests define several hundred prefixes for the same namespace. This causes a problem with the [Saxon](http://saxon.sourceforge.net/) XSLT processor, that I use to transform the requests. Saxon limits the the number of different prefixes for the same namespace to 255 and throws an exception when you define more prefixes. Can Axis 1.4 be configured to define smarter prefixes, so that there is only one prefix for each namespace?
I have the same issue. For the moment, I've worked around it by writing a BasicHandler extension, and then walking the SOAPPart myself and moving the namespace reference up to a parent node. I don't *like* this solution, but it does seem to work. I really hope somebody comes along and tells us what we have to do. ***EDIT*** This is way too complicated, and like I said, I don't like it at all, but here we go. I actually broke the functionality into a few classes (This wasn't the only manipulation that we needed to do in that project, so there were other implementations) I really hope that somebody can fix this soon. This uses dom4j to process the XML passing through the SOAP process, so you'll need dom4j to make it work. ``` public class XMLManipulationHandler extends BasicHandler { private static Log log = LogFactory.getLog(XMLManipulationHandler.class); private static List processingHandlers; public static void setProcessingHandlers(List handlers) { processingHandlers = handlers; } protected Document process(Document doc) { if (processingHandlers == null) { processingHandlers = new ArrayList(); processingHandlers.add(new EmptyProcessingHandler()); } log.trace(processingHandlers); treeWalk(doc.getRootElement()); return doc; } protected void treeWalk(Element element) { for (int i = 0, size = element.nodeCount(); i < size; i++) { Node node = element.node(i); for (int handlerIndex = 0; handlerIndex < processingHandlers.size(); handlerIndex++) { ProcessingHandler handler = (ProcessingHandler) processingHandlers.get(handlerIndex); handler.process(node); } if (node instanceof Element) { treeWalk((Element) node); } } } public void invoke(MessageContext context) throws AxisFault { if (!context.getPastPivot()) { SOAPMessage message = context.getMessage(); SOAPPart soapPart = message.getSOAPPart(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); baos.flush(); baos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); SAXReader saxReader = new SAXReader(); Document doc = saxReader.read(bais); doc = process(doc); DocumentSource ds = new DocumentSource(doc); soapPart.setContent(ds); message.saveChanges(); } catch (Exception e) { throw new AxisFault("Error Caught processing document in XMLManipulationHandler", e); } } } } ``` ``` public interface ProcessingHandler { public Node process(Node node); } ``` ``` public class NamespaceRemovalHandler implements ProcessingHandler { private static Log log = LogFactory.getLog(NamespaceRemovalHandler.class); private Namespace namespace; private String targetElement; private Set ignoreElements; public NamespaceRemovalHandler() { ignoreElements = new HashSet(); } public Node process(Node node) { if (node instanceof Element) { Element element = (Element) node; if (element.isRootElement()) { // Evidently, we never actually see the root node when we're called from // SOAP... } else { if (element.getName().equals(targetElement)) { log.trace("Found the target Element. Adding requested namespace"); Namespace already = element.getNamespaceForURI(namespace.getURI()); if (already == null) { element.add(namespace); } } else if (!ignoreElements.contains(element.getName())) { Namespace target = element.getNamespaceForURI(namespace.getURI()); if (target != null) { element.remove(target); element.setQName(new QName(element.getName(), namespace)); } } Attribute type = element.attribute("type"); if (type != null) { log.trace("Replacing type information: " + type.getText()); String typeText = type.getText(); typeText = typeText.replaceAll("ns[0-9]+", namespace.getPrefix()); type.setText(typeText); } } } return node; } public Namespace getNamespace() { return namespace; } public void setNamespace(Namespace namespace) { this.namespace = namespace; } /** * @return the targetElement */ public String getTargetElement() { return targetElement; } /** * @param targetElement the targetElement to set */ public void setTargetElement(String targetElement) { this.targetElement = targetElement; } /** * @return the ignoreElements */ public Set getIgnoreElements() { return ignoreElements; } /** * @param ignoreElements the ignoreElements to set */ public void setIgnoreElements(Set ignoreElements) { this.ignoreElements = ignoreElements; } public void addIgnoreElement(String element) { this.ignoreElements.add(element); } } ``` No warranty, etc, etc.
62,501
<p>I need to remotely install windows service on number of computers, so I use CreateService() and other service functions from winapi. I know admin password and user name for machines that I need access to. In order to gain access to remote machine I impersonate calling process with help of LogonUser like this: </p> <pre><code>//all variables are initialized correctly int status = 0; status = LogonUser(lpwUsername, lpwDomain, lpwPassword, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, &amp;hToken); if (status == 0) { //here comes a error } status = ImpersonateLoggedOnUser(hToken); if (status == 0) { //once again a error } //ok, now we are impersonated, do all service work there </code></pre> <p>So, I gain access to machine in a domain, but some of computers are out of domain. On machines that are out of domain this code doesn't work. Is there any way to access service manager on machine out of domain?</p>
[ { "answer_id": 62560, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>You can do it , the account needs to exist on the remote machine and you need to use the machine name for the domain name in the LogonUser call.</p>\n" }, { "answer_id": 101264, "author": "Jon Grant", "author_id": 18774, "author_profile": "https://Stackoverflow.com/users/18774", "pm_score": 0, "selected": false, "text": "<p>Rather than rolling your own, why not just use the SC built-in command?</p>\n" }, { "answer_id": 114935, "author": "Andrey Neverov", "author_id": 6698, "author_profile": "https://Stackoverflow.com/users/6698", "pm_score": 0, "selected": false, "text": "<p>OK, problem resolved (not really very good, but rather OK). I used WNetAddConnection() to ipc$ on remote machine. </p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6698/" ]
I need to remotely install windows service on number of computers, so I use CreateService() and other service functions from winapi. I know admin password and user name for machines that I need access to. In order to gain access to remote machine I impersonate calling process with help of LogonUser like this: ``` //all variables are initialized correctly int status = 0; status = LogonUser(lpwUsername, lpwDomain, lpwPassword, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, &hToken); if (status == 0) { //here comes a error } status = ImpersonateLoggedOnUser(hToken); if (status == 0) { //once again a error } //ok, now we are impersonated, do all service work there ``` So, I gain access to machine in a domain, but some of computers are out of domain. On machines that are out of domain this code doesn't work. Is there any way to access service manager on machine out of domain?
You can do it , the account needs to exist on the remote machine and you need to use the machine name for the domain name in the LogonUser call.
62,504
<p>I am using MS Access 2003. I want to run a lot of insert SQL statements in what is called 'Query' in MS Access. Is there any easy(or indeed any way) to do it?</p>
[ { "answer_id": 62572, "author": "Rikalous", "author_id": 4271, "author_profile": "https://Stackoverflow.com/users/4271", "pm_score": 1, "selected": false, "text": "<p>No - a query in Access is a single SQL statement. There is no way of creating a batch of several statements within one query object. \nYou could create multiple query objects and run them from a macro/module.</p>\n" }, { "answer_id": 62583, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 2, "selected": false, "text": "<p>Personally, I'd create a VBA subroutine to do it, and connect to the database using some form of sql connection.</p>\n\n<p>Off the top of my head, the code to do it should look something like:</p>\n\n<pre><code>Sub InsertLots ()\n Dim SqlConn as Connection\n SqlConn.Connect(\"your connection string\")\n SqlConn.Execute(\"INSERT &lt;tablename&gt; (column1, column2) VALUES (1, 2)\")\n SqlConn.Execute(\"INSERT &lt;tablename&gt; (column1, column2) VALUES (2, 3)\")\n SqlConn.Close()\nEnd Sub\n</code></pre>\n" }, { "answer_id": 65027, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 6, "selected": true, "text": "<p>yes and no.</p>\n\n<p>You can't do:</p>\n\n<pre><code>insert into foo (c1, c2, c3)\nvalues (\"v1a\", \"v2a\", \"v3a\"),\n (\"v1b\", \"v2b\", \"v3b\"),\n (\"v1c\", \"v2c\", \"v3c\")\n</code></pre>\n\n<p>but you can do</p>\n\n<pre><code>insert into foo (c1, c2, c3)\n select (v1, v2, v3) from bar\n</code></pre>\n\n<p>What does that get you if you don't already have the data in a table? Well, you could craft a Select statement composed of a lot of unions of Selects with hard coded results. </p>\n\n<pre><code>INSERT INTO foo (f1, f2, f3)\n SELECT *\n FROM (select top 1 \"b1a\" AS f1, \"b2a\" AS f2, \"b3a\" AS f3 from onerow\n union all\n select top 1 \"b1b\" AS f1, \"b2b\" AS f2, \"b3b\" AS f3 from onerow\n union all \n select top 1 \"b1c\" AS f1, \"b2c\" AS f2, \"b3c\" AS f3 from onerow)\n</code></pre>\n\n<p>Note: I also have to include a some form of a dummy table (e.g., onerow) to fool access into allowing the union (it must have at least one row in it), and you need the \"top 1\" to ensure you don't get repeats for a table with more than one row</p>\n\n<p>But then again, it would probably be easier just to do three separate insert statements,\nespecially if you are already building things up in a loop (unless of course the cost of doing the inserts is greater than the cost of your time to code it).</p>\n" }, { "answer_id": 66817, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 2, "selected": false, "text": "<p>I think it's inadvisable to propose a particular data interface, as Jonathan does, when you haven't clarified the context in which the code is going to run.</p>\n\n<p>If the data store is a Jet database, it makes little sense to use any form of ADO unless you're running your code from a scripting platform where it's the preferred choice. If you're in Access, this is definitely not the case, and DAO is the preferred interface.</p>\n" }, { "answer_id": 148584, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 1, "selected": false, "text": "<p>@Rik Garner: Not sure what you mean by 'batch' but the </p>\n\n<pre><code>INSERT INTO foo (f1, f2, f3)\n SELECT *\n FROM (select top 1 \"b1a\" AS f1, \"b2a\" AS f2, \"b3a\" AS f3 from onerow\n union all\n select top 1 \"b1b\" AS f1, \"b2b\" AS f2, \"b3b\" AS f3 from onerow\n union all \n select top 1 \"b1c\" AS f1, \"b2c\" AS f2, \"b3c\" AS f3 from onerow)\n</code></pre>\n\n<p>construct, although being a single SQL <em>statement</em>, will actually insert each row one at a time (rather than all at once) but in the same transaction: you can test this by adding a relevant constraint e.g. </p>\n\n<pre><code>ALTER TABLE foo ADD\n CONSTRAINT max_two_foo_rows\n CHECK (2 &gt;= (SELECT COUNT(*) FROM foo AS T2));\n</code></pre>\n\n<p>Assuming the table is empty, the above <code>INSERT INTO..SELECT..</code> should work: the fact it doesn't is because the constraint was checked after the first row was inserted rather than the after all three were inserted (a violation of ANSI SQL-92 but that's MS Access for you ); the fact the table remains empty shows that the internal transaction was rolled back.</p>\n\n<p>@David W. Fenton: you may have a strong personal preference for DAO but please do not be too hard on someone for choosing an alternative data access technology (in this case ADO), especially for a vanilla <code>INSERT</code> and when they qualify their comments with, \" Off the top of my head, the code to do it should look something like…\" After all, you can't use DAO to create a <code>CHECK</code> constraint :)</p>\n" }, { "answer_id": 15187738, "author": "user2129206", "author_id": 2129206, "author_profile": "https://Stackoverflow.com/users/2129206", "pm_score": 2, "selected": false, "text": "<p>MS Access does not allow multiple insert from same sql window. If you want to <strong><em>insert</em></strong>, say <strong>10 rows in table</strong>, say <strong>movie (mid, mname, mdirector,....)</strong>, you would need to \nopen the sql windows, </p>\n\n<ol>\n<li>type the 1st stmt, execute 1st stmt, delete 1st stmt</li>\n<li>type the 2nd stmt, execute 2nd stmt, delete 2nd stmt</li>\n<li>type the 3rd stmt, execute 3rd stmt, delete 3rd stmt ......</li>\n</ol>\n\n<p>Very boring. \nInstead you could import the lines from excel by doing:</p>\n\n<ol>\n<li>Right-click on the table name that you have already created</li>\n<li>Import from Excel (Import dialog box is opened)</li>\n<li>Browse to the excel file containing the records to be imported in the table</li>\n<li>Click on \"Append a copy of the records to the table:\"</li>\n<li>Select the required table (in this example movie)</li>\n<li>Click on \"OK\"</li>\n<li>Select the worksheet that contains the data in the spreadsheet</li>\n<li>Click on Finish</li>\n</ol>\n\n<p>The whole dataset in the excel has been loaded in the table \"MOVIE\"</p>\n" }, { "answer_id": 16428930, "author": "Mark", "author_id": 2360066, "author_profile": "https://Stackoverflow.com/users/2360066", "pm_score": 1, "selected": false, "text": "<p>MS Access can also Append data into a table from a simple text file. CSV the values (I simply used the Replace All box to delete all but the commas) and under External Data select the Text File.</p>\n\n<pre><code>From this:\nINSERT INTO CLASS VALUES('10012','ACCT-211','1','MWF 8:00-8:50 a.m.','BUS311','105');\nINSERT INTO CLASS VALUES('10013','ACCT-211','2','MWF 9:00-9:50 a.m.','BUS200','105');\nINSERT INTO CLASS VALUES('10014','ACCT-211','3','TTh 2:30-3:45 p.m.','BUS252','342');\nTo this:\n10012,ACCT-211,1,MWF 8:00-8:50 a.m.,BUS311,105\n10013,ACCT-211,2,MWF 9:00-9:50 a.m.,BUS200,105\n10014,ACCT-211,3,TTh 2:30-3:45 p.m.,BUS252,342\n</code></pre>\n" }, { "answer_id": 65726799, "author": "John Bentley", "author_id": 872154, "author_profile": "https://Stackoverflow.com/users/872154", "pm_score": 0, "selected": false, "text": "<p>Based on the VBA workaround from @Jonathan, and for execution in the current Access database:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Public Sub InsertMinimalData()\n CurrentDb.Execute &quot;INSERT INTO FinancialYear (FinancialYearID) VALUES ('FY2019/2020');&quot;\n CurrentDb.Execute &quot;INSERT INTO FinancialYear (FinancialYearID) VALUES ('FY2020/2021');&quot;\nEnd Sub\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6613/" ]
I am using MS Access 2003. I want to run a lot of insert SQL statements in what is called 'Query' in MS Access. Is there any easy(or indeed any way) to do it?
yes and no. You can't do: ``` insert into foo (c1, c2, c3) values ("v1a", "v2a", "v3a"), ("v1b", "v2b", "v3b"), ("v1c", "v2c", "v3c") ``` but you can do ``` insert into foo (c1, c2, c3) select (v1, v2, v3) from bar ``` What does that get you if you don't already have the data in a table? Well, you could craft a Select statement composed of a lot of unions of Selects with hard coded results. ``` INSERT INTO foo (f1, f2, f3) SELECT * FROM (select top 1 "b1a" AS f1, "b2a" AS f2, "b3a" AS f3 from onerow union all select top 1 "b1b" AS f1, "b2b" AS f2, "b3b" AS f3 from onerow union all select top 1 "b1c" AS f1, "b2c" AS f2, "b3c" AS f3 from onerow) ``` Note: I also have to include a some form of a dummy table (e.g., onerow) to fool access into allowing the union (it must have at least one row in it), and you need the "top 1" to ensure you don't get repeats for a table with more than one row But then again, it would probably be easier just to do three separate insert statements, especially if you are already building things up in a loop (unless of course the cost of doing the inserts is greater than the cost of your time to code it).
62,512
<p>I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using <code>STL</code> techniques such as vectors.</p> <p>Essentially I want my integer array dimensions to look like:</p> <pre><code>[ x ][ y ][ z ] </code></pre> <p>x and y are in the range 20-6000 z is known and equals 4.</p>
[ { "answer_id": 62532, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 5, "selected": true, "text": "<p>Have a look at the Boost <a href=\"http://www.boost.org/doc/libs/release/libs/multi_array\" rel=\"noreferrer\">multi-dimensional array</a> library. Here's an example (adapted from the Boost documentation):</p>\n\n<pre><code>#include \"boost/multi_array.hpp\"\n\nint main() {\n // Create a 3D array that is 20 x 30 x 4\n int x = 20;\n int y = 30;\n int z = 4;\n\n typedef boost::multi_array&lt;int, 3&gt; array_type;\n typedef array_type::index index;\n array_type my_array(boost::extents[x][y][z]);\n\n // Assign values to the elements\n int values = 0;\n for (index i = 0; i != x; ++i) {\n for (index j = 0; j != y; ++j) {\n for (index k = 0; k != z; ++k) {\n my_array[i][j][k] = values++;\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 62601, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 3, "selected": false, "text": "<p>Each pair of square brackets is a dereferencing operation (when applied to a pointer). As an example, the following pairs of lines of code are equivalent:</p>\n\n<pre><code>x = myArray[4];\nx = *(myArray+4);\n</code></pre>\n\n<p>&nbsp;</p>\n\n<pre><code>x = myArray[2][7];\nx = *((*(myArray+2))+7);\n</code></pre>\n\n<p>To use your suggested syntax you are simply dereferencing the value returned from the first dereference.</p>\n\n<pre><code>int*** myArray = (some allocation method, keep reading);\n//\n// All in one line:\nint value = myArray[x][y][z];\n//\n// Separated to multiple steps:\nint** deref1 = myArray[x];\nint* deref2 = deref1[y];\nint value = deref2[z];\n</code></pre>\n\n<p>To go about allocating this array, you simply need to recognise that you don't actually have a three-dimensional array of integers. You have an array of arrays of arrays of integers.</p>\n\n<pre><code>// Start by allocating an array for array of arrays\nint*** myArray = new int**[X_MAXIMUM];\n\n// Allocate an array for each element of the first array\nfor(int x = 0; x &lt; X_MAXIMUM; ++x)\n{\n myArray[x] = new int*[Y_MAXIMUM];\n\n // Allocate an array of integers for each element of this array\n for(int y = 0; y &lt; Y_MAXIMUM; ++y)\n {\n myArray[x][y] = new int[Z_MAXIMUM];\n\n // Specify an initial value (if desired)\n for(int z = 0; z &lt; Z_MAXIMUM; ++z)\n {\n myArray[x][y][z] = -1;\n }\n }\n}\n</code></pre>\n\n<p>Deallocating this array follows a similar process to allocating it:</p>\n\n<pre><code>for(int x = 0; x &lt; X_MAXIMUM; ++x)\n{\n for(int y = 0; y &lt; Y_MAXIMUM; ++y)\n {\n delete[] myArray[x][y];\n }\n\n delete[] myArray[x];\n}\n\ndelete[] myArray;\n</code></pre>\n" }, { "answer_id": 62659, "author": "Mark Webster", "author_id": 7068, "author_profile": "https://Stackoverflow.com/users/7068", "pm_score": 1, "selected": false, "text": "<p>It should be noted that, for all intents and purposes, you are dealing with only a 2D array, because the third (and least significant) dimension is known.</p>\n\n<p>Using the STL or Boost are quite good approaches if you don't know beforehand how many entries you will have in each dimension of the array, because they will give you dynamic memory allocation, and I recommend either of these approaches if your data set is to remain largely static, or if it to mostly only receive new entries and not many deletions.</p>\n\n<p>However, if you know something about your dataset beforehand, such as roughly how many items in total will be stored, or if the arrays are to be sparsely populated, you might be better off using some kind of hash/bucket function, and use the XYZ indices as your key. In this case, assuming no more than 8192 (13 bits) entries per dimension, you could get by with a 40-bit (5-byte) key. Or, assuming there are always 4 x Z entries, you would simply use a 26-bit XY key. This is one of the more efficient trade-offs between speed, memory usage, and dynamic allocation.</p>\n" }, { "answer_id": 62674, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 2, "selected": false, "text": "<p>With vectors:</p>\n\n<pre><code>std::vector&lt; std::vector&lt; std::vector&lt; int &gt; &gt; &gt; array3d;\n</code></pre>\n\n<p>Every element is accessible wit array3d[x][y][z] if the element was already added. (e.g. via push_back)</p>\n" }, { "answer_id": 62915, "author": "Paul Troon", "author_id": 6649, "author_profile": "https://Stackoverflow.com/users/6649", "pm_score": 1, "selected": false, "text": "<p>There are many advantages to using the STL to manage your memory over using new/delete. The choice of how to represent your data depends on how you plan to use it. One suggestion would be a class that hides the implementation decision and provides three dimensional get/set methods to a one dimensional STL vector. </p>\n\n<p>If you really believe you need to create a custom 3d vector type, investigate Boost first.</p>\n\n<pre><code>// a class that does something in 3 dimensions\n\nclass MySimpleClass\n{\npublic:\n\n MySimpleClass(const size_t inWidth, const size_t inHeight, const size_t inDepth) :\n mWidth(inWidth), mHeight(inHeight), mDepth(inDepth)\n {\n mArray.resize(mWidth * mHeight * mDepth);\n }\n\n\n // inline for speed\n int Get(const size_t inX, const size_t inY, const size_t inZ) {\n return mArray[(inZ * mWidth * mHeight) + (mY * mWidth) + mX];\n }\n\n void Set(const size_t inX, const size_t inY, const size_t inZ, const int inVal) {\n return mArray[(inZ * mWidth * mHeight) + (mY * mWidth) + mX];\n }\n\n // doing something uniform with the data is easier if it's not a vector of vectors\n void DoSomething()\n {\n std::transform(mArray.begin(), mArray.end(), mArray.begin(), MyUnaryFunc);\n }\n\nprivate:\n\n // dimensions of data\n size_t mWidth;\n size_t mHeight;\n size_t mDepth;\n\n // data buffer\n std::vector&lt; int &gt; mArray;\n};\n</code></pre>\n" }, { "answer_id": 63541, "author": "yrp", "author_id": 7228, "author_profile": "https://Stackoverflow.com/users/7228", "pm_score": -1, "selected": false, "text": "<p>Pieter's suggestion is good of course, but one thing you've to bear in mind is that in case of big arrays building it may be quite slow. Every time vector capacity changes, all the data has to be copied around ('n' vectors of vectors).</p>\n" }, { "answer_id": 4466150, "author": "kriss", "author_id": 168465, "author_profile": "https://Stackoverflow.com/users/168465", "pm_score": 3, "selected": false, "text": "<p>Below is a straightforward way to create 3D arrays using C or C++ in one chunk of memory for each array. No need to use BOOST (even if it's nice), or to split allocation between lines with multiple indirection (this is quite bad as it usually gives big performance penalty when accessing data and it fragments memory).</p>\n\n<p>The only thing to understand is that there is no such thing as multidimensional arrays, just arrays of arrays (of arrays). The innermost index being the farthest in memory.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main(){\n\n {\n // C Style Static 3D Arrays\n int a[10][20][30];\n a[9][19][29] = 10;\n printf(\"a[9][19][29]=%d\\n\", a[9][19][29]);\n }\n\n {\n // C Style dynamic 3D Arrays\n int (*a)[20][30];\n a = (int (*)[20][30])malloc(10*20*30*sizeof(int));\n a[9][19][29] = 10;\n printf(\"a[9][19][29]=%d\\n\", a[9][19][29]);\n free(a);\n }\n\n {\n // C++ Style dynamic 3D Arrays\n int (*a)[20][30];\n a = new int[10][20][30];\n a[9][19][29] = 10;\n printf(\"a[9][19][29]=%d\\n\", a[9][19][29]);\n delete [] a;\n }\n\n}\n</code></pre>\n\n<p>For your actual problem, as there potentially is two unknown dimensions, there is a problem with my proposal at it allow only one unknown dimension. There is several ways to manage that.</p>\n\n<p>The good news is that using variables now works with C, it is called variable length arrays. You look <a href=\"http://www.drdobbs.com/184401444;jsessionid=LAEWOLZQCC2AJQE1GHPSKH4ATMY32JVN\" rel=\"noreferrer\">here</a> for details.</p>\n\n<pre><code> int x = 100;\n int y = 200;\n int z = 30;\n\n {\n // C Style Static 3D Arrays \n int a[x][y][z];\n a[99][199][29] = 10;\n printf(\"a[99][199][29]=%d\\n\", a[99][199][29]);\n }\n\n {\n // C Style dynamic 3D Arrays\n int (*a)[y][z];\n a = (int (*)[y][z])malloc(x*y*z*sizeof(int));\n a[99][199][29] = 10;\n printf(\"a[99][199][29]=%d\\n\", a[99][199][29]);\n free(a);\n }\n</code></pre>\n\n<p>If using C++ the simplest way is probably to use operator overloading to stick with array syntax:</p>\n\n<pre><code> {\n class ThreeDArray {\n class InnerTwoDArray {\n int * data;\n size_t y;\n size_t z;\n public:\n InnerTwoDArray(int * data, size_t y, size_t z)\n : data(data), y(y), z(z) {}\n\n public:\n int * operator [](size_t y){ return data + y*z; }\n };\n\n int * data;\n size_t x;\n size_t y;\n size_t z;\n public:\n ThreeDArray(size_t x, size_t y, size_t z) : x(x), y(y), z(z) {\n data = (int*)malloc(x*y*z*sizeof data);\n }\n\n ~ThreeDArray(){ free(data); }\n\n InnerTwoDArray operator [](size_t x){\n return InnerTwoDArray(data + x*y*z, y, z);\n }\n };\n\n ThreeDArray a(x, y, z);\n a[99][199][29] = 10;\n printf(\"a[99][199][29]=%d\\n\", a[99][199][29]);\n }\n</code></pre>\n\n<p>The above code has some indirection cost for accessing InnerTwoDArray (but a good compiler can probably optimize it away) but uses only one memory chunk for array allocated on heap. Which is usually the most efficient choice.</p>\n\n<p>Obviously even if the above code is still simple and straightforward, STL or BOOST does it well, hence no need to reinvent the wheel. I still believe it is interesting to know it can be easily done.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6795/" ]
I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using `STL` techniques such as vectors. Essentially I want my integer array dimensions to look like: ``` [ x ][ y ][ z ] ``` x and y are in the range 20-6000 z is known and equals 4.
Have a look at the Boost [multi-dimensional array](http://www.boost.org/doc/libs/release/libs/multi_array) library. Here's an example (adapted from the Boost documentation): ``` #include "boost/multi_array.hpp" int main() { // Create a 3D array that is 20 x 30 x 4 int x = 20; int y = 30; int z = 4; typedef boost::multi_array<int, 3> array_type; typedef array_type::index index; array_type my_array(boost::extents[x][y][z]); // Assign values to the elements int values = 0; for (index i = 0; i != x; ++i) { for (index j = 0; j != y; ++j) { for (index k = 0; k != z; ++k) { my_array[i][j][k] = values++; } } } } ```
62,529
<p>The RoR tutorials posit one model per table for the ORM to work. My DB schema has some 70 tables divided conceptually into 5 groups of functionality (eg, any given table lives in one and only one functional group, and relations between tables of different groups are minimised.) So: should I design a model per conceptual group, or should I simply have 70 Rails models and leave the grouping 'conceptual'? Thanks!</p>
[ { "answer_id": 62677, "author": "Clinton Dreisbach", "author_id": 6262, "author_profile": "https://Stackoverflow.com/users/6262", "pm_score": 3, "selected": false, "text": "<p>Most likely, you should have 70 models. You could namespace the models to have 5 namespaces, one for each group, but that can be more trouble than it's worth. More likely, you have some common functionality throughout each group. In that case, I'd make a module for each group containing its behavior, and include that in each relevant model. Even if there's no shared functionality, doing this can let you quickly query a model for its conceptual group.</p>\n" }, { "answer_id": 62743, "author": "Ben", "author_id": 6998, "author_profile": "https://Stackoverflow.com/users/6998", "pm_score": 3, "selected": false, "text": "<p>You should definitely use one model per table in order to take advantage of all the ActiveRecord magic. </p>\n\n<p>But you could also group your models together into namespaces using modules and sub-directories, in order to avoid having to manage 70 files in your models directory.</p>\n\n<p>For example, you could have:</p>\n\n<pre><code>app/models/admin/user.rb\napp/models/admin/group.rb\n</code></pre>\n\n<p>for models Admin::User and Admin::Group, and</p>\n\n<pre><code>app/models/publishing/article.rb\napp/models/publishing/comment.rb\n</code></pre>\n\n<p>for Publishing::Article and Publishing::Comment</p>\n\n<p>And so forth...</p>\n" }, { "answer_id": 63689, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "<p>There may be a small number of cases where you can use the Rails standard single-table-inheritance model. Perhaps all of the classes in one particular functional grouping have the same fields (or nearly all the same). In that case, take advantage of the DRYness STI offers. When it doesn't make sense, though, use class-per-table.</p>\n\n<p>In the class-per-table version, you can't easily pull common functionality into a base class. Instead, pull it into a module. A hierarchy like the following might prove useful:</p>\n\n<pre><code>app/models/admin/base.rb - module Admin::Base, included by all other Admin::xxx\napp/models/admin/user.rb - class Admin::User, includes Admin::Base\napp/models/admin/group.rb - class Admin::Group, includes Admin::Base\n</code></pre>\n" }, { "answer_id": 65340, "author": "srboisvert", "author_id": 6805, "author_profile": "https://Stackoverflow.com/users/6805", "pm_score": 2, "selected": false, "text": "<p>Without knowing more details about the nature of the seventy tables and their conceptual relations it isn't really possible to give a good answer. Are these legacy tables or have you designed this from scratch?</p>\n\n<p>Are the tables related by some kind of inheritance pattern or could they be? Rails can do a limited form of inheritance. Look up Single Table Inheritance (STI).</p>\n\n<p>Personally, I would put a lot of effort into avoiding working with seventy tables simply because that is an awful lot of work - seventy Models &amp; Controllers and their 4+ views, helpers, layouts, and tests not to mention the memory load issue of keeping the design in ind. Unless of course I was getting paid by the hour and well enough to compensate for the repetition.</p>\n" }, { "answer_id": 68536, "author": "Dave Smylie", "author_id": 1505600, "author_profile": "https://Stackoverflow.com/users/1505600", "pm_score": 1, "selected": false, "text": "<p>It's already mentioned, it's hard to give decent advice without knowing your database schema etc, however, I would lean towards creating the 70+ models, (one for each of your tables.)</p>\n\n<p>You may be able to get away with ditching some model, but for the cost (negliable) you may as well have them there. </p>\n\n<p>You don't need to create a controller + views for each model (as answerd by srboisvert). You only need a controller for each resource (which I would expect to be a lot less than 70 - probably only 10 or 15 or so judging by your description).</p>\n" }, { "answer_id": 68571, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 2, "selected": false, "text": "<p>Before jumping in a making 70 models, please consider this question to help you decide:</p>\n\n<p>Would each of your tables be considered an \"object\" for example a \"cars\" table or are some of the tables holding only relationship information, all foreign key columns for example?</p>\n\n<p>In Rails only the \"object\" tables become models! (With some exception for specific types of associations) So it is very likely that if you have only 5 groups of functionality, you might not have 70 models. Also, if the groups of functionality you mentioned are vastly different, they may even be best suited in their own app.</p>\n" }, { "answer_id": 99671, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 4, "selected": true, "text": "<p>I cover this in one of my large apps by just making sure that the tables/models are conceptually grouped by name (with almost 1:1 table-model relationship). Example:</p>\n\n<pre><code>events\nevent_types\nevent_groups\nevent_attendees\netc...\n</code></pre>\n\n<p>That way when I'm using TextMate or whatever, the model files are nicely grouped together by the alpha sort. I have 80 models in this app, and it works well enough to keep things organised.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6941/" ]
The RoR tutorials posit one model per table for the ORM to work. My DB schema has some 70 tables divided conceptually into 5 groups of functionality (eg, any given table lives in one and only one functional group, and relations between tables of different groups are minimised.) So: should I design a model per conceptual group, or should I simply have 70 Rails models and leave the grouping 'conceptual'? Thanks!
I cover this in one of my large apps by just making sure that the tables/models are conceptually grouped by name (with almost 1:1 table-model relationship). Example: ``` events event_types event_groups event_attendees etc... ``` That way when I'm using TextMate or whatever, the model files are nicely grouped together by the alpha sort. I have 80 models in this app, and it works well enough to keep things organised.
62,567
<p>What is the easiest way to compare strings in Python, ignoring case?</p> <p>Of course one can do (str1.lower() &lt;= str2.lower()), etc., but this created two additional temporary strings (with the obvious alloc/g-c overheads).</p> <p>I guess I'm looking for an equivalent to C's stricmp().</p> <p>[Some more context requested, so I'll demonstrate with a trivial example:]</p> <p>Suppose you want to sort a looong list of strings. You simply do theList.sort(). This is O(n * log(n)) string comparisons and no memory management (since all strings and list elements are some sort of smart pointers). You are happy.</p> <p>Now, you want to do the same, but ignore the case (let's simplify and say all strings are ascii, so locale issues can be ignored). You can do theList.sort(key=lambda s: s.lower()), but then you cause two new allocations per comparison, plus burden the garbage-collector with the duplicated (lowered) strings. Each such memory-management noise is orders-of-magnitude slower than simple string comparison.</p> <p>Now, with an in-place stricmp()-like function, you do: theList.sort(cmp=stricmp) and it is as fast and as memory-friendly as theList.sort(). You are happy again.</p> <p>The problem is any Python-based case-insensitive comparison involves implicit string duplications, so I was expecting to find a C-based comparisons (maybe in module string).</p> <p>Could not find anything like that, hence the question here. (Hope this clarifies the question).</p>
[ { "answer_id": 62592, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "<p>I'm pretty sure you either have to use .lower() or use a regular expression. I'm not aware of a built-in case-insensitive string comparison function.</p>\n" }, { "answer_id": 62647, "author": "Moses Ting", "author_id": 7056, "author_profile": "https://Stackoverflow.com/users/7056", "pm_score": 1, "selected": false, "text": "<p>This is how you'd do it with re:</p>\n\n<pre><code>import re\np = re.compile('^hello$', re.I)\np.match('Hello')\np.match('hello')\np.match('HELLO')\n</code></pre>\n" }, { "answer_id": 62652, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": -1, "selected": false, "text": "<p>You could subclass <code>str</code> and create your own case-insenstive string class but IMHO that would be extremely unwise and create far more trouble than it's worth.</p>\n" }, { "answer_id": 62983, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>For occasional or even repeated comparisons, a few extra string objects shouldn't matter as long as this won't happen in the innermost loop of your core code or you don't have enough data to actually notice the performance impact. See if you do: doing things in a \"stupid\" way is much less stupid if you also do it less.</p>\n\n<p>If you seriously want to keep comparing lots and lots of text case-insensitively you could somehow keep the lowercase versions of the strings at hand to avoid finalization and re-creation, or normalize the whole data set into lowercase. This of course depends on the size of the data set. If there are a relatively few needles and a large haystack, replacing the needles with compiled regexp objects is one solution. If It's hard to say without seeing a concrete example.</p>\n" }, { "answer_id": 63007, "author": "Ricardo Reyes", "author_id": 3399, "author_profile": "https://Stackoverflow.com/users/3399", "pm_score": 2, "selected": false, "text": "<p>There's no built in equivalent to that function you want.</p>\n\n<p>You can write your own function that converts to .lower() each character at a time to avoid duplicating both strings, but I'm sure it will very cpu-intensive and extremely inefficient. </p>\n\n<p>Unless you are working with extremely long strings (so long that can cause a memory problem if duplicated) then I would keep it simple and use </p>\n\n<pre><code>str1.lower() == str2.lower()\n</code></pre>\n\n<p>You'll be ok</p>\n" }, { "answer_id": 63071, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 3, "selected": false, "text": "<p>Are you using this compare in a very-frequently-executed path of a highly-performance-sensitive application? Alternatively, are you running this on strings which are megabytes in size? If not, then you shouldn't worry about the performance and just use the .lower() method.</p>\n\n<p>The following code demonstrates that doing a case-insensitive compare by calling .lower() on two strings which are each almost a megabyte in size takes about 0.009 seconds on my 1.8GHz desktop computer:</p>\n\n<pre><code>from timeit import Timer\n\ns1 = \"1234567890\" * 100000 + \"a\"\ns2 = \"1234567890\" * 100000 + \"B\"\n\ncode = \"s1.lower() &lt; s2.lower()\"\ntime = Timer(code, \"from __main__ import s1, s2\").timeit(1000)\nprint time / 1000 # 0.00920499992371 on my machine\n</code></pre>\n\n<p>If indeed this is an extremely significant, performance-critical section of code, then I recommend writing a function in C and calling it from your Python code, since that will allow you to do a truly efficient case-insensitive search. Details on writing C extension modules can be found here: <a href=\"https://docs.python.org/extending/extending.html\" rel=\"nofollow noreferrer\">https://docs.python.org/extending/extending.html</a></p>\n" }, { "answer_id": 63820, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 3, "selected": false, "text": "<p>I can't find any other built-in way of doing case-insensitive comparison: The <a href=\"http://code.activestate.com/recipes/170242/\" rel=\"noreferrer\">python cook-book recipe</a> uses lower().</p>\n\n<p>However you have to be careful when using lower for comparisons because of the <a href=\"http://en.wikipedia.org/wiki/Turkish_dotted_and_dotless_I\" rel=\"noreferrer\">Turkish I problem</a>. Unfortunately Python's handling for Turkish Is is not good. ı is converted to I, but I is not converted to ı. İ is converted to i, but i is not converted to İ. </p>\n" }, { "answer_id": 65834, "author": "Dale Wilson", "author_id": 391806, "author_profile": "https://Stackoverflow.com/users/391806", "pm_score": 0, "selected": false, "text": "<p>You could translate each string to lowercase once --- lazily only when you need it, or as a prepass to the sort if you know you'll be sorting the entire collection of strings. There are several ways to attach this comparison key to the actual data being sorted, but these techniques should be addressed in a separate issue.</p>\n\n<p>Note that this technique can be used not only to handle upper/lower case issues, but for other types of sorting such as locale specific sorting, or \"Library-style\" title sorting that ignores leading articles and otherwise normalizes the data before sorting it.</p>\n" }, { "answer_id": 66547, "author": "patrickyoung", "author_id": 3701, "author_profile": "https://Stackoverflow.com/users/3701", "pm_score": -1, "selected": true, "text": "<p>In response to your clarification...</p>\n\n<p>You could use <a href=\"http://docs.python.org/lib/ctypes-ctypes-tutorial.html\" rel=\"nofollow noreferrer\">ctypes</a> to execute the c function \"strcasecmp\". Ctypes is included in Python 2.5. It provides the ability to call out to dll and shared libraries such as libc. Here is a quick example (Python on Linux; see link for Win32 help):</p>\n\n<pre><code>from ctypes import *\nlibc = CDLL(\"libc.so.6\") // see link above for Win32 help\nlibc.strcasecmp(\"THIS\", \"this\") // returns 0\nlibc.strcasecmp(\"THIS\", \"THAT\") // returns 8\n</code></pre>\n\n<p>may also want to reference <a href=\"http://linux.die.net/man/3/strcasecmp\" rel=\"nofollow noreferrer\">strcasecmp documentation</a></p>\n\n<p>Not really sure this is any faster or slower (have not tested), but it's a way to use a C function to do case insensitive string comparisons. </p>\n\n<p>~~~~~~~~~~~~~~</p>\n\n<p><a href=\"http://code.activestate.com/recipes/194371/\" rel=\"nofollow noreferrer\" title=\"ActiveState Code\">ActiveState Code - Recipe 194371: Case Insensitive Strings</a>\nis a recipe for creating a case insensitive string class. It might be a bit over kill for something quick, but could provide you with a common way of handling case insensitive strings if you plan on using them often.</p>\n" }, { "answer_id": 67388, "author": "Antoine P.", "author_id": 10194, "author_profile": "https://Stackoverflow.com/users/10194", "pm_score": 1, "selected": false, "text": "<p>The recommended idiom to sort lists of values using expensive-to-compute keys is to the so-called \"decorated pattern\". It consists simply in building a list of (key, value) tuples from the original list, and sort that list. Then it is trivial to eliminate the keys and get the list of sorted values:</p>\n\n<pre><code>&gt;&gt;&gt; original_list = ['a', 'b', 'A', 'B']\n&gt;&gt;&gt; decorated = [(s.lower(), s) for s in original_list]\n&gt;&gt;&gt; decorated.sort()\n&gt;&gt;&gt; sorted_list = [s[1] for s in decorated]\n&gt;&gt;&gt; sorted_list\n['A', 'a', 'B', 'b']\n</code></pre>\n\n<p>Or if you like one-liners:</p>\n\n<pre><code>&gt;&gt;&gt; sorted_list = [s[1] for s in sorted((s.lower(), s) for s in original_list)]\n&gt;&gt;&gt; sorted_list\n['A', 'a', 'B', 'b']\n</code></pre>\n\n<p>If you really worry about the cost of calling lower(), you can just store tuples of (lowered string, original string) everywhere. Tuples are the cheapest kind of containers in Python, they are also hashable so they can be used as dictionary keys, set members, etc.</p>\n" }, { "answer_id": 67583, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": false, "text": "<p>Your question implies that you don't need Unicode. Try the following code snippet; if it works for you, you're done:</p>\n\n<pre><code>Python 2.5.2 (r252:60911, Aug 22 2008, 02:34:17)\n[GCC 4.3.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n&gt;&gt;&gt; import locale\n&gt;&gt;&gt; locale.setlocale(locale.LC_COLLATE, \"en_US\")\n'en_US'\n&gt;&gt;&gt; sorted(\"ABCabc\", key=locale.strxfrm)\n['a', 'A', 'b', 'B', 'c', 'C']\n&gt;&gt;&gt; sorted(\"ABCabc\", cmp=locale.strcoll)\n['a', 'A', 'b', 'B', 'c', 'C']\n</code></pre>\n\n<p>Clarification: in case it is not obvious at first sight, locale.strcoll seems to be the function you need, avoiding the str.lower or locale.strxfrm \"duplicate\" strings.</p>\n" }, { "answer_id": 121364, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>Here is a benchmark showing that using <a href=\"http://docs.python.org/2/library/string.html?highlight=lower#string.lower\" rel=\"nofollow noreferrer\"><code>str.lower</code></a> is faster than the accepted answer's proposed method (<code>libc.strcasecmp</code>):</p>\n\n<pre><code>#!/usr/bin/env python2.7\nimport random\nimport timeit\n\nfrom ctypes import *\nlibc = CDLL('libc.dylib') # change to 'libc.so.6' on linux\n\nwith open('/usr/share/dict/words', 'r') as wordlist:\n words = wordlist.read().splitlines()\nrandom.shuffle(words)\nprint '%i words in list' % len(words)\n\nsetup = 'from __main__ import words, libc; gc.enable()'\nstmts = [\n ('simple sort', 'sorted(words)'),\n ('sort with key=str.lower', 'sorted(words, key=str.lower)'),\n ('sort with cmp=libc.strcasecmp', 'sorted(words, cmp=libc.strcasecmp)'),\n]\n\nfor (comment, stmt) in stmts:\n t = timeit.Timer(stmt=stmt, setup=setup)\n print '%s: %.2f msec/pass' % (comment, (1000*t.timeit(10)/10))\n</code></pre>\n\n<p>typical times on my machine:</p>\n\n<pre><code>235886 words in list\nsimple sort: 483.59 msec/pass\nsort with key=str.lower: 1064.70 msec/pass\nsort with cmp=libc.strcasecmp: 5487.86 msec/pass\n</code></pre>\n\n<p>So, the version with <code>str.lower</code> is not only the fastest by far, but also the most portable and pythonic of all the proposed solutions here.\nI have not profiled memory usage, but the original poster has still not given a compelling reason to worry about it. Also, who says that a call into the libc module doesn't duplicate any strings?</p>\n\n<p>NB: The <code>lower()</code> string method also has the advantage of being locale-dependent. Something you will probably not be getting right when writing your own \"optimised\" solution. Even so, due to bugs and missing features in Python, this kind of comparison may give you wrong results in a unicode context.</p>\n" }, { "answer_id": 193863, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 0, "selected": false, "text": "<p>Just use the <code>str().lower()</code> method, unless high-performance is important - in which case write that sorting method as a C extension.</p>\n\n<p><a href=\"http://starship.python.net/crew/arcege/extwriting/pyext.html\" rel=\"nofollow noreferrer\">\"How to write a Python Extension\"</a> seems like a decent intro..</p>\n\n<p>More interestingly, <a href=\"http://www.dalkescientific.com/writings/NBN/c_extensions.html\" rel=\"nofollow noreferrer\">This guide</a> compares using the ctypes library vs writing an external C module (the ctype is quite-substantially slower than the C extension).</p>\n" }, { "answer_id": 2711031, "author": "Benjamin Atkin", "author_id": 3461, "author_profile": "https://Stackoverflow.com/users/3461", "pm_score": 2, "selected": false, "text": "<p>When something isn't supported well in the standard library, I always look for a PyPI package. With virtualization and the ubiquity of modern Linux distributions, I no longer avoid Python extensions. PyICU seems to fit the bill: <a href=\"https://stackoverflow.com/a/1098160/3461\">https://stackoverflow.com/a/1098160/3461</a></p>\n\n<p>There now is also an option that is pure python. It's well tested: <a href=\"https://github.com/jtauber/pyuca\" rel=\"nofollow noreferrer\">https://github.com/jtauber/pyuca</a></p>\n\n<hr>\n\n<p><strong>Old answer:</strong></p>\n\n<p>I like the regular expression solution. Here's a function you can copy and paste into any function, thanks to python's block structure support.</p>\n\n<pre><code>def equals_ignore_case(str1, str2):\n import re\n return re.match(re.escape(str1) + r'\\Z', str2, re.I) is not None\n</code></pre>\n\n<p>Since I used match instead of search, I didn't need to add a caret (^) to the regular expression.</p>\n\n<p><strong>Note:</strong> This only checks equality, which is sometimes what is needed. I also wouldn't go so far as to say that I like it.</p>\n" }, { "answer_id": 7239139, "author": "trevorcroft", "author_id": 919044, "author_profile": "https://Stackoverflow.com/users/919044", "pm_score": 2, "selected": false, "text": "<p>This question is asking 2 very different things:</p>\n\n<ol>\n<li>What is the easiest way to compare strings in Python, ignoring case?</li>\n<li>I guess I'm looking for an equivalent to C's stricmp().</li>\n</ol>\n\n<p>Since #1 has been answered very well already (ie: str1.lower() &lt; str2.lower()) I will answer #2.</p>\n\n<pre><code>def strincmp(str1, str2, numchars=None):\n result = 0\n len1 = len(str1)\n len2 = len(str2)\n if numchars is not None:\n minlen = min(len1,len2,numchars)\n else:\n minlen = min(len1,len2)\n #end if\n orda = ord('a')\n ordz = ord('z')\n\n i = 0\n while i &lt; minlen and 0 == result:\n ord1 = ord(str1[i])\n ord2 = ord(str2[i])\n if ord1 &gt;= orda and ord1 &lt;= ordz:\n ord1 = ord1-32\n #end if\n if ord2 &gt;= orda and ord2 &lt;= ordz:\n ord2 = ord2-32\n #end if\n result = cmp(ord1, ord2)\n i += 1\n #end while\n\n if 0 == result and minlen != numchars:\n if len1 &lt; len2:\n result = -1\n elif len2 &lt; len1:\n result = 1\n #end if\n #end if\n\n return result\n#end def\n</code></pre>\n\n<p>Only use this function when it makes sense to as in many instances the lowercase technique will be superior.</p>\n\n<p>I only work with ascii strings, I'm not sure how this will behave with unicode.</p>\n" }, { "answer_id": 22249049, "author": "Venkatesh Bachu", "author_id": 1008603, "author_profile": "https://Stackoverflow.com/users/1008603", "pm_score": 0, "selected": false, "text": "<pre><code>import re\nif re.match('tEXT', 'text', re.IGNORECASE):\n # is True\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6984/" ]
What is the easiest way to compare strings in Python, ignoring case? Of course one can do (str1.lower() <= str2.lower()), etc., but this created two additional temporary strings (with the obvious alloc/g-c overheads). I guess I'm looking for an equivalent to C's stricmp(). [Some more context requested, so I'll demonstrate with a trivial example:] Suppose you want to sort a looong list of strings. You simply do theList.sort(). This is O(n \* log(n)) string comparisons and no memory management (since all strings and list elements are some sort of smart pointers). You are happy. Now, you want to do the same, but ignore the case (let's simplify and say all strings are ascii, so locale issues can be ignored). You can do theList.sort(key=lambda s: s.lower()), but then you cause two new allocations per comparison, plus burden the garbage-collector with the duplicated (lowered) strings. Each such memory-management noise is orders-of-magnitude slower than simple string comparison. Now, with an in-place stricmp()-like function, you do: theList.sort(cmp=stricmp) and it is as fast and as memory-friendly as theList.sort(). You are happy again. The problem is any Python-based case-insensitive comparison involves implicit string duplications, so I was expecting to find a C-based comparisons (maybe in module string). Could not find anything like that, hence the question here. (Hope this clarifies the question).
In response to your clarification... You could use [ctypes](http://docs.python.org/lib/ctypes-ctypes-tutorial.html) to execute the c function "strcasecmp". Ctypes is included in Python 2.5. It provides the ability to call out to dll and shared libraries such as libc. Here is a quick example (Python on Linux; see link for Win32 help): ``` from ctypes import * libc = CDLL("libc.so.6") // see link above for Win32 help libc.strcasecmp("THIS", "this") // returns 0 libc.strcasecmp("THIS", "THAT") // returns 8 ``` may also want to reference [strcasecmp documentation](http://linux.die.net/man/3/strcasecmp) Not really sure this is any faster or slower (have not tested), but it's a way to use a C function to do case insensitive string comparisons. ~~~~~~~~~~~~~~ [ActiveState Code - Recipe 194371: Case Insensitive Strings](http://code.activestate.com/recipes/194371/ "ActiveState Code") is a recipe for creating a case insensitive string class. It might be a bit over kill for something quick, but could provide you with a common way of handling case insensitive strings if you plan on using them often.
62,588
<p>I have some ASP.NET web services which all share a common helper class they only need to instantiate one instance of <em>per server</em>. It's used for simple translation of data, but does spend some time during start-up loading things from the web.config file, etc. <em>The helper class is 100% thread-safe. Think of it as a simple library of utility calls. I'd make all the methods shared on the class, but I want to load the initial configuration from web.config.</em> We've deployed the web services to IIS 6.0 and using an Application Pool, with a Web Garden of 15 workers.</p> <p>I declared the helper class as a Private Shared variable in Global.asax, and added a lazy load Shared ReadOnly property like this:</p> <pre><code>Private Shared _helper As MyHelperClass Public Shared ReadOnly Property Helper() As MyHelperClass Get If _helper Is Nothing Then _helper = New MyHelperClass() End If Return _helper End Get End Property </code></pre> <p>I have logging code in the constructor for <code>MyHelperClass()</code>, and it shows the constructor running for each request, even on the same thread. I'm sure I'm just missing some key detail of ASP.NET but MSDN hasn't been very helpful.</p> <p>I've tried doing similar things using both <code>Application("Helper")</code> and <code>Cache("Helper")</code> and I still saw the constructor run with each request.</p>
[ { "answer_id": 62913, "author": "Donny V.", "author_id": 1231, "author_profile": "https://Stackoverflow.com/users/1231", "pm_score": 0, "selected": false, "text": "<p>I 'v done something like this in my own app in the past and it caused all kinds of weird errors.\nEvery user will have access to everyone else's data in the property. Plus you could end up with one user being in the middle of using it and than getting cut off because its being requested by another user.</p>\n\n<p>No there not isolated.</p>\n" }, { "answer_id": 62924, "author": "JRoppert", "author_id": 6777, "author_profile": "https://Stackoverflow.com/users/6777", "pm_score": 2, "selected": false, "text": "<p>You can place your Helper in the Application State. Do this in global.asax:</p>\n\n<pre><code> void Application_Start(object sender, EventArgs e)\n {\n Application.Add(\"MyHelper\", new MyHelperClass());\n }\n</code></pre>\n\n<p>You can use the Helper that way:</p>\n\n<pre><code> MyHelperClass helper = (MyHelperClass)HttpContext.Current.Application[\"MyHelper\"];\n helper.Foo();\n</code></pre>\n\n<p>This results in a single instance of the MyHelperClass class that is created on application start and lives in application state. Since the instance is created in Application_Start, this happens only once for each HttpApplication instance and not per Request.</p>\n" }, { "answer_id": 63006, "author": "user7375", "author_id": 7375, "author_profile": "https://Stackoverflow.com/users/7375", "pm_score": 1, "selected": true, "text": "<p>It's not wise to use application state unless you absolutely require it, things are much simpler if you stick to using per-request objects. Any addition of state to the helper classes could cause all sorts of subtle errors. Use the HttpContext.Current items collection and intialise it per request. A VB module would do what you want, but you must be sure not to make it stateful.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6897/" ]
I have some ASP.NET web services which all share a common helper class they only need to instantiate one instance of *per server*. It's used for simple translation of data, but does spend some time during start-up loading things from the web.config file, etc. *The helper class is 100% thread-safe. Think of it as a simple library of utility calls. I'd make all the methods shared on the class, but I want to load the initial configuration from web.config.* We've deployed the web services to IIS 6.0 and using an Application Pool, with a Web Garden of 15 workers. I declared the helper class as a Private Shared variable in Global.asax, and added a lazy load Shared ReadOnly property like this: ``` Private Shared _helper As MyHelperClass Public Shared ReadOnly Property Helper() As MyHelperClass Get If _helper Is Nothing Then _helper = New MyHelperClass() End If Return _helper End Get End Property ``` I have logging code in the constructor for `MyHelperClass()`, and it shows the constructor running for each request, even on the same thread. I'm sure I'm just missing some key detail of ASP.NET but MSDN hasn't been very helpful. I've tried doing similar things using both `Application("Helper")` and `Cache("Helper")` and I still saw the constructor run with each request.
It's not wise to use application state unless you absolutely require it, things are much simpler if you stick to using per-request objects. Any addition of state to the helper classes could cause all sorts of subtle errors. Use the HttpContext.Current items collection and intialise it per request. A VB module would do what you want, but you must be sure not to make it stateful.
62,599
<p>How do you define your UserControls as being in a namespace below the project namespace, ie. [RootNameSpace].[SubSectionOfProgram].Controls?</p> <p><strong>Edit due to camainc's answer:</strong> I also have a constraint that I have to have all the code in a single project.</p> <p><strong>Edit to finalise question:</strong> As I suspected it isn't possible to do what I required so camainc's answer is the nearest solution.</p>
[ { "answer_id": 62817, "author": "camainc", "author_id": 7232, "author_profile": "https://Stackoverflow.com/users/7232", "pm_score": 2, "selected": true, "text": "<p>I'm not sure if this is what you are asking, but this is how we do it.</p>\n\n<p>We namespace all of our projects in a consistent manner, user controls are no different. We also namespace using the project settings window, although you could do it through a combination of the project window and in code.</p>\n\n<p>Each solution gets a namespace like this:</p>\n\n<pre><code>[CompanyName].[SolutionName].[ProjectName]\n</code></pre>\n\n<p>So, our user controls are normally in a project called \"Controls,\" which would have a namespace of:</p>\n\n<pre><code>OurCompany.ThisSolution.Controls\n</code></pre>\n\n<p>If we have controls that might span several different solutions, we just namespace it like so:</p>\n\n<pre><code>OurCompany.Common.Controls\n</code></pre>\n\n<p>Then, in our code we will import the library, or add the project to the solution.</p>\n\n<pre><code>Imports OurCompany\nImports OurCompany.Common\nImports OurCompany.Common.Controls\n</code></pre>\n\n<p>We also name the folders where the projects live the same as the namespace, down to but not including the company name (all solutions are assumed to be in the company namespace):</p>\n\n<p>\\Projects<br>\n\\Projects\\MySolution<br>\n\\Projects\\MySolution\\Controls</p>\n\n<p>-- or --</p>\n\n<p>\\Projects\\<br>\n\\Projects\\Common<br>\n\\Projects\\Common\\Assemblies<br>\n\\Projects\\Common\\Controls</p>\n\n<p>etc.</p>\n\n<p>Hope that helps...</p>\n" }, { "answer_id": 62957, "author": "Keithius", "author_id": 5956, "author_profile": "https://Stackoverflow.com/users/5956", "pm_score": 0, "selected": false, "text": "<p>Do you mean you want to be able to access user controls at runtime (in code) via </p>\n\n<blockquote>\n <p><code>[ProjectNamespace].[YourSpecialNamespace].Controls</code></p>\n</blockquote>\n\n<p>rather than the default of </p>\n\n<blockquote>\n <p><code>[ProjectNamespace].Controls</code></p>\n</blockquote>\n\n<p>? Because I don't believe that is possible. If I'm not mistaken, the <code>Controls</code> collection of your project/app is built-in by the framework - you can't change it. You can, as camainc noted, use the project settings window (or code) to place the controls themselves in a specific namespace thusly:</p>\n\n<blockquote>\n <p><code>Namespace [YourSpecialNamespace]</code></p>\n \n <p><code>Public Class Form1</code></p>\n \n <p><code>[...]</code></p>\n \n <p><code>End Class</code></p>\n \n <p><code>End Namespace</code></p>\n</blockquote>\n\n<p>Of course, thinking about it some more, I suppose you could design and build your own <code>Controls</code> collection in your namespace - perhaps as a wrapper for the built-in one... </p>\n" }, { "answer_id": 3904409, "author": "Cody Gray", "author_id": 366904, "author_profile": "https://Stackoverflow.com/users/366904", "pm_score": 1, "selected": false, "text": "<p>If you don't want the controls to be in a separate project, you can just add the Namespace keyword to the top of the code file. For example, I've done something like this in several projects:</p>\n\n<pre><code>Imports System.ComponentModel\n\nNamespace Controls\n Friend Class FloatingSearchForm\n\n 'Your code goes here...\n\n End Class\nEnd Namespace\n</code></pre>\n\n<p>You will not be able to specify that the controls are in a different root namespace than that specified for the project they are a part of. VB will simply append whatever you specify for the namespace to the namespace specified in the project properties window. So, if your entire project is \"AcmeCorporation.WidgetProgram\" and you add \"Namespace Controls\" to the top of a control file, the control will be in the namespace \"AcmeCorporation.WidgetProgram.Controls\". It is not possible to make the control appear in the \"AcmeCorporation.SomeOtherProgram.Controls\" namespace.</p>\n\n<p>Also note that if you are using the designer to edit your controls, you need to add the Namespace keyword to the hidden partial class created by the designer. Click the \"Show All Files\" button in the solution explorer, then click the expand arrow next to your control. You should see a \"*.Designer.vb\" file listed. Add the Namespace to that file as well. The designer will respect this modification, and your project should now compile without error. Obviously, the namespace specified in the designer partial class must be the same one as that specified in your class file! For the above example:</p>\n\n<pre><code>Namespace Controls\n &lt;Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()&gt; _\n Partial Class FloatingSearchForm\n\n 'Designer generated code\n\n End Class\nEnd Namespace\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6369/" ]
How do you define your UserControls as being in a namespace below the project namespace, ie. [RootNameSpace].[SubSectionOfProgram].Controls? **Edit due to camainc's answer:** I also have a constraint that I have to have all the code in a single project. **Edit to finalise question:** As I suspected it isn't possible to do what I required so camainc's answer is the nearest solution.
I'm not sure if this is what you are asking, but this is how we do it. We namespace all of our projects in a consistent manner, user controls are no different. We also namespace using the project settings window, although you could do it through a combination of the project window and in code. Each solution gets a namespace like this: ``` [CompanyName].[SolutionName].[ProjectName] ``` So, our user controls are normally in a project called "Controls," which would have a namespace of: ``` OurCompany.ThisSolution.Controls ``` If we have controls that might span several different solutions, we just namespace it like so: ``` OurCompany.Common.Controls ``` Then, in our code we will import the library, or add the project to the solution. ``` Imports OurCompany Imports OurCompany.Common Imports OurCompany.Common.Controls ``` We also name the folders where the projects live the same as the namespace, down to but not including the company name (all solutions are assumed to be in the company namespace): \Projects \Projects\MySolution \Projects\MySolution\Controls -- or -- \Projects\ \Projects\Common \Projects\Common\Assemblies \Projects\Common\Controls etc. Hope that helps...
62,606
<p>I'm using <code>int</code> as an example, but this applies to any value type in .Net</p> <p>In .Net 1 the following would throw a compiler exception:</p> <pre><code>int i = SomeFunctionThatReturnsInt(); if( i == null ) //compiler exception here </code></pre> <p>Now (in .Net 2 or 3.5) that exception has gone.</p> <p>I know why this is:</p> <pre><code>int? j = null; //nullable int if( i == j ) //this shouldn't throw an exception </code></pre> <p>The problem is that because <code>int?</code> is nullable and <code>int</code> now has a implicit cast to <code>int?</code>. The syntax above is compiler magic. Really we're doing:</p> <pre><code>Nullable&lt;int&gt; j = null; //nullable int //compiler is smart enough to do this if( (Nullable&lt;int&gt;) i == j) //and not this if( i == (int) j) </code></pre> <p>So now, when we do <code>i == null</code> we get:</p> <pre><code>if( (Nullable&lt;int&gt;) i == null ) </code></pre> <p>Given that C# is doing compiler logic to calculate this anyway why can't it be smart enough to not do it when dealing with absolute values like <code>null</code>?</p>
[ { "answer_id": 62724, "author": "ima", "author_id": 5733, "author_profile": "https://Stackoverflow.com/users/5733", "pm_score": 1, "selected": false, "text": "<p>Compiler still generates warning when you compare non-nullable type to null, which is just the way it should be. May be your warning level is too low or this was changed in recent versions (I only did that in .net 3.5).</p>\n" }, { "answer_id": 62747, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>Odd ... compiling this with VS2008, targetting .NET 3.5:</p>\n\n<pre><code>static int F()\n{\n return 42;\n}\n\nstatic void Main(string[] args)\n{\n int i = F();\n\n if (i == null)\n {\n }\n}\n</code></pre>\n\n<p>I get a compiler warning</p>\n\n<pre><code>warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'\n</code></pre>\n\n<p>And it generates the following IL ... which presumably the JIT will optimize away</p>\n\n<pre><code>L_0001: call int32 ConsoleApplication1.Program::F()\nL_0006: stloc.0 \nL_0007: ldc.i4.0 \nL_0008: ldc.i4.0 \nL_0009: ceq \nL_000b: stloc.1 \nL_000c: br.s L_000e\n</code></pre>\n\n<p>Can you post a code snippet?</p>\n" }, { "answer_id": 62775, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 3, "selected": true, "text": "<p>I don't think this is a compiler problem <em>per se</em>; an integer value is never null, but the idea of equating them isn't invalid; it's a valid function that always returns false. And the compiler knows; the code</p>\n\n<pre><code>bool oneIsNull = 1 == null;\n</code></pre>\n\n<p>compiles, but gives a compiler warning: <code>The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type '&lt;null&gt;'</code>.</p>\n\n<p>So if you want the compiler error back, go to the project properties and turn on 'treat warnings as errors' for this error, and you'll start seeing them as build-breaking problems again.</p>\n" }, { "answer_id": 63027, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "<p>The warning is new (3.5 I think) - the error is the same as if I'd done <code>1 == 2</code>, which it's smart enough to spot as never true.</p>\n\n<p>I suspect that with full 3.5 optimisations the whole statement will just be stripped out, as it's pretty smart with never true evaluations.</p>\n\n<p>While I might want <code>1==2</code> to compile (to switch off a function block while I test something else for instance) I don't want <code>1==null</code> to.</p>\n" }, { "answer_id": 63099, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": 0, "selected": false, "text": "<p>It ought to be a compile-time error, because the types are incompatible (value types can never be null). It's pretty sad that it isn't.</p>\n" }, { "answer_id": 63326, "author": "Michael Meadows", "author_id": 7643, "author_profile": "https://Stackoverflow.com/users/7643", "pm_score": 1, "selected": false, "text": "<p>The 2.0 framework introduced the nullable value type. Even though the literal constant \"1\" can never be null, its underlying type (int) can now be cast to a Nullable int type. My guess is that the compiler can no longer assume that int types are not nullable, even when it is a literal constant. I do get a warning when compiling 2.0:</p>\n\n<p>Warning 1 The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
I'm using `int` as an example, but this applies to any value type in .Net In .Net 1 the following would throw a compiler exception: ``` int i = SomeFunctionThatReturnsInt(); if( i == null ) //compiler exception here ``` Now (in .Net 2 or 3.5) that exception has gone. I know why this is: ``` int? j = null; //nullable int if( i == j ) //this shouldn't throw an exception ``` The problem is that because `int?` is nullable and `int` now has a implicit cast to `int?`. The syntax above is compiler magic. Really we're doing: ``` Nullable<int> j = null; //nullable int //compiler is smart enough to do this if( (Nullable<int>) i == j) //and not this if( i == (int) j) ``` So now, when we do `i == null` we get: ``` if( (Nullable<int>) i == null ) ``` Given that C# is doing compiler logic to calculate this anyway why can't it be smart enough to not do it when dealing with absolute values like `null`?
I don't think this is a compiler problem *per se*; an integer value is never null, but the idea of equating them isn't invalid; it's a valid function that always returns false. And the compiler knows; the code ``` bool oneIsNull = 1 == null; ``` compiles, but gives a compiler warning: `The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type '<null>'`. So if you want the compiler error back, go to the project properties and turn on 'treat warnings as errors' for this error, and you'll start seeing them as build-breaking problems again.
62,618
<p>I've got many, many mp3 files that I would like to merge into a single file. I've used the command line method</p> <pre><code>copy /b 1.mp3+2.mp3 3.mp3 </code></pre> <p>but it's a pain when there's a lot of them and their namings are inconsistent. The time never seems to come out right either.</p>
[ { "answer_id": 62635, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 3, "selected": false, "text": "<p>The time problem has to do with the ID3 headers of the MP3 files, which is something your method isn't taking into account as the entire file is copied.</p>\n\n<p>Do you have a language of choice that you want to use or doesn't it matter? That will affect what libraries are available that support the operations you want.</p>\n" }, { "answer_id": 62736, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Personally I would use something like mplayer with the audio pass though option eg -oac copy</p>\n" }, { "answer_id": 62762, "author": "David Precious", "author_id": 4040, "author_profile": "https://Stackoverflow.com/users/4040", "pm_score": 7, "selected": true, "text": "<p>As Thomas Owens pointed out, simply concatenating the files will leave multiple ID3 headers scattered throughout the resulting concatenated file - so the time/bitrate info will be wildly wrong.</p>\n\n<p>You're going to need to use a tool which can combine the audio data for you.</p>\n\n<p><a href=\"http://mp3wrap.sourceforge.net/\" rel=\"noreferrer\">mp3wrap</a> would be ideal for this - it's designed to join together MP3 files, without needing to decode + re-encode the data (which would result in a loss of audio quality) and will also deal with the ID3 tags intelligently.</p>\n\n<p>The resulting file can also be split back into its component parts using the mp3splt tool - mp3wrap adds information to the IDv3 comment to allow this.</p>\n" }, { "answer_id": 62785, "author": "Chris M.", "author_id": 6747, "author_profile": "https://Stackoverflow.com/users/6747", "pm_score": 2, "selected": false, "text": "<p>MP3 files have headers you need to respect.</p>\n\n<p>You could ether use a library like <a href=\"http://osalp.sourceforge.net/\" rel=\"nofollow noreferrer\">Open Source Audio Library Project</a> and write a tool around it.\nOr you can use a tool that understands mp3 files like <a href=\"http://audacity.sourceforge.net/\" rel=\"nofollow noreferrer\">Audacity</a>.</p>\n" }, { "answer_id": 62793, "author": "szeryf", "author_id": 7202, "author_profile": "https://Stackoverflow.com/users/7202", "pm_score": 1, "selected": false, "text": "<p>I would use Winamp to do this. Create a playlist of files you want to merge into one, select Disk Writer output plugin, choose filename and you're done. The file you will get will be correct MP3 file and you can set bitrate etc.</p>\n" }, { "answer_id": 574439, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 2, "selected": false, "text": "<p>As David says, <a href=\"http://mp3wrap.sourceforge.net/\" rel=\"nofollow noreferrer\">mp3wrap</a> is the way to go. However, I found that it didn't fix the audio length header, so iTunes refused to play the whole file even though all the data was there. (I merged three 7-minute files, but it only saw up to the first 7 minutes.)</p>\n\n<p>I dug up <a href=\"http://lyncd.com/2009/02/how-to-merge-mp3-files/\" rel=\"nofollow noreferrer\">this blog post</a>, which explains how to fix this and also how to copy the ID3 tags over from the original files (on its own, mp3wrap deletes your ID3 tags). Or to just copy the tags (using id3cp from <a href=\"http://id3lib.sourceforge.net/\" rel=\"nofollow noreferrer\">id3lib</a>), do:</p>\n\n<pre><code>id3cp original.mp3 new.mp3\n</code></pre>\n" }, { "answer_id": 1245493, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I'd not heard of mp3wrap before. Looks great. I'm guessing someone's made it into a gui as well somewhere. But, just to respond to the original post, I've written a gui that does the COPY /b method. So, under the covers, nothing new under the sun, but the program is all about making the process less painful if you have a lot of files to merge...AND you don't want to re-encode AND each set of files to merge are the same bitrate. If you have that (and you're on Windows), check out Mp3Merge at: <a href=\"http://www.leighweb.com/david/mp3merge\" rel=\"nofollow noreferrer\">http://www.leighweb.com/david/mp3merge</a> and see if that's what you're looking for.</p>\n" }, { "answer_id": 1479701, "author": "bmurphy1976", "author_id": 1931, "author_profile": "https://Stackoverflow.com/users/1931", "pm_score": 4, "selected": false, "text": "<p>Use ffmpeg or a similar tool to convert all of your MP3s into a consistent format, e.g. </p>\n\n<pre><code>ffmpeg -i originalA.mp3 -f mp3 -ab 128kb -ar 44100 -ac 2 intermediateA.mp3 \nffmpeg -i originalB.mp3 -f mp3 -ab 128kb -ar 44100 -ac 2 intermediateB.mp3\n</code></pre>\n\n<p>Then, at runtime, concat your files together: </p>\n\n<pre><code>cat intermediateA.mp3 intermediateB.mp3 &gt; output.mp3\n</code></pre>\n\n<p>Finally, run them through the tool <strong><a href=\"http://mp3val.sourceforge.net/\" rel=\"noreferrer\">MP3Val</a></strong> to fix any stream errors without forcing a full re-encode: </p>\n\n<pre><code>mp3val output.mp3 -f -nb\n</code></pre>\n" }, { "answer_id": 1759464, "author": "Daave311", "author_id": 214140, "author_profile": "https://Stackoverflow.com/users/214140", "pm_score": 0, "selected": false, "text": "<p>Instead of using the command line to do </p>\n\n<blockquote>\n <p>copy /b 1.mp3+2.mp3 3.mp3</p>\n</blockquote>\n\n<p>you could instead use <a href=\"http://www.softempire.com/the-rename-downloads.html\" rel=\"nofollow noreferrer\">\"The Rename\"</a> to rename all the MP3 fragments into a series of names that are in order based on some kind of counter. Then you could just use the same command line format but change it a little to: </p>\n\n<blockquote>\n <p>copy /b *.mp3 output_name.mp3</p>\n</blockquote>\n\n<p>That is assuming you ripped all of these fragment MP3's at the same time and they have the same audio settings. Worked great for me when I was converting an Audio book I had in .aa to a single .mp3. I had to burn all the .aa files to 9 CD's then rip all 9 CD's and then I was left with about 90 mp3's. Really a pain in the a55.</p>\n" }, { "answer_id": 4350108, "author": "Adam", "author_id": 529916, "author_profile": "https://Stackoverflow.com/users/529916", "pm_score": 2, "selected": false, "text": "<p><em>What I really wanted was a GUI to reorder them and output them as one file</em></p>\n\n<p><a href=\"http://www.playlistproducer.com/\" rel=\"nofollow\">Playlist Producer</a> does exactly that, decoding and reencoding them into a combined MP3. It's designed for creating mix tapes or simple podcasts, but you might find it useful.</p>\n\n<p>(Disclosure: I wrote the software, and I profit if you buy the Pro Edition. The Lite edition is a free version with a few limitations).</p>\n" }, { "answer_id": 5364985, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 6, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/62762/3195477\">David's answer</a> is correct that just concatenating the files will leave ID3 tags scattered inside (although this doesn't normally affect playback, so you can do \"copy /b\" or on UNIX \"cat a.mp3 b.mp3 > combined.mp3\" in a pinch).</p>\n\n<p>However, mp3wrap isn't exactly the right tool to just combine multiple MP3s into one \"clean\" file. Rather than using ID3, it actually inserts its own <a href=\"http://mp3wrap.sourceforge.net/mp3wrap-format.html\" rel=\"noreferrer\">custom data format</a> in amongst the MP3 frames (the \"wrap\" part), which causes issues with playback, particularly on iTunes and iPods. Although the file <em>will</em> play back fine if you just let them run from start to finish (because players will skip these is arbitrary non-MPEG bytes) the file duration and bitrate will be reported incorrectly, which breaks seeking. Also, mp3wrap will wipe out all your ID3 metadata, including cover art, and fail to update the VBR header with the correct file length.</p>\n\n<p><a href=\"http://tomclegg.net/mp3cat\" rel=\"noreferrer\">mp3cat</a> on its own will produce a good concatenated data file (so, better than mp3wrap), but it also strips ID3 tags and fails to update the VBR header with the correct length of the joined file.</p>\n\n<p>Here's a <a href=\"http://lyncd.com/2011/03/lossless-combine-mp3s/\" rel=\"noreferrer\">good explanation</a> of these issues and method (two actually) to combine MP3 files and produce a \"clean\" final result with original metadata intact -- it's command-line so works on Mac/Linux/BSD etc. It uses:</p>\n\n<ul>\n<li><a href=\"http://tomclegg.net/mp3cat\" rel=\"noreferrer\">mp3cat</a> to combine the MPEG data frames only into a continuous file, then</li>\n<li><a href=\"http://id3lib.sourceforge.net/\" rel=\"noreferrer\">id3cp</a> to copy all metadata over to the combined file, and finally </li>\n<li><a href=\"http://home.gna.org/vbrfix/\" rel=\"noreferrer\">VBRFix</a> to update the VBR header.</li>\n</ul>\n\n<p>For a Windows GUI tool, take a look at <a href=\"http://www.shchuka.com/software/mergemp3/\" rel=\"noreferrer\">Merge MP3</a> -- it takes care of everything. (VBRFix also comes in GUI form, but it doesn't do the joining.)</p>\n" }, { "answer_id": 16752087, "author": "James", "author_id": 410072, "author_profile": "https://Stackoverflow.com/users/410072", "pm_score": 1, "selected": false, "text": "<p>If you want something <strong><em>free</em></strong> with a simple user interface that makes a <strong>completely clean</strong> mp3 I recommend <a href=\"http://mp3joiner.net/\" rel=\"nofollow noreferrer\">MP3 Joiner</a>.</p>\n\n<p><strong>Features:</strong></p>\n\n<ul>\n<li>Strips ID3 data (both ID3v1 and ID3v2.x) and doesn't add it's own (unlike mp3wrap)</li>\n<li>Lossless joining (doesn't decode and re-encode the .mp3s). No codecs required.</li>\n<li>Simple UI (see below)</li>\n<li>Low memory usage (uses streams)</li>\n<li>Very fast (compared to mp3wrap)</li>\n<li>I wrote it :) - so you can request features and I'll add them.</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/TGvYH.png\" alt=\"MP3 Joiner app\"></p>\n\n<p>Links:</p>\n\n<ul>\n<li>MP3 Joiner website: <a href=\"http://mp3joiner.net/\" rel=\"nofollow noreferrer\">Here</a></li>\n<li>Latest installer: <a href=\"http://bytesoftly.com/Download/Apps/1/1.0/MP3JoinerSetup.exe\" rel=\"nofollow noreferrer\">Here</a></li>\n</ul>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4230/" ]
I've got many, many mp3 files that I would like to merge into a single file. I've used the command line method ``` copy /b 1.mp3+2.mp3 3.mp3 ``` but it's a pain when there's a lot of them and their namings are inconsistent. The time never seems to come out right either.
As Thomas Owens pointed out, simply concatenating the files will leave multiple ID3 headers scattered throughout the resulting concatenated file - so the time/bitrate info will be wildly wrong. You're going to need to use a tool which can combine the audio data for you. [mp3wrap](http://mp3wrap.sourceforge.net/) would be ideal for this - it's designed to join together MP3 files, without needing to decode + re-encode the data (which would result in a loss of audio quality) and will also deal with the ID3 tags intelligently. The resulting file can also be split back into its component parts using the mp3splt tool - mp3wrap adds information to the IDv3 comment to allow this.
62,629
<p>I need to determine when my Qt 4.4.1 application receives focus.</p> <p>I have come up with 2 possible solutions, but they both don’t work exactly as I would like.</p> <p>In the first possible solution, I connect the focusChanged() signal from qApp to a SLOT. In the slot I check the ‘old’ pointer. If it ‘0’, then I know we’ve switched to this application, and I do what I want. This seems to be the most reliable method of getting the application to detect focus in of the two solutions presented here, but suffers from the problem described below. </p> <p>In the second possible solution, I overrode the ‘focusInEvent()’ routine, and do what I want if the reason is ‘ActiveWindowFocusReason’.</p> <p>In both of these solutions, the code is executed at times when I don’t want it to be.</p> <p>For example, I have this code that overrides the focusInEvent() routine:</p> <pre><code>void ApplicationWindow::focusInEvent( QFocusEvent* p_event ) { Qt::FocusReason reason = p_event-&gt;reason(); if( reason == Qt::ActiveWindowFocusReason &amp;&amp; hasNewUpstreamData() ) { switch( QMessageBox::warning( this, "New Upstream Data Found!", "New upstream data exists!\n" "Do you want to refresh this simulation?", "&amp;Yes", "&amp;No", 0, 0, 1 ) ) { case 0: // Yes refreshSimulation(); break; case 1: // No break; } } } </code></pre> <p>When this gets executed, the QMessageBox dialog appears. However, when the dialog is dismissed by pressing either ‘yes’ or ‘no’, this function immediately gets called again because I suppose the focus changed back to the application window at that point with the ActiveWindowFocusReason. Obviously I don’t want this to happen.</p> <p>Likewise, if the user is using the application opening &amp; closing dialogs and windows etc, I don’t want this routine to activate. NOTE: I’m not sure of the circumstances when this routine is activated though since I’ve tried a bit, and it doesn’t happen for all windows &amp; dialogs, though it does happen at least for the one shown in the sample code.</p> <p>I only want it to activate if the application is focussed on from outside of this application, not when the main window is focussed in from other dialog windows.</p> <p>Is this possible? How can this be done?</p> <p>Thanks for any information, since this is very important for our application to do.</p> <p>Raymond.</p>
[ { "answer_id": 62820, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 0, "selected": false, "text": "<p>Looking at the Qt docs it seems that focus events are created each time a widget gets the focus, so the sample code you posted won't work for the reasons you stated. </p>\n\n<p>I am guessing that QApplication::focusedChanged does not work the way you want because some widgets don't accept keyboard events so also return null as the \"old\" widget even when changing focus within the same app.</p>\n\n<p>I am wondering whether you can do anything with QApplication::activeWindow()</p>\n\n<blockquote>\n <p>Returns the application top-level window that has the keyboard input focus, or 0 if no application window has the focus. Note that there might be an activeWindow() even if there is no focusWidget(), for example if no widget in that window accepts key events.</p>\n</blockquote>\n" }, { "answer_id": 173692, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>When your dialog is open, keyboard events don't go to your main window. After the dialog is closed, they do. That's a focus change. If you want to ignore the case where the focus switched from another window in your application, then you need to know when any window in your application has the focus. Make a variable and add a little more logic to your function. This will take some care, as the dialog will lose focus just before the main window gains focus.</p>\n" }, { "answer_id": 358253, "author": "Michael Bishop", "author_id": 45114, "author_profile": "https://Stackoverflow.com/users/45114", "pm_score": 3, "selected": false, "text": "<p>I think you need to track the <a href=\"http://doc.qt.io/qt-4.8/qevent.html#Type-enum\" rel=\"nofollow noreferrer\">QEvent::ApplicationActivate</a> event.</p>\n\n<p>You can put an <a href=\"http://doc.qt.io/qt-4.8/qobject.html#eventFilter\" rel=\"nofollow noreferrer\">event filter</a> on your QApplication instance and then look for it.</p>\n\n<pre><code>bool\nApplicationWindow::eventFilter( QObject * watched, QEvent * event )\n{\n if ( watched != qApp )\n goto finished;\n\n if ( event-&gt;type() != QEvent::ApplicationActivate )\n goto finished;\n\n // Invariant: we are now looking at an application activate event for\n // the application object\n if ( !hasNewUpstreamData() )\n goto finished;\n\n QMessageBox::StandardButton response =\n QMessageBox::warning( this, \"New Upstream Data Found!\",\n \"New upstream data exists!\\n\"\n \"Do you want to refresh this simulation?\",\n QMessageBox::Yes | QMessageBox::No) );\n\n if ( response == QMessageBox::Yes )\n refreshSimulation();\n\nfinished:\n return &lt;The-Superclass-here&gt;::eventFilter( watched, event );\n}\n\nApplicationWindow::ApplicationWindow(...)\n{\n if (qApp)\n qApp-&gt;installEventFilter( this );\n ...\n}\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/460958/" ]
I need to determine when my Qt 4.4.1 application receives focus. I have come up with 2 possible solutions, but they both don’t work exactly as I would like. In the first possible solution, I connect the focusChanged() signal from qApp to a SLOT. In the slot I check the ‘old’ pointer. If it ‘0’, then I know we’ve switched to this application, and I do what I want. This seems to be the most reliable method of getting the application to detect focus in of the two solutions presented here, but suffers from the problem described below. In the second possible solution, I overrode the ‘focusInEvent()’ routine, and do what I want if the reason is ‘ActiveWindowFocusReason’. In both of these solutions, the code is executed at times when I don’t want it to be. For example, I have this code that overrides the focusInEvent() routine: ``` void ApplicationWindow::focusInEvent( QFocusEvent* p_event ) { Qt::FocusReason reason = p_event->reason(); if( reason == Qt::ActiveWindowFocusReason && hasNewUpstreamData() ) { switch( QMessageBox::warning( this, "New Upstream Data Found!", "New upstream data exists!\n" "Do you want to refresh this simulation?", "&Yes", "&No", 0, 0, 1 ) ) { case 0: // Yes refreshSimulation(); break; case 1: // No break; } } } ``` When this gets executed, the QMessageBox dialog appears. However, when the dialog is dismissed by pressing either ‘yes’ or ‘no’, this function immediately gets called again because I suppose the focus changed back to the application window at that point with the ActiveWindowFocusReason. Obviously I don’t want this to happen. Likewise, if the user is using the application opening & closing dialogs and windows etc, I don’t want this routine to activate. NOTE: I’m not sure of the circumstances when this routine is activated though since I’ve tried a bit, and it doesn’t happen for all windows & dialogs, though it does happen at least for the one shown in the sample code. I only want it to activate if the application is focussed on from outside of this application, not when the main window is focussed in from other dialog windows. Is this possible? How can this be done? Thanks for any information, since this is very important for our application to do. Raymond.
I think you need to track the [QEvent::ApplicationActivate](http://doc.qt.io/qt-4.8/qevent.html#Type-enum) event. You can put an [event filter](http://doc.qt.io/qt-4.8/qobject.html#eventFilter) on your QApplication instance and then look for it. ``` bool ApplicationWindow::eventFilter( QObject * watched, QEvent * event ) { if ( watched != qApp ) goto finished; if ( event->type() != QEvent::ApplicationActivate ) goto finished; // Invariant: we are now looking at an application activate event for // the application object if ( !hasNewUpstreamData() ) goto finished; QMessageBox::StandardButton response = QMessageBox::warning( this, "New Upstream Data Found!", "New upstream data exists!\n" "Do you want to refresh this simulation?", QMessageBox::Yes | QMessageBox::No) ); if ( response == QMessageBox::Yes ) refreshSimulation(); finished: return <The-Superclass-here>::eventFilter( watched, event ); } ApplicationWindow::ApplicationWindow(...) { if (qApp) qApp->installEventFilter( this ); ... } ```
62,661
<p>What Direct3D render states should be used to implement Java's Porter-Duff compositing rules (CLEAR, SRC, SRCOVER, etc.)?</p>
[ { "answer_id": 67873, "author": "Corey Ross", "author_id": 5927, "author_profile": "https://Stackoverflow.com/users/5927", "pm_score": 2, "selected": false, "text": "<p>I'm haven't used Java too much, but based on the <a href=\"http://keithp.com/~keithp/porterduff/p253-porter.pdf\" rel=\"nofollow noreferrer\">white paper from 1984</a>, it should be a fairly straightforward mapping of render state blend modes.</p>\n\n<p>There are of course more that you can do than just these, like normal alpha blending (SourceAlpha, InvSourceAlpha) or additive (One, One) to name a few. <em>(I assume that you are asking about these specifically because you are porting some existing functionality? In that cause you may not care about other combinations...)</em></p>\n\n<p>Anyway, these assume a BlendOperation of Add and that AlphaBlendEnable is true.</p>\n\n<p>Clear</p>\n\n<pre><code>SourceBlend = Zero\nDestinationBlend = Zero\n</code></pre>\n\n<p>A</p>\n\n<pre><code>SourceBlend = One\nDestinationBlend = Zero\n</code></pre>\n\n<p>B</p>\n\n<pre><code>SourceBlend = Zero\nDestinationBlend = One\n</code></pre>\n\n<p>A over B</p>\n\n<pre><code>SourceBlend = One\nDestinationBlend = InvSourceAlpha\n</code></pre>\n\n<p>B over A</p>\n\n<pre><code>SourceBlend = InvDestinationAlpha\nDestinationBlend = One\n</code></pre>\n\n<p>A in B</p>\n\n<pre><code>SourceBlend = DestinationAlpha\nDestinationBlend = One\n</code></pre>\n\n<p>B in A</p>\n\n<pre><code>SourceBlend = Zero\nDestinationBlend = SourceAlpha\n</code></pre>\n\n<p>A out B</p>\n\n<pre><code>SourceBlend = InvDestinationAlpha\nDestinationBlend = Zero\n</code></pre>\n\n<p>B out A</p>\n\n<pre><code>SourceBlend = Zero\nDestinationBlend = InvSourceAlpha\n</code></pre>\n\n<p>A atop B</p>\n\n<pre><code>SourceBlend = DestinationAlpha\nDestinationBlend = InvSourceAlpha\n</code></pre>\n\n<p>B atop A</p>\n\n<pre><code>SourceBlend = InvDestinationAlpha\nDestinationBlend = SourceAlpha\n</code></pre>\n\n<p>A xor B</p>\n\n<pre><code>SourceBlend = InvDestinationAlpha\nDestinationBlend = InvSourceAlpha\n</code></pre>\n\n<p>Chaining these is a little more complex and would require either multiple passes or multiple texture inputs to a shader.</p>\n" }, { "answer_id": 68562, "author": "Neal", "author_id": 7071, "author_profile": "https://Stackoverflow.com/users/7071", "pm_score": 0, "selected": false, "text": "<p>When I implement the render states for \"A\" (that is paint the source pixel color/alpha and ignore the destination pixel color/alpha), Direct3D doesn't seem to perform the operation correctly if the source has an alpha value of zero. Instead of filling the target area with transparency, I'm seeing the target area remain unchanged. However, if I change the source alpha value to 1, the target area becomes \"virtually\" transparent. This happens even when I disable the alphablending render state, so I would presume this is an attempt at optimization that's actually a bug in Direct3D.</p>\n\n<p>Except for this situation, it would appear that Corey's render states are correct. Thanks, Corey!</p>\n" }, { "answer_id": 69665, "author": "Corey Ross", "author_id": 5927, "author_profile": "https://Stackoverflow.com/users/5927", "pm_score": 0, "selected": false, "text": "<p>One thing to check, make sure alpha test is off with</p>\n\n<pre><code>AlphaTestEnable = false\n</code></pre>\n\n<p>If that is on (along with something like AlphaFunction = Greater and ReferenceAlpha = 0), clear pixels could be thrown away regardless of the AlphaBlendEnable setting.</p>\n" }, { "answer_id": 8620911, "author": "benbuck", "author_id": 716058, "author_profile": "https://Stackoverflow.com/users/716058", "pm_score": 1, "selected": false, "text": "<p>For the \"A in B\" case, shouldn't DestinationBlend be Zero?</p>\n\n<p>A in B</p>\n\n<pre><code>SourceBlend = DestinationAlpha\nDestinationBlend = Zero\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7071/" ]
What Direct3D render states should be used to implement Java's Porter-Duff compositing rules (CLEAR, SRC, SRCOVER, etc.)?
I'm haven't used Java too much, but based on the [white paper from 1984](http://keithp.com/~keithp/porterduff/p253-porter.pdf), it should be a fairly straightforward mapping of render state blend modes. There are of course more that you can do than just these, like normal alpha blending (SourceAlpha, InvSourceAlpha) or additive (One, One) to name a few. *(I assume that you are asking about these specifically because you are porting some existing functionality? In that cause you may not care about other combinations...)* Anyway, these assume a BlendOperation of Add and that AlphaBlendEnable is true. Clear ``` SourceBlend = Zero DestinationBlend = Zero ``` A ``` SourceBlend = One DestinationBlend = Zero ``` B ``` SourceBlend = Zero DestinationBlend = One ``` A over B ``` SourceBlend = One DestinationBlend = InvSourceAlpha ``` B over A ``` SourceBlend = InvDestinationAlpha DestinationBlend = One ``` A in B ``` SourceBlend = DestinationAlpha DestinationBlend = One ``` B in A ``` SourceBlend = Zero DestinationBlend = SourceAlpha ``` A out B ``` SourceBlend = InvDestinationAlpha DestinationBlend = Zero ``` B out A ``` SourceBlend = Zero DestinationBlend = InvSourceAlpha ``` A atop B ``` SourceBlend = DestinationAlpha DestinationBlend = InvSourceAlpha ``` B atop A ``` SourceBlend = InvDestinationAlpha DestinationBlend = SourceAlpha ``` A xor B ``` SourceBlend = InvDestinationAlpha DestinationBlend = InvSourceAlpha ``` Chaining these is a little more complex and would require either multiple passes or multiple texture inputs to a shader.
62,689
<p>I'm trying to implement a data compression idea I've had, and since I'm imagining running it against a large corpus of test data, I had thought to code it in C (I mostly have experience in scripting languages like Ruby and Tcl.) </p> <p>Looking through the O'Reilly 'cow' books on C, I realize that I can't simply index the bits of a simple 'char' or 'int' type variable as I'd like to to do bitwise comparisons and operators. </p> <p>Am I correct in this perception? Is it reasonable for me to use an enumerated type for representing a bit (and make an array of these, and writing functions to convert to and from char)? If so, is such a type and functions defined in a standard library already somewhere? Are there other (better?) approaches? Is there some example code somewhere that someone could point me to?</p> <p>Thanks - </p>
[ { "answer_id": 62723, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 3, "selected": false, "text": "<p>It is possible.</p>\n\n<p>To set the nth bit, use OR:</p>\n\n<pre><code>x |= (1 &lt;&lt; 5); // sets the 5th-from right\n</code></pre>\n\n<p>To clear a bit, use AND:</p>\n\n<pre><code>x &amp;= ~(1 &lt;&lt; 5); // clears 5th-from-right\n</code></pre>\n\n<p>To flip a bit, use XOR:</p>\n\n<pre><code>x ^= (1 &lt;&lt; 5); // flips 5th-from-right\n</code></pre>\n\n<p>To get the value of a bit use shift and AND:</p>\n\n<pre><code>(x &amp; (1 &lt;&lt; 5)) &gt;&gt; 5 // gets the value (0 or 1) of the 5th-from-right\n</code></pre>\n\n<p>note: the shift right 5 is to ensure the value is either 0 or 1. If you're just interested in 0/not 0, you can get by without the shift.</p>\n" }, { "answer_id": 62757, "author": "TK.", "author_id": 1816, "author_profile": "https://Stackoverflow.com/users/1816", "pm_score": 0, "selected": false, "text": "<p>IF you want to index a bit you could:</p>\n\n<pre><code>bit = (char &amp; 0xF0) &gt;&gt; 7;\n</code></pre>\n\n<p>gets the msb of a char. You could even leave out the right shift and do a test on 0.</p>\n\n<pre><code>bit = char &amp; 0xF0;\n</code></pre>\n\n<p>if the bit is set the result will be > 0;</p>\n\n<p>obviousuly, you need to change the mask to get different bits (NB: the 0xF is the bit mask if it is unclear). It is possible to define numerous masks e.g.</p>\n\n<pre><code>#define BIT_0 0x1 // or 1 &lt;&lt; 0\n#define BIT_1 0x2 // or 1 &lt;&lt; 1\n#define BIT_2 0x4 // or 1 &lt;&lt; 2\n#define BIT_3 0x8 // or 1 &lt;&lt; 3\n</code></pre>\n\n<p>etc...</p>\n\n<p>This gives you:</p>\n\n<pre><code>bit = char &amp; BIT_1;\n</code></pre>\n\n<p>You can use these definitions in the above code to sucessfully index a bit within either a macro or a function.</p>\n\n<p>To set a bit:</p>\n\n<pre><code>char |= BIT_2;\n</code></pre>\n\n<p>To clear a bit:</p>\n\n<pre><code>char &amp;= ~BIT_3\n</code></pre>\n\n<p>To toggle a bit</p>\n\n<pre><code>char ^= BIT_4\n</code></pre>\n\n<p>This help?</p>\n" }, { "answer_id": 62782, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 2, "selected": false, "text": "<p>Have a look at the answers to <a href=\"https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c\">this question</a>.</p>\n" }, { "answer_id": 62783, "author": "Mladen Janković", "author_id": 6300, "author_profile": "https://Stackoverflow.com/users/6300", "pm_score": 1, "selected": false, "text": "<p>To query state of bit with specific index:</p>\n\n<pre><code>int index_state = variable &amp; ( 1 &lt;&lt; bit_index );\n</code></pre>\n\n<p>To set bit:</p>\n\n<pre><code>varabile |= 1 &lt;&lt; bit_index;\n</code></pre>\n\n<p>To restart bit:</p>\n\n<pre><code>variable &amp;= ~( 1 &lt;&lt; bit_index );\n</code></pre>\n" }, { "answer_id": 62842, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 0, "selected": false, "text": "<p>There is a standard library container for bits: std::vector. It is specialised in the library to be space efficient. There is also a boost dynamic_bitset class.</p>\n\n<p>These will let you perform operations on a set of boolean values, using one bit per value of underlying storage.</p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_36_0/libs/dynamic_bitset/dynamic_bitset.html\" rel=\"nofollow noreferrer\">Boost dynamic bitset documentation</a></p>\n\n<p>For the STL documentation, see your compiler documentation.</p>\n\n<p>Of course, you can also address the individual bits in other integral types by hand. If you do that, you should use unsigned types so that you don't get undefined behaviour if decide to do a right shift on a value with the high bit set. However, it sounds like you want the containers.</p>\n\n<p>To the commenter who claimed this takes 32x more space than necessary: boost::dynamic_bitset and vector are specialised to use one bit per entry, and so there is not a space penalty, assuming that you actually want more than the number of bits in a primitive type. These classes allow you to address individual bits in a large container with efficient underlying storage. If you just want (say) 32 bits, by all means, use an int. If you want some large number of bits, you can use a library container.</p>\n" }, { "answer_id": 62863, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Try using bitfields. Be careful the implementation can vary by compiler.</p>\n\n<p><a href=\"http://publications.gbdirect.co.uk/c_book/chapter6/bitfields.html\" rel=\"nofollow noreferrer\">http://publications.gbdirect.co.uk/c_book/chapter6/bitfields.html</a></p>\n" }, { "answer_id": 63037, "author": "Microserf", "author_id": 7474, "author_profile": "https://Stackoverflow.com/users/7474", "pm_score": 2, "selected": false, "text": "<p><strong>Theory</strong></p>\n\n<p>There is no C syntax for accessing or setting the n-th bit of a built-in datatype (e.g. a 'char'). However, you can access bits using a logical AND operation, and set bits using a logical OR operation.</p>\n\n<p>As an example, say that you have a variable that holds 1101 and you want to check the 2nd bit from the left. Simply perform a logical AND with 0100:</p>\n\n<pre><code>1101\n0100\n---- AND\n0100\n</code></pre>\n\n<p>If the result is non-zero, then the 2nd bit must have been set; otherwise is was not set.</p>\n\n<p>If you want to set the 3rd bit from the left, then perform a logical OR with 0010:</p>\n\n<pre><code>1101\n0010\n---- OR\n1111\n</code></pre>\n\n<p>You can use the C operators &amp;&amp; (for AND) and || (for OR) to perform these tasks. You will need to construct the bit access patterns (the 0100 and 0010 in the above examples) yourself. The trick is to remember that the least significant bit (LSB) counts 1s, the next LSB counts 2s, then 4s etc. So, the bit access pattern for the n-th LSB (starting at 0) is simply the value of 2^n. The easiest way to compute this in C is to shift the binary value 0001 (in this four bit example) to the left by the required number of places. As this value is always equal to 1 in unsigned integer-like quantities, this is just '1 &lt;&lt; n'</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>unsigned char myVal = 0x65; /* in hex; this is 01100101 in binary. */\n\n/* Q: is the 3-rd least significant bit set (again, the LSB is the 0th bit)? */\nunsigned char pattern = 1;\npattern &lt;&lt;= 3; /* Shift pattern left by three places.*/\n\nif(myVal &amp;&amp; (char)(1&lt;&lt;3)) {printf(\"Yes!\\n\");} /* Perform the test. */\n\n/* Set the most significant bit. */\nmyVal |= (char)(1&lt;&lt;7);\n</code></pre>\n\n<p>This example hasn't been tested, but should serve to illustrate the general idea.</p>\n" }, { "answer_id": 63041, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 4, "selected": true, "text": "<p>Following on from what Kyle has said, you can use a macro to do the hard work for you.</p>\n\n<blockquote>\n <p>It is possible.</p>\n \n <p>To set the nth bit, use OR:</p>\n \n <p>x |= (1 &lt;&lt; 5); // sets the 6th-from\n right</p>\n \n <p>To clear a bit, use AND:</p>\n \n <p>x &amp;= ~(1 &lt;&lt; 5); // clears\n 6th-from-right</p>\n \n <p>To flip a bit, use XOR:</p>\n \n <p>x ^= (1 &lt;&lt; 5); // flips 6th-from-right</p>\n</blockquote>\n\n<p><strong>Or...</strong></p>\n\n<pre><code>#define GetBit(var, bit) ((var &amp; (1 &lt;&lt; bit)) != 0) // Returns true / false if bit is set\n#define SetBit(var, bit) (var |= (1 &lt;&lt; bit))\n#define FlipBit(var, bit) (var ^= (1 &lt;&lt; bit))\n</code></pre>\n\n<p>Then you can use it in code like:</p>\n\n<pre><code>int myVar = 0;\nSetBit(myVar, 5);\nif (GetBit(myVar, 5))\n{\n // Do something\n}\n</code></pre>\n" }, { "answer_id": 63087, "author": "Mark D", "author_id": 7452, "author_profile": "https://Stackoverflow.com/users/7452", "pm_score": 0, "selected": false, "text": "<p>Individual bits can be indexed as follows. </p>\n\n<p>Define a struct like this one:</p>\n\n<pre><code>struct\n{\n unsigned bit0 : 1;\n unsigned bit1 : 1;\n unsigned bit2 : 1;\n unsigned bit3 : 1;\n unsigned reserved : 28;\n} bitPattern; \n</code></pre>\n\n<p>Now if I want to know the individual bit values of a var named \"value\", do the following:</p>\n\n<pre><code>CopyMemory( &amp;input, &amp;value, sizeof(value) );\n</code></pre>\n\n<p>To see if bit 2 is high or low:</p>\n\n<pre><code>int state = bitPattern.bit2;\n</code></pre>\n\n<p>Hope this helps.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to implement a data compression idea I've had, and since I'm imagining running it against a large corpus of test data, I had thought to code it in C (I mostly have experience in scripting languages like Ruby and Tcl.) Looking through the O'Reilly 'cow' books on C, I realize that I can't simply index the bits of a simple 'char' or 'int' type variable as I'd like to to do bitwise comparisons and operators. Am I correct in this perception? Is it reasonable for me to use an enumerated type for representing a bit (and make an array of these, and writing functions to convert to and from char)? If so, is such a type and functions defined in a standard library already somewhere? Are there other (better?) approaches? Is there some example code somewhere that someone could point me to? Thanks -
Following on from what Kyle has said, you can use a macro to do the hard work for you. > > It is possible. > > > To set the nth bit, use OR: > > > x |= (1 << 5); // sets the 6th-from > right > > > To clear a bit, use AND: > > > x &= ~(1 << 5); // clears > 6th-from-right > > > To flip a bit, use XOR: > > > x ^= (1 << 5); // flips 6th-from-right > > > **Or...** ``` #define GetBit(var, bit) ((var & (1 << bit)) != 0) // Returns true / false if bit is set #define SetBit(var, bit) (var |= (1 << bit)) #define FlipBit(var, bit) (var ^= (1 << bit)) ``` Then you can use it in code like: ``` int myVar = 0; SetBit(myVar, 5); if (GetBit(myVar, 5)) { // Do something } ```
62,776
<p>How do I implement a Copy menu item in a Windows application written in C#/.NET 2.0?</p> <p>I want to let the user to mark some text in a control and then select the Copy menu item from an Edit menu in the menubar of the application and then do a Paste in for example Excel. </p> <p>What makes my head spin is how to first determine which child form is active and then how to find the control that contains the marked text that should be copied to the clipboard. </p> <p>Help, please.</p>
[ { "answer_id": 62833, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": -1, "selected": false, "text": "<p>It seems to me that you might be better off breaking this into smaller tasks/questions.\nYou have a few issues you are stuck on from the way it sounds.</p>\n\n<p>You have multiple 'child' windows open. Is this an MDI application?\nWhen an action is performed on one of those child windows, it should fire an event in that window's event handlers. That is your first thing to set up. If this is a datagridview I would suggest a simple test to start. Try trapping the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectionchanged.aspx\" rel=\"nofollow noreferrer\">DataGridView.SelectionChanged</a> event. Just throw in something like <code>MessageBox.Show(\"I copied your datas!\");</code> for now.</p>\n\n<p>This should get you started where you will at least understand how this event will be raised to you.</p>\n\n<p>From here, we will need to know a little more about your datagrid, and the rows and child controls in those rows. Then we can likely create events in the render events that will be raised at the appropriate times, with the appropriate scope.</p>\n" }, { "answer_id": 62907, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 0, "selected": false, "text": "<p>Why not extending the control, so the control itself provides the data which should be copied into the clipboard.</p>\n\n<p>Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.input.applicationcommands.aspx\" rel=\"nofollow noreferrer\">ApplicationCommands</a> documentation.</p>\n" }, { "answer_id": 63004, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>To determine which window is open, you can query the Form.ActiveMDIChild property to get a reference to the currently active window. From there, you can do one of two things:</p>\n\n<p>1) If you create your own custom Form class (FormFoo for example) that has a new public member function GetCopiedData(), then inherit all of your application's child forms from that class, you can just do something like this:</p>\n\n<pre><code>((FormFoo)this.ActiveMDIChild).GetCopiedData();\n</code></pre>\n\n<p>Assuming the GetCopiedData function will have the form-specific implementation to detect what text should be copied to the clipboard.</p>\n\n<p>or</p>\n\n<p>2) You can use inheritance to detect the type of form that is active, and then do something to get the copied data depending on the type of form:</p>\n\n<pre><code>Form f = this.ActiveMDIChild;\nif(f is FormGrid)\n{\n ((FormGrid)f).GetGridCopiedData();\n} else if(f is FormText) {\n ((FormText)f).GetTextCopiedData();\n}\n</code></pre>\n\n<p>etc.</p>\n\n<p>That should get you started with finding the active window and how to implement a copy function. If you need more help copying out of a GridView, it may be best to post another question.</p>\n" }, { "answer_id": 63470, "author": "Petteri", "author_id": 7174, "author_profile": "https://Stackoverflow.com/users/7174", "pm_score": 4, "selected": true, "text": "<p>With the aid of some heavy pair programming a colleague of mine and I came up with this, feel free to refactor.</p>\n\n<p>The code is placed in the main form. The copyToolStripMenuItem_Click method handles the Click event on the Copy menu item in the Edit menu.</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Recursively traverse a tree of controls to find the control that has focus, if any\n /// &lt;/summary&gt;\n /// &lt;param name=\"c\"&gt;The control to search, might be a control container&lt;/param&gt;\n /// &lt;returns&gt;The control that either has focus or contains the control that has focus&lt;/returns&gt;\n private Control FindFocus(Control c) \n {\n foreach (Control k in c.Controls)\n {\n if (k.Focused)\n {\n return k;\n }\n else if (k.ContainsFocus)\n {\n return FindFocus(k);\n }\n }\n\n return null;\n }\n\n private void copyToolStripMenuItem_Click(object sender, EventArgs e)\n {\n Form f = this.ActiveMdiChild;\n\n // Find the control that has focus\n Control focusedControl = FindFocus(f.ActiveControl);\n\n // See if focusedControl is of a type that can select text/data\n if (focusedControl is TextBox)\n {\n TextBox tb = focusedControl as TextBox;\n Clipboard.SetDataObject(tb.SelectedText);\n }\n else if (focusedControl is DataGridView)\n {\n DataGridView dgv = focusedControl as DataGridView;\n Clipboard.SetDataObject(dgv.GetClipboardContent());\n }\n else if (...more?...)\n {\n }\n }\n</code></pre>\n" }, { "answer_id": 1207426, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If the form is tabbed and the target control is a DataGridView, it's sometimes possible for the Form's TabControl to be returned as the active control, using the above method, when the DataGridView is right clicked upon.</p>\n\n<p>I got around this by implementing the following handler for my DataGridView:-</p>\n\n<p>private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)</p>\n\n<p>{</p>\n\n<pre><code> if (e.Button == MouseButtons.Right)\n {\n dataGridView.Focus();\n\n dataGridView.CurrentCell = dataGridView[e.ColumnIndex, e.RowIndex];\n }\n</code></pre>\n\n<p>}</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7174/" ]
How do I implement a Copy menu item in a Windows application written in C#/.NET 2.0? I want to let the user to mark some text in a control and then select the Copy menu item from an Edit menu in the menubar of the application and then do a Paste in for example Excel. What makes my head spin is how to first determine which child form is active and then how to find the control that contains the marked text that should be copied to the clipboard. Help, please.
With the aid of some heavy pair programming a colleague of mine and I came up with this, feel free to refactor. The code is placed in the main form. The copyToolStripMenuItem\_Click method handles the Click event on the Copy menu item in the Edit menu. ``` /// <summary> /// Recursively traverse a tree of controls to find the control that has focus, if any /// </summary> /// <param name="c">The control to search, might be a control container</param> /// <returns>The control that either has focus or contains the control that has focus</returns> private Control FindFocus(Control c) { foreach (Control k in c.Controls) { if (k.Focused) { return k; } else if (k.ContainsFocus) { return FindFocus(k); } } return null; } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { Form f = this.ActiveMdiChild; // Find the control that has focus Control focusedControl = FindFocus(f.ActiveControl); // See if focusedControl is of a type that can select text/data if (focusedControl is TextBox) { TextBox tb = focusedControl as TextBox; Clipboard.SetDataObject(tb.SelectedText); } else if (focusedControl is DataGridView) { DataGridView dgv = focusedControl as DataGridView; Clipboard.SetDataObject(dgv.GetClipboardContent()); } else if (...more?...) { } } ```
62,804
<p>Is there a standard library method that converts a string that has duration in the standard ISO 8601 Duration (also used in XSD for its <code>duration</code> type) format into the .NET TimeSpan object?</p> <p>For example, P0DT1H0M0S which represents a duration of one hour, is converted into New TimeSpan(0,1,0,0,0).</p> <p>A Reverse converter does exist which works as follows: Xml.XmlConvert.ToString(New TimeSpan(0,1,0,0,0)) The above expression will return P0DT1H0M0S.</p>
[ { "answer_id": 63219, "author": "user7658", "author_id": 7658, "author_profile": "https://Stackoverflow.com/users/7658", "pm_score": 6, "selected": true, "text": "<p>This will convert from xs:duration to TimeSpan:</p>\n\n<pre><code>System.Xml.XmlConvert.ToTimeSpan(\"P0DT1H0M0S\")\n</code></pre>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.totimespan.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.totimespan.aspx</a></p>\n" }, { "answer_id": 5760821, "author": "Paul Williams", "author_id": 420400, "author_profile": "https://Stackoverflow.com/users/420400", "pm_score": 4, "selected": false, "text": "<p>One minor word of caution - XmlConvert.ToTimeSpan() is a little funny when working with months and years. The TimeSpan class does not have month or year members, probably because their length varies. However, ToTimeSpan() will happily accept a duration string with month or year values in it and <strong><em>guess</em></strong> at a duration, instead of throwing an exception. Observe:</p>\n\n<pre><code>PS C:\\Users\\troll&gt; [Reflection.Assembly]::LoadWithPartialName(\"System.Xml\")\n\nGAC Version Location\n--- ------- --------\nTrue v2.0.50727 C:\\Windows\\assembly\\GAC_MSIL\\System.Xml\\2.0.0.0__b77a5c561934e089\\System.Xml.dll\n\n\nPS C:\\Users\\troll&gt; [System.Xml.XmlConvert]::ToTimeSpan(\"P1M\")\n\n\nDays : 30\nHours : 0\nMinutes : 0\nSeconds : 0\nMilliseconds : 0\nTicks : 25920000000000\nTotalDays : 30\nTotalHours : 720\nTotalMinutes : 43200\nTotalSeconds : 2592000\nTotalMilliseconds : 2592000000\n\n\n\nPS C:\\Users\\troll&gt; [System.Xml.XmlConvert]::ToTimeSpan(\"P1Y\")\n\n\nDays : 365\nHours : 0\nMinutes : 0\nSeconds : 0\nMilliseconds : 0\nTicks : 315360000000000\nTotalDays : 365\nTotalHours : 8760\nTotalMinutes : 525600\nTotalSeconds : 31536000\nTotalMilliseconds : 31536000000\n\n\n\nPS C:\\Users\\troll&gt;\n</code></pre>\n" }, { "answer_id": 11923534, "author": "revington", "author_id": 344911, "author_profile": "https://Stackoverflow.com/users/344911", "pm_score": 0, "selected": false, "text": "<p>As @ima dirty troll said TimeSpan translates always years as 365 days and months as 30 days.</p>\n\n<pre><code>TimeSpan ts = System.Xml.XmlConvert.ToTimeSpan(\"P5Y\");\nDateTime now = new DateTime(2008,2,29);\nConsole.WriteLine(now + ts); // 27/02/2013 0:00:00\n</code></pre>\n\n<p>To address it you should add each field individually rather\nthan using TimeSpan.</p>\n\n<pre><code>DateTime now = new DateTime (2008, 2, 29);\nstring duration = \"P1Y\";\nRegex expr = \n new Regex (@\"(-?)P((\\d{1,4})Y)?((\\d{1,4})M)?((\\d{1,4})D)?(T((\\d{1,4})H)?((\\d{1,4})M)?((\\d{1,4}(\\.\\d{1,3})?)S)?)?\", RegexOptions.Compiled | RegexOptions.CultureInvariant);\nbool positiveDuration = false == (input [0] == '-');\n\nMatchCollection matches = expr.Matches (duration);\nvar g = matches [0];\nFunc&lt;int,int&gt; getNumber = x =&gt; {\n if (g.Groups.Count &lt; x || string.IsNullOrEmpty (g.Groups [x].ToString ())) {\n return 0;\n }\n\n int a = int.Parse (g.Groups [x].ToString ());\n\n return PositiveDuration ? a : a * -1;\n\n};\nnow.AddYears (getNumber (3));\nnow.AddMonths (getNumber (5));\nnow.AddDays (getNumber (7));\nnow.AddHours (getNumber (10));\nnow.AddMinutes (getNumber (12));\nnow.AddSeconds (getNumber (14));\nConsole.WriteLine (now); // 28/02/2012 0:00:00\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7105/" ]
Is there a standard library method that converts a string that has duration in the standard ISO 8601 Duration (also used in XSD for its `duration` type) format into the .NET TimeSpan object? For example, P0DT1H0M0S which represents a duration of one hour, is converted into New TimeSpan(0,1,0,0,0). A Reverse converter does exist which works as follows: Xml.XmlConvert.ToString(New TimeSpan(0,1,0,0,0)) The above expression will return P0DT1H0M0S.
This will convert from xs:duration to TimeSpan: ``` System.Xml.XmlConvert.ToTimeSpan("P0DT1H0M0S") ``` See <http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.totimespan.aspx>
62,810
<p>I use RCF with boost.serialization (why use RCF's copy when we already use the original?) It works OK, but when an exception is thrown in the server, it's not passed correctly to the client. Instead, I get an RCF::SerializationException quoting an <code>archive_exception</code> saying "class name too long". When I change the protocol to BsText, the exceptions is "unregistered class". When I change the protocol to SfBinary, it works. I've registered RemoteException on both server and client like this:</p> <pre><code>BOOST_CLASS_VERSION(RCF::RemoteException, 0) BOOST_CLASS_EXPORT(RCF::RemoteException) </code></pre> <p>I even tried serializing and deserializing a <code>boost::shared_ptr&lt;RCF::RemoteException&gt;</code> in the same test, and it works.</p> <p>So how can I make RCF pass exceptions correctly without resorting to SF?</p>
[ { "answer_id": 85626, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 0, "selected": false, "text": "<p>According to Jarl it works, check <a href=\"http://www.codeproject.com/KB/threads/Rcf_Ipc_For_Cpp.aspx?fid=248794&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;fr=101&amp;select=2365783\" rel=\"nofollow noreferrer\">codeproject</a> for a question and answer with sample code:</p>\n" }, { "answer_id": 132553, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 3, "selected": true, "text": "<p>Here's a patch given by Jarl at <a href=\"http://www.codeproject.com/KB/threads/Rcf_Ipc_For_Cpp.aspx?msg=2739150#xx2730536xx\" rel=\"nofollow noreferrer\">CodeProject</a>:</p>\n\n<p>In RcfServer.cpp, before the line where RcfServer::handleSession() is defined (around line 792), insert the following code:</p>\n\n<pre><code>void serialize(SerializationProtocolOut &amp; out, const RemoteException &amp; e)\n{\n serialize(out, std::auto_ptr&lt;RemoteException&gt;(new RemoteException(e)));\n}\n</code></pre>\n\n<p>And in Marshal.cpp, around line 37, replace this line:</p>\n\n<pre><code>ar &amp; boost::serialization::make_nvp(\"Dummy\", apt.get());\n</code></pre>\n\n<p>, with</p>\n\n<pre><code>T *pt = apt.get();\nar &amp; boost::serialization::make_nvp(\"Dummy\", pt);\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7224/" ]
I use RCF with boost.serialization (why use RCF's copy when we already use the original?) It works OK, but when an exception is thrown in the server, it's not passed correctly to the client. Instead, I get an RCF::SerializationException quoting an `archive_exception` saying "class name too long". When I change the protocol to BsText, the exceptions is "unregistered class". When I change the protocol to SfBinary, it works. I've registered RemoteException on both server and client like this: ``` BOOST_CLASS_VERSION(RCF::RemoteException, 0) BOOST_CLASS_EXPORT(RCF::RemoteException) ``` I even tried serializing and deserializing a `boost::shared_ptr<RCF::RemoteException>` in the same test, and it works. So how can I make RCF pass exceptions correctly without resorting to SF?
Here's a patch given by Jarl at [CodeProject](http://www.codeproject.com/KB/threads/Rcf_Ipc_For_Cpp.aspx?msg=2739150#xx2730536xx): In RcfServer.cpp, before the line where RcfServer::handleSession() is defined (around line 792), insert the following code: ``` void serialize(SerializationProtocolOut & out, const RemoteException & e) { serialize(out, std::auto_ptr<RemoteException>(new RemoteException(e))); } ``` And in Marshal.cpp, around line 37, replace this line: ``` ar & boost::serialization::make_nvp("Dummy", apt.get()); ``` , with ``` T *pt = apt.get(); ar & boost::serialization::make_nvp("Dummy", pt); ```
62,814
<p>Is there any difference between a binary semaphore and mutex or are they essentially the same?</p>
[ { "answer_id": 62883, "author": "Mladen Janković", "author_id": 6300, "author_profile": "https://Stackoverflow.com/users/6300", "pm_score": 9, "selected": false, "text": "<ul>\n<li>A <strong>mutex</strong> can be released only by <strong>the thread that had acquired it</strong>. <br></li>\n<li>A <strong>binary semaphore</strong> can be signaled <strong>by any thread</strong> (or process).</li>\n</ul>\n\n<p>so semaphores are more suitable for some synchronization problems like producer-consumer.</p>\n\n<p>On Windows, binary semaphores are more like event objects than mutexes.</p>\n" }, { "answer_id": 63084, "author": "Casey Barker", "author_id": 7046, "author_profile": "https://Stackoverflow.com/users/7046", "pm_score": 1, "selected": false, "text": "<p>The answer may depend on the target OS. For example, at least one RTOS implementation I'm familiar with will allow multiple sequential \"get\" operations against a single OS mutex, so long as they're all from within the same thread context. The multiple gets must be replaced by an equal number of puts before another thread will be allowed to get the mutex. <em>This differs from binary semaphores, for which only a single get is allowed at a time, regardless of thread contexts.</em></p>\n\n<p>The idea behind this type of mutex is that you protect an object by only allowing a single context to modify the data at a time. Even if the thread gets the mutex and then calls a function that further modifies the object (and gets/puts the protector mutex around its own operations), the operations should still be safe because they're all happening under a single thread.</p>\n\n<pre><code>{\n mutexGet(); // Other threads can no longer get the mutex.\n\n // Make changes to the protected object.\n // ...\n\n objectModify(); // Also gets/puts the mutex. Only allowed from this thread context.\n\n // Make more changes to the protected object.\n // ...\n\n mutexPut(); // Finally allows other threads to get the mutex.\n}\n</code></pre>\n\n<p>Of course, when using this feature, you must be certain that all accesses within a single thread really are safe!</p>\n\n<p>I'm not sure how common this approach is, or whether it applies outside of the systems with which I'm familiar. For an example of this kind of mutex, see the ThreadX RTOS.</p>\n" }, { "answer_id": 86021, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 10, "selected": false, "text": "<p>They are <strong>NOT</strong> the same thing. They are used for different purposes!<br>\nWhile both types of semaphores have a full/empty state and use the same API, their usage is very different. </p>\n\n<p><strong>Mutual Exclusion Semaphores</strong><br>\nMutual Exclusion semaphores are used to protect shared resources (data structure, file, etc..). </p>\n\n<p>A Mutex semaphore is \"owned\" by the task that takes it. If Task B attempts to semGive a mutex currently held by Task A, Task B's call will return an error and fail.</p>\n\n<p>Mutexes always use the following sequence: </p>\n\n<pre>\n - SemTake\n - Critical Section\n - SemGive</pre>\n\n<p>Here is a simple example:</p>\n\n<pre>\n Thread A Thread B\n Take Mutex\n access data\n ... Take Mutex &lt;== Will block\n ...\n Give Mutex access data &lt;== Unblocks\n ...\n Give Mutex\n</pre>\n\n<p><strong>Binary Semaphore</strong><br>\nBinary Semaphore address a totally different question: </p>\n\n<ul>\n<li>Task B is pended waiting for something to happen (a sensor being tripped for example).</li>\n<li>Sensor Trips and an Interrupt Service Routine runs. It needs to notify a task of the trip.</li>\n<li>Task B should run and take appropriate actions for the sensor trip. Then go back to waiting.</li>\n</ul>\n\n<pre><code>\n Task A Task B\n ... Take BinSemaphore &lt;== wait for something\n Do Something Noteworthy\n Give BinSemaphore do something &lt;== unblocks\n</code></pre>\n\n<p>Note that with a binary semaphore, it is OK for B to take the semaphore and A to give it.<br>\nAgain, a binary semaphore is NOT protecting a resource from access. The act of Giving and Taking a semaphore are fundamentally decoupled.<br>\nIt typically makes little sense for the same task to so a give and a take on the same binary semaphore.</p>\n" }, { "answer_id": 128892, "author": "ppi", "author_id": 2044155, "author_profile": "https://Stackoverflow.com/users/2044155", "pm_score": 6, "selected": false, "text": "<p>Their synchronization semantics are very different:</p>\n\n<ul>\n<li>mutexes allow serialization of access to a given resource i.e. multiple threads wait for a lock, one at a time and as previously said, the thread <em>owns</em> the lock until it is done: <strong>only</strong> this particular thread can unlock it.</li>\n<li>a binary semaphore is a counter with value 0 and 1: a task blocking on it until <strong>any</strong> task does a sem_post. The semaphore advertises that a resource is available, and it provides the mechanism to wait until it is signaled as being available.</li>\n</ul>\n\n<p>As such one can see a mutex as a token passed from task to tasks and a semaphore as traffic red-light (it <strong>signals</strong> someone that it can proceed).</p>\n" }, { "answer_id": 204524, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>On Windows, there are two differences between mutexes and binary semaphores:</p>\n\n<ol>\n<li><p>A mutex can only be released by the thread which has ownership, i.e. the thread which previously called the Wait function, (or which took ownership when creating it). A semaphore can be released by any thread.</p></li>\n<li><p>A thread can call a wait function repeatedly on a mutex without blocking. However, if you call a wait function twice on a binary semaphore without releasing the semaphore in between, the thread will block.</p></li>\n</ol>\n" }, { "answer_id": 311612, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Mutex work on blocking critical region, But Semaphore work on count.</p>\n" }, { "answer_id": 311648, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 5, "selected": false, "text": "<p>At a theoretical level, they are no different semantically. You can implement a mutex using semaphores or vice versa (see <a href=\"http://www.picturel.com/ucr/node32.html\" rel=\"noreferrer\">here</a> for an example). In practice, the implementations are different and they offer slightly different services.</p>\n<p>The practical difference (in terms of the system services surrounding them) is that the implementation of a mutex is aimed at being a more lightweight synchronisation mechanism. In oracle-speak, mutexes are known as <a href=\"http://dbataj.blogspot.com/2007/10/oracle-latch.html\" rel=\"noreferrer\">latches</a> and semaphores are known as <a href=\"http://www.dba-oracle.com/art_dbazine_waits.htm\" rel=\"noreferrer\">waits</a>.</p>\n<p>At the lowest level, they use some sort of atomic <a href=\"http://en.wikipedia.org/wiki/Test-and-set\" rel=\"noreferrer\">test and set</a> mechanism. This reads the current value of a memory location, computes some sort of conditional and writes out a value at that location in a single instruction that <a href=\"http://en.wikipedia.org/wiki/Atomic_operation\" rel=\"noreferrer\">cannot be interrupted</a>. This means that you can acquire a mutex and test to see if anyone else had it before you.</p>\n<p>A typical mutex implementation has a process or thread executing the test-and-set instruction and evaluating whether anything else had set the mutex. A key point here is that there is no interaction with the <a href=\"http://en.wikipedia.org/wiki/Scheduling_(computing)\" rel=\"noreferrer\">scheduler</a>, so we have no idea (and don't care) who has set the lock. Then we either give up our time slice and attempt it again when the task is re-scheduled or execute a <a href=\"http://en.wikipedia.org/wiki/Spinlock\" rel=\"noreferrer\">spin-lock</a>. A spin lock is an algorithm like:</p>\n<pre><code>Count down from 5000:\n i. Execute the test-and-set instruction\n ii. If the mutex is clear, we have acquired it in the previous instruction \n so we can exit the loop\n iii. When we get to zero, give up our time slice.\n</code></pre>\n<p>When we have finished executing our protected code (known as a <a href=\"http://en.wikipedia.org/wiki/Critical_section\" rel=\"noreferrer\">critical section</a>) we just set the mutex value to zero or whatever means 'clear.' If multiple tasks are attempting to acquire the mutex then the next task that happens to be scheduled after the mutex is released will get access to the resource. Typically you would use mutexes to control a synchronised resource where exclusive access is only needed for very short periods of time, normally to make an update to a shared data structure.</p>\n<p>A semaphore is a synchronised data structure (typically using a mutex) that has a count and some system call wrappers that interact with the scheduler in a bit more depth than the mutex libraries would. Semaphores are incremented and decremented and used to <a href=\"http://en.wikipedia.org/wiki/Blocking_(scheduling)\" rel=\"noreferrer\">block</a> tasks until something else is ready. See <a href=\"http://en.wikipedia.org/wiki/Producer-consumer_problem\" rel=\"noreferrer\">Producer/Consumer Problem</a> for a simple example of this. Semaphores are initialised to some value - a binary semaphore is just a special case where the semaphore is initialised to 1. Posting to a semaphore has the effect of waking up a waiting process.</p>\n<p>A basic semaphore algorithm looks like:</p>\n<pre><code>(somewhere in the program startup)\nInitialise the semaphore to its start-up value.\n\nAcquiring a semaphore\n i. (synchronised) Attempt to decrement the semaphore value\n ii. If the value would be less than zero, put the task on the tail of the list of tasks waiting on the semaphore and give up the time slice.\n\nPosting a semaphore\n i. (synchronised) Increment the semaphore value\n ii. If the value is greater or equal to the amount requested in the post at the front of the queue, take that task off the queue and make it runnable. \n iii. Repeat (ii) for all tasks until the posted value is exhausted or there are no more tasks waiting.\n</code></pre>\n<p>In the case of a binary semaphore the main practical difference between the two is the nature of the system services surrounding the actual data structure.</p>\n<p>EDIT: As evan has rightly pointed out, spinlocks will slow down a single processor machine. You would only use a spinlock on a multi-processor box because on a single processor the process holding the mutex will never reset it while another task is running. Spinlocks are only useful on multi-processor architectures.</p>\n" }, { "answer_id": 346678, "author": "dlinsin", "author_id": 198, "author_profile": "https://Stackoverflow.com/users/198", "pm_score": 9, "selected": false, "text": "<p><a href=\"http://koti.mbnet.fi/niclasw/MutexSemaphore.html\" rel=\"noreferrer\">The Toilet example</a> is an enjoyable analogy:</p>\n\n<blockquote>\n <p>Mutex:</p>\n \n <p>Is a key to a toilet. One person can\n have the key - occupy the toilet - at\n the time. When finished, the person\n gives (frees) the key to the next\n person in the queue.</p>\n \n <p>Officially: \"Mutexes are typically\n used to serialise access to a section\n of re-entrant code that cannot be\n executed concurrently by more than one\n thread. A mutex object only allows one\n thread into a controlled section,\n forcing other threads which attempt to\n gain access to that section to wait\n until the first thread has exited from\n that section.\" Ref: Symbian Developer\n Library</p>\n \n <p>(A mutex is really a semaphore with\n value 1.)</p>\n \n <p>Semaphore:</p>\n \n <p>Is the number of free identical toilet\n keys. Example, say we have four\n toilets with identical locks and keys.\n The semaphore count - the count of\n keys - is set to 4 at beginning (all\n four toilets are free), then the count\n value is decremented as people are\n coming in. If all toilets are full,\n ie. there are no free keys left, the\n semaphore count is 0. Now, when eq.\n one person leaves the toilet,\n semaphore is increased to 1 (one free\n key), and given to the next person in\n the queue.</p>\n \n <p>Officially: \"A semaphore restricts the\n number of simultaneous users of a\n shared resource up to a maximum\n number. Threads can request access to\n the resource (decrementing the\n semaphore), and can signal that they\n have finished using the resource\n (incrementing the semaphore).\" Ref:\n Symbian Developer Library</p>\n</blockquote>\n" }, { "answer_id": 1541938, "author": "teki", "author_id": 103267, "author_profile": "https://Stackoverflow.com/users/103267", "pm_score": 7, "selected": false, "text": "<p>Nice articles on the topic:</p>\n\n<ul>\n<li><a href=\"https://blog.feabhas.com/2009/09/mutex-vs-semaphores-%E2%80%93-part-1-semaphores/\" rel=\"noreferrer\">MUTEX VS. SEMAPHORES – PART 1: SEMAPHORES</a></li>\n<li><a href=\"https://blog.feabhas.com/2009/09/mutex-vs-semaphores-%E2%80%93-part-2-the-mutex/\" rel=\"noreferrer\">MUTEX VS. SEMAPHORES – PART 2: THE MUTEX</a></li>\n<li><a href=\"https://blog.feabhas.com/2009/10/mutex-vs-semaphores-%E2%80%93-part-3-final-part-mutual-exclusion-problems/\" rel=\"noreferrer\">MUTEX VS. SEMAPHORES – PART 3 (FINAL PART): MUTUAL EXCLUSION PROBLEMS</a></li>\n</ul>\n\n<p><strong>From part 2:</strong></p>\n\n<blockquote>\n <p>The mutex is similar to the principles\n of the binary semaphore with one\n significant difference: the principle\n of ownership. Ownership is the simple\n concept that when a task locks\n (acquires) a mutex only it can unlock\n (release) it. If a task tries to\n unlock a mutex it hasn’t locked (thus\n doesn’t own) then an error condition\n is encountered and, most importantly,\n the mutex is not unlocked. If the\n mutual exclusion object doesn't have\n ownership then, irrelevant of what it\n is called, it is not a mutex.</p>\n</blockquote>\n" }, { "answer_id": 2757170, "author": "Mickey", "author_id": 331291, "author_profile": "https://Stackoverflow.com/users/331291", "pm_score": 3, "selected": false, "text": "<p>Modified question is - What's the difference between A mutex and a \"binary\" semaphore in \"Linux\"?</p>\n\n<p>Ans: Following are the differences –\ni) Scope – The scope of mutex is within a process address space which has created it and is used for synchronization of threads. Whereas semaphore can be used across process space and hence it can be used for interprocess synchronization.</p>\n\n<p>ii) Mutex is lightweight and faster than semaphore. Futex is even faster.</p>\n\n<p>iii) Mutex can be acquired by same thread successfully multiple times with condition that it should release it same number of times. Other thread trying to acquire will block. Whereas in case of semaphore if same process tries to acquire it again it blocks as it can be acquired only once.</p>\n" }, { "answer_id": 3517129, "author": "jilles", "author_id": 298656, "author_profile": "https://Stackoverflow.com/users/298656", "pm_score": 2, "selected": false, "text": "<p>Apart from the fact that mutexes have an owner, the two objects may be optimized for different usage. Mutexes are designed to be held only for a short time; violating this can cause poor performance and unfair scheduling. For example, a running thread may be permitted to acquire a mutex, even though another thread is already blocked on it. Semaphores may provide more fairness, or fairness can be forced using several condition variables.</p>\n" }, { "answer_id": 5212270, "author": "Charan", "author_id": 477081, "author_profile": "https://Stackoverflow.com/users/477081", "pm_score": 3, "selected": false, "text": "<p>A <em>Mutex</em> controls access to a single shared resource. It provides operations to <em>acquire()</em> access to that resource and <em>release()</em> it when done.</p>\n\n<p>A <em>Semaphore</em> controls access to a shared pool of resources. It provides operations to <em>Wait()</em> until one of the resources in the pool becomes available, and <em>Signal()</em> when it is given back to the pool.</p>\n\n<p>When number of resources a Semaphore protects is greater than 1, it is called a <em>Counting Semaphore</em>. When it controls one resource, it is called a <em>Boolean Semaphore</em>. A boolean semaphore is equivalent to a mutex.</p>\n\n<p>Thus a Semaphore is a higher level abstraction than Mutex. A Mutex can be implemented using a Semaphore but not the other way around.</p>\n" }, { "answer_id": 9410398, "author": "ajay bidari", "author_id": 979786, "author_profile": "https://Stackoverflow.com/users/979786", "pm_score": 2, "selected": false, "text": "<p>In windows the difference is as below.\n<strong>MUTEX:</strong> process which successfully executes <strong>wait</strong> has to execute a <strong>signal</strong> and vice versa. <strong>BINARY SEMAPHORES:</strong> Different processes can execute <strong>wait</strong> or <strong>signal</strong> operation on a semaphore.</p>\n" }, { "answer_id": 9532228, "author": "laksbv", "author_id": 1228058, "author_profile": "https://Stackoverflow.com/users/1228058", "pm_score": 1, "selected": false, "text": "<p>Mutexes have ownership, unlike semaphores. Although any thread, within the scope of a mutex, can get an unlocked mutex and lock access to the same critical section of code,<em>only the thread that locked a mutex <strong>should</strong> unlock it</em>.</p>\n" }, { "answer_id": 13559646, "author": "user1852497", "author_id": 1852497, "author_profile": "https://Stackoverflow.com/users/1852497", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.geeksforgeeks.org/archives/9102\" rel=\"nofollow\">http://www.geeksforgeeks.org/archives/9102</a> discusses in details.</p>\n\n<p><code>Mutex</code> is locking mechanism used to synchronize access to a resource.\n<code>Semaphore</code> is signaling mechanism. </p>\n\n<p>Its up to to programmer if he/she wants to use binary semaphore in place of mutex.</p>\n" }, { "answer_id": 13824078, "author": "paxi", "author_id": 1895252, "author_profile": "https://Stackoverflow.com/users/1895252", "pm_score": 3, "selected": false, "text": "<p>You obviously use mutex to lock a data in one thread getting accessed by another thread at the same time. Assume that you have just called <code>lock()</code> and in the process of accessing data. This means that you don’t expect any other thread (or another instance of the same thread-code) to access the same data locked by the same mutex. That is, if it is the same thread-code getting executed on a different thread instance, hits the lock, then the <code>lock()</code> should block the control flow there. This applies to a thread that uses a different thread-code, which is also accessing the same data and which is also locked by the same mutex. In this case, you are still in the process of accessing the data and you may take, say, another 15 secs to reach the mutex unlock (so that the other thread that is getting blocked in mutex lock would unblock and would allow the control to access the data). Do you at any cost allow yet another thread to just unlock the same mutex, and in turn, allow the thread that is already waiting (blocking) in the mutex lock to unblock and access the data? Hope you got what I am saying here?\nAs per, agreed upon universal definition!, </p>\n\n<ul>\n<li>with “mutex” this can’t happen. No other thread can unlock the lock\nin your thread</li>\n<li>with “binary-semaphore” this can happen. Any other thread can unlock\nthe lock in your thread</li>\n</ul>\n\n<p>So, if you are very particular about using binary-semaphore instead of mutex, then you should be very careful in “scoping” the locks and unlocks. I mean that every control-flow that hits every lock should hit an unlock call, also there shouldn’t be any “first unlock”, rather it should be always “first lock”.</p>\n" }, { "answer_id": 15494351, "author": "mannnnerd", "author_id": 1926158, "author_profile": "https://Stackoverflow.com/users/1926158", "pm_score": 2, "selected": false, "text": "<p>Mutex is used to protect the sensitive code and data, semaphore is used to synchronization.You also can have practical use with protect the sensitive code, but there might be a risk that release the protection by the other thread by operation V.So The main difference between bi-semaphore and mutex is the ownership.For instance by toilet , Mutex is like that one can enter the toilet and lock the door, no one else can enter until the man get out, bi-semaphore is like that one can enter the toilet and lock the door, but someone else could enter by asking the administrator to open the door, it's ridiculous.</p>\n" }, { "answer_id": 16616869, "author": "Jamshad Ahmad", "author_id": 2395315, "author_profile": "https://Stackoverflow.com/users/2395315", "pm_score": 4, "selected": false, "text": "<p>Mutex are used for \" Locking Mechanisms \". one process at a time can use a shared resource</p>\n\n<p>whereas</p>\n\n<p>Semaphores are used for \" Signaling Mechanisms \" \nlike \"I am done , now can continue\"</p>\n" }, { "answer_id": 18200546, "author": "Raghav Navada", "author_id": 612581, "author_profile": "https://Stackoverflow.com/users/612581", "pm_score": 2, "selected": false, "text": "<p>The concept was clear to me after going over above posts. But there were some lingering questions. So, I wrote this small piece of code. </p>\n\n<p>When we try to give a semaphore without taking it, it goes through. But, when you try to give a mutex without taking it, it fails. I tested this on a Windows platform. Enable USE_MUTEX to run the same code using a MUTEX.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\n#define xUSE_MUTEX 1\n#define MAX_SEM_COUNT 1\n\nDWORD WINAPI Thread_no_1( LPVOID lpParam );\nDWORD WINAPI Thread_no_2( LPVOID lpParam );\n\nHANDLE Handle_Of_Thread_1 = 0;\nHANDLE Handle_Of_Thread_2 = 0;\nint Data_Of_Thread_1 = 1;\nint Data_Of_Thread_2 = 2;\nHANDLE ghMutex = NULL;\nHANDLE ghSemaphore = NULL;\n\n\nint main(void)\n{\n\n#ifdef USE_MUTEX\n ghMutex = CreateMutex( NULL, FALSE, NULL);\n if (ghMutex == NULL) \n {\n printf(\"CreateMutex error: %d\\n\", GetLastError());\n return 1;\n }\n#else\n // Create a semaphore with initial and max counts of MAX_SEM_COUNT\n ghSemaphore = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);\n if (ghSemaphore == NULL) \n {\n printf(\"CreateSemaphore error: %d\\n\", GetLastError());\n return 1;\n }\n#endif\n // Create thread 1.\n Handle_Of_Thread_1 = CreateThread( NULL, 0,Thread_no_1, &amp;Data_Of_Thread_1, 0, NULL); \n if ( Handle_Of_Thread_1 == NULL)\n {\n printf(\"Create first thread problem \\n\");\n return 1;\n }\n\n /* sleep for 5 seconds **/\n Sleep(5 * 1000);\n\n /*Create thread 2 */\n Handle_Of_Thread_2 = CreateThread( NULL, 0,Thread_no_2, &amp;Data_Of_Thread_2, 0, NULL); \n if ( Handle_Of_Thread_2 == NULL)\n {\n printf(\"Create second thread problem \\n\");\n return 1;\n }\n\n // Sleep for 20 seconds\n Sleep(20 * 1000);\n\n printf(\"Out of the program \\n\");\n return 0;\n}\n\n\nint my_critical_section_code(HANDLE thread_handle)\n{\n\n#ifdef USE_MUTEX\n if(thread_handle == Handle_Of_Thread_1)\n {\n /* get the lock */\n WaitForSingleObject(ghMutex, INFINITE);\n printf(\"Thread 1 holding the mutex \\n\");\n }\n#else\n /* get the semaphore */\n if(thread_handle == Handle_Of_Thread_1)\n {\n WaitForSingleObject(ghSemaphore, INFINITE);\n printf(\"Thread 1 holding semaphore \\n\");\n }\n#endif\n\n if(thread_handle == Handle_Of_Thread_1)\n {\n /* sleep for 10 seconds */\n Sleep(10 * 1000);\n#ifdef USE_MUTEX\n printf(\"Thread 1 about to release mutex \\n\");\n#else\n printf(\"Thread 1 about to release semaphore \\n\");\n#endif\n }\n else\n {\n /* sleep for 3 secconds */\n Sleep(3 * 1000);\n }\n\n#ifdef USE_MUTEX\n /* release the lock*/\n if(!ReleaseMutex(ghMutex))\n {\n printf(\"Release Mutex error in thread %d: error # %d\\n\", (thread_handle == Handle_Of_Thread_1 ? 1:2),GetLastError());\n }\n#else\n if (!ReleaseSemaphore(ghSemaphore,1,NULL) ) \n {\n printf(\"ReleaseSemaphore error in thread %d: error # %d\\n\",(thread_handle == Handle_Of_Thread_1 ? 1:2), GetLastError());\n }\n#endif\n\n return 0;\n}\n\nDWORD WINAPI Thread_no_1( LPVOID lpParam ) \n{ \n my_critical_section_code(Handle_Of_Thread_1);\n return 0;\n}\n\n\nDWORD WINAPI Thread_no_2( LPVOID lpParam ) \n{\n my_critical_section_code(Handle_Of_Thread_2);\n return 0;\n}\n</code></pre>\n\n<p>The very fact that semaphore lets you signal \"it is done using a resource\", even though it never owned the resource, makes me think there is a very loose coupling between owning and signaling in the case of semaphores. </p>\n" }, { "answer_id": 20113248, "author": "Hemant", "author_id": 1302408, "author_profile": "https://Stackoverflow.com/users/1302408", "pm_score": 7, "selected": false, "text": "<p>Since none of the above answer clears the confusion, here is one which cleared my confusion.</p>\n\n<blockquote>\n <p>Strictly speaking, <strong>a mutex is a locking mechanism</strong> used to\n synchronize access to a resource. Only one task (can be a thread or\n process based on OS abstraction) can acquire the mutex. It means there\n will be ownership associated with mutex, and only the owner can\n release the lock (mutex).</p>\n \n <p><strong>Semaphore is signaling mechanism</strong> (“I am done, you can carry on” kind of signal). For example, if you are listening songs (assume it as\n one task) on your mobile and at the same time your friend called you,\n an interrupt will be triggered upon which an interrupt service routine\n (ISR) will signal the call processing task to wakeup.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://www.geeksforgeeks.org/mutex-vs-semaphore/\" rel=\"noreferrer\">http://www.geeksforgeeks.org/mutex-vs-semaphore/</a></p>\n" }, { "answer_id": 23944923, "author": "Saurabh Sinha", "author_id": 3252237, "author_profile": "https://Stackoverflow.com/users/3252237", "pm_score": 4, "selected": false, "text": "<p>Myth:</p>\n\n<p>Couple of article says that \"binary semaphore and mutex are same\" or \"Semaphore with value 1 is mutex\" but the basic difference is Mutex can be released only by thread that had acquired it, while you can signal semaphore from any other thread</p>\n\n<p>Key Points:</p>\n\n<p>•A thread can acquire more than one lock (Mutex).</p>\n\n<p>•A mutex can be locked more than once only if its a recursive mutex, here lock and unlock for mutex should be same</p>\n\n<p>•If a thread which had already locked a mutex, tries to lock the mutex again, it will enter into the waiting list of that mutex, which results in deadlock. </p>\n\n<p>•Binary semaphore and mutex are similar but not same.</p>\n\n<p>•Mutex is costly operation due to protection protocols associated with it.</p>\n\n<p>•Main aim of mutex is achieve atomic access or lock on resource</p>\n" }, { "answer_id": 25469033, "author": "Praveen_Shukla", "author_id": 3719105, "author_profile": "https://Stackoverflow.com/users/3719105", "pm_score": 4, "selected": false, "text": "<p>Though mutex &amp; semaphores are used as synchronization primitives ,there is a big difference between them.\nIn the case of mutex, only the thread that locked or acquired the mutex can unlock it.\nIn the case of a semaphore, a thread waiting on a semaphore can be signaled by a different thread.\nSome operating system supports using mutex &amp; semaphores between process. Typically usage is creating in shared memory.</p>\n" }, { "answer_id": 29345098, "author": "buddy", "author_id": 103465, "author_profile": "https://Stackoverflow.com/users/103465", "pm_score": 3, "selected": false, "text": "<p>Diff between Binary Semaphore and Mutex:\nOWNERSHIP:\n<strong>Semaphores can be signalled (posted) even from a non current owner. It means you can simply post from any other thread, though you are not the owner.</strong></p>\n\n<p>Semaphore is a public property in process, It can be simply posted by a non owner thread.\nPlease Mark this difference in BOLD letters, it mean a lot. </p>\n" }, { "answer_id": 33154919, "author": "Neeraj Sh", "author_id": 5450768, "author_profile": "https://Stackoverflow.com/users/5450768", "pm_score": 0, "selected": false, "text": "<p>Mutex and binary semaphore are both of the same usage, but in reality, they are different.</p>\n\n<p>In case of mutex, only the thread which have locked it can unlock it. If any other thread comes to lock it, it will wait. </p>\n\n<p>In case of semaphone, that's not the case. Semaphore is not tied up with a particular thread ID.</p>\n" }, { "answer_id": 34494207, "author": "Rahul Yadav", "author_id": 4037532, "author_profile": "https://Stackoverflow.com/users/4037532", "pm_score": -1, "selected": false, "text": "<p>Almost all of the above said it right. Let me also try my bit to clarify if somebody still has a doubt.</p>\n\n<ul>\n<li>Mutex -> used for serialization</li>\n<li>Semaphore-> synchronization.</li>\n</ul>\n\n<p>Purpose of both are different however, same functionality could be achieved through both of them with careful programming.</p>\n\n<p>Standard Example-> producer consumer problem.</p>\n\n<pre><code>initial value of SemaVar=0\n\nProducer Consumer\n--- SemaWait()-&gt;decrement SemaVar \nproduce data\n---\nSemaSignal SemaVar or SemaVar++ ---&gt;consumer unblocks as SemVar is 1 now.\n</code></pre>\n\n<p>Hope I could clarify.</p>\n" }, { "answer_id": 35305718, "author": "Dom045", "author_id": 830514, "author_profile": "https://Stackoverflow.com/users/830514", "pm_score": 1, "selected": false, "text": "<p>As many folks here have mentioned, a mutex is used to protect a critical piece of code (AKA critical section.) You will acquire the mutex (lock), enter critical section, and release mutex (unlock) <strong>all in the same thread</strong>.</p>\n\n<p>While using a semaphore, you can make a thread wait on a semaphore (say thread A), until another thread (say thread B)completes whatever task, and then sets the Semaphore for thread A to stop the wait, and continue its task.</p>\n" }, { "answer_id": 38391937, "author": "Adi06411", "author_id": 6521452, "author_profile": "https://Stackoverflow.com/users/6521452", "pm_score": 2, "selected": false, "text": "<p>While a binary semaphore may be used as a mutex, a mutex is a more specific use-case, in that only the process that locked the mutex is supposed to unlock it. This ownership constraint makes it possible to provide protection against:</p>\n\n<ul>\n<li>Accidental release</li>\n<li>Recursive Deadlock</li>\n<li>Task Death Deadlock</li>\n</ul>\n\n<p>These constraints are not always present because they degrade the speed. During the development of your code, you can enable these checks temporarily. </p>\n\n<p>e.g. you can enable Error check attribute in your mutex. Error checking mutexes return <code>EDEADLK</code> if you try to lock the same one twice and <code>EPERM</code> if you unlock a mutex that isn't yours.</p>\n\n<pre><code>pthread_mutex_t mutex;\npthread_mutexattr_t attr;\npthread_mutexattr_init (&amp;attr);\npthread_mutexattr_settype (&amp;attr, PTHREAD_MUTEX_ERRORCHECK_NP);\npthread_mutex_init (&amp;mutex, &amp;attr);\n</code></pre>\n\n<p>Once initialised we can place these checks in our code like this:</p>\n\n<pre><code>if(pthread_mutex_unlock(&amp;mutex)==EPERM)\n printf(\"Unlock failed:Mutex not owned by this thread\\n\");\n</code></pre>\n" }, { "answer_id": 45533202, "author": "Sumit Naik", "author_id": 4590926, "author_profile": "https://Stackoverflow.com/users/4590926", "pm_score": 4, "selected": false, "text": "<p>Mutex: Suppose we have critical section thread T1 wants to access it then it follows below steps.\nT1:</p>\n\n<ol>\n<li>Lock</li>\n<li>Use Critical Section</li>\n<li>Unlock</li>\n</ol>\n\n<p>Binary semaphore: It works based on signaling wait and signal.\nwait(s) decrease \"s\" value by one usually \"s\" value is initialize with value \"1\",\nsignal(s) increases \"s\" value by one. if \"s\" value is 1 means no one is using critical section, when value is 0 means critical section is in use.\nsuppose thread T2 is using critical section then it follows below steps.\nT2 : </p>\n\n<ol>\n<li>wait(s)//initially s value is one after calling wait it's value decreased by one i.e 0</li>\n<li>Use critical section</li>\n<li>signal(s) // now s value is increased and it become 1</li>\n</ol>\n\n<p>Main difference between Mutex and Binary semaphore is in Mutext if thread lock the critical section then it has to unlock critical section no other thread can unlock it, but in case of Binary semaphore if one thread locks critical section using wait(s) function then value of s become \"0\" and no one can access it until value of \"s\" become 1 but suppose some other thread calls signal(s) then value of \"s\" become 1 and it allows other function to use critical section.\nhence in Binary semaphore thread doesn't have ownership.</p>\n" }, { "answer_id": 56268218, "author": "ilias iliadis", "author_id": 2362556, "author_profile": "https://Stackoverflow.com/users/2362556", "pm_score": -1, "selected": false, "text": "<p>\"binary semaphore\" is a programming language circumvent to use a «semaphore» like «mutex». Apparently there are two very big differences:</p>\n\n<ol>\n<li><p>The way you call each one of them.</p></li>\n<li><p>The maximum length of the \"identifier\".</p></li>\n</ol>\n" }, { "answer_id": 57661994, "author": "kjohri", "author_id": 1518661, "author_profile": "https://Stackoverflow.com/users/1518661", "pm_score": 0, "selected": false, "text": "<p>The basic issue is concurrency. There is more than one flow of control. Think about two processes using a shared memory. Now only one process can access the shared memory at a time. If more than one process accesses the shared memory at a time, the contents of shared memory would get corrupted. It is like a railroad track. Only one train can run on it, else there would be an accident.So there is a signalling mechanism, which a driver checks. If the signal is green, the train can go and if it is red it has to wait to use the track. Similarly in case of shared memory, there is a binary semaphore. If the semaphore is 1, a process acquires it (makes it 0) and goes ahead and accesses it. If the semaphore is 0, the process waits. The functionality the binary semaphore has to provide is mutual exclusion (or mutex, in short) so that only one of the many concurrent entities (process or thread) mutually excludes others. It is a plus that we have counting semaphores, which help in synchronizing multiple instances of a resource.</p>\n\n<p>Mutual exclusion is the basic functionality provided by semaphores. Now in the context of threads, we might have a different name and syntax for it. But the underlying concept is the same: how to keep integrity of code and data in concurrent programming. In my opinion, things like ownership, and associated checks are refinements provided by implementations.</p>\n" }, { "answer_id": 57809820, "author": "Ganesh Chowdhary Sadanala", "author_id": 8706759, "author_profile": "https://Stackoverflow.com/users/8706759", "pm_score": 2, "selected": false, "text": "<p><strong>Best Solution</strong></p>\n\n<p>The only difference is <br/></p>\n\n<p>1.Mutex -> lock and unlock are under the ownership of a thread that locks the mutex.<br/></p>\n\n<p>2.Semaphore -> No ownership i.e; if one thread calls semwait(s) any other thread can call sempost(s) to remove the lock.</p>\n" }, { "answer_id": 59246656, "author": "Vijay Panchal", "author_id": 2185004, "author_profile": "https://Stackoverflow.com/users/2185004", "pm_score": 1, "selected": false, "text": "<p><strong>MUTEX</strong></p>\n\n<p>Until recently, the only sleeping lock in the kernel was the semaphore. Most users of semaphores instantiated a semaphore with a count of one and treated them as a mutual exclusion lock—a sleeping version of the spin-lock. Unfortunately, semaphores are rather generic and do not impose any usage constraints. This makes them useful for managing exclusive access in obscure situations, such as complicated dances between the kernel and userspace. But it also means that simpler locking is harder to do, and the lack of enforced rules makes any sort of automated debugging or constraint enforcement impossible. Seeking a simpler sleeping lock, the kernel developers introduced the mutex.Yes, as you are now accustomed to, that is a confusing name. Let’s clarify.The term “mutex” is a generic name to refer to any sleeping lock that enforces mutual exclusion, such as a semaphore with a usage count of one. In recent Linux kernels, the proper noun “mutex” is now also a specific type of sleeping lock that implements mutual exclusion.That is, a mutex is a mutex.</p>\n\n<p>The simplicity and efficiency of the mutex come from the additional constraints it imposes on its users over and above what the semaphore requires. Unlike a semaphore, which implements the most basic of behaviour in accordance with Dijkstra’s original design, the mutex has a stricter, narrower use case:\nn Only one task can hold the mutex at a time. That is, the usage count on a mutex is always one. </p>\n\n<ol>\n<li>Whoever locked a mutex must unlock it. That is, you cannot lock a mutex in one\ncontext and then unlock it in another. This means that the mutex isn’t suitable for more complicated synchronizations between kernel and user-space. Most use cases,\nhowever, cleanly lock and unlock from the same context.</li>\n<li>Recursive locks and unlocks are not allowed. That is, you cannot recursively acquire the same mutex, and you cannot unlock an unlocked mutex.</li>\n<li>A process cannot exit while holding a mutex.</li>\n<li>A mutex cannot be acquired by an interrupt handler or bottom half, even with\nmutex_trylock().</li>\n<li>A mutex can be managed only via the official API: It must be initialized via the methods described in this section and cannot be copied, hand initialized, or reinitialized.</li>\n</ol>\n\n<p>[1] Linux Kernel Development, Third Edition Robert Love</p>\n" }, { "answer_id": 60917006, "author": "Mrinal Verma", "author_id": 7363183, "author_profile": "https://Stackoverflow.com/users/7363183", "pm_score": 2, "selected": false, "text": "<p>I think most of the answers here were confusing especially those saying that mutex can be released only by the process that holds it but semaphore can be signaled by ay process. The above line is kind of vague in terms of semaphore. To understand we should know that there are two kinds of semaphore one is called counting semaphore and the other is called a binary semaphore. In counting semaphore handles access to n number of resources where n can be defined before the use. Each semaphore has a count variable, which keeps the count of the number of resources in use, initially, it is set to n. Each process that wishes to uses a resource performs a wait() operation on the semaphore (thereby decrementing the count). When a process releases a resource, it performs a release() operation (incrementing the count). When the count becomes 0, all the resources are being used. After that, the process waits until the count becomes more than 0. Now here is the catch only the process that holds the resource can increase the count no other process can increase the count only the processes holding a resource can increase the count and the process waiting for the semaphore again checks and when it sees the resource available it decreases the count again. So in terms of binary semaphore, only the process holding the semaphore can increase the count, and count remains zero until it stops using the semaphore and increases the count and other process gets the chance to access the semaphore.</p>\n\n<p>The main difference between binary semaphore and mutex is that semaphore is a signaling mechanism and mutex is a locking mechanism, but binary semaphore seems to function like mutex that creates confusion, but both are different concepts suitable for a different kinds of work.</p>\n" }, { "answer_id": 65410727, "author": "Puttaraju", "author_id": 442992, "author_profile": "https://Stackoverflow.com/users/442992", "pm_score": -1, "selected": false, "text": "<p>You can clearly remember difference by this:</p>\n<ol>\n<li><p>Mutex lock : is for protecting critical region,\nMutex can't be used across processes, only used in single process</p>\n</li>\n<li><p>Semaphore: is for signalling availability of a resource.\nSemaphore can be used both across processes and across processes.</p>\n</li>\n</ol>\n" }, { "answer_id": 67110016, "author": "DataCrusade1999", "author_id": 13128057, "author_profile": "https://Stackoverflow.com/users/13128057", "pm_score": 0, "selected": false, "text": "<p>Mutex is a Criteria(Out of 4) that any algorithm that intends to solve the Critical Section Problem must follow whereas binary semaphore in itself is a variable that can take values 0 and 1.</p>\n" }, { "answer_id": 73937642, "author": "TonyParker", "author_id": 3964247, "author_profile": "https://Stackoverflow.com/users/3964247", "pm_score": 0, "selected": false, "text": "<ul>\n<li>Mutex uses a locking mechanism i.e. if a process wants to use a\nresource then it locks the resource, uses it and then release it. But\non the other hand, semaphore uses a signalling mechanism where wait()\nand signal() methods are used to show if a process is releasing a\nresource or taking a resource.</li>\n<li>A mutex is an object but semaphore is an integer variable.</li>\n<li>In semaphore, we have wait() and signal() functions. But in mutex,\nthere is no such function.</li>\n<li>A mutex object allows multiple process threads to access a single\nshared resource but only one at a time. On the other hand, semaphore\nallows multiple process threads to access the finite instance of the\nresource until available.</li>\n<li>In mutex, the lock can be acquired and released by the same process\nat a time. But the value of the semaphore variable can be modified by\nany process that needs some resource but only one process can change\nthe value at a time.</li>\n</ul>\n<p>A useful read, I learned and copied from <a href=\"https://afteracademy.com/blog/difference-between-mutex-and-semaphore-in-operating-system\" rel=\"nofollow noreferrer\">here</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7086/" ]
Is there any difference between a binary semaphore and mutex or are they essentially the same?
They are **NOT** the same thing. They are used for different purposes! While both types of semaphores have a full/empty state and use the same API, their usage is very different. **Mutual Exclusion Semaphores** Mutual Exclusion semaphores are used to protect shared resources (data structure, file, etc..). A Mutex semaphore is "owned" by the task that takes it. If Task B attempts to semGive a mutex currently held by Task A, Task B's call will return an error and fail. Mutexes always use the following sequence: ``` - SemTake - Critical Section - SemGive ``` Here is a simple example: ``` Thread A Thread B Take Mutex access data ... Take Mutex <== Will block ... Give Mutex access data <== Unblocks ... Give Mutex ``` **Binary Semaphore** Binary Semaphore address a totally different question: * Task B is pended waiting for something to happen (a sensor being tripped for example). * Sensor Trips and an Interrupt Service Routine runs. It needs to notify a task of the trip. * Task B should run and take appropriate actions for the sensor trip. Then go back to waiting. ``` Task A Task B ... Take BinSemaphore <== wait for something Do Something Noteworthy Give BinSemaphore do something <== unblocks ``` Note that with a binary semaphore, it is OK for B to take the semaphore and A to give it. Again, a binary semaphore is NOT protecting a resource from access. The act of Giving and Taking a semaphore are fundamentally decoupled. It typically makes little sense for the same task to so a give and a take on the same binary semaphore.
62,916
<p>I have installed and setup RubyCAS-Server and RubyCAS-Client on my machine. Login works perfectly but when I try to logout I get this error message from the RubyCAS-Server:</p> <pre><code>Camping Problem! CASServer::Controllers::Logout.GET ActiveRecord::StatementInvalid Mysql::Error: Unknown column 'username' in 'where clause': SELECT * FROM `casserver_pgt` WHERE (username = 'lgs') : </code></pre> <p>I am using version 0.6 of the gem. Looking at the migrations in the RubyCAS-Server it looks like there shouldn't be a username column in that table at all.</p> <p>Does anyone know why this is happening and what I can do about it?</p>
[ { "answer_id": 62914, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 0, "selected": false, "text": "<p>Are you unable to use the <a href=\"http://msdn.microsoft.com/en-us/library/aa335422(VS.71).aspx\" rel=\"nofollow noreferrer\">MessageBox class</a>?</p>\n" }, { "answer_id": 62928, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 2, "selected": false, "text": "<p>Do you need something more than what can be provided by MsgBox?</p>\n\n<pre><code>MsgBox(\"Do you want to see this message?\", MsgBoxStyle.OkCancel + MsgBoxStyle.Information, \"Respond\")\n</code></pre>\n" }, { "answer_id": 62945, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>Of course there's MessageBox (shorthand <em>MsgBox</em> in VB.Net) and also the windows common dialogs like Open File, Save File, Print, ColorPicker, etc.</p>\n\n<p>However, none of those really qualify as templates. </p>\n\n<p>I can sympathize with wanting a better message box from time to time. You might try code project: I'll bet you'll see a dozen...</p>\n" }, { "answer_id": 62950, "author": "camainc", "author_id": 7232, "author_profile": "https://Stackoverflow.com/users/7232", "pm_score": 2, "selected": true, "text": "<p>Why not create your own template? I've done that with several types of forms, not just dialogs. It is a great way to give yourself a jump-start.</p>\n\n<p>Create your basic dialog, keeping it as generic as possible, then save it as a template.</p>\n\n<p>Here is an article that will help you:</p>\n\n<p><a href=\"http://www.builderau.com.au/program/dotnet/soa/Save-time-with-Visual-Studio-2005-project-templates/0,339028399,339285540,00.htm\" rel=\"nofollow noreferrer\">http://www.builderau.com.au/program/dotnet/soa/Save-time-with-Visual-Studio-2005-project-templates/0,339028399,339285540,00.htm</a></p>\n\n<p>And:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/magazine/cc188697.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc188697.aspx</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3842/" ]
I have installed and setup RubyCAS-Server and RubyCAS-Client on my machine. Login works perfectly but when I try to logout I get this error message from the RubyCAS-Server: ``` Camping Problem! CASServer::Controllers::Logout.GET ActiveRecord::StatementInvalid Mysql::Error: Unknown column 'username' in 'where clause': SELECT * FROM `casserver_pgt` WHERE (username = 'lgs') : ``` I am using version 0.6 of the gem. Looking at the migrations in the RubyCAS-Server it looks like there shouldn't be a username column in that table at all. Does anyone know why this is happening and what I can do about it?
Why not create your own template? I've done that with several types of forms, not just dialogs. It is a great way to give yourself a jump-start. Create your basic dialog, keeping it as generic as possible, then save it as a template. Here is an article that will help you: <http://www.builderau.com.au/program/dotnet/soa/Save-time-with-Visual-Studio-2005-project-templates/0,339028399,339285540,00.htm> And: <http://msdn.microsoft.com/en-us/magazine/cc188697.aspx>
62,929
<p>I am getting the following error trying to read from a socket. I'm doing a <code>readInt()</code> on that <code>InputStream</code>, and I am getting this error. Perusing the documentation this suggests that the client part of the connection closed the connection. In this scenario, I am the server.</p> <p>I have access to the client log files and it is not closing the connection, and in fact its log files suggest I am closing the connection. So does anybody have an idea why this is happening? What else to check for? Does this arise when there are local resources that are perhaps reaching thresholds?</p> <hr> <p>I do note that I have the following line:</p> <pre><code>socket.setSoTimeout(10000); </code></pre> <p>just prior to the <code>readInt()</code>. There is a reason for this (long story), but just curious, are there circumstances under which this might lead to the indicated error? I have the server running in my IDE, and I happened to leave my IDE stuck on a breakpoint, and I then noticed the exact same errors begin appearing in my own logs in my IDE.</p> <p>Anyway, just mentioning it, hopefully not a red herring. :-(</p>
[ { "answer_id": 62996, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 4, "selected": false, "text": "<p>Whenever I have had odd issues like this, I usually sit down with a tool like <a href=\"http://www.wireshark.org/\" rel=\"noreferrer\">WireShark</a> and look at the raw data being passed back and forth. You might be surprised where things are being disconnected, and you are only being <em>notified</em> when you try and read.</p>\n" }, { "answer_id": 63155, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 6, "selected": false, "text": "<p>Connection reset simply means that a TCP RST was received. This happens when your peer receives data that it can't process, and there can be various reasons for that.</p>\n\n<p>The simplest is when you close the socket, and then write more data on the output stream. By closing the socket, you told your peer that you are done talking, and it can forget about your connection. When you send more data on that stream anyway, the peer rejects it with an RST to let you know it isn't listening.</p>\n\n<p>In other cases, an intervening firewall or even the remote host itself might \"forget\" about your TCP connection. This could happen if you don't send any data for a long time (2 hours is a common time-out), or because the peer was rebooted and lost its information about active connections. Sending data on one of these defunct connections will cause a RST too.</p>\n\n<hr>\n\n<p><em>Update in response to additional information:</em> </p>\n\n<p>Take a close look at your handling of the <code>SocketTimeoutException</code>. This exception is raised if the configured timeout is exceeded while blocked on a socket operation. The state of the socket itself is not changed when this exception is thrown, but if your exception handler closes the socket, and then tries to write to it, you'll be in a connection reset condition. <code>setSoTimeout()</code> is meant to give you a clean way to break out of a <code>read()</code> operation that might otherwise block forever, without doing dirty things like closing the socket from another thread.</p>\n" }, { "answer_id": 4300803, "author": "user207421", "author_id": 207421, "author_profile": "https://Stackoverflow.com/users/207421", "pm_score": 7, "selected": false, "text": "<p>There are several possible causes.</p>\n\n<ol>\n<li><p>The other end has deliberately reset the connection, in a way which I will not document here. It is rare, and generally incorrect, for application software to do this, but it is not unknown for commercial software.</p></li>\n<li><p>More commonly, it is caused by writing to a connection that the other end has already closed normally. In other words an application protocol error.</p></li>\n<li><p>It can also be caused by closing a socket when there is unread data in the socket receive buffer.</p></li>\n<li><p>In Windows, 'software caused connection abort', which is not the same as 'connection reset', is caused by network problems sending from your end. There's a Microsoft knowledge base article about this.</p></li>\n</ol>\n" }, { "answer_id": 5452194, "author": "kml_ckr", "author_id": 459904, "author_profile": "https://Stackoverflow.com/users/459904", "pm_score": 3, "selected": false, "text": "<p>I had the same error. I found the solution for problem now. The problem was client program was finishing before server read the streams.</p>\n" }, { "answer_id": 17816678, "author": "Scott S", "author_id": 312921, "author_profile": "https://Stackoverflow.com/users/312921", "pm_score": 4, "selected": false, "text": "<p>Embarrassing to say it, but when I had this problem, it was simply a mistake that I was closing the connection before I read all the data. In cases with small strings being returned, it worked, but that was probably due to the whole response was buffered, before I closed it.</p>\n\n<p>In cases of longer amounts of text being returned, the exception was thrown, since more then a buffer was coming back.</p>\n\n<p>You might check for this oversight. Remember opening a URL is like a file, be sure to close it (release the connection) once it has been fully read.</p>\n" }, { "answer_id": 24681365, "author": "pmartin8", "author_id": 1400157, "author_profile": "https://Stackoverflow.com/users/1400157", "pm_score": 1, "selected": false, "text": "<p>I also had this problem with a Java program trying to send a command on a server via SSH. The problem was with the machine executing the Java code. It didn't have the permission to connect to the remote server. The write() method was doing alright, but the read() method was throwing a java.net.SocketException: Connection reset. I fixed this problem with adding the client SSH key to the remote server known keys. </p>\n" }, { "answer_id": 30123818, "author": "Pino", "author_id": 685806, "author_profile": "https://Stackoverflow.com/users/685806", "pm_score": 3, "selected": false, "text": "<p>I had this problem with a SOA system written in Java. I was running both the client and the server on different physical machines and they worked fine for a long time, then those nasty connection resets appeared in the client log and there wasn't anything strange in the server log. Restarting both client and server didn't solve the problem. Finally we discovered that the heap on the server side was rather full so we increased the memory available to the JVM: problem solved! Note that there was no OutOfMemoryError in the log: memory was just scarce, not exhausted.</p>\n" }, { "answer_id": 31741436, "author": "Davut Gürbüz", "author_id": 413032, "author_profile": "https://Stackoverflow.com/users/413032", "pm_score": 4, "selected": false, "text": "<p>You should inspect full trace very carefully,</p>\n<p>I've a server socket application and fixed a <code>java.net.SocketException: Connection reset</code> case.</p>\n<p>In my case it happens while reading from a clientSocket <code>Socket</code> object which is closed its connection because of some reason. (Network lost,firewall or application crash or intended close)</p>\n<p>Actually I was re-establishing connection when I got an error while reading from this Socket object.</p>\n<pre><code>Socket clientSocket = ServerSocket.accept();\nis = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));\nint readed = is.read(); // WHERE ERROR STARTS !!!\n</code></pre>\n<p>The interesting thing is <code>for my JAVA Socket</code> if a client connects to my <code>ServerSocket</code> and close its connection without sending anything <code>is.read()</code> is being called repeatedly.It seems because of being in an infinite while loop for reading from this socket you try to read from a closed connection.\nIf you use something like below for read operation;</p>\n<pre><code>while(true)\n{\n Receive();\n}\n</code></pre>\n<p>Then you get a stackTrace something like below on and on</p>\n<pre><code>java.net.SocketException: Socket is closed\n at java.net.ServerSocket.accept(ServerSocket.java:494)\n</code></pre>\n<p>What I did is just closing ServerSocket and renewing my connection and waiting for further incoming client connections</p>\n<pre><code>String Receive() throws Exception\n{\ntry { \n int readed = is.read();\n ....\n}catch(Exception e)\n{\n tryReConnect();\n logit(); //etc\n}\n\n\n//...\n}\n</code></pre>\n<p>This reestablises my connection for unknown client socket losts</p>\n<pre><code>private void tryReConnect()\n {\n try\n {\n ServerSocket.close();\n //empty my old lost connection and let it get by garbage col. immediately \n clientSocket=null;\n System.gc();\n //Wait a new client Socket connection and address this to my local variable\n clientSocket= ServerSocket.accept(); // Waiting for another Connection\n System.out.println(&quot;Connection established...&quot;);\n }catch (Exception e) {\n String message=&quot;ReConnect not successful &quot;+e.getMessage();\n logit();//etc...\n }\n }\n</code></pre>\n<p>I couldn't find another way because as you see from below image you can't understand whether connection is lost or not without a <code>try and catch</code> ,because everything seems right . I got this snapshot while I was getting <code>Connection reset</code> continuously.</p>\n<p><a href=\"https://i.stack.imgur.com/T75Ul.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/T75Ul.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 57515659, "author": "Sumiya", "author_id": 2473061, "author_profile": "https://Stackoverflow.com/users/2473061", "pm_score": 2, "selected": false, "text": "<p>Check your server's Java version. Happened to me because my Weblogic 10.3.6 was on JDK 1.7.0_75 which was on TLSv1. The rest endpoint I was trying to consume was shutting down anything below TLSv1.2. </p>\n\n<p>By default Weblogic was trying to negotiate the strongest shared protocol. See details here: <a href=\"https://stackoverflow.com/questions/34283829/issues-with-setting-https-protocols-system-property-for-https-connections\">Issues with setting https.protocols System Property for HTTPS connections</a>.</p>\n\n<p>I added verbose SSL logging to identify the supported TLS. This indicated TLSv1 was being used for the handshake.<br/>\n<code>-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager -Djava.security.debug=access:stack</code></p>\n\n<p>I resolved this by pushing the feature out to our JDK8-compatible product, JDK8 defaults to TLSv1.2. For those restricted to JDK7, I also successfully tested a workaround for Java 7 by upgrading to TLSv1.2. I used this answer: <a href=\"https://stackoverflow.com/questions/39157422/how-to-enable-tls-1-2-in-java-7\">How to enable TLS 1.2 in Java 7</a></p>\n" }, { "answer_id": 62217112, "author": "bmck", "author_id": 2119761, "author_profile": "https://Stackoverflow.com/users/2119761", "pm_score": 0, "selected": false, "text": "<p>In my experience, I often encounter the following situations;</p>\n\n<ol>\n<li><p>If you work in a corporate company, contact the network and security team. Because in requests made to external services, it may be necessary to <strong>give permission for the relevant endpoint.</strong></p></li>\n<li><p>Another issue is that the <strong>SSL certificate may have expired</strong> on the server where your application is running.</p></li>\n</ol>\n" }, { "answer_id": 68480666, "author": "tsotzolas", "author_id": 3832031, "author_profile": "https://Stackoverflow.com/users/3832031", "pm_score": 1, "selected": false, "text": "<p>In my case was <code>DNS problem</code> .<br />\nI put in <code>host file</code> the resolved IP and everything works fine.\nOf course it is not a permanent solution put this give me time to fix the DNS problem.</p>\n" }, { "answer_id": 68488293, "author": "Thiago Ferreira", "author_id": 8907047, "author_profile": "https://Stackoverflow.com/users/8907047", "pm_score": 0, "selected": false, "text": "<p>I've seen this problem. In my case, there was an error caused by reusing the same ClientRequest object in an specific Java class. That project was using <a href=\"https://docs.jboss.org/resteasy/docs/3.0.13.Final/javadocs/org/jboss/resteasy/client/ClientRequest.html\" rel=\"nofollow noreferrer\">Jboss Resteasy</a>.</p>\n<ol>\n<li>Initially only one method was using/invoking the object ClientRequest (placed as global variable in the class) to do a request in an specific URL.</li>\n<li>After that, another method was created to get data with another URL, reusing the same ClientRequest object, though.</li>\n</ol>\n<p><strong>The solution: in the same class was created another ClientRequest object and exclusively to not be reused.</strong></p>\n" }, { "answer_id": 71227340, "author": "Djek-Grif", "author_id": 2471275, "author_profile": "https://Stackoverflow.com/users/2471275", "pm_score": 0, "selected": false, "text": "<p>In my case it was problem with TSL version. I was using Retrofit with OkHttp client and after update ALB on server side I should have to delete my config with <strong>connectionSpecs</strong>:</p>\n<pre><code>OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();\n List&lt;ConnectionSpec&gt; connectionSpecs = new ArrayList&lt;&gt;();\n connectionSpecs.add(ConnectionSpec.COMPATIBLE_TLS);\n // clientBuilder.connectionSpecs(connectionSpecs);\n</code></pre>\n<p>So try to remove or add this config to use different TSL configurations.</p>\n" }, { "answer_id": 73825492, "author": "MaVRoSCy", "author_id": 1387157, "author_profile": "https://Stackoverflow.com/users/1387157", "pm_score": 0, "selected": false, "text": "<p>I used to get the 'NotifyUtil::java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:...' message in the Apache Console of my Netbeans7.4 setup.</p>\n<p>I tried many solutions to get away from it, what worked for me is enabling the TLS on Tomcat.</p>\n<p>Here is how to:</p>\n<blockquote>\n<p>Create a keystore file to store the server's private key and\nself-signed certificate by executing the following command:</p>\n<p>Windows:</p>\n<p>&quot;%JAVA_HOME%\\bin\\keytool&quot; -genkey -alias tomcat -keyalg RSA</p>\n<p>Unix:</p>\n<p>$JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA</p>\n<p>and specify a password value of &quot;changeit&quot;.</p>\n</blockquote>\n<p>As per <a href=\"https://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html\" rel=\"nofollow noreferrer\">https://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html</a>\n(This will create a .keystore file in your localuser dir)</p>\n<p>Then edit server.xml (uncomment and edit relevant lines) file (%CATALINA_HOME%apache-tomcat-7.0.41.0_base\\conf\\server.xml) to enable SSL and TLS protocol:</p>\n<pre><code> &lt;Connector port=&quot;8443&quot; protocol=&quot;HTTP/1.1&quot; SSLEnabled=&quot;true&quot;\n maxThreads=&quot;150&quot; scheme=&quot;https&quot; secure=&quot;true&quot;\n clientAuth=&quot;false&quot; sslProtocol=&quot;TLS&quot; keystorePass=&quot;changeit&quot; /&gt;\n</code></pre>\n<p>I hope this helps</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am getting the following error trying to read from a socket. I'm doing a `readInt()` on that `InputStream`, and I am getting this error. Perusing the documentation this suggests that the client part of the connection closed the connection. In this scenario, I am the server. I have access to the client log files and it is not closing the connection, and in fact its log files suggest I am closing the connection. So does anybody have an idea why this is happening? What else to check for? Does this arise when there are local resources that are perhaps reaching thresholds? --- I do note that I have the following line: ``` socket.setSoTimeout(10000); ``` just prior to the `readInt()`. There is a reason for this (long story), but just curious, are there circumstances under which this might lead to the indicated error? I have the server running in my IDE, and I happened to leave my IDE stuck on a breakpoint, and I then noticed the exact same errors begin appearing in my own logs in my IDE. Anyway, just mentioning it, hopefully not a red herring. :-(
There are several possible causes. 1. The other end has deliberately reset the connection, in a way which I will not document here. It is rare, and generally incorrect, for application software to do this, but it is not unknown for commercial software. 2. More commonly, it is caused by writing to a connection that the other end has already closed normally. In other words an application protocol error. 3. It can also be caused by closing a socket when there is unread data in the socket receive buffer. 4. In Windows, 'software caused connection abort', which is not the same as 'connection reset', is caused by network problems sending from your end. There's a Microsoft knowledge base article about this.
62,936
<p>For example: <code>man(1)</code>, <code>find(3)</code>, <code>updatedb(2)</code>? </p> <p>What do the numbers in parentheses (Brit. "brackets") mean?</p>
[ { "answer_id": 62943, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 7, "selected": false, "text": "<p>The section the command is documented in the manual. The list of sections is documented on man's manual. For example:</p>\n\n<pre><code>man 1 man\nman 3 find\n</code></pre>\n\n<p>This is useful for when similar or exactly equal commands exist on different sections</p>\n" }, { "answer_id": 62972, "author": "Ian G", "author_id": 5764, "author_profile": "https://Stackoverflow.com/users/5764", "pm_score": 10, "selected": true, "text": "<p>It's the section that the man page for the command is assigned to.</p>\n<p>These are split as</p>\n<ol>\n<li>General commands</li>\n<li>System calls</li>\n<li>C library functions</li>\n<li>Special files (usually devices, those found in /dev) and drivers</li>\n<li>File formats and conventions</li>\n<li>Games and screensavers</li>\n<li>Miscellanea</li>\n<li>System administration commands and daemons</li>\n</ol>\n<p>Original descriptions of each section can be seen in the <a href=\"https://web.archive.org/web/20170601064537/http://plan9.bell-labs.com/7thEdMan/v7vol1.pdf\" rel=\"noreferrer\">Unix Programmer's Manual</a> (page ii).</p>\n<p>In order to access a man page given as &quot;foo(5)&quot;, run:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>man 5 foo\n</code></pre>\n" }, { "answer_id": 62990, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 3, "selected": false, "text": "<p>It indicates the section of the man pages the command is found in. The -s switch on the man command can be used to limit a search to certain sections.</p>\n\n<p>When you view a man page, the top left gives the name of the section, e.g.:</p>\n\n<p>User Commands printf(1)<br>\nStandard C Library Functions printf(3C)</p>\n\n<p>So if you are trying to look up C functions and don't want to accidentally see a page for a user command that shares the same name, you would do 'man -s 3C ...'</p>\n" }, { "answer_id": 63098, "author": "TREE", "author_id": 6973, "author_profile": "https://Stackoverflow.com/users/6973", "pm_score": 4, "selected": false, "text": "<p>Note also that on other unixes, the method of specifying the section differs. On solaris, for example, it is:</p>\n\n<pre><code>man -s 1 man\n</code></pre>\n" }, { "answer_id": 63238, "author": "LepardUK", "author_id": 44247, "author_profile": "https://Stackoverflow.com/users/44247", "pm_score": 6, "selected": false, "text": "<p>The reason why the section numbers are significant is that many years ago when disk space was more of an issue than it is now the sections could be installed individually.</p>\n\n<p>Many systems only had 1 and 8 installed for instance. These days people tend to look the commands up on google instead.</p>\n" }, { "answer_id": 608893, "author": "Bob Setterbo", "author_id": 426708, "author_profile": "https://Stackoverflow.com/users/426708", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Man_page#Manual_sections\" rel=\"nofollow noreferrer\">Wikipedia</a> details about Manual Sections:</p>\n\n<ol>\n<li>General commands</li>\n<li>System calls</li>\n<li>Library functions, covering in particular the C standard library</li>\n<li>Special files (usually devices, those found in /dev) and drivers</li>\n<li>File formats and conventions</li>\n<li>Games and screensavers</li>\n<li>Miscellanea</li>\n<li>System administration commands and daemons</li>\n</ol>\n" }, { "answer_id": 58496243, "author": "Gabriel Staples", "author_id": 4561887, "author_profile": "https://Stackoverflow.com/users/4561887", "pm_score": 5, "selected": false, "text": "<p>As <a href=\"https://stackoverflow.com/a/62972/4561887\">@Ian G says</a>, they are the man page sections. Let's take this one step further though:</p>\n<h2>1. See the man page for the <code>man</code> command with <code>man man</code>, and it shows the 9 sections as follows:</h2>\n<pre><code>DESCRIPTION\n man is the system's manual pager. Each page argument given\n to man is normally the name of a program, utility or func‐\n tion. The manual page associated with each of these argu‐\n ments is then found and displayed. A section, if provided,\n will direct man to look only in that section of the manual.\n The default action is to search in all of the available sec‐\n tions following a pre-defined order (&quot;1 n l 8 3 2 3posix 3pm\n 3perl 5 4 9 6 7&quot; by default, unless overridden by the SEC‐\n TION directive in /etc/manpath.config), and to show only the\n first page found, even if page exists in several sections.\n\n The table below shows the section numbers of the manual fol‐\n lowed by the types of pages they contain.\n\n 1 Executable programs or shell commands\n 2 System calls (functions provided by the kernel)\n 3 Library calls (functions within program libraries)\n 4 Special files (usually found in /dev)\n 5 File formats and conventions eg /etc/passwd\n 6 Games\n 7 Miscellaneous (including macro packages and conven‐\n tions), e.g. man(7), groff(7)\n 8 System administration commands (usually only for root)\n 9 Kernel routines [Non standard]\n\n A manual page consists of several sections.\n\n\n</code></pre>\n<h2>2. <code>man &lt;section_num&gt; &lt;cmd&gt;</code></h2>\n<p>Let's imagine you are Googling around for Linux commands. You find the <code>OPEN(2)</code> pg online: <a href=\"http://man7.org/linux/man-pages/man2/open.2.html\" rel=\"noreferrer\">open(2) — Linux manual page</a>.</p>\n<p>To see this in the man pages on your pc, simply type in <code>man 2 open</code>.</p>\n<p>For <a href=\"http://man7.org/linux/man-pages/man3/fopen.3.html\" rel=\"noreferrer\"><code>FOPEN(3)</code></a> use <code>man 3 fopen</code>, etc.</p>\n<h2>3. <code>man &lt;section_num&gt; intro</code></h2>\n<p>To read the intro pages to a section, type in <code>man &lt;section_num&gt; intro</code>, such as <code>man 1 intro</code>, <code>man 2 intro</code>, <code>man 7 intro</code>, etc.</p>\n<p>To view all man page intros in succession, one-after-the-other, do <code>man -a intro</code>. The intro page for Section 1 will open. Press <kbd>q</kbd> to quit, then press <kbd>Enter</kbd> to view the intro for Section 8. Press <kbd>q</kbd> to quit, then press <kbd>Enter</kbd> to view the intro for Section 3. Continue this process until done. Each time after hitting <kbd>q</kbd>, it'll take you back to the main terminal screen but you'll still be in an interactive prompt, and you'll see this line:</p>\n<pre><code>--Man-- next: intro(8) [ view (return) | skip (Ctrl-D) | quit (Ctrl-C) ]\n</code></pre>\n<p>Note that the Section order that <code>man -a intro</code> will take you through is:</p>\n<ol>\n<li>Section 1</li>\n<li>Section 8</li>\n<li>Section 3</li>\n<li>Section 2</li>\n<li>Section 5</li>\n<li>Section 4</li>\n<li>Section 6</li>\n<li>Section 7</li>\n</ol>\n<p>This search order is intentional, as the <code>man man</code> page explains:</p>\n<pre><code>The default action is to search in all of the available sections follow‐\ning a pre-defined order (&quot;1 n l 8 3 2 3posix 3pm 3perl 5 4 9 6 7&quot; by default, unless overrid‐\nden by the SECTION directive in /etc/manpath.config)\n</code></pre>\n<p>Why did they choose this order? I don't know (please answer in the comments if you know), but just realize this order is correct and intentional.</p>\n<h2>Related:</h2>\n<ol>\n<li><a href=\"https://www.google.com/search?q=linux+what+does+the+number+mean+in+parenthesis+after+a+function%3F&amp;oq=linux+what+does+the+number+mean+in+parenthesis+after+a+function%3F&amp;aqs=chrome..69i57j69i64.9867j0j7&amp;sourceid=chrome&amp;ie=UTF-8\" rel=\"noreferrer\">Google search for &quot;linux what does the number mean in parenthesis after a function?&quot;</a></li>\n<li><a href=\"https://superuser.com/questions/297702/what-do-the-parentheses-and-number-after-a-unix-command-or-c-function-mean\">SuperUser: What do the parentheses and number after a Unix command or C function mean?</a></li>\n<li><a href=\"https://unix.stackexchange.com/questions/3586/what-do-the-numbers-in-a-man-page-mean\">Unix &amp; Linux: What do the numbers in a man page mean?</a></li>\n</ol>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7370/" ]
For example: `man(1)`, `find(3)`, `updatedb(2)`? What do the numbers in parentheses (Brit. "brackets") mean?
It's the section that the man page for the command is assigned to. These are split as 1. General commands 2. System calls 3. C library functions 4. Special files (usually devices, those found in /dev) and drivers 5. File formats and conventions 6. Games and screensavers 7. Miscellanea 8. System administration commands and daemons Original descriptions of each section can be seen in the [Unix Programmer's Manual](https://web.archive.org/web/20170601064537/http://plan9.bell-labs.com/7thEdMan/v7vol1.pdf) (page ii). In order to access a man page given as "foo(5)", run: ```sh man 5 foo ```
62,940
<p>Need to show a credits screen where I want to acknowledge the many contributors to my application. </p> <p>Want it to be an automatically scrolling box, much like the credits roll at the end of the film.</p>
[ { "answer_id": 62978, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 0, "selected": false, "text": "<p>A quick and dirty method would be to use a Panel with a long list of Label controls on it that list out the various people and contributions. Then you need to set the Panel to be AutoScroll so that it has a vertical scrollbar because the list of labels goes past the bottom of the displayed Panel. Then add a time that updates the AutoScrollOffset by 1 vertical pixel each timer tick. When you get to the bottom you reset the offset to 0 and carry on. The only downside is the vertical scrollbar showing.</p>\n" }, { "answer_id": 62998, "author": "Anheledir", "author_id": 5703, "author_profile": "https://Stackoverflow.com/users/5703", "pm_score": 2, "selected": false, "text": "<p>A easy-to-use snippet would be to make a multiline textbox. With a timer you may insert line after line and scroll to the end after that:</p>\n\n<pre><code>textbox1.SelectionStart = textbox1.Text.Length;\ntextbox1.ScrollToCaret();\ntextbox1.Refresh();\n</code></pre>\n\n<p>Not the best method but it's simple and working. There are also some free controls available for exactly this auto-scrolling.</p>\n" }, { "answer_id": 63053, "author": "jlew", "author_id": 7450, "author_profile": "https://Stackoverflow.com/users/7450", "pm_score": 0, "selected": false, "text": "<p>Embed a WebBrowser control, and use a <a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-22_11-5076826.html\" rel=\"nofollow noreferrer\">technique like this</a> to do some javascript scrolling of the HTML content of your choice.</p>\n" }, { "answer_id": 63064, "author": "Jason", "author_id": 7391, "author_profile": "https://Stackoverflow.com/users/7391", "pm_score": 0, "selected": false, "text": "<p>If you're using a .NET form you can just flick to the HTML view and use the marquee html element:</p>\n\n<p><a href=\"http://www.htmlcodetutorial.com/_MARQUEE.html\" rel=\"nofollow noreferrer\">http://www.htmlcodetutorial.com/_MARQUEE.html</a></p>\n\n<p>To be honest it's not great and I wouldn't use it for a commercial job since it can come across as a bit tacky - mainly because it's been overused on so many bad sites in the past. However, it might just be a quick solution to your problem.</p>\n\n<p>Another option is to use some of the features of the Scriptaculous JavaScript library:</p>\n\n<p><a href=\"http://script.aculo.us/\" rel=\"nofollow noreferrer\">http://script.aculo.us/</a></p>\n\n<p>It has many functions for moving text around and is much more powerful.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Need to show a credits screen where I want to acknowledge the many contributors to my application. Want it to be an automatically scrolling box, much like the credits roll at the end of the film.
A easy-to-use snippet would be to make a multiline textbox. With a timer you may insert line after line and scroll to the end after that: ``` textbox1.SelectionStart = textbox1.Text.Length; textbox1.ScrollToCaret(); textbox1.Refresh(); ``` Not the best method but it's simple and working. There are also some free controls available for exactly this auto-scrolling.
62,963
<p>Last year, Scott Guthrie <a href="http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx" rel="noreferrer">stated</a> “You can actually override the raw SQL that LINQ to SQL uses if you want absolute control over the SQL executed”, but I can’t find documentation describing an extensibility method.</p> <p>I would like to modify the following LINQ to SQL query:</p> <pre>using (NorthwindContext northwind = new NorthwindContext ()) { var q = from row in northwind.Customers let orderCount = row.Orders.Count () select new { row.ContactName, orderCount }; }</pre> <p>Which results in the following TSQL:</p> <pre>SELECT [t0].[ContactName], ( SELECT COUNT(*) FROM [dbo].[Orders] AS [t1] WHERE [t1].[CustomerID] = [t0].[CustomerID] ) AS [orderCount] FROM [dbo].[Customers] AS [t0]</pre> <p>To:</p> <pre>using (NorthwindContext northwind = new NorthwindContext ()) { var q = from row in northwind.Customers.With ( TableHint.NoLock, TableHint.Index (0)) let orderCount = row.Orders.With ( TableHint.HoldLock).Count () select new { row.ContactName, orderCount }; }</pre> <p>Which <em>would</em> result in the following TSQL:</p> <pre>SELECT [t0].[ContactName], ( SELECT COUNT(*) FROM [dbo].[Orders] AS [t1] WITH (HOLDLOCK) WHERE [t1].[CustomerID] = [t0].[CustomerID] ) AS [orderCount] FROM [dbo].[Customers] AS [t0] WITH (NOLOCK, INDEX(0))</pre> <p>Using:</p> <pre>public static Table&lt;TEntity&gt; With&lt;TEntity&gt; ( this Table&lt;TEntity&gt; table, params TableHint[] args) where TEntity : class { //TODO: implement return table; } public static EntitySet&lt;TEntity&gt; With&lt;TEntity&gt; ( this EntitySet&lt;TEntity&gt; entitySet, params TableHint[] args) where TEntity : class { //TODO: implement return entitySet; }</pre> <p>And</p> <pre> public class TableHint { //TODO: implement public static TableHint NoLock; public static TableHint HoldLock; public static TableHint Index (int id) { return null; } public static TableHint Index (string name) { return null; } }</pre> <p>Using some type of LINQ to SQL extensibility, other than <a href="http://blogs.msdn.com/mattwar/archive/2008/05/04/mocks-nix-an-extensible-linq-to-sql-datacontext.aspx" rel="noreferrer">this one</a>. Any ideas?</p>
[ { "answer_id": 64612, "author": "user8456", "author_id": 8456, "author_profile": "https://Stackoverflow.com/users/8456", "pm_score": -1, "selected": false, "text": "<p><code>DataContext x = new DataContext</code></p>\n\n<p>Something like this perhaps?</p>\n\n<p><code>var a = x.Where().with()</code>...etc </p>\n\n<p>It lets you have a much finer control over the SQL.</p>\n" }, { "answer_id": 67999, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 5, "selected": true, "text": "<p>The ability to change the underlying provider and thus modify the SQL did not make the final cut in LINQ to SQL.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5869/" ]
Last year, Scott Guthrie [stated](http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx) “You can actually override the raw SQL that LINQ to SQL uses if you want absolute control over the SQL executed”, but I can’t find documentation describing an extensibility method. I would like to modify the following LINQ to SQL query: ``` using (NorthwindContext northwind = new NorthwindContext ()) { var q = from row in northwind.Customers let orderCount = row.Orders.Count () select new { row.ContactName, orderCount }; } ``` Which results in the following TSQL: ``` SELECT [t0].[ContactName], ( SELECT COUNT(*) FROM [dbo].[Orders] AS [t1] WHERE [t1].[CustomerID] = [t0].[CustomerID] ) AS [orderCount] FROM [dbo].[Customers] AS [t0] ``` To: ``` using (NorthwindContext northwind = new NorthwindContext ()) { var q = from row in northwind.Customers.With ( TableHint.NoLock, TableHint.Index (0)) let orderCount = row.Orders.With ( TableHint.HoldLock).Count () select new { row.ContactName, orderCount }; } ``` Which *would* result in the following TSQL: ``` SELECT [t0].[ContactName], ( SELECT COUNT(*) FROM [dbo].[Orders] AS [t1] WITH (HOLDLOCK) WHERE [t1].[CustomerID] = [t0].[CustomerID] ) AS [orderCount] FROM [dbo].[Customers] AS [t0] WITH (NOLOCK, INDEX(0)) ``` Using: ``` public static Table<TEntity> With<TEntity> ( this Table<TEntity> table, params TableHint[] args) where TEntity : class { //TODO: implement return table; } public static EntitySet<TEntity> With<TEntity> ( this EntitySet<TEntity> entitySet, params TableHint[] args) where TEntity : class { //TODO: implement return entitySet; } ``` And ``` public class TableHint { //TODO: implement public static TableHint NoLock; public static TableHint HoldLock; public static TableHint Index (int id) { return null; } public static TableHint Index (string name) { return null; } } ``` Using some type of LINQ to SQL extensibility, other than [this one](http://blogs.msdn.com/mattwar/archive/2008/05/04/mocks-nix-an-extensible-linq-to-sql-datacontext.aspx). Any ideas?
The ability to change the underlying provider and thus modify the SQL did not make the final cut in LINQ to SQL.
62,987
<p>A project I'm working on at the moment involves refactoring a C# Com Object which serves as a database access layer to some Sql 2005 databases.</p> <p>The author of the existent code has built all the sql queries manually using a string and many if-statements to construct the fairly complex sql statement (~10 joins, >10 sub selects, ~15-25 where conditions and GroupBy's). The base table is always the same one, but the structure of joins, conditions and groupings depend on a set of parameters that are passed into my class/method.</p> <p>Constructing the sql query like this does work but it obviously isn't a very elegant solution (and rather hard to read/understand and maintain as well)... I could just write a simple "querybuilder" myself but I am pretty sure that I am not the first one with this kind of problem, hence my questions:</p> <ul> <li>How do <em>you</em> construct your database queries?</li> <li>Does C# offer an easy way to dynamically build queries?</li> </ul>
[ { "answer_id": 63009, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.google.com/search?q=dynamic+LINQ+tutorial\" rel=\"nofollow noreferrer\">LINQ</a> is the way to go.</p>\n" }, { "answer_id": 63013, "author": "Mike Becatti", "author_id": 6617, "author_profile": "https://Stackoverflow.com/users/6617", "pm_score": 0, "selected": false, "text": "<p>You may want to consider LINQ or an O/R Mapper like this one: <a href=\"http://www.llblgen.com/\" rel=\"nofollow noreferrer\">http://www.llblgen.com/</a> </p>\n" }, { "answer_id": 63725, "author": "sgwill", "author_id": 1204, "author_profile": "https://Stackoverflow.com/users/1204", "pm_score": 4, "selected": true, "text": "<p>I used C# and Linq to do something similar to get log entries filtered on user input (see <a href=\"https://stackoverflow.com/questions/11194/conditional-linq-queries\">Conditional Linq Queries</a>):</p>\n\n<pre><code>IQueryable&lt;Log&gt; matches = m_Locator.Logs;\n\n// Users filter\nif (usersFilter)\n matches = matches.Where(l =&gt; l.UserName == comboBoxUsers.Text);\n\n // Severity filter\n if (severityFilter)\n matches = matches.Where(l =&gt; l.Severity == comboBoxSeverity.Text);\n\n Logs = (from log in matches\n orderby log.EventTime descending\n select log).ToList();\n</code></pre>\n\n<p>Edit: The query isn't performed until .ToList() in the last statement.</p>\n" }, { "answer_id": 63802, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 1, "selected": false, "text": "<p>This is the way I'd do it:</p>\n\n<pre><code>public IQueryable&lt;ClientEntity&gt; GetClients(Expression&lt;Func&lt;ClientModel, bool&gt;&gt; criteria)\n {\n return (\n from model in Context.Client.AsExpandable()\n where criteria.Invoke(model)\n select new Ibfx.AppServer.Imsdb.Entities.Client.ClientEntity()\n {\n Id = model.Id,\n ClientNumber = model.ClientNumber,\n NameFirst = model.NameFirst,\n //more propertie here\n\n }\n );\n }\n</code></pre>\n\n<p>The <em>Expression</em> parameter you pass in will be the dynamic query you'll build with the different WHERE clauses, JOINS, etc. This Expression will get <em>Invoked</em> at run time and give you what you need.</p>\n\n<p>Here's a sample of how to call it:</p>\n\n<pre><code>public IQueryable&lt;ClientEntity&gt; GetClientsWithWebAccountId(int webAccountId)\n {\n var criteria = PredicateBuilder.True&lt;ClientModel&gt;();\n criteria = criteria.And(c =&gt; c.ClientWebAccount.WebAccountId.Equals(webAccountId));\n return GetClients(criteria);\n }\n</code></pre>\n" }, { "answer_id": 63907, "author": "rhys", "author_id": 7299, "author_profile": "https://Stackoverflow.com/users/7299", "pm_score": 1, "selected": false, "text": "<p>Its worth considering if you can implement as a parameterised strored procedure and optimise it in the database rather than dynamically generating the SQL via LINQ or an ORM at runtime. Often this will perform better. I know its a bit old fashioned but sometimes its the most effective approach.</p>\n" }, { "answer_id": 64034, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If using C# and .NET 3.5, with the addition of MS SQL Server then LINQ to SQL is definitely the way to go. If you are using anything other than that combination, I'd recommend an ORM route, such as <a href=\"http://sourceforge.net/projects/nhibernate\" rel=\"nofollow noreferrer\">nHibernate</a> or <a href=\"http://subsonicproject.com/\" rel=\"nofollow noreferrer\">Subsonic</a>.</p>\n" }, { "answer_id": 66524, "author": "Wiren", "author_id": 2538222, "author_profile": "https://Stackoverflow.com/users/2538222", "pm_score": 2, "selected": false, "text": "<p>Unless executiontime is really important, I would consider refactoring the business logic that (so often) tends to find its way down to the datalayer and into gazillion-long stored procs. In terms of maintainabillity, editabillity and appendabillity I always try to (as the C# programmer I am) lift code up to the businesslayer. </p>\n\n<p>Trying to sort out someone elses 8000 line SQL Script is not my favorite task.</p>\n\n<p>:)</p>\n\n<p>//W</p>\n" }, { "answer_id": 67815, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 1, "selected": false, "text": "<p>I understand the potential of Linq but I have yet to see anyone try and do a Linq query of the complexity that Ben is suggesting</p>\n\n<blockquote>\n <p>the fairly complex sql statement (~10 joins, >10 sub selects, ~15-25 where conditions and GroupBy's)</p>\n</blockquote>\n\n<p>Does anyone have examples of large Linq queries, and any commentary on their manageability?</p>\n" }, { "answer_id": 69818, "author": "KristoferA", "author_id": 11241, "author_profile": "https://Stackoverflow.com/users/11241", "pm_score": 1, "selected": false, "text": "<p>Linq to SQL together with System.Linq.Dynamic brings some nice possibilities.</p>\n\n<p>I have posted a couple of sample code snippets here:\n<a href=\"http://blog.huagati.com/res/index.php/2008/06/23/application-architecture-part-2-data-access-layer-dynamic-linq\" rel=\"nofollow noreferrer\">http://blog.huagati.com/res/index.php/2008/06/23/application-architecture-part-2-data-access-layer-dynamic-linq</a></p>\n\n<p>...and here:\n<a href=\"http://episteme.arstechnica.com/eve/forums/a/tpc/f/6330927813/m/717004553931?r=777003863931#777003863931\" rel=\"nofollow noreferrer\">http://episteme.arstechnica.com/eve/forums/a/tpc/f/6330927813/m/717004553931?r=777003863931#777003863931</a></p>\n" }, { "answer_id": 1954753, "author": "Patrick Karcher", "author_id": 97890, "author_profile": "https://Stackoverflow.com/users/97890", "pm_score": 1, "selected": false, "text": "<p>I'm coming at this late and have no chance for an upvote, but there's a great solution that I haven't seen considered: A combination of procedure/function with linq-to-object. Or to-xml or to-datatable I suppose.</p>\n\n<p>I've been this in this exact situation, with a massive dynamically built query that was kindof an impressive achievement, but the complexity of which made for an upkeep nightmare. I had so many green comments to help the poor sap who had to come along later and understand it. I was in classic asp so I had few alternatives.</p>\n\n<p>What I have done since is a combination of <strong>function/procedure and linq</strong>. Often the <em>total complexity</em> is less than the complexity of trying to do it one place. Pass some of the your criteria to the UDF, which becomes much more manageable. This gives you a manageable and understandable result-set. Apply your remaining distinctions using linq.</p>\n\n<p>You can use the advantages of both:</p>\n\n<ul>\n<li>Reduce the total records as much as\npossible on the server; get as many\ncrazy joins taken care of on the\nserver. Databases are <em>good</em> at this\nstuff.</li>\n<li>Linq (to object etc.) isn't as powerful but is great at expressing complex criteria; so use it for various possible distinctions that add complexity to the code but that the db wouldn't be much better at handling. Operating on a reduced, normalized result set, linq can express complixity without much performance penalty.</li>\n</ul>\n\n<p>How to decide which criteria to handle in the db and which with linq? Use your judgement. If you can efficiently handle complex db queries, you can handle this. Part art, part science.</p>\n" }, { "answer_id": 4824014, "author": "Jonathan Wood", "author_id": 522663, "author_profile": "https://Stackoverflow.com/users/522663", "pm_score": 0, "selected": false, "text": "<p>There a kind of experimental try at a QueryBuilder class at <a href=\"http://www.blackbeltcoder.com/Articles/strings/a-sql-querybuilder-class\" rel=\"nofollow\">http://www.blackbeltcoder.com/Articles/strings/a-sql-querybuilder-class</a>. Might be worth a look.</p>\n" }, { "answer_id": 5245399, "author": "Oleg", "author_id": 651485, "author_profile": "https://Stackoverflow.com/users/651485", "pm_score": 0, "selected": false, "text": "<p>Check out <a href=\"http://sqlom.sourceforge.net\" rel=\"nofollow\">http://sqlom.sourceforge.net</a>. I think it does exactly what you are looking for.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5005/" ]
A project I'm working on at the moment involves refactoring a C# Com Object which serves as a database access layer to some Sql 2005 databases. The author of the existent code has built all the sql queries manually using a string and many if-statements to construct the fairly complex sql statement (~10 joins, >10 sub selects, ~15-25 where conditions and GroupBy's). The base table is always the same one, but the structure of joins, conditions and groupings depend on a set of parameters that are passed into my class/method. Constructing the sql query like this does work but it obviously isn't a very elegant solution (and rather hard to read/understand and maintain as well)... I could just write a simple "querybuilder" myself but I am pretty sure that I am not the first one with this kind of problem, hence my questions: * How do *you* construct your database queries? * Does C# offer an easy way to dynamically build queries?
I used C# and Linq to do something similar to get log entries filtered on user input (see [Conditional Linq Queries](https://stackoverflow.com/questions/11194/conditional-linq-queries)): ``` IQueryable<Log> matches = m_Locator.Logs; // Users filter if (usersFilter) matches = matches.Where(l => l.UserName == comboBoxUsers.Text); // Severity filter if (severityFilter) matches = matches.Where(l => l.Severity == comboBoxSeverity.Text); Logs = (from log in matches orderby log.EventTime descending select log).ToList(); ``` Edit: The query isn't performed until .ToList() in the last statement.
62,995
<p>I am currently building in Version 3.5 of the .Net framework and I have a resource (.resx) file that I am trying to access in a web application. I have exposed the .resx properties as public access modifiers and am able to access these properties in the controller files or other .cs files in the web app. My question is this: Is it possible to access the name/value pairs within my view page? I'd like to do something like this...</p> <pre><code>text="&lt;%$ Resources: Namespace.ResourceFileName, NAME %&gt;" </code></pre> <p>or some other similar method in the view page.</p>
[ { "answer_id": 63062, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": 2, "selected": false, "text": "<p>Expose the resource property you want to consume in the page as a protected page property. Then you can just do use \"this.ResourceName\"</p>\n" }, { "answer_id": 63083, "author": "Mike Becatti", "author_id": 6617, "author_profile": "https://Stackoverflow.com/users/6617", "pm_score": 4, "selected": true, "text": "\n\n<pre class=\"lang-cs prettyprint-override\"><code>&lt;%= Resources.&lt;ResourceName&gt;.&lt;Property&gt; %&gt;\n</code></pre>\n" }, { "answer_id": 63328, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 1, "selected": false, "text": "<p>If you are using ASP.NET 2.0 or higher, after you compile with the resource file, you can reference it through the Resources namespace:</p>\n\n<pre><code>text = Resources.YourResourceFilename.YourProperty;\n</code></pre>\n\n<p>You even get Intellisense on the filenames and properties.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/62995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7215/" ]
I am currently building in Version 3.5 of the .Net framework and I have a resource (.resx) file that I am trying to access in a web application. I have exposed the .resx properties as public access modifiers and am able to access these properties in the controller files or other .cs files in the web app. My question is this: Is it possible to access the name/value pairs within my view page? I'd like to do something like this... ``` text="<%$ Resources: Namespace.ResourceFileName, NAME %>" ``` or some other similar method in the view page.
```cs <%= Resources.<ResourceName>.<Property> %> ```
63,008
<p>I'm writing a C# application which downloads a compressed database backup via FTP. The application then needs to extract the backup and restore it to the default database location.</p> <p>I will not know which version of SQL Server will be installed on the machine where the application runs. Therefore, I need to find the default location based on the instance name (which is in the config file).</p> <p>The examples I found all had a registry key which they read, but this will not work, since this assumes that only one instance of SQL is installed.</p> <p>Another example I found created a database, read that database's file properties, the deleting the database once it was done. That's just cumbersome.</p> <p>I did find something in the .NET framework which should work, ie:</p> <p><pre><code>Microsoft.SqlServer.Management.Smo.Server(ServerName).Settings.DefaultFile</code></pre></p> <p>The problem is that this is returning empty strings, which does not help.</p> <p>I also need to find out the NT account under which the SQL service is running, so that I can grant read access to that user on the backup file once I have the it extracted.</p>
[ { "answer_id": 63200, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 1, "selected": false, "text": "<p>One option, that may be a simpler solution, is to create a new database on your destination server and then RESTORE over that database with your backup. Your backup will be in the right place and you will not have to fuss with \"MOVING\" the backup file when you restore it. SQL expects backups to be restored to exactly the same physical path that they were backed up from. If that is not the case you have to use the MOVE option during RESTORE.\nThis solution also makes it easier to rename the database in the process if, for example, you want to tack a date onto the name.</p>\n" }, { "answer_id": 63273, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 2, "selected": false, "text": "<p>One way would be to use the same location as the master database. You can query the SQL Server instance for that with the following SQL:</p>\n\n<pre><code>select filename from master.dbo.sysdatabases where name = 'master'\n</code></pre>\n\n<p>That will return the full path of the master database. With that path, you can use the FileInfo object to extract the just the directory portion of that path. That avoids the guess work of checking the registry for the instance of SQL Server that you are trying to connect to.</p>\n" }, { "answer_id": 119735, "author": "Richard C", "author_id": 6389, "author_profile": "https://Stackoverflow.com/users/6389", "pm_score": 4, "selected": true, "text": "<p>What I discovered is that </p>\n\n<pre><code>Microsoft.SqlServer.Management.Smo.Server(ServerName).Settings.DefaultFile\n</code></pre>\n\n<p>only returns non-null when there is no path explicitly defined. As soon as you specify a path which is not the default, then this function returns that path correctly.</p>\n\n<p>So, a simple workaround was to check whether this function returns a string, or null. If it returns a string, then use that, but if it's null, use</p>\n\n<pre><code>Microsoft.SqlServer.Management.Smo.Server(ServerName).Information.RootDirectory + \"\\\\DATA\\\\\"\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6389/" ]
I'm writing a C# application which downloads a compressed database backup via FTP. The application then needs to extract the backup and restore it to the default database location. I will not know which version of SQL Server will be installed on the machine where the application runs. Therefore, I need to find the default location based on the instance name (which is in the config file). The examples I found all had a registry key which they read, but this will not work, since this assumes that only one instance of SQL is installed. Another example I found created a database, read that database's file properties, the deleting the database once it was done. That's just cumbersome. I did find something in the .NET framework which should work, ie: ``` Microsoft.SqlServer.Management.Smo.Server(ServerName).Settings.DefaultFile ``` The problem is that this is returning empty strings, which does not help. I also need to find out the NT account under which the SQL service is running, so that I can grant read access to that user on the backup file once I have the it extracted.
What I discovered is that ``` Microsoft.SqlServer.Management.Smo.Server(ServerName).Settings.DefaultFile ``` only returns non-null when there is no path explicitly defined. As soon as you specify a path which is not the default, then this function returns that path correctly. So, a simple workaround was to check whether this function returns a string, or null. If it returns a string, then use that, but if it's null, use ``` Microsoft.SqlServer.Management.Smo.Server(ServerName).Information.RootDirectory + "\\DATA\\" ```
63,011
<p>I'm displaying a set of images as an overlay using Google Maps. Displaying these images should be in an endless loop but most most browsers detect this, and display a warning. </p> <p>Is there a way to make a endless loop in JavaScript so that it isn't stopped or warned against by the browser?</p>
[ { "answer_id": 63039, "author": "Erik", "author_id": 6733, "author_profile": "https://Stackoverflow.com/users/6733", "pm_score": 4, "selected": true, "text": "<p>Try <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval\" rel=\"nofollow noreferrer\">setInterval</a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/settimeout\" rel=\"nofollow noreferrer\">setTimeout</a>.</p>\n\n<p>Here is an example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(show = (o) =&gt; setTimeout(() =&gt; {\r\n\r\n console.log(o)\r\n show(++o)\r\n\r\n}, 1000))(1);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 63047, "author": "Crippledsmurf", "author_id": 35031, "author_profile": "https://Stackoverflow.com/users/35031", "pm_score": 0, "selected": false, "text": "<p>Perhaps try using a timer which retrieves the next image each time it ticks, unfortunately i don't know any JavaScript so I can't provide a code sample</p>\n" }, { "answer_id": 63050, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>You should use a timer to continuously bring new images instead of an infinite loop. Check the <code>setTimeout()</code> function. The caveat is that you should call it in a function that calls itself, for it to wait again. Example taken from <a href=\"http://www.w3schools.com/js/js_timing.asp\" rel=\"nofollow noreferrer\">w3schools</a>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var c = 0\r\nvar t;\r\n\r\nfunction timedCount() {\r\n document.getElementById('txt').value = c;\r\n c = c + 1;\r\n t = setTimeout(\"timedCount()\", 1000);\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;form&gt;\r\n &lt;input type=\"button\" value=\"Start count!\" onClick=\"timedCount()\"&gt;\r\n &lt;input type=\"text\" id=\"txt\"&gt;\r\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 63057, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 1, "selected": false, "text": "<p>Instead of using an infinite loop, make a timer that keeps firing every n seconds - you'll get the 'run forever' aspect without the browser hang.</p>\n" }, { "answer_id": 63080, "author": "Wyatt", "author_id": 6886, "author_profile": "https://Stackoverflow.com/users/6886", "pm_score": 0, "selected": false, "text": "<pre><code>function foo() {\n alert('hi');\n setTimeout(foo, 5000);\n}\n</code></pre>\n\n<p>Then just use an action like \"onload\" to kick off 'foo'</p>\n" }, { "answer_id": 63096, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 2, "selected": false, "text": "<p>The following code will set an interval and set the image to the next image from an array of image sources every second.</p>\n\n<pre><code>function setImage(){\n var Static = arguments.callee;\n Static.currentImage = (Static.currentImage || 0);\n var elm = document.getElementById(\"imageContainer\");\n elm.src = imageArray[Static.currentImage++];\n}\nimageInterval = setInterval(setImage, 1000);\n</code></pre>\n" }, { "answer_id": 63168, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If it fits your case, you can keep loading new images to respond to user interaction, like <a href=\"http://flickriver.com/photos\" rel=\"nofollow noreferrer\">this website does</a> (just scroll down).</p>\n" }, { "answer_id": 64520, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 0, "selected": false, "text": "<p>Just a formal answer:</p>\n\n<pre><code>var i = 0;\n\nwhile (i &lt; 1) {\n do something...\n\n if (i &lt; 1) i = 0;\n else i = fooling_function(i); // must return 0\n}\n</code></pre>\n\n<p>I think no browser would detect such things. </p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7417/" ]
I'm displaying a set of images as an overlay using Google Maps. Displaying these images should be in an endless loop but most most browsers detect this, and display a warning. Is there a way to make a endless loop in JavaScript so that it isn't stopped or warned against by the browser?
Try [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) or [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/settimeout). Here is an example: ```js (show = (o) => setTimeout(() => { console.log(o) show(++o) }, 1000))(1); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
63,043
<p>Has anybody got this to actually work? Documentation is non existent on how to enable this feature and I get missing attribute exceptions despite having a 3.5 SP1 project. </p>
[ { "answer_id": 63554, "author": "Doanair", "author_id": 4774, "author_profile": "https://Stackoverflow.com/users/4774", "pm_score": 0, "selected": false, "text": "<p>There are several serialization options in WCF: Data contract, XML Serialization and and raw data payload. Which of these are you trying to use? From the question, it seems you are trying to use something other than objects decorated with datacontact attributes. Is that what you are asking?</p>\n" }, { "answer_id": 63598, "author": "user7375", "author_id": 7375, "author_profile": "https://Stackoverflow.com/users/7375", "pm_score": 0, "selected": false, "text": "<p>Yes, I am attempting to use the attribute free serialization that was announced as part of SP1 (<a href=\"http://www.pluralsight.com/community/blogs/aaron/archive/2008/05/13/50934.aspx\" rel=\"nofollow noreferrer\">http://www.pluralsight.com/community/blogs/aaron/archive/2008/05/13/50934.aspx</a>). Damned if I can get it to work and there's no documentation for it.</p>\n" }, { "answer_id": 63788, "author": "Doanair", "author_id": 4774, "author_profile": "https://Stackoverflow.com/users/4774", "pm_score": 1, "selected": false, "text": "<p>I got this to work on a test app just fine... </p>\n\n<p>Service Definition:</p>\n\n<pre><code>[ServiceContract]\npublic interface IService1\n{\n\n [OperationContract]\n CompositeType GetData(int value);\n\n}\n\n\npublic class CompositeType\n{\n bool boolValue = true;\n string stringValue = \"Hello \";\n\n public bool BoolValue\n {\n get { return boolValue; }\n set { boolValue = value; }\n }\n\n public string StringValue\n {\n get { return stringValue; }\n set { stringValue = value; }\n }\n}\n</code></pre>\n\n<p>Service Implementation:</p>\n\n<pre><code>public class Service1 : IService1\n{\n public CompositeType GetData(int value)\n {\n return new CompositeType()\n {\n BoolValue = true,\n StringValue = value.ToString()\n };\n }\n\n}\n</code></pre>\n" }, { "answer_id": 63828, "author": "user7375", "author_id": 7375, "author_profile": "https://Stackoverflow.com/users/7375", "pm_score": 0, "selected": false, "text": "<p>Possibly my use of abstract base classes is confusing the matter, though I am adding everything into the known types list. </p>\n" }, { "answer_id": 74263, "author": "Doanair", "author_id": 4774, "author_profile": "https://Stackoverflow.com/users/4774", "pm_score": 0, "selected": false, "text": "<p>Yes, it could have to do with abstract classes and inheritance. It sometimes can mess with serialization. Also, it could be visibility of the classes and class hierarchy as well if everything is not public.</p>\n" }, { "answer_id": 472236, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>I found that it doesn't work with internal/private types, but making my type public it worked fine. This means no anonymous types either :(</p>\n\n<p>Using reflector I found the method ClassDataContract.IsNonAttributedTypeValidForSerialization(Type) that seems to make the decision. It's the last line that seems to be the killer, the type must be visible, so no internal/private types allowed :(</p>\n\n<pre><code>internal static bool IsNonAttributedTypeValidForSerialization(Type type)\n{\n if (type.IsArray)\n {\n return false;\n }\n if (type.IsEnum)\n {\n return false;\n }\n if (type.IsGenericParameter)\n {\n return false;\n }\n if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))\n {\n return false;\n }\n if (type.IsPointer)\n {\n return false;\n }\n if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))\n {\n return false;\n }\n foreach (Type type2 in type.GetInterfaces())\n {\n if (CollectionDataContract.IsCollectionInterface(type2))\n {\n return false;\n }\n }\n if (type.IsSerializable)\n {\n return false;\n }\n if (Globals.TypeOfISerializable.IsAssignableFrom(type))\n {\n return false;\n }\n if (type.IsDefined(Globals.TypeOfDataContractAttribute, false))\n {\n return false;\n }\n if (type == Globals.TypeOfExtensionDataObject)\n {\n return false;\n }\n if (type.IsValueType)\n {\n return type.IsVisible;\n }\n return (type.IsVisible &amp;&amp; (type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, Globals.EmptyTypeArray, null) != null));\n</code></pre>\n\n<p>}</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7375/" ]
Has anybody got this to actually work? Documentation is non existent on how to enable this feature and I get missing attribute exceptions despite having a 3.5 SP1 project.
I found that it doesn't work with internal/private types, but making my type public it worked fine. This means no anonymous types either :( Using reflector I found the method ClassDataContract.IsNonAttributedTypeValidForSerialization(Type) that seems to make the decision. It's the last line that seems to be the killer, the type must be visible, so no internal/private types allowed :( ``` internal static bool IsNonAttributedTypeValidForSerialization(Type type) { if (type.IsArray) { return false; } if (type.IsEnum) { return false; } if (type.IsGenericParameter) { return false; } if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { return false; } if (type.IsPointer) { return false; } if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) { return false; } foreach (Type type2 in type.GetInterfaces()) { if (CollectionDataContract.IsCollectionInterface(type2)) { return false; } } if (type.IsSerializable) { return false; } if (Globals.TypeOfISerializable.IsAssignableFrom(type)) { return false; } if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) { return false; } if (type == Globals.TypeOfExtensionDataObject) { return false; } if (type.IsValueType) { return type.IsVisible; } return (type.IsVisible && (type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, Globals.EmptyTypeArray, null) != null)); ``` }
63,067
<p>We have to connect to a third party SOAP service and we are using WCF to do so. The service was developed using Apache AXIS, and we have no control over it, and have no influence to change how it works. The problem we are seeing is that it expects the requests to be formatted using Web Services Security, so we are doing all the correct signing, etc. The response from the 3rd party however, is not secured. If we sniff the wire, we see the response coming back fine (albeit without any timestamp, signature etc.). The underlying .NET components throw this as an error because it sees it as a security issue, so we don't actually receive the soap response as such. Is there any way to configure the WCF framework for sending secure requests, but not to expect security fields in the response? Looking at the OASIS specs, it doesn't appear to mandate that the responses must be secure.</p> <p>For information, here's the exception we see:</p> <p>The exception we receive is:</p> <pre><code>System.ServiceModel.Security.MessageSecurityException was caught Message="Security processor was unable to find a security header in the message. This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security." Source="mscorlib" StackTrace: Server stack trace: at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(Message&amp; message, TimeSpan timeout) at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(Message&amp; message, TimeSpan timeout) at System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(Message&amp; message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates) at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout) at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) </code></pre> <p>Incidentally, I've seen plenty of posts stating that if you leave the timestamp out, then the security fields will not be expected. This is not an option - The service we are communicating with mandates timestamps. </p>
[ { "answer_id": 63651, "author": "Doanair", "author_id": 4774, "author_profile": "https://Stackoverflow.com/users/4774", "pm_score": 2, "selected": false, "text": "<p>Funny you should ask this question. I asked Microsoft how to do this about a year ago. At the time, using .NET 3.0, it was not possible. Not sure if that changed in the 3.5 world. But, no, there was no physical way of adding security to the request and leaving the response empty.</p>\n\n<p>At my previous employer we used a model that required a WS-Security header using certificates on the request but the response was left unsecured.</p>\n\n<p>You can do this with ASMX web services and WSE, but not with WCF v3.0.</p>\n" }, { "answer_id": 63656, "author": "user8032", "author_id": 8032, "author_profile": "https://Stackoverflow.com/users/8032", "pm_score": 2, "selected": false, "text": "<p>There is a good chance you will not be able to get away with configuration alone. I had to do some integration work with Axxis (our end was WSE3 -- WCF's ancestor), and I had to write some code and stick it into WSE3's pipeline to massage the response from Axxis before passing it over to WSE3. The good news is that adding these handlers to the pipeline is fairly straightforward, and once in the handler, you just get an instance of a SoapMessage, and can do anything you want with it (like removing the timestamp, for example)</p>\n" }, { "answer_id": 1105612, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Microsoft has a hotfix for this functionality now.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/971493\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/971493</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We have to connect to a third party SOAP service and we are using WCF to do so. The service was developed using Apache AXIS, and we have no control over it, and have no influence to change how it works. The problem we are seeing is that it expects the requests to be formatted using Web Services Security, so we are doing all the correct signing, etc. The response from the 3rd party however, is not secured. If we sniff the wire, we see the response coming back fine (albeit without any timestamp, signature etc.). The underlying .NET components throw this as an error because it sees it as a security issue, so we don't actually receive the soap response as such. Is there any way to configure the WCF framework for sending secure requests, but not to expect security fields in the response? Looking at the OASIS specs, it doesn't appear to mandate that the responses must be secure. For information, here's the exception we see: The exception we receive is: ``` System.ServiceModel.Security.MessageSecurityException was caught Message="Security processor was unable to find a security header in the message. This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security." Source="mscorlib" StackTrace: Server stack trace: at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessageCore(Message& message, TimeSpan timeout) at System.ServiceModel.Security.TransportSecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout) at System.ServiceModel.Security.SecurityProtocol.VerifyIncomingMessage(Message& message, TimeSpan timeout, SecurityProtocolCorrelationState[] correlationStates) at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout) at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) ``` Incidentally, I've seen plenty of posts stating that if you leave the timestamp out, then the security fields will not be expected. This is not an option - The service we are communicating with mandates timestamps.
Funny you should ask this question. I asked Microsoft how to do this about a year ago. At the time, using .NET 3.0, it was not possible. Not sure if that changed in the 3.5 world. But, no, there was no physical way of adding security to the request and leaving the response empty. At my previous employer we used a model that required a WS-Security header using certificates on the request but the response was left unsecured. You can do this with ASMX web services and WSE, but not with WCF v3.0.
63,104
<p>When a previous Vim session crashed, you are greeted with the "Swap file ... already exists!" for each and every file that was open in the previous session.</p> <p>Can you make this Vim recovery prompt smarter? (Without switching off recovery!) Specifically, I'm thinking of:</p> <ul> <li>If the swapped version does not contain unsaved changes and the editing process is no longer running, can you make Vim automatically delete the swap file?</li> <li>Can you automate the suggested process of saving the recovered file under a new name, merging it with file on disk and then deleting the old swap file, so that minimal interaction is required? Especially when the swap version and the disk version are the same, everything should be automatic.</li> </ul> <p>I discovered the <code>SwapExists</code> autocommand but I don't know if it can help with these tasks.</p>
[ { "answer_id": 63341, "author": "Chouser", "author_id": 7624, "author_profile": "https://Stackoverflow.com/users/7624", "pm_score": 6, "selected": true, "text": "<p>I have vim store my swap files in a single local directory, by having this in my .vimrc:</p>\n\n<pre><code>set directory=~/.vim/swap,.\n</code></pre>\n\n<p>Among other benefits, this makes the swap files easy to find all at once.\nNow when my laptop loses power or whatever and I start back up with a bunch of swap files laying around, I just run my <code>cleanswap</code> script:</p>\n\n<pre><code>TMPDIR=$(mktemp -d) || exit 1\nRECTXT=\"$TMPDIR/vim.recovery.$USER.txt\"\nRECFN=\"$TMPDIR/vim.recovery.$USER.fn\"\ntrap 'rm -f \"$RECTXT\" \"$RECFN\"; rmdir \"$TMPDIR\"' 0 1 2 3 15\nfor q in ~/.vim/swap/.*sw? ~/.vim/swap/*; do\n [[ -f $q ]] || continue\n rm -f \"$RECTXT\" \"$RECFN\"\n vim -X -r \"$q\" \\\n -c \"w! $RECTXT\" \\\n -c \"let fn=expand('%')\" \\\n -c \"new $RECFN\" \\\n -c \"exec setline( 1, fn )\" \\\n -c w\\! \\\n -c \"qa\"\n if [[ ! -f $RECFN ]]; then\n echo \"nothing to recover from $q\"\n rm -f \"$q\"\n continue\n fi\n CRNT=\"$(cat $RECFN)\"\n if diff --strip-trailing-cr --brief \"$CRNT\" \"$RECTXT\"; then\n echo \"removing redundant $q\"\n echo \" for $CRNT\"\n rm -f \"$q\"\n else\n echo $q contains changes\n vim -n -d \"$CRNT\" \"$RECTXT\"\n rm -i \"$q\" || exit\n fi\ndone\n</code></pre>\n\n<p>This will remove any swap files that are up-to-date with the real files. Any that don't match are brought up in a vimdiff window so I can merge in my unsaved changes.</p>\n\n<p>--Chouser</p>\n" }, { "answer_id": 220543, "author": "Jack Senechal", "author_id": 29833, "author_profile": "https://Stackoverflow.com/users/29833", "pm_score": 5, "selected": false, "text": "<p>I just discovered this:</p>\n\n<p><a href=\"http://vimdoc.sourceforge.net/htmldoc/diff.html#:DiffOrig\" rel=\"noreferrer\">http://vimdoc.sourceforge.net/htmldoc/diff.html#:DiffOrig</a></p>\n\n<p>I copied and pasted the DiffOrig command into my .vimrc file and it works like a charm. This greatly eases the recovery of swap files. I have no idea why it isn't included by default in VIM.</p>\n\n<p>Here's the command for those who are in a hurry:</p>\n\n<pre><code> command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis\n \\ | wincmd p | diffthis\n</code></pre>\n" }, { "answer_id": 784372, "author": "Mark Grimes", "author_id": 13233, "author_profile": "https://Stackoverflow.com/users/13233", "pm_score": 2, "selected": false, "text": "<p>Great tip DiffOrig is perfect. Here is a bash script I use to run it on each swap file under the current directory:</p>\n\n<pre><code>#!/bin/bash\n\nswap_files=`find . -name \"*.swp\"`\n\nfor s in $swap_files ; do\n orig_file=`echo $s | perl -pe 's!/\\.([^/]*).swp$!/$1!' `\n echo \"Editing $orig_file\"\n sleep 1\n vim -r $orig_file -c \"DiffOrig\"\n echo -n \" Ok to delete swap file? [y/n] \"\n read resp\n if [ \"$resp\" == \"y\" ] ; then\n echo \" Deleting $s\"\n rm $s\n fi\ndone\n</code></pre>\n\n<p>Probably could use some more error checking and quoting but has worked so far.</p>\n" }, { "answer_id": 5826793, "author": "coppit", "author_id": 730300, "author_profile": "https://Stackoverflow.com/users/730300", "pm_score": 4, "selected": false, "text": "<p>The accepted answer is busted for a very important use case. Let's say you create a new buffer and type for 2 hours without ever saving, then your laptop crashes. If you run the suggested script <strong>it will delete your one and only record, the .swp swap file</strong>. I'm not sure what the right fix is, but it looks like the diff command ends up comparing the same file to itself in this case. The edited version below checks for this case and gives the user a chance to save the file somewhere.</p>\n\n<pre><code>#!/bin/bash\n\nSWAP_FILE_DIR=~/temp/vim_swp\nIFS=$'\\n'\n\nTMPDIR=$(mktemp -d) || exit 1\nRECTXT=\"$TMPDIR/vim.recovery.$USER.txt\"\nRECFN=\"$TMPDIR/vim.recovery.$USER.fn\"\ntrap 'rm -f \"$RECTXT\" \"$RECFN\"; rmdir \"$TMPDIR\"' 0 1 2 3 15\nfor q in $SWAP_FILE_DIR/.*sw? $SWAP_FILE_DIR/*; do\n echo $q\n [[ -f $q ]] || continue\n rm -f \"$RECTXT\" \"$RECFN\"\n vim -X -r \"$q\" \\\n -c \"w! $RECTXT\" \\\n -c \"let fn=expand('%')\" \\\n -c \"new $RECFN\" \\\n -c \"exec setline( 1, fn )\" \\\n -c w\\! \\\n -c \"qa\"\n if [[ ! -f $RECFN ]]; then\n echo \"nothing to recover from $q\"\n rm -f \"$q\"\n continue\n fi\n CRNT=\"$(cat $RECFN)\"\n if [ \"$CRNT\" = \"$RECTXT\" ]; then\n echo \"Can't find original file. Press enter to open vim so you can save the file. The swap file will be deleted afterward!\"\n read\n vim \"$CRNT\"\n rm -f \"$q\"\n else if diff --strip-trailing-cr --brief \"$CRNT\" \"$RECTXT\"; then\n echo \"Removing redundant $q\"\n echo \" for $CRNT\"\n rm -f \"$q\"\n else\n echo $q contains changes, or there may be no original saved file\n vim -n -d \"$CRNT\" \"$RECTXT\"\n rm -i \"$q\" || exit\n fi\n fi\ndone\n</code></pre>\n" }, { "answer_id": 16742978, "author": "Mario Aguilera", "author_id": 289870, "author_profile": "https://Stackoverflow.com/users/289870", "pm_score": 0, "selected": false, "text": "<p>I prefer to not set my VIM working directory in the .vimrc. Here's a modification of chouser's script that copies the swap files to the swap path on demand checking for duplicates and then reconciles them. This was written rushed, make sure to evaluate it before putting it to practical use.</p>\n\n<pre><code>#!/bin/bash\n\nif [[ \"$1\" == \"-h\" ]] || [[ \"$1\" == \"--help\" ]]; then\n echo \"Moves VIM swap files under &lt;base-path&gt; to ~/.vim/swap and reconciles differences\"\n echo \"usage: $0 &lt;base-path&gt;\"\n exit 0\nfi\n\nif [ -z \"$1\" ] || [ ! -d \"$1\" ]; then\n echo \"directory path not provided or invalid, see $0 -h\"\n exit 1\nfi\n\necho looking for duplicate file names in hierarchy\nswaps=\"$(find $1 -name '.*.swp' | while read file; do echo $(basename $file); done | sort | uniq -c | egrep -v \"^[[:space:]]*1\")\"\nif [ -z \"$swaps\" ]; then\n echo no duplicates found\n files=$(find $1 -name '.*.swp')\n if [ ! -d ~/.vim/swap ]; then mkdir ~/.vim/swap; fi\n echo \"moving files to swap space ~./vim/swap\"\n mv $files ~/.vim/swap\n echo \"executing reconciliation\"\n TMPDIR=$(mktemp -d) || exit 1\n RECTXT=\"$TMPDIR/vim.recovery.$USER.txt\"\n RECFN=\"$TMPDIR/vim.recovery.$USER.fn\"\n trap 'rm -f \"$RECTXT\" \"$RECFN\"; rmdir \"$TMPDIR\"' 0 1 2 3 15\n for q in ~/.vim/swap/.*sw? ~/.vim/swap/*; do\n [[ -f $q ]] || continue\n rm -f \"$RECTXT\" \"$RECFN\"\n vim -X -r \"$q\" \\\n -c \"w! $RECTXT\" \\\n -c \"let fn=expand('%')\" \\\n -c \"new $RECFN\" \\\n -c \"exec setline( 1, fn )\" \\\n -c w\\! \\\n -c \"qa\"\n if [[ ! -f $RECFN ]]; then\n echo \"nothing to recover from $q\"\n rm -f \"$q\"\n continue\n fi\n CRNT=\"$(cat $RECFN)\"\n if diff --strip-trailing-cr --brief \"$CRNT\" \"$RECTXT\"; then\n echo \"removing redundant $q\"\n echo \" for $CRNT\"\n rm -f \"$q\"\n else\n echo $q contains changes\n vim -n -d \"$CRNT\" \"$RECTXT\"\n rm -i \"$q\" || exit\n fi\n done\nelse\n echo duplicates found, please address their swap reconciliation manually:\n find $1 -name '.*.swp' | while read file; do echo $(basename $file); done | sort | uniq -c | egrep '^[[:space:]]*[2-9][0-9]*.*'\nfi\n</code></pre>\n" }, { "answer_id": 23016290, "author": "Miguel", "author_id": 2773308, "author_profile": "https://Stackoverflow.com/users/2773308", "pm_score": 0, "selected": false, "text": "<p>I have this on my .bashrc file. I would like to give appropriate credit to part of this code but I forgot where I got it from.</p>\n\n<pre><code>mswpclean(){\n\nfor i in `find -L -name '*swp'`\ndo\n swpf=$i\n aux=${swpf//\"/.\"/\"/\"}\n orif=${aux//.swp/}\n bakf=${aux//.swp/.sbak}\n\n vim -r $swpf -c \":wq! $bakf\" &amp;&amp; rm $swpf\n if cmp \"$bakf\" \"$orif\" -s\n then rm $bakf &amp;&amp; echo \"Swap file was not different: Deleted\" $swpf\n else vimdiff $bakf $orif\n fi\ndone\n\nfor i in `find -L -name '*sbak'`\ndo\n bakf=$i\n orif=${bakf//.sbak/}\n if test $orif -nt $bakf\n then rm $bakf &amp;&amp; echo \"Backup file deleted:\" $bakf\n else echo \"Backup file kept as:\" $bakf\n fi\ndone }\n</code></pre>\n\n<p>I just run this on the root of my project and, IF the file is different, it opens vim diff. Then, the last file to be saved will be kept. To make it perfect I would just need to replace the last else:</p>\n\n<pre><code>else echo \"Backup file kept as:\" $bakf\n</code></pre>\n\n<p>by something like</p>\n\n<pre><code>else vim $bakf -c \":wq! $orif\" &amp;&amp; echo \"Backup file kept and saved as:\" $orif\n</code></pre>\n\n<p>but I didn't get time to properly test it.</p>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 39894423, "author": "user3386050", "author_id": 3386050, "author_profile": "https://Stackoverflow.com/users/3386050", "pm_score": 0, "selected": false, "text": "<p>find ./ -type f -name \".*sw[klmnop]\" -delete</p>\n\n<p>Credit: @Shwaydogg\n<a href=\"https://superuser.com/questions/480367/whats-the-easiest-way-to-delete-vim-swapfiles-ive-already-recovered-from\">https://superuser.com/questions/480367/whats-the-easiest-way-to-delete-vim-swapfiles-ive-already-recovered-from</a></p>\n\n<p>Navigate to directory first</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6918/" ]
When a previous Vim session crashed, you are greeted with the "Swap file ... already exists!" for each and every file that was open in the previous session. Can you make this Vim recovery prompt smarter? (Without switching off recovery!) Specifically, I'm thinking of: * If the swapped version does not contain unsaved changes and the editing process is no longer running, can you make Vim automatically delete the swap file? * Can you automate the suggested process of saving the recovered file under a new name, merging it with file on disk and then deleting the old swap file, so that minimal interaction is required? Especially when the swap version and the disk version are the same, everything should be automatic. I discovered the `SwapExists` autocommand but I don't know if it can help with these tasks.
I have vim store my swap files in a single local directory, by having this in my .vimrc: ``` set directory=~/.vim/swap,. ``` Among other benefits, this makes the swap files easy to find all at once. Now when my laptop loses power or whatever and I start back up with a bunch of swap files laying around, I just run my `cleanswap` script: ``` TMPDIR=$(mktemp -d) || exit 1 RECTXT="$TMPDIR/vim.recovery.$USER.txt" RECFN="$TMPDIR/vim.recovery.$USER.fn" trap 'rm -f "$RECTXT" "$RECFN"; rmdir "$TMPDIR"' 0 1 2 3 15 for q in ~/.vim/swap/.*sw? ~/.vim/swap/*; do [[ -f $q ]] || continue rm -f "$RECTXT" "$RECFN" vim -X -r "$q" \ -c "w! $RECTXT" \ -c "let fn=expand('%')" \ -c "new $RECFN" \ -c "exec setline( 1, fn )" \ -c w\! \ -c "qa" if [[ ! -f $RECFN ]]; then echo "nothing to recover from $q" rm -f "$q" continue fi CRNT="$(cat $RECFN)" if diff --strip-trailing-cr --brief "$CRNT" "$RECTXT"; then echo "removing redundant $q" echo " for $CRNT" rm -f "$q" else echo $q contains changes vim -n -d "$CRNT" "$RECTXT" rm -i "$q" || exit fi done ``` This will remove any swap files that are up-to-date with the real files. Any that don't match are brought up in a vimdiff window so I can merge in my unsaved changes. --Chouser
63,150
<p>While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:</p> <pre><code>public String appendWithDelimiter( String original, String addition, String delimiter ) { if ( original.equals( "" ) ) { return addition; } else { return original + delimiter + addition; } } String parameterString = ""; if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," ); if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," ); </code></pre> <p>I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.</p> <p>In Ruby, I can do something like this instead, which feels much more elegant:</p> <pre><code>parameterArray = []; parameterArray &lt;&lt; "elementName" if condition; parameterArray &lt;&lt; "anotherElementName" if anotherCondition; parameterString = parameterArray.join(","); </code></pre> <p>But since Java lacks a join command, I couldn't figure out anything equivalent.</p> <p>So, what's the best way to do this in Java?</p>
[ { "answer_id": 63173, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 4, "selected": false, "text": "<p>Use an approach based on <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html\" rel=\"noreferrer\"><code>java.lang.StringBuilder</code></a>! (\"A mutable sequence of characters. \")</p>\n\n<p>Like you mentioned, all those string concatenations are creating Strings all over. <code>StringBuilder</code> won't do that.</p>\n\n<p>Why <code>StringBuilder</code> instead of <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html\" rel=\"noreferrer\"><code>StringBuffer</code></a>? From the <code>StringBuilder</code> javadoc:</p>\n\n<blockquote>\n <p>Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations. </p>\n</blockquote>\n" }, { "answer_id": 63186, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 2, "selected": false, "text": "<p>You can use Java's <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html\" rel=\"nofollow noreferrer\"><code>StringBuilder</code></a> type for this. There's also <code>StringBuffer</code>, but it contains extra thread safety logic that is often unnecessary.</p>\n" }, { "answer_id": 63191, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 2, "selected": false, "text": "<p>Why not write your own join() method? It would take as parameters collection of Strings and a delimiter String. Within the method iterate over the collection and build up your result in a StringBuffer.</p>\n" }, { "answer_id": 63201, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": false, "text": "<p>You can generalize it, but there's no join in Java, as you well say.</p>\n\n<p><a href=\"http://snippets.dzone.com/posts/show/91\" rel=\"noreferrer\">This</a> might work better. </p>\n\n<pre><code>public static String join(Iterable&lt;? extends CharSequence&gt; s, String delimiter) {\n Iterator&lt;? extends CharSequence&gt; iter = s.iterator();\n if (!iter.hasNext()) return \"\";\n StringBuilder buffer = new StringBuilder(iter.next());\n while (iter.hasNext()) buffer.append(delimiter).append(iter.next());\n return buffer.toString();\n}\n</code></pre>\n" }, { "answer_id": 63217, "author": "martinatime", "author_id": 1353, "author_profile": "https://Stackoverflow.com/users/1353", "pm_score": 0, "selected": false, "text": "<p>You can try something like this:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nif (condition) { sb.append(\"elementName\").append(\",\"); }\nif (anotherCondition) { sb.append(\"anotherElementName\").append(\",\"); }\nString parameterString = sb.toString();\n</code></pre>\n" }, { "answer_id": 63218, "author": "izb", "author_id": 974, "author_profile": "https://Stackoverflow.com/users/974", "pm_score": -1, "selected": false, "text": "<pre><code>public static String join(String[] strings, char del)\n{\n StringBuffer sb = new StringBuffer();\n int len = strings.length;\n boolean appended = false;\n for (int i = 0; i &lt; len; i++)\n {\n if (appended)\n {\n sb.append(del);\n }\n sb.append(\"\"+strings[i]);\n appended = true;\n }\n return sb.toString();\n}\n</code></pre>\n" }, { "answer_id": 63226, "author": "newdayrising", "author_id": 3126, "author_profile": "https://Stackoverflow.com/users/3126", "pm_score": 1, "selected": false, "text": "<p>You should probably use a <code>StringBuilder</code> with the <code>append</code> method to construct your result, but otherwise this is as good of a solution as Java has to offer.</p>\n" }, { "answer_id": 63229, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 1, "selected": false, "text": "<p>Why don't you do in Java the same thing you are doing in ruby, that is creating the delimiter separated string only after you've added all the pieces to the array?</p>\n\n<pre><code>ArrayList&lt;String&gt; parms = new ArrayList&lt;String&gt;();\nif (someCondition) parms.add(\"someString\");\nif (anotherCondition) parms.add(\"someOtherString\");\n// ...\nString sep = \"\"; StringBuffer b = new StringBuffer();\nfor (String p: parms) {\n b.append(sep);\n b.append(p);\n sep = \"yourDelimiter\";\n}\n</code></pre>\n\n<p>You may want to move that for loop in a separate helper method, and also use StringBuilder instead of StringBuffer...</p>\n\n<p><em>Edit</em>: fixed the order of appends.</p>\n" }, { "answer_id": 63258, "author": "Martin Gladdish", "author_id": 7686, "author_profile": "https://Stackoverflow.com/users/7686", "pm_score": 10, "selected": true, "text": "<h3>Pre Java 8:</h3>\n\n<p>Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby: </p>\n\n<p><a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join(java.lang.Iterable,%20char)\" rel=\"noreferrer\"><code>StringUtils.join(java.lang.Iterable,char)</code></a></p>\n\n<hr>\n\n<h3>Java 8:</h3>\n\n<p>Java 8 provides joining out of the box via <code>StringJoiner</code> and <code>String.join()</code>. The snippets below show how you can use them:</p>\n\n<p><a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html\" rel=\"noreferrer\"><code>StringJoiner</code></a></p>\n\n<pre><code>StringJoiner joiner = new StringJoiner(\",\");\njoiner.add(\"01\").add(\"02\").add(\"03\");\nString joinedString = joiner.toString(); // \"01,02,03\"\n</code></pre>\n\n<hr>\n\n<p><a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-\" rel=\"noreferrer\"><code>String.join(CharSequence delimiter, CharSequence... elements))</code></a></p>\n\n<pre><code>String joinedString = String.join(\" - \", \"04\", \"05\", \"06\"); // \"04 - 05 - 06\"\n</code></pre>\n\n<hr>\n\n<p><a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-\" rel=\"noreferrer\"><code>String.join(CharSequence delimiter, Iterable&lt;? extends CharSequence&gt; elements)</code></a></p>\n\n<pre><code>List&lt;String&gt; strings = new LinkedList&lt;&gt;();\nstrings.add(\"Java\");strings.add(\"is\");\nstrings.add(\"cool\");\nString message = String.join(\" \", strings);\n//message returned is: \"Java is cool\"\n</code></pre>\n" }, { "answer_id": 63274, "author": "Rob Dickerson", "author_id": 7530, "author_profile": "https://Stackoverflow.com/users/7530", "pm_score": 6, "selected": false, "text": "<p>You could write a little join-style utility method that works on java.util.Lists</p>\n\n<pre><code>public static String join(List&lt;String&gt; list, String delim) {\n\n StringBuilder sb = new StringBuilder();\n\n String loopDelim = \"\";\n\n for(String s : list) {\n\n sb.append(loopDelim);\n sb.append(s); \n\n loopDelim = delim;\n }\n\n return sb.toString();\n}\n</code></pre>\n\n<p>Then use it like so:</p>\n\n<pre><code> List&lt;String&gt; list = new ArrayList&lt;String&gt;();\n\n if( condition ) list.add(\"elementName\");\n if( anotherCondition ) list.add(\"anotherElementName\");\n\n join(list, \",\");\n</code></pre>\n" }, { "answer_id": 63282, "author": "killdash10", "author_id": 7621, "author_profile": "https://Stackoverflow.com/users/7621", "pm_score": 0, "selected": false, "text": "<p>So basically something like this:</p>\n\n<pre><code>public static String appendWithDelimiter(String original, String addition, String delimiter) {\n\nif (original.equals(\"\")) {\n return addition;\n} else {\n StringBuilder sb = new StringBuilder(original.length() + addition.length() + delimiter.length());\n sb.append(original);\n sb.append(delimiter);\n sb.append(addition);\n return sb.toString();\n }\n}\n</code></pre>\n" }, { "answer_id": 63305, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://commons.apache.org/\" rel=\"noreferrer\">Apache commons</a> StringUtils class has a join method.</p>\n" }, { "answer_id": 63306, "author": "Mikezx6r", "author_id": 5382, "author_profile": "https://Stackoverflow.com/users/5382", "pm_score": 0, "selected": false, "text": "<p>Don't know if this really is any better, but at least it's using StringBuilder, which may be slightly more efficient.</p>\n\n<p>Down below is a more generic approach if you can build up the list of parameters BEFORE doing any parameter delimiting.</p>\n\n<pre><code>// Answers real question\npublic String appendWithDelimiters(String delimiter, String original, String addition) {\n StringBuilder sb = new StringBuilder(original);\n if(sb.length()!=0) {\n sb.append(delimiter).append(addition);\n } else {\n sb.append(addition);\n }\n return sb.toString();\n}\n\n\n// A more generic case.\n// ... means a list of indeterminate length of Strings.\npublic String appendWithDelimitersGeneric(String delimiter, String... strings) {\n StringBuilder sb = new StringBuilder();\n for (String string : strings) {\n if(sb.length()!=0) {\n sb.append(delimiter).append(string);\n } else {\n sb.append(string);\n }\n }\n\n return sb.toString();\n}\n\npublic void testAppendWithDelimiters() {\n String string = appendWithDelimitersGeneric(\",\", \"string1\", \"string2\", \"string3\");\n}\n</code></pre>\n" }, { "answer_id": 63324, "author": "Yaba", "author_id": 7524, "author_profile": "https://Stackoverflow.com/users/7524", "pm_score": 0, "selected": false, "text": "<p>Your approach is not too bad, but you should use a StringBuffer instead of using the + sign. The + has the big disadvantage that a new String instance is being created for each single operation. The longer your string gets, the bigger the overhead. So using a StringBuffer should be the fastest way:</p>\n\n<pre><code>public StringBuffer appendWithDelimiter( StringBuffer original, String addition, String delimiter ) {\n if ( original == null ) {\n StringBuffer buffer = new StringBuffer();\n buffer.append(addition);\n return buffer;\n } else {\n buffer.append(delimiter);\n buffer.append(addition);\n return original;\n }\n}\n</code></pre>\n\n<p>After you have finished creating your string simply call toString() on the returned StringBuffer.</p>\n" }, { "answer_id": 63351, "author": "Eric Normand", "author_id": 7492, "author_profile": "https://Stackoverflow.com/users/7492", "pm_score": 3, "selected": false, "text": "<p>I would use Google Collections. There is a nice Join facility.<br>\n<a href=\"http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/base/Join.html\" rel=\"noreferrer\">http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/base/Join.html</a></p>\n\n<p>But if I wanted to write it on my own,</p>\n\n<pre><code>package util;\n\nimport java.util.ArrayList;\nimport java.util.Iterable;\nimport java.util.Collections;\nimport java.util.Iterator;\n\npublic class Utils {\n // accept a collection of objects, since all objects have toString()\n public static String join(String delimiter, Iterable&lt;? extends Object&gt; objs) {\n if (objs.isEmpty()) {\n return \"\";\n }\n Iterator&lt;? extends Object&gt; iter = objs.iterator();\n StringBuilder buffer = new StringBuilder();\n buffer.append(iter.next());\n while (iter.hasNext()) {\n buffer.append(delimiter).append(iter.next());\n }\n return buffer.toString();\n }\n\n // for convenience\n public static String join(String delimiter, Object... objs) {\n ArrayList&lt;Object&gt; list = new ArrayList&lt;Object&gt;();\n Collections.addAll(list, objs);\n return join(delimiter, list);\n }\n}\n</code></pre>\n\n<p>I think it works better with an object collection, since now you don't have to convert your objects to strings before you join them.</p>\n" }, { "answer_id": 63407, "author": "Aaron", "author_id": 2628, "author_profile": "https://Stackoverflow.com/users/2628", "pm_score": 0, "selected": false, "text": "<p>Instead of using string concatenation, you should use StringBuilder if your code is not threaded, and StringBuffer if it is.</p>\n" }, { "answer_id": 63418, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You're making this a little more complicated than it has to be. Let's start with the end of your example:</p>\n\n<pre><code>String parameterString = \"\";\nif ( condition ) parameterString = appendWithDelimiter( parameterString, \"elementName\", \",\" );\nif ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, \"anotherElementName\", \",\" );\n</code></pre>\n\n<p>With the small change of using a StringBuilder instead of a String, this becomes:</p>\n\n<pre><code>StringBuilder parameterString = new StringBuilder();\nif (condition) parameterString.append(\"elementName\").append(\",\");\nif (anotherCondition) parameterString.append(\"anotherElementName\").append(\",\");\n...\n</code></pre>\n\n<p>When you're done (I assume you have to check a few other conditions as well), just make sure you remove the tailing comma with a command like this:</p>\n\n<pre><code>if (parameterString.length() &gt; 0) \n parameterString.deleteCharAt(parameterString.length() - 1);\n</code></pre>\n\n<p>And finally, get the string you want with</p>\n\n<pre><code>parameterString.toString();\n</code></pre>\n\n<p>You could also replace the \",\" in the second call to append with a generic delimiter string that can be set to anything. If you have a list of things you know you need to append (non-conditionally), you could put this code inside a method that takes a list of strings. </p>\n" }, { "answer_id": 63840, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 0, "selected": false, "text": "<pre><code>//Note: if you have access to Java5+, \n//use StringBuilder in preference to StringBuffer. \n//All that has to be replaced is the class name. \n//StringBuffer will work in Java 1.4, though.\n\nappendWithDelimiter( StringBuffer buffer, String addition, \n String delimiter ) {\n if ( buffer.length() == 0) {\n buffer.append(addition);\n } else {\n buffer.append(delimiter);\n buffer.append(addition);\n }\n}\n\n\nStringBuffer parameterBuffer = new StringBuffer();\nif ( condition ) { \n appendWithDelimiter(parameterBuffer, \"elementName\", \",\" );\n}\nif ( anotherCondition ) {\n appendWithDelimiter(parameterBuffer, \"anotherElementName\", \",\" );\n}\n\n//Finally, to return a string representation, call toString() when returning.\nreturn parameterBuffer.toString(); \n</code></pre>\n" }, { "answer_id": 76070, "author": "Mark B", "author_id": 13070, "author_profile": "https://Stackoverflow.com/users/13070", "pm_score": 1, "selected": false, "text": "<p>With Java 5 variable args, so you don't have to stuff all your strings into a collection or array explicitly:</p>\n\n<pre><code>import junit.framework.Assert;\nimport org.junit.Test;\n\npublic class StringUtil\n{\n public static String join(String delim, String... strings)\n {\n StringBuilder builder = new StringBuilder();\n\n if (strings != null)\n {\n for (String str : strings)\n {\n if (builder.length() &gt; 0)\n {\n builder.append(delim).append(\" \");\n }\n builder.append(str);\n }\n } \n return builder.toString();\n }\n @Test\n public void joinTest()\n {\n Assert.assertEquals(\"\", StringUtil.join(\",\", null));\n Assert.assertEquals(\"\", StringUtil.join(\",\", \"\"));\n Assert.assertEquals(\"\", StringUtil.join(\",\", new String[0]));\n Assert.assertEquals(\"test\", StringUtil.join(\",\", \"test\"));\n Assert.assertEquals(\"foo, bar\", StringUtil.join(\",\", \"foo\", \"bar\"));\n Assert.assertEquals(\"foo, bar, x\", StringUtil.join(\",\", \"foo\", \"bar\", \"x\"));\n }\n}\n</code></pre>\n" }, { "answer_id": 76216, "author": "user13276", "author_id": 13276, "author_profile": "https://Stackoverflow.com/users/13276", "pm_score": 0, "selected": false, "text": "<p>So a couple of things you might do to get the feel that it seems like you're looking for:</p>\n\n<p>1) Extend List class - and add the join method to it. The join method would simply do the work of concatenating and adding the delimiter (which could be a param to the join method)</p>\n\n<p>2) It looks like Java 7 is going to be adding extension methods to java - which allows you just to attach a specific method on to a class: so you could write that join method and add it as an extension method to List or even to Collection.</p>\n\n<p>Solution 1 is probably the only realistic one, now, though since Java 7 isn't out yet :) But it should work just fine.</p>\n\n<p>To use both of these, you'd just add all your items to the List or Collection as usual, and then call the new custom method to 'join' them.</p>\n" }, { "answer_id": 297128, "author": "akuhn", "author_id": 24468, "author_profile": "https://Stackoverflow.com/users/24468", "pm_score": 2, "selected": false, "text": "<p>Use StringBuilder and class <code>Separator</code></p>\n\n<pre><code>StringBuilder buf = new StringBuilder();\nSeparator sep = new Separator(\", \");\nfor (String each : list) {\n buf.append(sep).append(each);\n}\n</code></pre>\n\n<p>Separator wraps a delimiter. The delimiter is returned by Separator's <code>toString</code> method, unless on the first call which returns the empty string!</p>\n\n<p>Source code for class <code>Separator</code></p>\n\n<pre><code>public class Separator {\n\n private boolean skipFirst;\n private final String value;\n\n public Separator() {\n this(\", \");\n }\n\n public Separator(String value) {\n this.value = value;\n this.skipFirst = true;\n }\n\n public void reset() {\n skipFirst = true;\n }\n\n public String toString() {\n String sep = skipFirst ? \"\" : value;\n skipFirst = false;\n return sep;\n }\n\n}\n</code></pre>\n" }, { "answer_id": 2179425, "author": "dfa", "author_id": 89266, "author_profile": "https://Stackoverflow.com/users/89266", "pm_score": 0, "selected": false, "text": "<p>using <a href=\"http://bitbucket.org/dfa/dollar\" rel=\"nofollow noreferrer\">Dollar</a> is simple as typing:</p>\n\n<pre><code>String joined = $(aCollection).join(\",\");\n</code></pre>\n\n<p>NB: it works also for Array and other data types</p>\n\n<h2>Implementation</h2>\n\n<p>Internally it uses a very neat trick:</p>\n\n<pre><code>@Override\npublic String join(String separator) {\n Separator sep = new Separator(separator);\n StringBuilder sb = new StringBuilder();\n\n for (T item : iterable) {\n sb.append(sep).append(item);\n }\n\n return sb.toString();\n}\n</code></pre>\n\n<p>the class <code>Separator</code> return the empty String only the first time that it is invoked, then it returns the separator:</p>\n\n<pre><code>class Separator {\n\n private final String separator;\n private boolean wasCalled;\n\n public Separator(String separator) {\n this.separator = separator;\n this.wasCalled = false;\n }\n\n @Override\n public String toString() {\n if (!wasCalled) {\n wasCalled = true;\n return \"\";\n } else {\n return separator;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 3338199, "author": "java al", "author_id": 402658, "author_profile": "https://Stackoverflow.com/users/402658", "pm_score": 0, "selected": false, "text": "<p>Slight improvement [speed] of version from izb:</p>\n\n<pre><code>public static String join(String[] strings, char del)\n{\n StringBuilder sb = new StringBuilder();\n int len = strings.length;\n\n if(len &gt; 1) \n {\n len -= 1;\n }else\n {\n return strings[0];\n }\n\n for (int i = 0; i &lt; len; i++)\n {\n sb.append(strings[i]).append(del);\n }\n\n sb.append(strings[i]);\n\n return sb.toString();\n}\n</code></pre>\n" }, { "answer_id": 6011632, "author": "Kevin", "author_id": 357951, "author_profile": "https://Stackoverflow.com/users/357951", "pm_score": 6, "selected": false, "text": "<p>In the case of Android, the StringUtils class from commons isn't available, so for this I used</p>\n\n<pre><code>android.text.TextUtils.join(CharSequence delimiter, Iterable tokens)\n</code></pre>\n\n<p><a href=\"http://developer.android.com/reference/android/text/TextUtils.html\">http://developer.android.com/reference/android/text/TextUtils.html</a></p>\n" }, { "answer_id": 12471817, "author": "Alex K", "author_id": 876298, "author_profile": "https://Stackoverflow.com/users/876298", "pm_score": 5, "selected": false, "text": "<p>The <a href=\"http://code.google.com/p/guava-libraries/\">Google's Guava library</a> has <strong><em><a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Joiner.html\">com.google.common.base.Joiner</a></em></strong> class which helps to solve such tasks.</p>\n\n<p>Samples:</p>\n\n<pre><code>\"My pets are: \" + Joiner.on(\", \").join(Arrays.asList(\"rabbit\", \"parrot\", \"dog\")); \n// returns \"My pets are: rabbit, parrot, dog\"\n\nJoiner.on(\" AND \").join(Arrays.asList(\"field1=1\" , \"field2=2\", \"field3=3\"));\n// returns \"field1=1 AND field2=2 AND field3=3\"\n\nJoiner.on(\",\").skipNulls().join(Arrays.asList(\"London\", \"Moscow\", null, \"New York\", null, \"Paris\"));\n// returns \"London,Moscow,New York,Paris\"\n\nJoiner.on(\", \").useForNull(\"Team held a draw\").join(Arrays.asList(\"FC Barcelona\", \"FC Bayern\", null, null, \"Chelsea FC\", \"AC Milan\"));\n// returns \"FC Barcelona, FC Bayern, Team held a draw, Team held a draw, Chelsea FC, AC Milan\"\n</code></pre>\n\n<hr>\n\n<p>Here is an <a href=\"http://code.google.com/p/guava-libraries/wiki/StringsExplained\">article about Guava's string utilities</a>.</p>\n" }, { "answer_id": 20013838, "author": "Craig P. Motlin", "author_id": 23572, "author_profile": "https://Stackoverflow.com/users/23572", "pm_score": 2, "selected": false, "text": "<p>If you're using <a href=\"https://www.eclipse.org/collections/\" rel=\"nofollow noreferrer\">Eclipse Collections</a>, you can use <code>makeString()</code> or <code>appendString()</code>.</p>\n\n<p><code>makeString()</code> returns a <code>String</code> representation, similar to <code>toString()</code>.</p>\n\n<p>It has three forms</p>\n\n<ul>\n<li><code>makeString(start, separator, end)</code></li>\n<li><code>makeString(separator)</code> defaults start and end to empty strings</li>\n<li><code>makeString()</code> defaults the separator to <code>\", \"</code> (comma and space)</li>\n</ul>\n\n<p>Code example:</p>\n\n<pre><code>MutableList&lt;Integer&gt; list = FastList.newListWith(1, 2, 3);\nassertEquals(\"[1/2/3]\", list.makeString(\"[\", \"/\", \"]\"));\nassertEquals(\"1/2/3\", list.makeString(\"/\"));\nassertEquals(\"1, 2, 3\", list.makeString());\nassertEquals(list.toString(), list.makeString(\"[\", \", \", \"]\"));\n</code></pre>\n\n<p><code>appendString()</code> is similar to <code>makeString()</code>, but it appends to an <code>Appendable</code> (like <code>StringBuilder</code>) and is <code>void</code>. It has the same three forms, with an additional first argument, the Appendable.</p>\n\n<pre><code>MutableList&lt;Integer&gt; list = FastList.newListWith(1, 2, 3);\nAppendable appendable = new StringBuilder();\nlist.appendString(appendable, \"[\", \"/\", \"]\");\nassertEquals(\"[1/2/3]\", appendable.toString());\n</code></pre>\n\n<p>If you can't convert your collection to an Eclipse Collections type, just adapt it with the relevant adapter.</p>\n\n<pre><code>List&lt;Object&gt; list = ...;\nListAdapter.adapt(list).makeString(\",\");\n</code></pre>\n\n<p><strong>Note:</strong> I am a committer for Eclipse collections.</p>\n" }, { "answer_id": 22577623, "author": "micha", "author_id": 1115554, "author_profile": "https://Stackoverflow.com/users/1115554", "pm_score": 5, "selected": false, "text": "<p>In Java 8 you can use <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-\" rel=\"noreferrer\"><code>String.join()</code></a>:</p>\n\n<pre><code>List&lt;String&gt; list = Arrays.asList(\"foo\", \"bar\", \"baz\");\nString joined = String.join(\" and \", list); // \"foo and bar and baz\"\n</code></pre>\n\n<p>Also have a look at <a href=\"https://stackoverflow.com/a/22577565/1115554\">this answer</a> for a Stream API example.</p>\n" }, { "answer_id": 22659416, "author": "Thamme Gowda", "author_id": 1506477, "author_profile": "https://Stackoverflow.com/users/1506477", "pm_score": 2, "selected": false, "text": "<p>And a minimal one (if you don't want to include Apache Commons or Gauva into project dependencies just for the sake of joining strings)</p>\n\n<pre><code>/**\n *\n * @param delim : String that should be kept in between the parts\n * @param parts : parts that needs to be joined\n * @return a String that's formed by joining the parts\n */\nprivate static final String join(String delim, String... parts) {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i &lt; parts.length - 1; i++) {\n builder.append(parts[i]).append(delim);\n }\n if(parts.length &gt; 0){\n builder.append(parts[parts.length - 1]);\n }\n return builder.toString();\n}\n</code></pre>\n" }, { "answer_id": 27599779, "author": "gladiator", "author_id": 1072826, "author_profile": "https://Stackoverflow.com/users/1072826", "pm_score": 5, "selected": false, "text": "<p>in Java 8 you can do this like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>list.stream().map(Object::toString)\n .collect(Collectors.joining(delimiter));\n</code></pre>\n\n<p>if list has nulls you can use:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>list.stream().map(String::valueOf)\n .collect(Collectors.joining(delimiter))\n</code></pre>\n\n<p>it also supports prefix and suffix:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>list.stream().map(String::valueOf)\n .collect(Collectors.joining(delimiter, prefix, suffix));\n</code></pre>\n" }, { "answer_id": 28063943, "author": "рüффп", "author_id": 628006, "author_profile": "https://Stackoverflow.com/users/628006", "pm_score": 1, "selected": false, "text": "<p>For those who are in a Spring context their <a href=\"http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StringUtils.html\" rel=\"nofollow\">StringUtils</a> class is useful as well:</p>\n\n<p>There are many useful shortcuts like:</p>\n\n<ul>\n<li>collectionToCommaDelimitedString(Collection coll)</li>\n<li>collectionToDelimitedString(Collection coll, String delim)</li>\n<li>arrayToDelimitedString(Object[] arr, String delim)</li>\n</ul>\n\n<p>and many others. </p>\n\n<p>This can be helpful if you are not already using Java 8 and you are already in a Spring context.</p>\n\n<p>I prefer it against the Apache Commons (although very good as well) for the Collection support which is easier like this:</p>\n\n<pre><code>// Encoding Set&lt;String&gt; to String delimited \nString asString = org.springframework.util.StringUtils.collectionToDelimitedString(codes, \";\");\n\n// Decoding String delimited to Set\nSet&lt;String&gt; collection = org.springframework.util.StringUtils.commaDelimitedListToSet(asString);\n</code></pre>\n" }, { "answer_id": 29135746, "author": "maXp", "author_id": 3094065, "author_profile": "https://Stackoverflow.com/users/3094065", "pm_score": 0, "selected": false, "text": "<p>Fix answer Rob Dickerson.</p>\n\n<p>It's easier to use:</p>\n\n<pre><code>public static String join(String delimiter, String... values)\n{\n StringBuilder stringBuilder = new StringBuilder();\n\n for (String value : values)\n {\n stringBuilder.append(value);\n stringBuilder.append(delimiter);\n }\n\n String result = stringBuilder.toString();\n\n return result.isEmpty() ? result : result.substring(0, result.length() - 1);\n}\n</code></pre>\n" }, { "answer_id": 33451093, "author": "gstackoverflow", "author_id": 2674303, "author_profile": "https://Stackoverflow.com/users/2674303", "pm_score": 3, "selected": false, "text": "<h2>Java 8</h2>\n\n<pre><code>stringCollection.stream().collect(Collectors.joining(\", \"));\n</code></pre>\n" }, { "answer_id": 36839833, "author": "Ankit Lalan", "author_id": 6251178, "author_profile": "https://Stackoverflow.com/users/6251178", "pm_score": 2, "selected": false, "text": "<p>If you are using Spring MVC then you can try following steps.</p>\n\n<pre><code>import org.springframework.util.StringUtils;\n\nList&lt;String&gt; groupIds = new List&lt;String&gt;; \ngroupIds.add(\"a\"); \ngroupIds.add(\"b\"); \ngroupIds.add(\"c\");\n\nString csv = StringUtils.arrayToCommaDelimitedString(groupIds.toArray());\n</code></pre>\n\n<p>It will result to <code>a,b,c</code></p>\n" }, { "answer_id": 39067118, "author": "Philipp Grigoryev", "author_id": 3281886, "author_profile": "https://Stackoverflow.com/users/3281886", "pm_score": 0, "selected": false, "text": "<p>I personally quite often use the following simple solution for logging purposes:</p>\n\n<pre><code>List lst = Arrays.asList(\"ab\", \"bc\", \"cd\");\nString str = lst.toString().replaceAll(\"[\\\\[\\\\]]\", \"\");\n</code></pre>\n" }, { "answer_id": 49860671, "author": "Luis Aguilar", "author_id": 9572533, "author_profile": "https://Stackoverflow.com/users/9572533", "pm_score": 3, "selected": false, "text": "<p>Java 8 Native Type</p>\n\n<pre><code>List&lt;Integer&gt; example;\nexample.add(1);\nexample.add(2);\nexample.add(3);\n...\nexample.stream().collect(Collectors.joining(\",\"));\n</code></pre>\n\n<p>Java 8 Custom Object:</p>\n\n<pre><code>List&lt;Person&gt; person;\n...\nperson.stream().map(Person::getAge).collect(Collectors.joining(\",\"));\n</code></pre>\n" }, { "answer_id": 59099866, "author": "Dhruv Naik", "author_id": 10789713, "author_profile": "https://Stackoverflow.com/users/10789713", "pm_score": 0, "selected": false, "text": "<p>If you want to apply comma in a List of object's properties. This is the way i found most useful. </p>\n\n<p>here <strong>getName()</strong> is a string property of a class i have been trying to add \",\" to.</p>\n\n<p><strong>String message = listName.stream().map(list -> list.getName()).collect(Collectors.joining(\", \"));</strong></p>\n" }, { "answer_id": 73844686, "author": "VIVek", "author_id": 12591119, "author_profile": "https://Stackoverflow.com/users/12591119", "pm_score": 0, "selected": false, "text": "<blockquote>\n<p>Don't use join, delimiter or StringJoiner methods and classes as they\nwont work below Android N and O versions. Else use a simple code logic\nas;</p>\n</blockquote>\n<pre><code> List&lt;String&gt; tags= emp.getTags();\n String tagTxt=&quot;&quot;;\n for (String s : tags) {\n if (tagTxt.isEmpty()){\n tagTxt=s;\n }else\n tagTxt= tagTxt+&quot;, &quot;+s;\n } \n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2041950/" ]
While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this: ``` public String appendWithDelimiter( String original, String addition, String delimiter ) { if ( original.equals( "" ) ) { return addition; } else { return original + delimiter + addition; } } String parameterString = ""; if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," ); if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," ); ``` I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization. In Ruby, I can do something like this instead, which feels much more elegant: ``` parameterArray = []; parameterArray << "elementName" if condition; parameterArray << "anotherElementName" if anotherCondition; parameterString = parameterArray.join(","); ``` But since Java lacks a join command, I couldn't figure out anything equivalent. So, what's the best way to do this in Java?
### Pre Java 8: Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby: [`StringUtils.join(java.lang.Iterable,char)`](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join(java.lang.Iterable,%20char)) --- ### Java 8: Java 8 provides joining out of the box via `StringJoiner` and `String.join()`. The snippets below show how you can use them: [`StringJoiner`](https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html) ``` StringJoiner joiner = new StringJoiner(","); joiner.add("01").add("02").add("03"); String joinedString = joiner.toString(); // "01,02,03" ``` --- [`String.join(CharSequence delimiter, CharSequence... elements))`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-) ``` String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06" ``` --- [`String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-) ``` List<String> strings = new LinkedList<>(); strings.add("Java");strings.add("is"); strings.add("cool"); String message = String.join(" ", strings); //message returned is: "Java is cool" ```
63,166
<p>I once had the task of determining the following performance parameters from inside a running application:</p> <ul> <li>Total virtual memory available</li> <li>Virtual memory currently used</li> <li>Virtual memory currently used by my process<hr></li> <li>Total RAM available</li> <li>RAM currently used</li> <li>RAM currently used by my process<hr></li> <li>% CPU currently used</li> <li>% CPU currently used by my process</li> </ul> <p>The code had to run on Windows and Linux. Even though this seems to be a standard task, finding the necessary information in the manuals (WIN32 API, GNU docs) as well as on the Internet took me several days, because there's so much incomplete/incorrect/outdated information on this topic to be found out there.</p> <p>In order to save others from going through the same trouble, I thought it would be a good idea to collect all the scattered information plus what I found by trial and error here in one place.</p>
[ { "answer_id": 64166, "author": "Lanzelot", "author_id": 7381, "author_profile": "https://Stackoverflow.com/users/7381", "pm_score": 10, "selected": false, "text": "<h2>Windows</h2>\n<p>Some of the above values are easily available from the appropriate Win32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit &quot;unintuitive&quot; and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...)</p>\n<p>Note: for clarity all error checking has been omitted from the following code. Do check the return codes...!</p>\n<ul>\n<li><p>Total Virtual Memory:</p>\n<pre><code>#include &quot;windows.h&quot;\n\nMEMORYSTATUSEX memInfo;\nmemInfo.dwLength = sizeof(MEMORYSTATUSEX);\nGlobalMemoryStatusEx(&amp;memInfo);\nDWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;\n</code></pre>\n<p>Note: The name &quot;TotalPageFile&quot; is a bit misleading here. In reality this parameter gives the &quot;Virtual Memory Size&quot;, which is size of swap file plus installed RAM.</p>\n</li>\n<li><p>Virtual Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code> DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;\n</code></pre>\n</li>\n<li><p>Virtual Memory currently used by current process:</p>\n<pre><code>#include &quot;windows.h&quot;\n#include &quot;psapi.h&quot;\n\nPROCESS_MEMORY_COUNTERS_EX pmc;\nGetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&amp;pmc, sizeof(pmc));\nSIZE_T virtualMemUsedByMe = pmc.PrivateUsage;\n</code></pre>\n</li>\n<li><p>Total Physical Memory (RAM):</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>DWORDLONG totalPhysMem = memInfo.ullTotalPhys;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used by current process:</p>\n<p>Same code as in &quot;Virtual Memory currently used by current process&quot; and then</p>\n<pre><code>SIZE_T physMemUsedByMe = pmc.WorkingSetSize;\n</code></pre>\n</li>\n<li><p>CPU currently used:</p>\n<pre><code>#include &quot;TCHAR.h&quot;\n#include &quot;pdh.h&quot;\n\nstatic PDH_HQUERY cpuQuery;\nstatic PDH_HCOUNTER cpuTotal;\n\nvoid init(){\n PdhOpenQuery(NULL, NULL, &amp;cpuQuery);\n // You can also use L&quot;\\\\Processor(*)\\\\% Processor Time&quot; and get individual CPU values with PdhGetFormattedCounterArray()\n PdhAddEnglishCounter(cpuQuery, L&quot;\\\\Processor(_Total)\\\\% Processor Time&quot;, NULL, &amp;cpuTotal);\n PdhCollectQueryData(cpuQuery);\n}\n\ndouble getCurrentValue(){\n PDH_FMT_COUNTERVALUE counterVal;\n\n PdhCollectQueryData(cpuQuery);\n PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &amp;counterVal);\n return counterVal.doubleValue;\n}\n</code></pre>\n</li>\n<li><p>CPU currently used by current process:</p>\n<pre><code>#include &quot;windows.h&quot;\n\nstatic ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;\nstatic int numProcessors;\nstatic HANDLE self;\n\nvoid init(){\n SYSTEM_INFO sysInfo;\n FILETIME ftime, fsys, fuser;\n\n GetSystemInfo(&amp;sysInfo);\n numProcessors = sysInfo.dwNumberOfProcessors;\n\n GetSystemTimeAsFileTime(&amp;ftime);\n memcpy(&amp;lastCPU, &amp;ftime, sizeof(FILETIME));\n\n self = GetCurrentProcess();\n GetProcessTimes(self, &amp;ftime, &amp;ftime, &amp;fsys, &amp;fuser);\n memcpy(&amp;lastSysCPU, &amp;fsys, sizeof(FILETIME));\n memcpy(&amp;lastUserCPU, &amp;fuser, sizeof(FILETIME));\n}\n\ndouble getCurrentValue(){\n FILETIME ftime, fsys, fuser;\n ULARGE_INTEGER now, sys, user;\n double percent;\n\n GetSystemTimeAsFileTime(&amp;ftime);\n memcpy(&amp;now, &amp;ftime, sizeof(FILETIME));\n\n GetProcessTimes(self, &amp;ftime, &amp;ftime, &amp;fsys, &amp;fuser);\n memcpy(&amp;sys, &amp;fsys, sizeof(FILETIME));\n memcpy(&amp;user, &amp;fuser, sizeof(FILETIME));\n percent = (sys.QuadPart - lastSysCPU.QuadPart) +\n (user.QuadPart - lastUserCPU.QuadPart);\n percent /= (now.QuadPart - lastCPU.QuadPart);\n percent /= numProcessors;\n lastCPU = now;\n lastUserCPU = user;\n lastSysCPU = sys;\n\n return percent * 100;\n}\n</code></pre>\n</li>\n</ul>\n<hr />\n<h2>Linux</h2>\n<p>On Linux the choice that seemed obvious at first was to use the POSIX APIs like <code>getrusage()</code> etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!?</p>\n<p>In the end I got all values via a combination of reading the pseudo-filesystem <code>/proc</code> and kernel calls.</p>\n<ul>\n<li><p>Total Virtual Memory:</p>\n<pre><code>#include &quot;sys/types.h&quot;\n#include &quot;sys/sysinfo.h&quot;\n\nstruct sysinfo memInfo;\n\nsysinfo (&amp;memInfo);\nlong long totalVirtualMem = memInfo.totalram;\n//Add other values in next statement to avoid int overflow on right hand side...\ntotalVirtualMem += memInfo.totalswap;\ntotalVirtualMem *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Virtual Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>long long virtualMemUsed = memInfo.totalram - memInfo.freeram;\n//Add other values in next statement to avoid int overflow on right hand side...\nvirtualMemUsed += memInfo.totalswap - memInfo.freeswap;\nvirtualMemUsed *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Virtual Memory currently used by current process:</p>\n<pre><code>#include &quot;stdlib.h&quot;\n#include &quot;stdio.h&quot;\n#include &quot;string.h&quot;\n\nint parseLine(char* line){\n // This assumes that a digit will be found and the line ends in &quot; Kb&quot;.\n int i = strlen(line);\n const char* p = line;\n while (*p &lt;'0' || *p &gt; '9') p++;\n line[i-3] = '\\0';\n i = atoi(p);\n return i;\n}\n\nint getValue(){ //Note: this value is in KB!\n FILE* file = fopen(&quot;/proc/self/status&quot;, &quot;r&quot;);\n int result = -1;\n char line[128];\n\n while (fgets(line, 128, file) != NULL){\n if (strncmp(line, &quot;VmSize:&quot;, 7) == 0){\n result = parseLine(line);\n break;\n }\n }\n fclose(file);\n return result;\n}\n</code></pre>\n</li>\n<li><p>Total Physical Memory (RAM):</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>long long totalPhysMem = memInfo.totalram;\n//Multiply in next statement to avoid int overflow on right hand side...\ntotalPhysMem *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>long long physMemUsed = memInfo.totalram - memInfo.freeram;\n//Multiply in next statement to avoid int overflow on right hand side...\nphysMemUsed *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used by current process:</p>\n<p>Change getValue() in &quot;Virtual Memory currently used by current process&quot; as follows:</p>\n<pre><code>int getValue(){ //Note: this value is in KB!\n FILE* file = fopen(&quot;/proc/self/status&quot;, &quot;r&quot;);\n int result = -1;\n char line[128];\n\n while (fgets(line, 128, file) != NULL){\n if (strncmp(line, &quot;VmRSS:&quot;, 6) == 0){\n result = parseLine(line);\n break;\n }\n }\n fclose(file);\n return result;\n}\n</code></pre>\n</li>\n</ul>\n<p></p>\n<ul>\n<li><p>CPU currently used:</p>\n<pre><code>#include &quot;stdlib.h&quot;\n#include &quot;stdio.h&quot;\n#include &quot;string.h&quot;\n\nstatic unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;\n\nvoid init(){\n FILE* file = fopen(&quot;/proc/stat&quot;, &quot;r&quot;);\n fscanf(file, &quot;cpu %llu %llu %llu %llu&quot;, &amp;lastTotalUser, &amp;lastTotalUserLow,\n &amp;lastTotalSys, &amp;lastTotalIdle);\n fclose(file);\n}\n\ndouble getCurrentValue(){\n double percent;\n FILE* file;\n unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;\n\n file = fopen(&quot;/proc/stat&quot;, &quot;r&quot;);\n fscanf(file, &quot;cpu %llu %llu %llu %llu&quot;, &amp;totalUser, &amp;totalUserLow,\n &amp;totalSys, &amp;totalIdle);\n fclose(file);\n\n if (totalUser &lt; lastTotalUser || totalUserLow &lt; lastTotalUserLow ||\n totalSys &lt; lastTotalSys || totalIdle &lt; lastTotalIdle){\n //Overflow detection. Just skip this value.\n percent = -1.0;\n }\n else{\n total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +\n (totalSys - lastTotalSys);\n percent = total;\n total += (totalIdle - lastTotalIdle);\n percent /= total;\n percent *= 100;\n }\n\n lastTotalUser = totalUser;\n lastTotalUserLow = totalUserLow;\n lastTotalSys = totalSys;\n lastTotalIdle = totalIdle;\n\n return percent;\n}\n</code></pre>\n</li>\n<li><p>CPU currently used by current process:</p>\n<pre><code>#include &quot;stdlib.h&quot;\n#include &quot;stdio.h&quot;\n#include &quot;string.h&quot;\n#include &quot;sys/times.h&quot;\n#include &quot;sys/vtimes.h&quot;\n\nstatic clock_t lastCPU, lastSysCPU, lastUserCPU;\nstatic int numProcessors;\n\nvoid init(){\n FILE* file;\n struct tms timeSample;\n char line[128];\n\n lastCPU = times(&amp;timeSample);\n lastSysCPU = timeSample.tms_stime;\n lastUserCPU = timeSample.tms_utime;\n\n file = fopen(&quot;/proc/cpuinfo&quot;, &quot;r&quot;);\n numProcessors = 0;\n while(fgets(line, 128, file) != NULL){\n if (strncmp(line, &quot;processor&quot;, 9) == 0) numProcessors++;\n }\n fclose(file);\n}\n\ndouble getCurrentValue(){\n struct tms timeSample;\n clock_t now;\n double percent;\n\n now = times(&amp;timeSample);\n if (now &lt;= lastCPU || timeSample.tms_stime &lt; lastSysCPU ||\n timeSample.tms_utime &lt; lastUserCPU){\n //Overflow detection. Just skip this value.\n percent = -1.0;\n }\n else{\n percent = (timeSample.tms_stime - lastSysCPU) +\n (timeSample.tms_utime - lastUserCPU);\n percent /= (now - lastCPU);\n percent /= numProcessors;\n percent *= 100;\n }\n lastCPU = now;\n lastSysCPU = timeSample.tms_stime;\n lastUserCPU = timeSample.tms_utime;\n\n return percent;\n}\n</code></pre>\n</li>\n</ul>\n<hr />\n<h2>TODO: Other Platforms</h2>\n<p>I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by <code>getrusage()</code> and similar functions?</p>\n" }, { "answer_id": 64422, "author": "Martin Del Vecchio", "author_id": 5397, "author_profile": "https://Stackoverflow.com/users/5397", "pm_score": 6, "selected": false, "text": "<h1>Linux</h1>\n\n<p>In Linux, this information is available in the /proc file system. I'm not a big fan of the text file format used, as each Linux distribution seems to customize at least one important file. A quick look as the source to 'ps' reveals the mess.</p>\n\n<p>But here is where to find the information you seek:</p>\n\n<p><strong>/proc/meminfo</strong> contains the majority of the system-wide information you seek. Here it looks like on my system; I think you are interested in <strong>MemTotal</strong>, <strong>MemFree</strong>, <strong>SwapTotal</strong>, and <strong>SwapFree</strong>:</p>\n\n<pre><code>Anderson cxc # more /proc/meminfo\nMemTotal: 4083948 kB\nMemFree: 2198520 kB\nBuffers: 82080 kB\nCached: 1141460 kB\nSwapCached: 0 kB\nActive: 1137960 kB\nInactive: 608588 kB\nHighTotal: 3276672 kB\nHighFree: 1607744 kB\nLowTotal: 807276 kB\nLowFree: 590776 kB\nSwapTotal: 2096440 kB\nSwapFree: 2096440 kB\nDirty: 32 kB\nWriteback: 0 kB\nAnonPages: 523252 kB\nMapped: 93560 kB\nSlab: 52880 kB\nSReclaimable: 24652 kB\nSUnreclaim: 28228 kB\nPageTables: 2284 kB\nNFS_Unstable: 0 kB\nBounce: 0 kB\nCommitLimit: 4138412 kB\nCommitted_AS: 1845072 kB\nVmallocTotal: 118776 kB\nVmallocUsed: 3964 kB\nVmallocChunk: 112860 kB\nHugePages_Total: 0\nHugePages_Free: 0\nHugePages_Rsvd: 0\nHugepagesize: 2048 kB\n</code></pre>\n\n<p>For CPU utilization, you have to do a little work. Linux makes available overall CPU utilization since system start; this probably isn't what you are interested in. If you want to know what the CPU utilization was for the last second, or 10 seconds, then you need to query the information and calculate it yourself.</p>\n\n<p>The information is available in <strong>/proc/stat</strong>, which is documented pretty well at <a href=\"http://www.linuxhowtos.org/System/procstat.htm\" rel=\"noreferrer\">http://www.linuxhowtos.org/System/procstat.htm</a>; here is what it looks like on my 4-core box:</p>\n\n<pre><code>Anderson cxc # more /proc/stat\ncpu 2329889 0 2364567 1063530460 9034 9463 96111 0\ncpu0 572526 0 636532 265864398 2928 1621 6899 0\ncpu1 590441 0 531079 265949732 4763 351 8522 0\ncpu2 562983 0 645163 265796890 682 7490 71650 0\ncpu3 603938 0 551790 265919440 660 0 9040 0\nintr 37124247\nctxt 50795173133\nbtime 1218807985\nprocesses 116889\nprocs_running 1\nprocs_blocked 0\n</code></pre>\n\n<p>First, you need to determine how many CPUs (or processors, or processing cores) are available in the system. To do this, count the number of 'cpuN' entries, where N starts at 0 and increments. Don't count the 'cpu' line, which is a combination of the cpuN lines. In my example, you can see cpu0 through cpu3, for a total of 4 processors. From now on, you can ignore cpu0..cpu3, and focus only on the 'cpu' line.</p>\n\n<p>Next, you need to know that the fourth number in these lines is a measure of idle time, and thus the fourth number on the 'cpu' line is the total idle time for all processors since boot time. This time is measured in Linux \"jiffies\", which are 1/100 of a second each. </p>\n\n<p>But you don't care about the total idle time; you care about the idle time in a given period, e.g., the last second. Do calculate that, you need to read this file twice, 1 second apart.Then you can do a diff of the fourth value of the line. For example, if you take a sample and get:</p>\n\n<pre><code>cpu 2330047 0 2365006 1063853632 9035 9463 96114 0\n</code></pre>\n\n<p>Then one second later you get this sample:</p>\n\n<pre><code>cpu 2330047 0 2365007 1063854028 9035 9463 96114 0\n</code></pre>\n\n<p>Subtract the two numbers, and you get a diff of 396, which means that your CPU had been idle for 3.96 seconds out of the last 1.00 second. The trick, of course, is that you need to divide by the number of processors. 3.96 / 4 = 0.99, and there is your idle percentage; 99% idle, and 1% busy.</p>\n\n<p>In my code, I have a ring buffer of 360 entries, and I read this file every second. That lets me quickly calculate the CPU utilization for 1 second, 10 seconds, etc., all the way up to 1 hour.</p>\n\n<p>For the process-specific information, you have to look in <strong>/proc/pid</strong>; if you don't care abut your pid, you can look in /proc/self.</p>\n\n<p>CPU used by your process is available in <strong>/proc/self/stat</strong>. This is an odd-looking file consisting of a single line; for example:</p>\n\n<pre><code>19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2\n 7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364\n8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0\n</code></pre>\n\n<p>The important data here are the 13th and 14th tokens (0 and 770 here). The 13th token is the number of jiffies that the process has executed in user mode, and the 14th is the number of jiffies that the process has executed in kernel mode. Add the two together, and you have its total CPU utilization.</p>\n\n<p>Again, you will have to sample this file periodically, and calculate the diff, in order to determine the process's CPU usage over time. </p>\n\n<p><strong>Edit:</strong> remember that when you calculate your process's CPU utilization, you have to take into account 1) the number of threads in your process, and 2) the number of processors in the system. For example, if your single-threaded process is using only 25% of the CPU, that could be good or bad. Good on a single-processor system, but bad on a 4-processor system; this means that your process is running constantly, and using 100% of the CPU cycles available to it.</p>\n\n<p>For the process-specific memory information, you ahve to look at /proc/self/status, which looks like this:</p>\n\n<pre><code>Name: whatever\nState: S (sleeping)\nTgid: 19340\nPid: 19340\nPPid: 19115\nTracerPid: 0\nUid: 0 0 0 0\nGid: 0 0 0 0\nFDSize: 256\nGroups: 0 1 2 3 4 6 10 11 20 26 27\nVmPeak: 676252 kB\nVmSize: 651352 kB\nVmLck: 0 kB\nVmHWM: 420300 kB\nVmRSS: 420296 kB\nVmData: 581028 kB\nVmStk: 112 kB\nVmExe: 11672 kB\nVmLib: 76608 kB\nVmPTE: 1244 kB\nThreads: 77\nSigQ: 0/36864\nSigPnd: 0000000000000000\nShdPnd: 0000000000000000\nSigBlk: fffffffe7ffbfeff\nSigIgn: 0000000010001000\nSigCgt: 20000001800004fc\nCapInh: 0000000000000000\nCapPrm: 00000000ffffffff\nCapEff: 00000000fffffeff\nCpus_allowed: 0f\nMems_allowed: 1\nvoluntary_ctxt_switches: 6518\nnonvoluntary_ctxt_switches: 6598\n</code></pre>\n\n<p>The entries that start with 'Vm' are the interesting ones:</p>\n\n<ul>\n<li><strong>VmPeak</strong> is the maximum virtual memory space used by the process, in kB (1024 bytes).</li>\n<li><strong>VmSize</strong> is the current virtual memory space used by the process, in kB. In my example, it's pretty large: 651,352 kB, or about 636 megabytes.</li>\n<li><strong>VmRss</strong> is the amount of memory that have been mapped into the process' address space, or its resident set size. This is substantially smaller (420,296 kB, or about 410 megabytes). The difference: my program has mapped 636 MB via mmap(), but has only accessed 410 MB of it, and thus only 410 MB of pages have been assigned to it.</li>\n</ul>\n\n<p>The only item I'm not sure about is <strong>Swapspace currently used by my process</strong>. I don't know if this is available.</p>\n" }, { "answer_id": 1911863, "author": "Michael Taylor", "author_id": 172534, "author_profile": "https://Stackoverflow.com/users/172534", "pm_score": 7, "selected": false, "text": "<h1>Mac OS X</h1>\n<h2>Total Virtual Memory</h2>\n<p>This one is tricky on Mac OS X because it doesn't use a preset swap partition or file like Linux. Here's an entry from Apple's documentation:</p>\n<blockquote>\n<p><strong>Note:</strong> Unlike most Unix-based operating systems, Mac OS X does not use a preallocated swap partition for virtual memory. Instead, it uses all of the available space on the machine’s boot partition.</p>\n</blockquote>\n<p>So, if you want to know how much virtual memory is still available, you need to get the size of the root partition. You can do that like this:</p>\n<pre><code>struct statfs stats;\nif (0 == statfs(&quot;/&quot;, &amp;stats))\n{\n myFreeSwap = (uint64_t)stats.f_bsize * stats.f_bfree;\n}\n</code></pre>\n<h2>Total Virtual Currently Used</h2>\n<p>Calling systcl with the &quot;vm.swapusage&quot; key provides interesting information about swap usage:</p>\n<pre><code>sysctl -n vm.swapusage\nvm.swapusage: total = 3072.00M used = 2511.78M free = 560.22M (encrypted)\n</code></pre>\n<p>Not that the total swap usage displayed here can change if more swap is needed as explained in the section above. So the total is actually the <em>current</em> swap total. In C++, this data can be queried this way:</p>\n<pre><code>xsw_usage vmusage = {0};\nsize_t size = sizeof(vmusage);\nif( sysctlbyname(&quot;vm.swapusage&quot;, &amp;vmusage, &amp;size, NULL, 0)!=0 )\n{\n perror( &quot;unable to get swap usage by calling sysctlbyname(\\&quot;vm.swapusage\\&quot;,...)&quot; );\n}\n</code></pre>\n<p>Note that the &quot;xsw_usage&quot;, declared in sysctl.h, seems not documented and I suspect there there is a more portable way of accessing these values.</p>\n<h2>Virtual Memory Currently Used by my Process</h2>\n<p>You can get statistics about your current process using the <code>task_info</code> function. That includes the current resident size of your process and the current virtual size.</p>\n<pre><code>#include&lt;mach/mach.h&gt;\n\nstruct task_basic_info t_info;\nmach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;\n\nif (KERN_SUCCESS != task_info(mach_task_self(),\n TASK_BASIC_INFO, (task_info_t)&amp;t_info,\n &amp;t_info_count))\n{\n return -1;\n}\n// resident size is in t_info.resident_size;\n// virtual size is in t_info.virtual_size;\n</code></pre>\n<h2>Total RAM available</h2>\n<p>The amount of physical RAM available in your system is available using the <code>sysctl</code> system function like this:</p>\n<pre><code>#include &lt;sys/types.h&gt;\n#include &lt;sys/sysctl.h&gt;\n...\nint mib[2];\nint64_t physical_memory;\nmib[0] = CTL_HW;\nmib[1] = HW_MEMSIZE;\nlength = sizeof(int64_t);\nsysctl(mib, 2, &amp;physical_memory, &amp;length, NULL, 0);\n</code></pre>\n<h2>RAM Currently Used</h2>\n<p>You can get general memory statistics from the <code>host_statistics</code> system function.</p>\n<pre><code>#include &lt;mach/vm_statistics.h&gt;\n#include &lt;mach/mach_types.h&gt;\n#include &lt;mach/mach_init.h&gt;\n#include &lt;mach/mach_host.h&gt;\n\nint main(int argc, const char * argv[]) {\n vm_size_t page_size;\n mach_port_t mach_port;\n mach_msg_type_number_t count;\n vm_statistics64_data_t vm_stats;\n\n mach_port = mach_host_self();\n count = sizeof(vm_stats) / sizeof(natural_t);\n if (KERN_SUCCESS == host_page_size(mach_port, &amp;page_size) &amp;&amp;\n KERN_SUCCESS == host_statistics64(mach_port, HOST_VM_INFO,\n (host_info64_t)&amp;vm_stats, &amp;count))\n {\n long long free_memory = (int64_t)vm_stats.free_count * (int64_t)page_size;\n\n long long used_memory = ((int64_t)vm_stats.active_count +\n (int64_t)vm_stats.inactive_count +\n (int64_t)vm_stats.wire_count) * (int64_t)page_size;\n printf(&quot;free memory: %lld\\nused memory: %lld\\n&quot;, free_memory, used_memory);\n }\n\n return 0;\n}\n</code></pre>\n<p>One thing to note here are that there are five types of memory pages in Mac OS X. They are as follows:</p>\n<ol>\n<li><strong>Wired</strong> pages that are locked in place and cannot be swapped out</li>\n<li><strong>Active</strong> pages that are loading into physical memory and would be relatively difficult to swap out</li>\n<li><strong>Inactive</strong> pages that are loaded into memory, but haven't been used recently and may not even be needed at all. These are potential candidates for swapping. This memory would probably need to be flushed.</li>\n<li><strong>Cached</strong> pages that have been some how cached that are likely to be easily reused. Cached memory probably would not require flushing. It is still possible for cached pages to be reactivated</li>\n<li><strong>Free</strong> pages that are completely free and ready to be used.</li>\n</ol>\n<p>It is good to note that just because Mac OS X may show very little actual free memory at times that it may not be a good indication of how much is ready to be used on short notice.</p>\n<h2>RAM Currently Used by my Process</h2>\n<p>See the &quot;Virtual Memory Currently Used by my Process&quot; above. The same code applies.</p>\n" }, { "answer_id": 13947253, "author": "Mohsen Zahraee", "author_id": 1907986, "author_profile": "https://Stackoverflow.com/users/1907986", "pm_score": 4, "selected": false, "text": "<p><strong>In Windows you can get CPU usage by the code below:</strong></p>\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n\n//------------------------------------------------------------------------------------------------------------------\n// Prototype(s)...\n//------------------------------------------------------------------------------------------------------------------\nCHAR cpuusage(void);\n\n//-----------------------------------------------------\ntypedef BOOL ( __stdcall * pfnGetSystemTimes)( LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime );\nstatic pfnGetSystemTimes s_pfnGetSystemTimes = NULL;\n\nstatic HMODULE s_hKernel = NULL;\n//-----------------------------------------------------\nvoid GetSystemTimesAddress()\n{\n if(s_hKernel == NULL)\n {\n s_hKernel = LoadLibrary(L&quot;Kernel32.dll&quot;);\n if(s_hKernel != NULL)\n {\n s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress(s_hKernel, &quot;GetSystemTimes&quot;);\n if(s_pfnGetSystemTimes == NULL)\n {\n FreeLibrary(s_hKernel);\n s_hKernel = NULL;\n }\n }\n }\n}\n//----------------------------------------------------------------------------------------------------------------\n\n//----------------------------------------------------------------------------------------------------------------\n// cpuusage(void)\n// ==============\n// Return a CHAR value in the range 0 - 100 representing actual CPU usage in percent.\n//----------------------------------------------------------------------------------------------------------------\nCHAR cpuusage()\n{\n FILETIME ft_sys_idle;\n FILETIME ft_sys_kernel;\n FILETIME ft_sys_user;\n\n ULARGE_INTEGER ul_sys_idle;\n ULARGE_INTEGER ul_sys_kernel;\n ULARGE_INTEGER ul_sys_user;\n\n static ULARGE_INTEGER ul_sys_idle_old;\n static ULARGE_INTEGER ul_sys_kernel_old;\n static ULARGE_INTEGER ul_sys_user_old;\n\n CHAR usage = 0;\n\n // We cannot directly use GetSystemTimes in the C language\n /* Add this line :: pfnGetSystemTimes */\n s_pfnGetSystemTimes(&amp;ft_sys_idle, /* System idle time */\n &amp;ft_sys_kernel, /* system kernel time */\n &amp;ft_sys_user); /* System user time */\n\n CopyMemory(&amp;ul_sys_idle , &amp;ft_sys_idle , sizeof(FILETIME)); // Could been optimized away...\n CopyMemory(&amp;ul_sys_kernel, &amp;ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away...\n CopyMemory(&amp;ul_sys_user , &amp;ft_sys_user , sizeof(FILETIME)); // Could been optimized away...\n\n usage =\n (\n (\n (\n (\n (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+\n (ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)\n )\n -\n (ul_sys_idle.QuadPart-ul_sys_idle_old.QuadPart)\n )\n *\n (100)\n )\n /\n (\n (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+\n (ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)\n )\n );\n\n ul_sys_idle_old.QuadPart = ul_sys_idle.QuadPart;\n ul_sys_user_old.QuadPart = ul_sys_user.QuadPart;\n ul_sys_kernel_old.QuadPart = ul_sys_kernel.QuadPart;\n\n return usage;\n}\n\n\n//------------------------------------------------------------------------------------------------------------------\n// Entry point\n//------------------------------------------------------------------------------------------------------------------\nint main(void)\n{\n int n;\n GetSystemTimesAddress();\n for(n=0; n&lt;20; n++)\n {\n printf(&quot;CPU Usage: %3d%%\\r&quot;, cpuusage());\n Sleep(2000);\n }\n printf(&quot;\\n&quot;);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 30452461, "author": "Boernii", "author_id": 4894793, "author_profile": "https://Stackoverflow.com/users/4894793", "pm_score": 2, "selected": false, "text": "<h1>QNX</h1>\n<p>Since this is like a &quot;wikipage of code&quot; I want to add some code from the QNX Knowledge base (note: this is not my work, but I checked it and it works fine on my system):</p>\n<p>How to get CPU usage in %: <a href=\"http://www.qnx.com/support/knowledgebase.html?id=50130000000P9b5\" rel=\"nofollow noreferrer\">http://www.qnx.com/support/knowledgebase.html?id=50130000000P9b5</a></p>\n<pre><code>#include &lt;atomic.h&gt;\n#include &lt;libc.h&gt;\n#include &lt;pthread.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;sys/iofunc.h&gt;\n#include &lt;sys/neutrino.h&gt;\n#include &lt;sys/resmgr.h&gt;\n#include &lt;sys/syspage.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;inttypes.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;sys/types.h&gt;\n#include &lt;sys/debug.h&gt;\n#include &lt;sys/procfs.h&gt;\n#include &lt;sys/syspage.h&gt;\n#include &lt;sys/neutrino.h&gt;\n#include &lt;sys/time.h&gt;\n#include &lt;time.h&gt;\n#include &lt;fcntl.h&gt;\n#include &lt;devctl.h&gt;\n#include &lt;errno.h&gt;\n\n#define MAX_CPUS 32\n\nstatic float Loads[MAX_CPUS];\nstatic _uint64 LastSutime[MAX_CPUS];\nstatic _uint64 LastNsec[MAX_CPUS];\nstatic int ProcFd = -1;\nstatic int NumCpus = 0;\n\n\nint find_ncpus(void) {\n return NumCpus;\n}\n\nint get_cpu(int cpu) {\n int ret;\n ret = (int)Loads[ cpu % MAX_CPUS ];\n ret = max(0,ret);\n ret = min(100,ret);\n return( ret );\n}\n\nstatic _uint64 nanoseconds( void ) {\n _uint64 sec, usec;\n struct timeval tval;\n gettimeofday( &amp;tval, NULL );\n sec = tval.tv_sec;\n usec = tval.tv_usec;\n return( ( ( sec * 1000000 ) + usec ) * 1000 );\n}\n\nint sample_cpus( void ) {\n int i;\n debug_thread_t debug_data;\n _uint64 current_nsec, sutime_delta, time_delta;\n memset( &amp;debug_data, 0, sizeof( debug_data ) );\n \n for( i=0; i&lt;NumCpus; i++ ) {\n /* Get the sutime of the idle thread #i+1 */\n debug_data.tid = i + 1;\n devctl( ProcFd, DCMD_PROC_TIDSTATUS,\n &amp;debug_data, sizeof( debug_data ), NULL );\n /* Get the current time */\n current_nsec = nanoseconds();\n /* Get the deltas between now and the last samples */\n sutime_delta = debug_data.sutime - LastSutime[i];\n time_delta = current_nsec - LastNsec[i];\n /* Figure out the load */\n Loads[i] = 100.0 - ( (float)( sutime_delta * 100 ) / (float)time_delta );\n /* Flat out strange rounding issues. */\n if( Loads[i] &lt; 0 ) {\n Loads[i] = 0;\n }\n /* Keep these for reference in the next cycle */\n LastNsec[i] = current_nsec;\n LastSutime[i] = debug_data.sutime;\n }\n return EOK;\n}\n\nint init_cpu( void ) {\n int i;\n debug_thread_t debug_data;\n memset( &amp;debug_data, 0, sizeof( debug_data ) );\n/* Open a connection to proc to talk over.*/\n ProcFd = open( &quot;/proc/1/as&quot;, O_RDONLY );\n if( ProcFd == -1 ) {\n fprintf( stderr, &quot;pload: Unable to access procnto: %s\\n&quot;,strerror( errno ) );\n fflush( stderr );\n return -1;\n }\n i = fcntl(ProcFd,F_GETFD);\n if(i != -1){\n i |= FD_CLOEXEC;\n if(fcntl(ProcFd,F_SETFD,i) != -1){\n /* Grab this value */\n NumCpus = _syspage_ptr-&gt;num_cpu;\n /* Get a starting point for the comparisons */\n for( i=0; i&lt;NumCpus; i++ ) {\n /*\n * the sutime of idle thread is how much\n * time that thread has been using, we can compare this\n * against how much time has passed to get an idea of the\n * load on the system.\n */\n debug_data.tid = i + 1;\n devctl( ProcFd, DCMD_PROC_TIDSTATUS, &amp;debug_data, sizeof( debug_data ), NULL );\n LastSutime[i] = debug_data.sutime;\n LastNsec[i] = nanoseconds();\n }\n return(EOK);\n }\n }\n close(ProcFd);\n return(-1);\n}\n\nvoid close_cpu(void){\n if(ProcFd != -1){\n close(ProcFd);\n ProcFd = -1;\n }\n}\n\nint main(int argc, char* argv[]){\n int i,j;\n init_cpu();\n printf(&quot;System has: %d CPUs\\n&quot;, NumCpus);\n for(i=0; i&lt;20; i++) {\n sample_cpus();\n for(j=0; j&lt;NumCpus;j++)\n printf(&quot;CPU #%d: %f\\n&quot;, j, Loads[j]);\n sleep(1);\n }\n close_cpu();\n}\n</code></pre>\n<p>How to get the free (!) memory: <a href=\"http://www.qnx.com/support/knowledgebase.html?id=50130000000mlbx\" rel=\"nofollow noreferrer\">http://www.qnx.com/support/knowledgebase.html?id=50130000000mlbx</a></p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;errno.h&gt;\n#include &lt;err.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;sys/types.h&gt;\n\nint main( int argc, char *argv[] ){\n struct stat statbuf;\n paddr_t freemem;\n stat( &quot;/proc&quot;, &amp;statbuf );\n freemem = (paddr_t)statbuf.st_size;\n printf( &quot;Free memory: %d bytes\\n&quot;, freemem );\n printf( &quot;Free memory: %d KB\\n&quot;, freemem / 1024 );\n printf( &quot;Free memory: %d MB\\n&quot;, freemem / ( 1024 * 1024 ) );\n return 0;\n} \n</code></pre>\n" }, { "answer_id": 31464645, "author": "Mark Lakata", "author_id": 364818, "author_profile": "https://Stackoverflow.com/users/364818", "pm_score": 4, "selected": false, "text": "<h1>Linux</h1>\n\n<p>A portable way of reading memory and load numbers is the <a href=\"http://man7.org/linux/man-pages/man2/sysinfo.2.html\" rel=\"noreferrer\"><code>sysinfo</code> call</a></p>\n\n<h2>Usage</h2>\n\n<pre><code> #include &lt;sys/sysinfo.h&gt;\n\n int sysinfo(struct sysinfo *info);\n</code></pre>\n\n<h2>DESCRIPTION</h2>\n\n<pre><code> Until Linux 2.3.16, sysinfo() used to return information in the\n following structure:\n\n struct sysinfo {\n long uptime; /* Seconds since boot */\n unsigned long loads[3]; /* 1, 5, and 15 minute load averages */\n unsigned long totalram; /* Total usable main memory size */\n unsigned long freeram; /* Available memory size */\n unsigned long sharedram; /* Amount of shared memory */\n unsigned long bufferram; /* Memory used by buffers */\n unsigned long totalswap; /* Total swap space size */\n unsigned long freeswap; /* swap space still available */\n unsigned short procs; /* Number of current processes */\n char _f[22]; /* Pads structure to 64 bytes */\n };\n\n and the sizes were given in bytes.\n\n Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure\n is:\n\n struct sysinfo {\n long uptime; /* Seconds since boot */\n unsigned long loads[3]; /* 1, 5, and 15 minute load averages */\n unsigned long totalram; /* Total usable main memory size */\n unsigned long freeram; /* Available memory size */\n unsigned long sharedram; /* Amount of shared memory */\n unsigned long bufferram; /* Memory used by buffers */\n unsigned long totalswap; /* Total swap space size */\n unsigned long freeswap; /* swap space still available */\n unsigned short procs; /* Number of current processes */\n unsigned long totalhigh; /* Total high memory size */\n unsigned long freehigh; /* Available high memory size */\n unsigned int mem_unit; /* Memory unit size in bytes */\n char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding to 64 bytes */\n };\n\n and the sizes are given as multiples of mem_unit bytes.\n</code></pre>\n" }, { "answer_id": 40268513, "author": "Salman Ghaffar", "author_id": 7037557, "author_profile": "https://Stackoverflow.com/users/7037557", "pm_score": 0, "selected": false, "text": "<p>I used this following code in my C++ project and it worked fine:</p>\n\n<pre><code>static HANDLE self;\nstatic int numProcessors;\nSYSTEM_INFO sysInfo;\n\ndouble percent;\n\nnumProcessors = sysInfo.dwNumberOfProcessors;\n\n//Getting system times information\nFILETIME SysidleTime;\nFILETIME SyskernelTime; \nFILETIME SysuserTime; \nULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;\nGetSystemTimes(&amp;SysidleTime, &amp;SyskernelTime, &amp;SysuserTime);\nmemcpy(&amp;SyskernelTimeInt, &amp;SyskernelTime, sizeof(FILETIME));\nmemcpy(&amp;SysuserTimeInt, &amp;SysuserTime, sizeof(FILETIME));\n__int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart; \n\n//Getting process times information\nFILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;\nULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;\nGetProcessTimes(self, &amp;ProccreationTime, &amp;ProcexitTime, &amp;ProcKernelTime, &amp;ProcUserTime);\nmemcpy(&amp;ProcKernelTimeInt, &amp;ProcKernelTime, sizeof(FILETIME));\nmemcpy(&amp;ProcUserTimeInt, &amp;ProcUserTime, sizeof(FILETIME));\n__int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;\n//QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)\n\npercent = 100*(numerator/denomenator);\n</code></pre>\n" }, { "answer_id": 42925322, "author": "Steven Warner", "author_id": 4721690, "author_profile": "https://Stackoverflow.com/users/4721690", "pm_score": 2, "selected": false, "text": "<h3>For Linux</h3>\n<p>You can also use /proc/self/statm to get a single line of numbers containing key process memory information which is a faster thing to process than going through a long list of reported information as you get from proc/self/status</p>\n<p>See <em><a href=\"http://man7.org/linux/man-pages/man5/proc.5.html\" rel=\"nofollow noreferrer\">proc(5)</a></em></p>\n<pre class=\"lang-none prettyprint-override\"><code>/proc/[pid]/statm\n\n Provides information about memory usage, measured in pages.\n The columns are:\n\n size (1) total program size\n (same as VmSize in /proc/[pid]/status)\n resident (2) resident set size\n (same as VmRSS in /proc/[pid]/status)\n shared (3) number of resident shared pages (i.e., backed by a file)\n (same as RssFile+RssShmem in /proc/[pid]/status)\n text (4) text (code)\n lib (5) library (unused since Linux 2.6; always 0)\n data (6) data + stack\n dt (7) dirty pages (unused since Linux 2.6; always 0)\n</code></pre>\n" }, { "answer_id": 49996245, "author": "souch", "author_id": 4964856, "author_profile": "https://Stackoverflow.com/users/4964856", "pm_score": 2, "selected": false, "text": "<p><strong>Mac OS X - CPU</strong></p>\n<p>Overall CPU usage:</p>\n<p>From <em><a href=\"https://stackoverflow.com/questions/8736713/retrieve-system-information-on-macos-x\">Retrieve system information on Mac OS X</a></em>:</p>\n<pre><code>#include &lt;mach/mach_init.h&gt;\n#include &lt;mach/mach_error.h&gt;\n#include &lt;mach/mach_host.h&gt;\n#include &lt;mach/vm_map.h&gt;\n\nstatic unsigned long long _previousTotalTicks = 0;\nstatic unsigned long long _previousIdleTicks = 0;\n\n// Returns 1.0f for &quot;CPU fully pinned&quot;, 0.0f for &quot;CPU idle&quot;, or somewhere in between\n// You'll need to call this at regular intervals, since it measures the load between\n// the previous call and the current one.\nfloat GetCPULoad()\n{\n host_cpu_load_info_data_t cpuinfo;\n mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;\n if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&amp;cpuinfo, &amp;count) == KERN_SUCCESS)\n {\n unsigned long long totalTicks = 0;\n for(int i=0; i&lt;CPU_STATE_MAX; i++) totalTicks += cpuinfo.cpu_ticks[i];\n return CalculateCPULoad(cpuinfo.cpu_ticks[CPU_STATE_IDLE], totalTicks);\n }\n else return -1.0f;\n}\n\nfloat CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)\n{\n unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks;\n unsigned long long idleTicksSinceLastTime = idleTicks-_previousIdleTicks;\n float ret = 1.0f-((totalTicksSinceLastTime &gt; 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);\n _previousTotalTicks = totalTicks;\n _previousIdleTicks = idleTicks;\n return ret;\n}\n</code></pre>\n" }, { "answer_id": 65270655, "author": "Marisa Kirisame", "author_id": 7984460, "author_profile": "https://Stackoverflow.com/users/7984460", "pm_score": 0, "selected": false, "text": "<p>On Linux, you cannot/should not get &quot;Total Available Physical Memory&quot; with SysInfo's freeram or by doing some arithmetic on totalram.</p>\n<p>The recommended way to do this is by reading proc/meminfo, quoting <em><a href=\"https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773\" rel=\"nofollow noreferrer\">kernel/git/torvalds/linux.git, <em>/proc/meminfo: provide estimated available memory</em></a></em>:</p>\n<blockquote>\n<p>Many load balancing and workload placing programs check /proc/meminfo to\nestimate how much free memory is available. They generally do this by\nadding up &quot;free&quot; and &quot;cached&quot;, which was fine ten years ago, but is\npretty much guaranteed to be wrong today.</p>\n</blockquote>\n<blockquote>\n<p>It is more convenient to provide such an estimate in /proc/meminfo. If things change in the future, we only have to change it in one place.</p>\n</blockquote>\n<p>One way to do it is as <em><a href=\"https://stackoverflow.com/questions/349889/how-do-you-determine-the-amount-of-linux-system-ram-in-c/350039#350039\">Adam Rosenfield's answer to <em>How do you determine the amount of Linux system RAM in C++?</em></a></em> suggest: read the file, and use fscanf to grab the line (but instead of going for MemTotal, go for MemAvailable)</p>\n<p>Likewise, if you want to get the total amount of physical memory used, depending on what you mean by &quot;use&quot;, you might not want to subtract freeram from totalram, but subtract memavailable from memtotal to get what top or htop tells you.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7381/" ]
I once had the task of determining the following performance parameters from inside a running application: * Total virtual memory available * Virtual memory currently used * Virtual memory currently used by my process --- * Total RAM available * RAM currently used * RAM currently used by my process --- * % CPU currently used * % CPU currently used by my process The code had to run on Windows and Linux. Even though this seems to be a standard task, finding the necessary information in the manuals (WIN32 API, GNU docs) as well as on the Internet took me several days, because there's so much incomplete/incorrect/outdated information on this topic to be found out there. In order to save others from going through the same trouble, I thought it would be a good idea to collect all the scattered information plus what I found by trial and error here in one place.
Windows ------- Some of the above values are easily available from the appropriate Win32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit "unintuitive" and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...) Note: for clarity all error checking has been omitted from the following code. Do check the return codes...! * Total Virtual Memory: ``` #include "windows.h" MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(&memInfo); DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile; ``` Note: The name "TotalPageFile" is a bit misleading here. In reality this parameter gives the "Virtual Memory Size", which is size of swap file plus installed RAM. * Virtual Memory currently used: Same code as in "Total Virtual Memory" and then ``` DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile; ``` * Virtual Memory currently used by current process: ``` #include "windows.h" #include "psapi.h" PROCESS_MEMORY_COUNTERS_EX pmc; GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)); SIZE_T virtualMemUsedByMe = pmc.PrivateUsage; ``` * Total Physical Memory (RAM): Same code as in "Total Virtual Memory" and then ``` DWORDLONG totalPhysMem = memInfo.ullTotalPhys; ``` * Physical Memory currently used: Same code as in "Total Virtual Memory" and then ``` DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys; ``` * Physical Memory currently used by current process: Same code as in "Virtual Memory currently used by current process" and then ``` SIZE_T physMemUsedByMe = pmc.WorkingSetSize; ``` * CPU currently used: ``` #include "TCHAR.h" #include "pdh.h" static PDH_HQUERY cpuQuery; static PDH_HCOUNTER cpuTotal; void init(){ PdhOpenQuery(NULL, NULL, &cpuQuery); // You can also use L"\\Processor(*)\\% Processor Time" and get individual CPU values with PdhGetFormattedCounterArray() PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal); PdhCollectQueryData(cpuQuery); } double getCurrentValue(){ PDH_FMT_COUNTERVALUE counterVal; PdhCollectQueryData(cpuQuery); PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal); return counterVal.doubleValue; } ``` * CPU currently used by current process: ``` #include "windows.h" static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU; static int numProcessors; static HANDLE self; void init(){ SYSTEM_INFO sysInfo; FILETIME ftime, fsys, fuser; GetSystemInfo(&sysInfo); numProcessors = sysInfo.dwNumberOfProcessors; GetSystemTimeAsFileTime(&ftime); memcpy(&lastCPU, &ftime, sizeof(FILETIME)); self = GetCurrentProcess(); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); memcpy(&lastSysCPU, &fsys, sizeof(FILETIME)); memcpy(&lastUserCPU, &fuser, sizeof(FILETIME)); } double getCurrentValue(){ FILETIME ftime, fsys, fuser; ULARGE_INTEGER now, sys, user; double percent; GetSystemTimeAsFileTime(&ftime); memcpy(&now, &ftime, sizeof(FILETIME)); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); memcpy(&sys, &fsys, sizeof(FILETIME)); memcpy(&user, &fuser, sizeof(FILETIME)); percent = (sys.QuadPart - lastSysCPU.QuadPart) + (user.QuadPart - lastUserCPU.QuadPart); percent /= (now.QuadPart - lastCPU.QuadPart); percent /= numProcessors; lastCPU = now; lastUserCPU = user; lastSysCPU = sys; return percent * 100; } ``` --- Linux ----- On Linux the choice that seemed obvious at first was to use the POSIX APIs like `getrusage()` etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!? In the end I got all values via a combination of reading the pseudo-filesystem `/proc` and kernel calls. * Total Virtual Memory: ``` #include "sys/types.h" #include "sys/sysinfo.h" struct sysinfo memInfo; sysinfo (&memInfo); long long totalVirtualMem = memInfo.totalram; //Add other values in next statement to avoid int overflow on right hand side... totalVirtualMem += memInfo.totalswap; totalVirtualMem *= memInfo.mem_unit; ``` * Virtual Memory currently used: Same code as in "Total Virtual Memory" and then ``` long long virtualMemUsed = memInfo.totalram - memInfo.freeram; //Add other values in next statement to avoid int overflow on right hand side... virtualMemUsed += memInfo.totalswap - memInfo.freeswap; virtualMemUsed *= memInfo.mem_unit; ``` * Virtual Memory currently used by current process: ``` #include "stdlib.h" #include "stdio.h" #include "string.h" int parseLine(char* line){ // This assumes that a digit will be found and the line ends in " Kb". int i = strlen(line); const char* p = line; while (*p <'0' || *p > '9') p++; line[i-3] = '\0'; i = atoi(p); return i; } int getValue(){ //Note: this value is in KB! FILE* file = fopen("/proc/self/status", "r"); int result = -1; char line[128]; while (fgets(line, 128, file) != NULL){ if (strncmp(line, "VmSize:", 7) == 0){ result = parseLine(line); break; } } fclose(file); return result; } ``` * Total Physical Memory (RAM): Same code as in "Total Virtual Memory" and then ``` long long totalPhysMem = memInfo.totalram; //Multiply in next statement to avoid int overflow on right hand side... totalPhysMem *= memInfo.mem_unit; ``` * Physical Memory currently used: Same code as in "Total Virtual Memory" and then ``` long long physMemUsed = memInfo.totalram - memInfo.freeram; //Multiply in next statement to avoid int overflow on right hand side... physMemUsed *= memInfo.mem_unit; ``` * Physical Memory currently used by current process: Change getValue() in "Virtual Memory currently used by current process" as follows: ``` int getValue(){ //Note: this value is in KB! FILE* file = fopen("/proc/self/status", "r"); int result = -1; char line[128]; while (fgets(line, 128, file) != NULL){ if (strncmp(line, "VmRSS:", 6) == 0){ result = parseLine(line); break; } } fclose(file); return result; } ``` * CPU currently used: ``` #include "stdlib.h" #include "stdio.h" #include "string.h" static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle; void init(){ FILE* file = fopen("/proc/stat", "r"); fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow, &lastTotalSys, &lastTotalIdle); fclose(file); } double getCurrentValue(){ double percent; FILE* file; unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total; file = fopen("/proc/stat", "r"); fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow, &totalSys, &totalIdle); fclose(file); if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow || totalSys < lastTotalSys || totalIdle < lastTotalIdle){ //Overflow detection. Just skip this value. percent = -1.0; } else{ total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) + (totalSys - lastTotalSys); percent = total; total += (totalIdle - lastTotalIdle); percent /= total; percent *= 100; } lastTotalUser = totalUser; lastTotalUserLow = totalUserLow; lastTotalSys = totalSys; lastTotalIdle = totalIdle; return percent; } ``` * CPU currently used by current process: ``` #include "stdlib.h" #include "stdio.h" #include "string.h" #include "sys/times.h" #include "sys/vtimes.h" static clock_t lastCPU, lastSysCPU, lastUserCPU; static int numProcessors; void init(){ FILE* file; struct tms timeSample; char line[128]; lastCPU = times(&timeSample); lastSysCPU = timeSample.tms_stime; lastUserCPU = timeSample.tms_utime; file = fopen("/proc/cpuinfo", "r"); numProcessors = 0; while(fgets(line, 128, file) != NULL){ if (strncmp(line, "processor", 9) == 0) numProcessors++; } fclose(file); } double getCurrentValue(){ struct tms timeSample; clock_t now; double percent; now = times(&timeSample); if (now <= lastCPU || timeSample.tms_stime < lastSysCPU || timeSample.tms_utime < lastUserCPU){ //Overflow detection. Just skip this value. percent = -1.0; } else{ percent = (timeSample.tms_stime - lastSysCPU) + (timeSample.tms_utime - lastUserCPU); percent /= (now - lastCPU); percent /= numProcessors; percent *= 100; } lastCPU = now; lastSysCPU = timeSample.tms_stime; lastUserCPU = timeSample.tms_utime; return percent; } ``` --- TODO: Other Platforms --------------------- I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by `getrusage()` and similar functions?
63,181
<p>In Flex, I have an xml document such as the following:</p> <pre><code>var xml:XML = &lt;root&gt;&lt;node&gt;value1&lt;/node&gt;&lt;node&gt;value2&lt;/node&gt;&lt;node&gt;value3&lt;/node&gt;&lt;/root&gt; </code></pre> <p>At runtime, I want to create a TextInput control for each node under root, and have the values bound to the values in the XML. As far as I can tell I can't use BindingUtils to bind to e4x nodes at runtime (please tell me if I'm wrong here!), so I'm trying to do this by hand:</p> <pre><code>for each (var node:XML in xml.node) { var textInput:TextInput = new TextInput(); var handler:Function = function(event:Event):void { node.setChildren(event.target.text); }; textInput.text = node.text(); textInput.addEventListener(Event.CHANGE, handler); this.addChild(pileHeightEditor); } </code></pre> <p>My problem is that when the user edits one of the TextInputs, the node getting assigned to is always the last one encountered in the for loop. I am used to this pattern from C#, where each time an anonymous function is created, a "snapshot" of the values of the used values is taken, so "node" would be different in each handler function.</p> <p>How do I "take a snapshot" of the current value of node to use in the handler? Or should I be using a different pattern in Flex?</p>
[ { "answer_id": 64166, "author": "Lanzelot", "author_id": 7381, "author_profile": "https://Stackoverflow.com/users/7381", "pm_score": 10, "selected": false, "text": "<h2>Windows</h2>\n<p>Some of the above values are easily available from the appropriate Win32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit &quot;unintuitive&quot; and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...)</p>\n<p>Note: for clarity all error checking has been omitted from the following code. Do check the return codes...!</p>\n<ul>\n<li><p>Total Virtual Memory:</p>\n<pre><code>#include &quot;windows.h&quot;\n\nMEMORYSTATUSEX memInfo;\nmemInfo.dwLength = sizeof(MEMORYSTATUSEX);\nGlobalMemoryStatusEx(&amp;memInfo);\nDWORDLONG totalVirtualMem = memInfo.ullTotalPageFile;\n</code></pre>\n<p>Note: The name &quot;TotalPageFile&quot; is a bit misleading here. In reality this parameter gives the &quot;Virtual Memory Size&quot;, which is size of swap file plus installed RAM.</p>\n</li>\n<li><p>Virtual Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code> DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;\n</code></pre>\n</li>\n<li><p>Virtual Memory currently used by current process:</p>\n<pre><code>#include &quot;windows.h&quot;\n#include &quot;psapi.h&quot;\n\nPROCESS_MEMORY_COUNTERS_EX pmc;\nGetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&amp;pmc, sizeof(pmc));\nSIZE_T virtualMemUsedByMe = pmc.PrivateUsage;\n</code></pre>\n</li>\n<li><p>Total Physical Memory (RAM):</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>DWORDLONG totalPhysMem = memInfo.ullTotalPhys;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used by current process:</p>\n<p>Same code as in &quot;Virtual Memory currently used by current process&quot; and then</p>\n<pre><code>SIZE_T physMemUsedByMe = pmc.WorkingSetSize;\n</code></pre>\n</li>\n<li><p>CPU currently used:</p>\n<pre><code>#include &quot;TCHAR.h&quot;\n#include &quot;pdh.h&quot;\n\nstatic PDH_HQUERY cpuQuery;\nstatic PDH_HCOUNTER cpuTotal;\n\nvoid init(){\n PdhOpenQuery(NULL, NULL, &amp;cpuQuery);\n // You can also use L&quot;\\\\Processor(*)\\\\% Processor Time&quot; and get individual CPU values with PdhGetFormattedCounterArray()\n PdhAddEnglishCounter(cpuQuery, L&quot;\\\\Processor(_Total)\\\\% Processor Time&quot;, NULL, &amp;cpuTotal);\n PdhCollectQueryData(cpuQuery);\n}\n\ndouble getCurrentValue(){\n PDH_FMT_COUNTERVALUE counterVal;\n\n PdhCollectQueryData(cpuQuery);\n PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &amp;counterVal);\n return counterVal.doubleValue;\n}\n</code></pre>\n</li>\n<li><p>CPU currently used by current process:</p>\n<pre><code>#include &quot;windows.h&quot;\n\nstatic ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU;\nstatic int numProcessors;\nstatic HANDLE self;\n\nvoid init(){\n SYSTEM_INFO sysInfo;\n FILETIME ftime, fsys, fuser;\n\n GetSystemInfo(&amp;sysInfo);\n numProcessors = sysInfo.dwNumberOfProcessors;\n\n GetSystemTimeAsFileTime(&amp;ftime);\n memcpy(&amp;lastCPU, &amp;ftime, sizeof(FILETIME));\n\n self = GetCurrentProcess();\n GetProcessTimes(self, &amp;ftime, &amp;ftime, &amp;fsys, &amp;fuser);\n memcpy(&amp;lastSysCPU, &amp;fsys, sizeof(FILETIME));\n memcpy(&amp;lastUserCPU, &amp;fuser, sizeof(FILETIME));\n}\n\ndouble getCurrentValue(){\n FILETIME ftime, fsys, fuser;\n ULARGE_INTEGER now, sys, user;\n double percent;\n\n GetSystemTimeAsFileTime(&amp;ftime);\n memcpy(&amp;now, &amp;ftime, sizeof(FILETIME));\n\n GetProcessTimes(self, &amp;ftime, &amp;ftime, &amp;fsys, &amp;fuser);\n memcpy(&amp;sys, &amp;fsys, sizeof(FILETIME));\n memcpy(&amp;user, &amp;fuser, sizeof(FILETIME));\n percent = (sys.QuadPart - lastSysCPU.QuadPart) +\n (user.QuadPart - lastUserCPU.QuadPart);\n percent /= (now.QuadPart - lastCPU.QuadPart);\n percent /= numProcessors;\n lastCPU = now;\n lastUserCPU = user;\n lastSysCPU = sys;\n\n return percent * 100;\n}\n</code></pre>\n</li>\n</ul>\n<hr />\n<h2>Linux</h2>\n<p>On Linux the choice that seemed obvious at first was to use the POSIX APIs like <code>getrusage()</code> etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!?</p>\n<p>In the end I got all values via a combination of reading the pseudo-filesystem <code>/proc</code> and kernel calls.</p>\n<ul>\n<li><p>Total Virtual Memory:</p>\n<pre><code>#include &quot;sys/types.h&quot;\n#include &quot;sys/sysinfo.h&quot;\n\nstruct sysinfo memInfo;\n\nsysinfo (&amp;memInfo);\nlong long totalVirtualMem = memInfo.totalram;\n//Add other values in next statement to avoid int overflow on right hand side...\ntotalVirtualMem += memInfo.totalswap;\ntotalVirtualMem *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Virtual Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>long long virtualMemUsed = memInfo.totalram - memInfo.freeram;\n//Add other values in next statement to avoid int overflow on right hand side...\nvirtualMemUsed += memInfo.totalswap - memInfo.freeswap;\nvirtualMemUsed *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Virtual Memory currently used by current process:</p>\n<pre><code>#include &quot;stdlib.h&quot;\n#include &quot;stdio.h&quot;\n#include &quot;string.h&quot;\n\nint parseLine(char* line){\n // This assumes that a digit will be found and the line ends in &quot; Kb&quot;.\n int i = strlen(line);\n const char* p = line;\n while (*p &lt;'0' || *p &gt; '9') p++;\n line[i-3] = '\\0';\n i = atoi(p);\n return i;\n}\n\nint getValue(){ //Note: this value is in KB!\n FILE* file = fopen(&quot;/proc/self/status&quot;, &quot;r&quot;);\n int result = -1;\n char line[128];\n\n while (fgets(line, 128, file) != NULL){\n if (strncmp(line, &quot;VmSize:&quot;, 7) == 0){\n result = parseLine(line);\n break;\n }\n }\n fclose(file);\n return result;\n}\n</code></pre>\n</li>\n<li><p>Total Physical Memory (RAM):</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>long long totalPhysMem = memInfo.totalram;\n//Multiply in next statement to avoid int overflow on right hand side...\ntotalPhysMem *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used:</p>\n<p>Same code as in &quot;Total Virtual Memory&quot; and then</p>\n<pre><code>long long physMemUsed = memInfo.totalram - memInfo.freeram;\n//Multiply in next statement to avoid int overflow on right hand side...\nphysMemUsed *= memInfo.mem_unit;\n</code></pre>\n</li>\n<li><p>Physical Memory currently used by current process:</p>\n<p>Change getValue() in &quot;Virtual Memory currently used by current process&quot; as follows:</p>\n<pre><code>int getValue(){ //Note: this value is in KB!\n FILE* file = fopen(&quot;/proc/self/status&quot;, &quot;r&quot;);\n int result = -1;\n char line[128];\n\n while (fgets(line, 128, file) != NULL){\n if (strncmp(line, &quot;VmRSS:&quot;, 6) == 0){\n result = parseLine(line);\n break;\n }\n }\n fclose(file);\n return result;\n}\n</code></pre>\n</li>\n</ul>\n<p></p>\n<ul>\n<li><p>CPU currently used:</p>\n<pre><code>#include &quot;stdlib.h&quot;\n#include &quot;stdio.h&quot;\n#include &quot;string.h&quot;\n\nstatic unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;\n\nvoid init(){\n FILE* file = fopen(&quot;/proc/stat&quot;, &quot;r&quot;);\n fscanf(file, &quot;cpu %llu %llu %llu %llu&quot;, &amp;lastTotalUser, &amp;lastTotalUserLow,\n &amp;lastTotalSys, &amp;lastTotalIdle);\n fclose(file);\n}\n\ndouble getCurrentValue(){\n double percent;\n FILE* file;\n unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total;\n\n file = fopen(&quot;/proc/stat&quot;, &quot;r&quot;);\n fscanf(file, &quot;cpu %llu %llu %llu %llu&quot;, &amp;totalUser, &amp;totalUserLow,\n &amp;totalSys, &amp;totalIdle);\n fclose(file);\n\n if (totalUser &lt; lastTotalUser || totalUserLow &lt; lastTotalUserLow ||\n totalSys &lt; lastTotalSys || totalIdle &lt; lastTotalIdle){\n //Overflow detection. Just skip this value.\n percent = -1.0;\n }\n else{\n total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) +\n (totalSys - lastTotalSys);\n percent = total;\n total += (totalIdle - lastTotalIdle);\n percent /= total;\n percent *= 100;\n }\n\n lastTotalUser = totalUser;\n lastTotalUserLow = totalUserLow;\n lastTotalSys = totalSys;\n lastTotalIdle = totalIdle;\n\n return percent;\n}\n</code></pre>\n</li>\n<li><p>CPU currently used by current process:</p>\n<pre><code>#include &quot;stdlib.h&quot;\n#include &quot;stdio.h&quot;\n#include &quot;string.h&quot;\n#include &quot;sys/times.h&quot;\n#include &quot;sys/vtimes.h&quot;\n\nstatic clock_t lastCPU, lastSysCPU, lastUserCPU;\nstatic int numProcessors;\n\nvoid init(){\n FILE* file;\n struct tms timeSample;\n char line[128];\n\n lastCPU = times(&amp;timeSample);\n lastSysCPU = timeSample.tms_stime;\n lastUserCPU = timeSample.tms_utime;\n\n file = fopen(&quot;/proc/cpuinfo&quot;, &quot;r&quot;);\n numProcessors = 0;\n while(fgets(line, 128, file) != NULL){\n if (strncmp(line, &quot;processor&quot;, 9) == 0) numProcessors++;\n }\n fclose(file);\n}\n\ndouble getCurrentValue(){\n struct tms timeSample;\n clock_t now;\n double percent;\n\n now = times(&amp;timeSample);\n if (now &lt;= lastCPU || timeSample.tms_stime &lt; lastSysCPU ||\n timeSample.tms_utime &lt; lastUserCPU){\n //Overflow detection. Just skip this value.\n percent = -1.0;\n }\n else{\n percent = (timeSample.tms_stime - lastSysCPU) +\n (timeSample.tms_utime - lastUserCPU);\n percent /= (now - lastCPU);\n percent /= numProcessors;\n percent *= 100;\n }\n lastCPU = now;\n lastSysCPU = timeSample.tms_stime;\n lastUserCPU = timeSample.tms_utime;\n\n return percent;\n}\n</code></pre>\n</li>\n</ul>\n<hr />\n<h2>TODO: Other Platforms</h2>\n<p>I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by <code>getrusage()</code> and similar functions?</p>\n" }, { "answer_id": 64422, "author": "Martin Del Vecchio", "author_id": 5397, "author_profile": "https://Stackoverflow.com/users/5397", "pm_score": 6, "selected": false, "text": "<h1>Linux</h1>\n\n<p>In Linux, this information is available in the /proc file system. I'm not a big fan of the text file format used, as each Linux distribution seems to customize at least one important file. A quick look as the source to 'ps' reveals the mess.</p>\n\n<p>But here is where to find the information you seek:</p>\n\n<p><strong>/proc/meminfo</strong> contains the majority of the system-wide information you seek. Here it looks like on my system; I think you are interested in <strong>MemTotal</strong>, <strong>MemFree</strong>, <strong>SwapTotal</strong>, and <strong>SwapFree</strong>:</p>\n\n<pre><code>Anderson cxc # more /proc/meminfo\nMemTotal: 4083948 kB\nMemFree: 2198520 kB\nBuffers: 82080 kB\nCached: 1141460 kB\nSwapCached: 0 kB\nActive: 1137960 kB\nInactive: 608588 kB\nHighTotal: 3276672 kB\nHighFree: 1607744 kB\nLowTotal: 807276 kB\nLowFree: 590776 kB\nSwapTotal: 2096440 kB\nSwapFree: 2096440 kB\nDirty: 32 kB\nWriteback: 0 kB\nAnonPages: 523252 kB\nMapped: 93560 kB\nSlab: 52880 kB\nSReclaimable: 24652 kB\nSUnreclaim: 28228 kB\nPageTables: 2284 kB\nNFS_Unstable: 0 kB\nBounce: 0 kB\nCommitLimit: 4138412 kB\nCommitted_AS: 1845072 kB\nVmallocTotal: 118776 kB\nVmallocUsed: 3964 kB\nVmallocChunk: 112860 kB\nHugePages_Total: 0\nHugePages_Free: 0\nHugePages_Rsvd: 0\nHugepagesize: 2048 kB\n</code></pre>\n\n<p>For CPU utilization, you have to do a little work. Linux makes available overall CPU utilization since system start; this probably isn't what you are interested in. If you want to know what the CPU utilization was for the last second, or 10 seconds, then you need to query the information and calculate it yourself.</p>\n\n<p>The information is available in <strong>/proc/stat</strong>, which is documented pretty well at <a href=\"http://www.linuxhowtos.org/System/procstat.htm\" rel=\"noreferrer\">http://www.linuxhowtos.org/System/procstat.htm</a>; here is what it looks like on my 4-core box:</p>\n\n<pre><code>Anderson cxc # more /proc/stat\ncpu 2329889 0 2364567 1063530460 9034 9463 96111 0\ncpu0 572526 0 636532 265864398 2928 1621 6899 0\ncpu1 590441 0 531079 265949732 4763 351 8522 0\ncpu2 562983 0 645163 265796890 682 7490 71650 0\ncpu3 603938 0 551790 265919440 660 0 9040 0\nintr 37124247\nctxt 50795173133\nbtime 1218807985\nprocesses 116889\nprocs_running 1\nprocs_blocked 0\n</code></pre>\n\n<p>First, you need to determine how many CPUs (or processors, or processing cores) are available in the system. To do this, count the number of 'cpuN' entries, where N starts at 0 and increments. Don't count the 'cpu' line, which is a combination of the cpuN lines. In my example, you can see cpu0 through cpu3, for a total of 4 processors. From now on, you can ignore cpu0..cpu3, and focus only on the 'cpu' line.</p>\n\n<p>Next, you need to know that the fourth number in these lines is a measure of idle time, and thus the fourth number on the 'cpu' line is the total idle time for all processors since boot time. This time is measured in Linux \"jiffies\", which are 1/100 of a second each. </p>\n\n<p>But you don't care about the total idle time; you care about the idle time in a given period, e.g., the last second. Do calculate that, you need to read this file twice, 1 second apart.Then you can do a diff of the fourth value of the line. For example, if you take a sample and get:</p>\n\n<pre><code>cpu 2330047 0 2365006 1063853632 9035 9463 96114 0\n</code></pre>\n\n<p>Then one second later you get this sample:</p>\n\n<pre><code>cpu 2330047 0 2365007 1063854028 9035 9463 96114 0\n</code></pre>\n\n<p>Subtract the two numbers, and you get a diff of 396, which means that your CPU had been idle for 3.96 seconds out of the last 1.00 second. The trick, of course, is that you need to divide by the number of processors. 3.96 / 4 = 0.99, and there is your idle percentage; 99% idle, and 1% busy.</p>\n\n<p>In my code, I have a ring buffer of 360 entries, and I read this file every second. That lets me quickly calculate the CPU utilization for 1 second, 10 seconds, etc., all the way up to 1 hour.</p>\n\n<p>For the process-specific information, you have to look in <strong>/proc/pid</strong>; if you don't care abut your pid, you can look in /proc/self.</p>\n\n<p>CPU used by your process is available in <strong>/proc/self/stat</strong>. This is an odd-looking file consisting of a single line; for example:</p>\n\n<pre><code>19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2\n 7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364\n8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0\n</code></pre>\n\n<p>The important data here are the 13th and 14th tokens (0 and 770 here). The 13th token is the number of jiffies that the process has executed in user mode, and the 14th is the number of jiffies that the process has executed in kernel mode. Add the two together, and you have its total CPU utilization.</p>\n\n<p>Again, you will have to sample this file periodically, and calculate the diff, in order to determine the process's CPU usage over time. </p>\n\n<p><strong>Edit:</strong> remember that when you calculate your process's CPU utilization, you have to take into account 1) the number of threads in your process, and 2) the number of processors in the system. For example, if your single-threaded process is using only 25% of the CPU, that could be good or bad. Good on a single-processor system, but bad on a 4-processor system; this means that your process is running constantly, and using 100% of the CPU cycles available to it.</p>\n\n<p>For the process-specific memory information, you ahve to look at /proc/self/status, which looks like this:</p>\n\n<pre><code>Name: whatever\nState: S (sleeping)\nTgid: 19340\nPid: 19340\nPPid: 19115\nTracerPid: 0\nUid: 0 0 0 0\nGid: 0 0 0 0\nFDSize: 256\nGroups: 0 1 2 3 4 6 10 11 20 26 27\nVmPeak: 676252 kB\nVmSize: 651352 kB\nVmLck: 0 kB\nVmHWM: 420300 kB\nVmRSS: 420296 kB\nVmData: 581028 kB\nVmStk: 112 kB\nVmExe: 11672 kB\nVmLib: 76608 kB\nVmPTE: 1244 kB\nThreads: 77\nSigQ: 0/36864\nSigPnd: 0000000000000000\nShdPnd: 0000000000000000\nSigBlk: fffffffe7ffbfeff\nSigIgn: 0000000010001000\nSigCgt: 20000001800004fc\nCapInh: 0000000000000000\nCapPrm: 00000000ffffffff\nCapEff: 00000000fffffeff\nCpus_allowed: 0f\nMems_allowed: 1\nvoluntary_ctxt_switches: 6518\nnonvoluntary_ctxt_switches: 6598\n</code></pre>\n\n<p>The entries that start with 'Vm' are the interesting ones:</p>\n\n<ul>\n<li><strong>VmPeak</strong> is the maximum virtual memory space used by the process, in kB (1024 bytes).</li>\n<li><strong>VmSize</strong> is the current virtual memory space used by the process, in kB. In my example, it's pretty large: 651,352 kB, or about 636 megabytes.</li>\n<li><strong>VmRss</strong> is the amount of memory that have been mapped into the process' address space, or its resident set size. This is substantially smaller (420,296 kB, or about 410 megabytes). The difference: my program has mapped 636 MB via mmap(), but has only accessed 410 MB of it, and thus only 410 MB of pages have been assigned to it.</li>\n</ul>\n\n<p>The only item I'm not sure about is <strong>Swapspace currently used by my process</strong>. I don't know if this is available.</p>\n" }, { "answer_id": 1911863, "author": "Michael Taylor", "author_id": 172534, "author_profile": "https://Stackoverflow.com/users/172534", "pm_score": 7, "selected": false, "text": "<h1>Mac OS X</h1>\n<h2>Total Virtual Memory</h2>\n<p>This one is tricky on Mac OS X because it doesn't use a preset swap partition or file like Linux. Here's an entry from Apple's documentation:</p>\n<blockquote>\n<p><strong>Note:</strong> Unlike most Unix-based operating systems, Mac OS X does not use a preallocated swap partition for virtual memory. Instead, it uses all of the available space on the machine’s boot partition.</p>\n</blockquote>\n<p>So, if you want to know how much virtual memory is still available, you need to get the size of the root partition. You can do that like this:</p>\n<pre><code>struct statfs stats;\nif (0 == statfs(&quot;/&quot;, &amp;stats))\n{\n myFreeSwap = (uint64_t)stats.f_bsize * stats.f_bfree;\n}\n</code></pre>\n<h2>Total Virtual Currently Used</h2>\n<p>Calling systcl with the &quot;vm.swapusage&quot; key provides interesting information about swap usage:</p>\n<pre><code>sysctl -n vm.swapusage\nvm.swapusage: total = 3072.00M used = 2511.78M free = 560.22M (encrypted)\n</code></pre>\n<p>Not that the total swap usage displayed here can change if more swap is needed as explained in the section above. So the total is actually the <em>current</em> swap total. In C++, this data can be queried this way:</p>\n<pre><code>xsw_usage vmusage = {0};\nsize_t size = sizeof(vmusage);\nif( sysctlbyname(&quot;vm.swapusage&quot;, &amp;vmusage, &amp;size, NULL, 0)!=0 )\n{\n perror( &quot;unable to get swap usage by calling sysctlbyname(\\&quot;vm.swapusage\\&quot;,...)&quot; );\n}\n</code></pre>\n<p>Note that the &quot;xsw_usage&quot;, declared in sysctl.h, seems not documented and I suspect there there is a more portable way of accessing these values.</p>\n<h2>Virtual Memory Currently Used by my Process</h2>\n<p>You can get statistics about your current process using the <code>task_info</code> function. That includes the current resident size of your process and the current virtual size.</p>\n<pre><code>#include&lt;mach/mach.h&gt;\n\nstruct task_basic_info t_info;\nmach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;\n\nif (KERN_SUCCESS != task_info(mach_task_self(),\n TASK_BASIC_INFO, (task_info_t)&amp;t_info,\n &amp;t_info_count))\n{\n return -1;\n}\n// resident size is in t_info.resident_size;\n// virtual size is in t_info.virtual_size;\n</code></pre>\n<h2>Total RAM available</h2>\n<p>The amount of physical RAM available in your system is available using the <code>sysctl</code> system function like this:</p>\n<pre><code>#include &lt;sys/types.h&gt;\n#include &lt;sys/sysctl.h&gt;\n...\nint mib[2];\nint64_t physical_memory;\nmib[0] = CTL_HW;\nmib[1] = HW_MEMSIZE;\nlength = sizeof(int64_t);\nsysctl(mib, 2, &amp;physical_memory, &amp;length, NULL, 0);\n</code></pre>\n<h2>RAM Currently Used</h2>\n<p>You can get general memory statistics from the <code>host_statistics</code> system function.</p>\n<pre><code>#include &lt;mach/vm_statistics.h&gt;\n#include &lt;mach/mach_types.h&gt;\n#include &lt;mach/mach_init.h&gt;\n#include &lt;mach/mach_host.h&gt;\n\nint main(int argc, const char * argv[]) {\n vm_size_t page_size;\n mach_port_t mach_port;\n mach_msg_type_number_t count;\n vm_statistics64_data_t vm_stats;\n\n mach_port = mach_host_self();\n count = sizeof(vm_stats) / sizeof(natural_t);\n if (KERN_SUCCESS == host_page_size(mach_port, &amp;page_size) &amp;&amp;\n KERN_SUCCESS == host_statistics64(mach_port, HOST_VM_INFO,\n (host_info64_t)&amp;vm_stats, &amp;count))\n {\n long long free_memory = (int64_t)vm_stats.free_count * (int64_t)page_size;\n\n long long used_memory = ((int64_t)vm_stats.active_count +\n (int64_t)vm_stats.inactive_count +\n (int64_t)vm_stats.wire_count) * (int64_t)page_size;\n printf(&quot;free memory: %lld\\nused memory: %lld\\n&quot;, free_memory, used_memory);\n }\n\n return 0;\n}\n</code></pre>\n<p>One thing to note here are that there are five types of memory pages in Mac OS X. They are as follows:</p>\n<ol>\n<li><strong>Wired</strong> pages that are locked in place and cannot be swapped out</li>\n<li><strong>Active</strong> pages that are loading into physical memory and would be relatively difficult to swap out</li>\n<li><strong>Inactive</strong> pages that are loaded into memory, but haven't been used recently and may not even be needed at all. These are potential candidates for swapping. This memory would probably need to be flushed.</li>\n<li><strong>Cached</strong> pages that have been some how cached that are likely to be easily reused. Cached memory probably would not require flushing. It is still possible for cached pages to be reactivated</li>\n<li><strong>Free</strong> pages that are completely free and ready to be used.</li>\n</ol>\n<p>It is good to note that just because Mac OS X may show very little actual free memory at times that it may not be a good indication of how much is ready to be used on short notice.</p>\n<h2>RAM Currently Used by my Process</h2>\n<p>See the &quot;Virtual Memory Currently Used by my Process&quot; above. The same code applies.</p>\n" }, { "answer_id": 13947253, "author": "Mohsen Zahraee", "author_id": 1907986, "author_profile": "https://Stackoverflow.com/users/1907986", "pm_score": 4, "selected": false, "text": "<p><strong>In Windows you can get CPU usage by the code below:</strong></p>\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n\n//------------------------------------------------------------------------------------------------------------------\n// Prototype(s)...\n//------------------------------------------------------------------------------------------------------------------\nCHAR cpuusage(void);\n\n//-----------------------------------------------------\ntypedef BOOL ( __stdcall * pfnGetSystemTimes)( LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime );\nstatic pfnGetSystemTimes s_pfnGetSystemTimes = NULL;\n\nstatic HMODULE s_hKernel = NULL;\n//-----------------------------------------------------\nvoid GetSystemTimesAddress()\n{\n if(s_hKernel == NULL)\n {\n s_hKernel = LoadLibrary(L&quot;Kernel32.dll&quot;);\n if(s_hKernel != NULL)\n {\n s_pfnGetSystemTimes = (pfnGetSystemTimes)GetProcAddress(s_hKernel, &quot;GetSystemTimes&quot;);\n if(s_pfnGetSystemTimes == NULL)\n {\n FreeLibrary(s_hKernel);\n s_hKernel = NULL;\n }\n }\n }\n}\n//----------------------------------------------------------------------------------------------------------------\n\n//----------------------------------------------------------------------------------------------------------------\n// cpuusage(void)\n// ==============\n// Return a CHAR value in the range 0 - 100 representing actual CPU usage in percent.\n//----------------------------------------------------------------------------------------------------------------\nCHAR cpuusage()\n{\n FILETIME ft_sys_idle;\n FILETIME ft_sys_kernel;\n FILETIME ft_sys_user;\n\n ULARGE_INTEGER ul_sys_idle;\n ULARGE_INTEGER ul_sys_kernel;\n ULARGE_INTEGER ul_sys_user;\n\n static ULARGE_INTEGER ul_sys_idle_old;\n static ULARGE_INTEGER ul_sys_kernel_old;\n static ULARGE_INTEGER ul_sys_user_old;\n\n CHAR usage = 0;\n\n // We cannot directly use GetSystemTimes in the C language\n /* Add this line :: pfnGetSystemTimes */\n s_pfnGetSystemTimes(&amp;ft_sys_idle, /* System idle time */\n &amp;ft_sys_kernel, /* system kernel time */\n &amp;ft_sys_user); /* System user time */\n\n CopyMemory(&amp;ul_sys_idle , &amp;ft_sys_idle , sizeof(FILETIME)); // Could been optimized away...\n CopyMemory(&amp;ul_sys_kernel, &amp;ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away...\n CopyMemory(&amp;ul_sys_user , &amp;ft_sys_user , sizeof(FILETIME)); // Could been optimized away...\n\n usage =\n (\n (\n (\n (\n (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+\n (ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)\n )\n -\n (ul_sys_idle.QuadPart-ul_sys_idle_old.QuadPart)\n )\n *\n (100)\n )\n /\n (\n (ul_sys_kernel.QuadPart - ul_sys_kernel_old.QuadPart)+\n (ul_sys_user.QuadPart - ul_sys_user_old.QuadPart)\n )\n );\n\n ul_sys_idle_old.QuadPart = ul_sys_idle.QuadPart;\n ul_sys_user_old.QuadPart = ul_sys_user.QuadPart;\n ul_sys_kernel_old.QuadPart = ul_sys_kernel.QuadPart;\n\n return usage;\n}\n\n\n//------------------------------------------------------------------------------------------------------------------\n// Entry point\n//------------------------------------------------------------------------------------------------------------------\nint main(void)\n{\n int n;\n GetSystemTimesAddress();\n for(n=0; n&lt;20; n++)\n {\n printf(&quot;CPU Usage: %3d%%\\r&quot;, cpuusage());\n Sleep(2000);\n }\n printf(&quot;\\n&quot;);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 30452461, "author": "Boernii", "author_id": 4894793, "author_profile": "https://Stackoverflow.com/users/4894793", "pm_score": 2, "selected": false, "text": "<h1>QNX</h1>\n<p>Since this is like a &quot;wikipage of code&quot; I want to add some code from the QNX Knowledge base (note: this is not my work, but I checked it and it works fine on my system):</p>\n<p>How to get CPU usage in %: <a href=\"http://www.qnx.com/support/knowledgebase.html?id=50130000000P9b5\" rel=\"nofollow noreferrer\">http://www.qnx.com/support/knowledgebase.html?id=50130000000P9b5</a></p>\n<pre><code>#include &lt;atomic.h&gt;\n#include &lt;libc.h&gt;\n#include &lt;pthread.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;sys/iofunc.h&gt;\n#include &lt;sys/neutrino.h&gt;\n#include &lt;sys/resmgr.h&gt;\n#include &lt;sys/syspage.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;inttypes.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;sys/types.h&gt;\n#include &lt;sys/debug.h&gt;\n#include &lt;sys/procfs.h&gt;\n#include &lt;sys/syspage.h&gt;\n#include &lt;sys/neutrino.h&gt;\n#include &lt;sys/time.h&gt;\n#include &lt;time.h&gt;\n#include &lt;fcntl.h&gt;\n#include &lt;devctl.h&gt;\n#include &lt;errno.h&gt;\n\n#define MAX_CPUS 32\n\nstatic float Loads[MAX_CPUS];\nstatic _uint64 LastSutime[MAX_CPUS];\nstatic _uint64 LastNsec[MAX_CPUS];\nstatic int ProcFd = -1;\nstatic int NumCpus = 0;\n\n\nint find_ncpus(void) {\n return NumCpus;\n}\n\nint get_cpu(int cpu) {\n int ret;\n ret = (int)Loads[ cpu % MAX_CPUS ];\n ret = max(0,ret);\n ret = min(100,ret);\n return( ret );\n}\n\nstatic _uint64 nanoseconds( void ) {\n _uint64 sec, usec;\n struct timeval tval;\n gettimeofday( &amp;tval, NULL );\n sec = tval.tv_sec;\n usec = tval.tv_usec;\n return( ( ( sec * 1000000 ) + usec ) * 1000 );\n}\n\nint sample_cpus( void ) {\n int i;\n debug_thread_t debug_data;\n _uint64 current_nsec, sutime_delta, time_delta;\n memset( &amp;debug_data, 0, sizeof( debug_data ) );\n \n for( i=0; i&lt;NumCpus; i++ ) {\n /* Get the sutime of the idle thread #i+1 */\n debug_data.tid = i + 1;\n devctl( ProcFd, DCMD_PROC_TIDSTATUS,\n &amp;debug_data, sizeof( debug_data ), NULL );\n /* Get the current time */\n current_nsec = nanoseconds();\n /* Get the deltas between now and the last samples */\n sutime_delta = debug_data.sutime - LastSutime[i];\n time_delta = current_nsec - LastNsec[i];\n /* Figure out the load */\n Loads[i] = 100.0 - ( (float)( sutime_delta * 100 ) / (float)time_delta );\n /* Flat out strange rounding issues. */\n if( Loads[i] &lt; 0 ) {\n Loads[i] = 0;\n }\n /* Keep these for reference in the next cycle */\n LastNsec[i] = current_nsec;\n LastSutime[i] = debug_data.sutime;\n }\n return EOK;\n}\n\nint init_cpu( void ) {\n int i;\n debug_thread_t debug_data;\n memset( &amp;debug_data, 0, sizeof( debug_data ) );\n/* Open a connection to proc to talk over.*/\n ProcFd = open( &quot;/proc/1/as&quot;, O_RDONLY );\n if( ProcFd == -1 ) {\n fprintf( stderr, &quot;pload: Unable to access procnto: %s\\n&quot;,strerror( errno ) );\n fflush( stderr );\n return -1;\n }\n i = fcntl(ProcFd,F_GETFD);\n if(i != -1){\n i |= FD_CLOEXEC;\n if(fcntl(ProcFd,F_SETFD,i) != -1){\n /* Grab this value */\n NumCpus = _syspage_ptr-&gt;num_cpu;\n /* Get a starting point for the comparisons */\n for( i=0; i&lt;NumCpus; i++ ) {\n /*\n * the sutime of idle thread is how much\n * time that thread has been using, we can compare this\n * against how much time has passed to get an idea of the\n * load on the system.\n */\n debug_data.tid = i + 1;\n devctl( ProcFd, DCMD_PROC_TIDSTATUS, &amp;debug_data, sizeof( debug_data ), NULL );\n LastSutime[i] = debug_data.sutime;\n LastNsec[i] = nanoseconds();\n }\n return(EOK);\n }\n }\n close(ProcFd);\n return(-1);\n}\n\nvoid close_cpu(void){\n if(ProcFd != -1){\n close(ProcFd);\n ProcFd = -1;\n }\n}\n\nint main(int argc, char* argv[]){\n int i,j;\n init_cpu();\n printf(&quot;System has: %d CPUs\\n&quot;, NumCpus);\n for(i=0; i&lt;20; i++) {\n sample_cpus();\n for(j=0; j&lt;NumCpus;j++)\n printf(&quot;CPU #%d: %f\\n&quot;, j, Loads[j]);\n sleep(1);\n }\n close_cpu();\n}\n</code></pre>\n<p>How to get the free (!) memory: <a href=\"http://www.qnx.com/support/knowledgebase.html?id=50130000000mlbx\" rel=\"nofollow noreferrer\">http://www.qnx.com/support/knowledgebase.html?id=50130000000mlbx</a></p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;errno.h&gt;\n#include &lt;err.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;sys/types.h&gt;\n\nint main( int argc, char *argv[] ){\n struct stat statbuf;\n paddr_t freemem;\n stat( &quot;/proc&quot;, &amp;statbuf );\n freemem = (paddr_t)statbuf.st_size;\n printf( &quot;Free memory: %d bytes\\n&quot;, freemem );\n printf( &quot;Free memory: %d KB\\n&quot;, freemem / 1024 );\n printf( &quot;Free memory: %d MB\\n&quot;, freemem / ( 1024 * 1024 ) );\n return 0;\n} \n</code></pre>\n" }, { "answer_id": 31464645, "author": "Mark Lakata", "author_id": 364818, "author_profile": "https://Stackoverflow.com/users/364818", "pm_score": 4, "selected": false, "text": "<h1>Linux</h1>\n\n<p>A portable way of reading memory and load numbers is the <a href=\"http://man7.org/linux/man-pages/man2/sysinfo.2.html\" rel=\"noreferrer\"><code>sysinfo</code> call</a></p>\n\n<h2>Usage</h2>\n\n<pre><code> #include &lt;sys/sysinfo.h&gt;\n\n int sysinfo(struct sysinfo *info);\n</code></pre>\n\n<h2>DESCRIPTION</h2>\n\n<pre><code> Until Linux 2.3.16, sysinfo() used to return information in the\n following structure:\n\n struct sysinfo {\n long uptime; /* Seconds since boot */\n unsigned long loads[3]; /* 1, 5, and 15 minute load averages */\n unsigned long totalram; /* Total usable main memory size */\n unsigned long freeram; /* Available memory size */\n unsigned long sharedram; /* Amount of shared memory */\n unsigned long bufferram; /* Memory used by buffers */\n unsigned long totalswap; /* Total swap space size */\n unsigned long freeswap; /* swap space still available */\n unsigned short procs; /* Number of current processes */\n char _f[22]; /* Pads structure to 64 bytes */\n };\n\n and the sizes were given in bytes.\n\n Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure\n is:\n\n struct sysinfo {\n long uptime; /* Seconds since boot */\n unsigned long loads[3]; /* 1, 5, and 15 minute load averages */\n unsigned long totalram; /* Total usable main memory size */\n unsigned long freeram; /* Available memory size */\n unsigned long sharedram; /* Amount of shared memory */\n unsigned long bufferram; /* Memory used by buffers */\n unsigned long totalswap; /* Total swap space size */\n unsigned long freeswap; /* swap space still available */\n unsigned short procs; /* Number of current processes */\n unsigned long totalhigh; /* Total high memory size */\n unsigned long freehigh; /* Available high memory size */\n unsigned int mem_unit; /* Memory unit size in bytes */\n char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding to 64 bytes */\n };\n\n and the sizes are given as multiples of mem_unit bytes.\n</code></pre>\n" }, { "answer_id": 40268513, "author": "Salman Ghaffar", "author_id": 7037557, "author_profile": "https://Stackoverflow.com/users/7037557", "pm_score": 0, "selected": false, "text": "<p>I used this following code in my C++ project and it worked fine:</p>\n\n<pre><code>static HANDLE self;\nstatic int numProcessors;\nSYSTEM_INFO sysInfo;\n\ndouble percent;\n\nnumProcessors = sysInfo.dwNumberOfProcessors;\n\n//Getting system times information\nFILETIME SysidleTime;\nFILETIME SyskernelTime; \nFILETIME SysuserTime; \nULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;\nGetSystemTimes(&amp;SysidleTime, &amp;SyskernelTime, &amp;SysuserTime);\nmemcpy(&amp;SyskernelTimeInt, &amp;SyskernelTime, sizeof(FILETIME));\nmemcpy(&amp;SysuserTimeInt, &amp;SysuserTime, sizeof(FILETIME));\n__int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart; \n\n//Getting process times information\nFILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;\nULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;\nGetProcessTimes(self, &amp;ProccreationTime, &amp;ProcexitTime, &amp;ProcKernelTime, &amp;ProcUserTime);\nmemcpy(&amp;ProcKernelTimeInt, &amp;ProcKernelTime, sizeof(FILETIME));\nmemcpy(&amp;ProcUserTimeInt, &amp;ProcUserTime, sizeof(FILETIME));\n__int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;\n//QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)\n\npercent = 100*(numerator/denomenator);\n</code></pre>\n" }, { "answer_id": 42925322, "author": "Steven Warner", "author_id": 4721690, "author_profile": "https://Stackoverflow.com/users/4721690", "pm_score": 2, "selected": false, "text": "<h3>For Linux</h3>\n<p>You can also use /proc/self/statm to get a single line of numbers containing key process memory information which is a faster thing to process than going through a long list of reported information as you get from proc/self/status</p>\n<p>See <em><a href=\"http://man7.org/linux/man-pages/man5/proc.5.html\" rel=\"nofollow noreferrer\">proc(5)</a></em></p>\n<pre class=\"lang-none prettyprint-override\"><code>/proc/[pid]/statm\n\n Provides information about memory usage, measured in pages.\n The columns are:\n\n size (1) total program size\n (same as VmSize in /proc/[pid]/status)\n resident (2) resident set size\n (same as VmRSS in /proc/[pid]/status)\n shared (3) number of resident shared pages (i.e., backed by a file)\n (same as RssFile+RssShmem in /proc/[pid]/status)\n text (4) text (code)\n lib (5) library (unused since Linux 2.6; always 0)\n data (6) data + stack\n dt (7) dirty pages (unused since Linux 2.6; always 0)\n</code></pre>\n" }, { "answer_id": 49996245, "author": "souch", "author_id": 4964856, "author_profile": "https://Stackoverflow.com/users/4964856", "pm_score": 2, "selected": false, "text": "<p><strong>Mac OS X - CPU</strong></p>\n<p>Overall CPU usage:</p>\n<p>From <em><a href=\"https://stackoverflow.com/questions/8736713/retrieve-system-information-on-macos-x\">Retrieve system information on Mac OS X</a></em>:</p>\n<pre><code>#include &lt;mach/mach_init.h&gt;\n#include &lt;mach/mach_error.h&gt;\n#include &lt;mach/mach_host.h&gt;\n#include &lt;mach/vm_map.h&gt;\n\nstatic unsigned long long _previousTotalTicks = 0;\nstatic unsigned long long _previousIdleTicks = 0;\n\n// Returns 1.0f for &quot;CPU fully pinned&quot;, 0.0f for &quot;CPU idle&quot;, or somewhere in between\n// You'll need to call this at regular intervals, since it measures the load between\n// the previous call and the current one.\nfloat GetCPULoad()\n{\n host_cpu_load_info_data_t cpuinfo;\n mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;\n if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&amp;cpuinfo, &amp;count) == KERN_SUCCESS)\n {\n unsigned long long totalTicks = 0;\n for(int i=0; i&lt;CPU_STATE_MAX; i++) totalTicks += cpuinfo.cpu_ticks[i];\n return CalculateCPULoad(cpuinfo.cpu_ticks[CPU_STATE_IDLE], totalTicks);\n }\n else return -1.0f;\n}\n\nfloat CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)\n{\n unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks;\n unsigned long long idleTicksSinceLastTime = idleTicks-_previousIdleTicks;\n float ret = 1.0f-((totalTicksSinceLastTime &gt; 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);\n _previousTotalTicks = totalTicks;\n _previousIdleTicks = idleTicks;\n return ret;\n}\n</code></pre>\n" }, { "answer_id": 65270655, "author": "Marisa Kirisame", "author_id": 7984460, "author_profile": "https://Stackoverflow.com/users/7984460", "pm_score": 0, "selected": false, "text": "<p>On Linux, you cannot/should not get &quot;Total Available Physical Memory&quot; with SysInfo's freeram or by doing some arithmetic on totalram.</p>\n<p>The recommended way to do this is by reading proc/meminfo, quoting <em><a href=\"https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773\" rel=\"nofollow noreferrer\">kernel/git/torvalds/linux.git, <em>/proc/meminfo: provide estimated available memory</em></a></em>:</p>\n<blockquote>\n<p>Many load balancing and workload placing programs check /proc/meminfo to\nestimate how much free memory is available. They generally do this by\nadding up &quot;free&quot; and &quot;cached&quot;, which was fine ten years ago, but is\npretty much guaranteed to be wrong today.</p>\n</blockquote>\n<blockquote>\n<p>It is more convenient to provide such an estimate in /proc/meminfo. If things change in the future, we only have to change it in one place.</p>\n</blockquote>\n<p>One way to do it is as <em><a href=\"https://stackoverflow.com/questions/349889/how-do-you-determine-the-amount-of-linux-system-ram-in-c/350039#350039\">Adam Rosenfield's answer to <em>How do you determine the amount of Linux system RAM in C++?</em></a></em> suggest: read the file, and use fscanf to grab the line (but instead of going for MemTotal, go for MemAvailable)</p>\n<p>Likewise, if you want to get the total amount of physical memory used, depending on what you mean by &quot;use&quot;, you might not want to subtract freeram from totalram, but subtract memavailable from memtotal to get what top or htop tells you.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6448/" ]
In Flex, I have an xml document such as the following: ``` var xml:XML = <root><node>value1</node><node>value2</node><node>value3</node></root> ``` At runtime, I want to create a TextInput control for each node under root, and have the values bound to the values in the XML. As far as I can tell I can't use BindingUtils to bind to e4x nodes at runtime (please tell me if I'm wrong here!), so I'm trying to do this by hand: ``` for each (var node:XML in xml.node) { var textInput:TextInput = new TextInput(); var handler:Function = function(event:Event):void { node.setChildren(event.target.text); }; textInput.text = node.text(); textInput.addEventListener(Event.CHANGE, handler); this.addChild(pileHeightEditor); } ``` My problem is that when the user edits one of the TextInputs, the node getting assigned to is always the last one encountered in the for loop. I am used to this pattern from C#, where each time an anonymous function is created, a "snapshot" of the values of the used values is taken, so "node" would be different in each handler function. How do I "take a snapshot" of the current value of node to use in the handler? Or should I be using a different pattern in Flex?
Windows ------- Some of the above values are easily available from the appropriate Win32 API, I just list them here for completeness. Others, however, need to be obtained from the Performance Data Helper library (PDH), which is a bit "unintuitive" and takes a lot of painful trial and error to get to work. (At least it took me quite a while, perhaps I've been only a bit stupid...) Note: for clarity all error checking has been omitted from the following code. Do check the return codes...! * Total Virtual Memory: ``` #include "windows.h" MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(&memInfo); DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile; ``` Note: The name "TotalPageFile" is a bit misleading here. In reality this parameter gives the "Virtual Memory Size", which is size of swap file plus installed RAM. * Virtual Memory currently used: Same code as in "Total Virtual Memory" and then ``` DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile; ``` * Virtual Memory currently used by current process: ``` #include "windows.h" #include "psapi.h" PROCESS_MEMORY_COUNTERS_EX pmc; GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)); SIZE_T virtualMemUsedByMe = pmc.PrivateUsage; ``` * Total Physical Memory (RAM): Same code as in "Total Virtual Memory" and then ``` DWORDLONG totalPhysMem = memInfo.ullTotalPhys; ``` * Physical Memory currently used: Same code as in "Total Virtual Memory" and then ``` DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys; ``` * Physical Memory currently used by current process: Same code as in "Virtual Memory currently used by current process" and then ``` SIZE_T physMemUsedByMe = pmc.WorkingSetSize; ``` * CPU currently used: ``` #include "TCHAR.h" #include "pdh.h" static PDH_HQUERY cpuQuery; static PDH_HCOUNTER cpuTotal; void init(){ PdhOpenQuery(NULL, NULL, &cpuQuery); // You can also use L"\\Processor(*)\\% Processor Time" and get individual CPU values with PdhGetFormattedCounterArray() PdhAddEnglishCounter(cpuQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal); PdhCollectQueryData(cpuQuery); } double getCurrentValue(){ PDH_FMT_COUNTERVALUE counterVal; PdhCollectQueryData(cpuQuery); PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal); return counterVal.doubleValue; } ``` * CPU currently used by current process: ``` #include "windows.h" static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU; static int numProcessors; static HANDLE self; void init(){ SYSTEM_INFO sysInfo; FILETIME ftime, fsys, fuser; GetSystemInfo(&sysInfo); numProcessors = sysInfo.dwNumberOfProcessors; GetSystemTimeAsFileTime(&ftime); memcpy(&lastCPU, &ftime, sizeof(FILETIME)); self = GetCurrentProcess(); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); memcpy(&lastSysCPU, &fsys, sizeof(FILETIME)); memcpy(&lastUserCPU, &fuser, sizeof(FILETIME)); } double getCurrentValue(){ FILETIME ftime, fsys, fuser; ULARGE_INTEGER now, sys, user; double percent; GetSystemTimeAsFileTime(&ftime); memcpy(&now, &ftime, sizeof(FILETIME)); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); memcpy(&sys, &fsys, sizeof(FILETIME)); memcpy(&user, &fuser, sizeof(FILETIME)); percent = (sys.QuadPart - lastSysCPU.QuadPart) + (user.QuadPart - lastUserCPU.QuadPart); percent /= (now.QuadPart - lastCPU.QuadPart); percent /= numProcessors; lastCPU = now; lastUserCPU = user; lastSysCPU = sys; return percent * 100; } ``` --- Linux ----- On Linux the choice that seemed obvious at first was to use the POSIX APIs like `getrusage()` etc. I spent some time trying to get this to work, but never got meaningful values. When I finally checked the kernel sources themselves, I found out that apparently these APIs are not yet completely implemented as of Linux kernel 2.6!? In the end I got all values via a combination of reading the pseudo-filesystem `/proc` and kernel calls. * Total Virtual Memory: ``` #include "sys/types.h" #include "sys/sysinfo.h" struct sysinfo memInfo; sysinfo (&memInfo); long long totalVirtualMem = memInfo.totalram; //Add other values in next statement to avoid int overflow on right hand side... totalVirtualMem += memInfo.totalswap; totalVirtualMem *= memInfo.mem_unit; ``` * Virtual Memory currently used: Same code as in "Total Virtual Memory" and then ``` long long virtualMemUsed = memInfo.totalram - memInfo.freeram; //Add other values in next statement to avoid int overflow on right hand side... virtualMemUsed += memInfo.totalswap - memInfo.freeswap; virtualMemUsed *= memInfo.mem_unit; ``` * Virtual Memory currently used by current process: ``` #include "stdlib.h" #include "stdio.h" #include "string.h" int parseLine(char* line){ // This assumes that a digit will be found and the line ends in " Kb". int i = strlen(line); const char* p = line; while (*p <'0' || *p > '9') p++; line[i-3] = '\0'; i = atoi(p); return i; } int getValue(){ //Note: this value is in KB! FILE* file = fopen("/proc/self/status", "r"); int result = -1; char line[128]; while (fgets(line, 128, file) != NULL){ if (strncmp(line, "VmSize:", 7) == 0){ result = parseLine(line); break; } } fclose(file); return result; } ``` * Total Physical Memory (RAM): Same code as in "Total Virtual Memory" and then ``` long long totalPhysMem = memInfo.totalram; //Multiply in next statement to avoid int overflow on right hand side... totalPhysMem *= memInfo.mem_unit; ``` * Physical Memory currently used: Same code as in "Total Virtual Memory" and then ``` long long physMemUsed = memInfo.totalram - memInfo.freeram; //Multiply in next statement to avoid int overflow on right hand side... physMemUsed *= memInfo.mem_unit; ``` * Physical Memory currently used by current process: Change getValue() in "Virtual Memory currently used by current process" as follows: ``` int getValue(){ //Note: this value is in KB! FILE* file = fopen("/proc/self/status", "r"); int result = -1; char line[128]; while (fgets(line, 128, file) != NULL){ if (strncmp(line, "VmRSS:", 6) == 0){ result = parseLine(line); break; } } fclose(file); return result; } ``` * CPU currently used: ``` #include "stdlib.h" #include "stdio.h" #include "string.h" static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle; void init(){ FILE* file = fopen("/proc/stat", "r"); fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow, &lastTotalSys, &lastTotalIdle); fclose(file); } double getCurrentValue(){ double percent; FILE* file; unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total; file = fopen("/proc/stat", "r"); fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow, &totalSys, &totalIdle); fclose(file); if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow || totalSys < lastTotalSys || totalIdle < lastTotalIdle){ //Overflow detection. Just skip this value. percent = -1.0; } else{ total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) + (totalSys - lastTotalSys); percent = total; total += (totalIdle - lastTotalIdle); percent /= total; percent *= 100; } lastTotalUser = totalUser; lastTotalUserLow = totalUserLow; lastTotalSys = totalSys; lastTotalIdle = totalIdle; return percent; } ``` * CPU currently used by current process: ``` #include "stdlib.h" #include "stdio.h" #include "string.h" #include "sys/times.h" #include "sys/vtimes.h" static clock_t lastCPU, lastSysCPU, lastUserCPU; static int numProcessors; void init(){ FILE* file; struct tms timeSample; char line[128]; lastCPU = times(&timeSample); lastSysCPU = timeSample.tms_stime; lastUserCPU = timeSample.tms_utime; file = fopen("/proc/cpuinfo", "r"); numProcessors = 0; while(fgets(line, 128, file) != NULL){ if (strncmp(line, "processor", 9) == 0) numProcessors++; } fclose(file); } double getCurrentValue(){ struct tms timeSample; clock_t now; double percent; now = times(&timeSample); if (now <= lastCPU || timeSample.tms_stime < lastSysCPU || timeSample.tms_utime < lastUserCPU){ //Overflow detection. Just skip this value. percent = -1.0; } else{ percent = (timeSample.tms_stime - lastSysCPU) + (timeSample.tms_utime - lastUserCPU); percent /= (now - lastCPU); percent /= numProcessors; percent *= 100; } lastCPU = now; lastSysCPU = timeSample.tms_stime; lastUserCPU = timeSample.tms_utime; return percent; } ``` --- TODO: Other Platforms --------------------- I would assume, that some of the Linux code also works for the Unixes, except for the parts that read the /proc pseudo-filesystem. Perhaps on Unix these parts can be replaced by `getrusage()` and similar functions?
63,206
<p>If Java application requires certain JRE version then how can I check its availability on Mac OS X during installation?</p>
[ { "answer_id": 63227, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 2, "selected": true, "text": "<p>It should be as simple as looking at /System/Library/Frameworks/JavaVM.framework/Versions/</p>\n\n<p>E.g. from my machine:</p>\n\n<pre><code>manoa:~ stu$ ll /System/Library/Frameworks/JavaVM.framework/Versions/\ntotal 56\n774077 lrwxr-xr-x 1 root wheel 5 Jul 23 15:31 1.3 -&gt; 1.3.1\n167151 drwxr-xr-x 3 root wheel 102 Jan 14 2008 1.3.1\n167793 lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.4 -&gt; 1.4.2\n774079 lrwxr-xr-x 1 root wheel 3 Jul 23 15:31 1.4.1 -&gt; 1.4\n166913 drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.4.2\n168494 lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.5 -&gt; 1.5.0\n166930 drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.5.0\n774585 lrwxr-xr-x 1 root wheel 5 Jul 23 15:31 1.6 -&gt; 1.6.0\n747415 drwxr-xr-x 8 root wheel 272 Jul 23 10:24 1.6.0\n167155 drwxr-xr-x 8 root wheel 272 Jul 23 15:31 A\n776765 lrwxr-xr-x 1 root wheel 1 Jul 23 15:31 Current -&gt; A\n774125 lrwxr-xr-x 1 root wheel 3 Jul 23 15:31 CurrentJDK -&gt; 1.5\nmanoa:~ stu$ \n</code></pre>\n" }, { "answer_id": 63236, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 0, "selected": false, "text": "<p>This artical may help:\n<a href=\"http://developer.apple.com/technotes/tn2002/tn2110.html\" rel=\"nofollow noreferrer\">http://developer.apple.com/technotes/tn2002/tn2110.html</a><br />\nSummery:</p>\n\n<pre><code>String javaVersion = System.getProperty(\"java.version\");\nif (javaVersion.startsWith(\"1.4\")) {\n // New features for 1.4\n}\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7292/" ]
If Java application requires certain JRE version then how can I check its availability on Mac OS X during installation?
It should be as simple as looking at /System/Library/Frameworks/JavaVM.framework/Versions/ E.g. from my machine: ``` manoa:~ stu$ ll /System/Library/Frameworks/JavaVM.framework/Versions/ total 56 774077 lrwxr-xr-x 1 root wheel 5 Jul 23 15:31 1.3 -> 1.3.1 167151 drwxr-xr-x 3 root wheel 102 Jan 14 2008 1.3.1 167793 lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.4 -> 1.4.2 774079 lrwxr-xr-x 1 root wheel 3 Jul 23 15:31 1.4.1 -> 1.4 166913 drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.4.2 168494 lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.5 -> 1.5.0 166930 drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.5.0 774585 lrwxr-xr-x 1 root wheel 5 Jul 23 15:31 1.6 -> 1.6.0 747415 drwxr-xr-x 8 root wheel 272 Jul 23 10:24 1.6.0 167155 drwxr-xr-x 8 root wheel 272 Jul 23 15:31 A 776765 lrwxr-xr-x 1 root wheel 1 Jul 23 15:31 Current -> A 774125 lrwxr-xr-x 1 root wheel 3 Jul 23 15:31 CurrentJDK -> 1.5 manoa:~ stu$ ```
63,291
<p>How do I select all the columns in a table that only contain NULL values for all the rows? I'm using <strong>MS SQL Server 2005</strong>. I'm trying to find out which columns are not used in the table so I can delete them.</p>
[ { "answer_id": 63312, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>SELECT cols\nFROM table\nWHERE cols IS NULL\n</code></pre>\n" }, { "answer_id": 63374, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": -1, "selected": false, "text": "<p>You might need to clarify a bit. What are you really trying to accomplish? If you really want to find out the column names that only contain null values, then you will have to loop through the scheama and do a dynamic query based on that.</p>\n\n<p>I don't know which DBMS you are using, so I'll put some pseudo-code here.</p>\n\n<pre><code>for each col\nbegin\n @cmd = 'if not exists (select * from tablename where ' + col + ' is not null begin print ' + col + ' end'\nexec(@cmd)\nend\n</code></pre>\n" }, { "answer_id": 63412, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 3, "selected": false, "text": "<p>Or did you want to just see if a column only has NULL values (and, thus, is probably unused)?</p>\n\n<p>Further clarification of the question might help.</p>\n\n<p><strong>EDIT:</strong>\nOk.. here's some really rough code to get you going...</p>\n\n<pre><code>SET NOCOUNT ON\nDECLARE @TableName Varchar(100)\nSET @TableName='YourTableName'\nCREATE TABLE #NullColumns (ColumnName Varchar(100), OnlyNulls BIT)\nINSERT INTO #NullColumns (ColumnName, OnlyNulls) SELECT c.name, 0 FROM syscolumns c INNER JOIN sysobjects o ON c.id = o.id AND o.name = @TableName AND o.xtype = 'U'\nDECLARE @DynamicSQL AS Nvarchar(2000)\nDECLARE @ColumnName Varchar(100)\nDECLARE @RC INT\n SELECT TOP 1 @ColumnName = ColumnName FROM #NullColumns WHERE OnlyNulls=0\n WHILE @@ROWCOUNT &gt; 0\n BEGIN\n SET @RC=0\n SET @DynamicSQL = 'SELECT TOP 1 1 As HasNonNulls FROM ' + @TableName + ' (nolock) WHERE ''' + @ColumnName + ''' IS NOT NULL'\n EXEC sp_executesql @DynamicSQL\n set @RC=@@rowcount\n IF @RC=1\n BEGIN\n SET @DynamicSQL = 'UPDATE #NullColumns SET OnlyNulls=1 WHERE ColumnName=''' + @ColumnName + ''''\n EXEC sp_executesql @DynamicSQL\n END\n ELSE\n BEGIN\n SET @DynamicSQL = 'DELETE FROM #NullColumns WHERE ColumnName=''' + @ColumnName+ ''''\n EXEC sp_executesql @DynamicSQL\n END\n SELECT TOP 1 @ColumnName = ColumnName FROM #NullColumns WHERE OnlyNulls=0\n END\n\nSELECT * FROM #NullColumns\n\nDROP TABLE #NullColumns\nSET NOCOUNT OFF\n</code></pre>\n\n<p>Yes, there are easier ways, but I have a meeting to go to right now. Good luck!</p>\n" }, { "answer_id": 63432, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": 0, "selected": false, "text": "<p>You'll have to loop over the set of columns and check each one. You should be able to get a list of all columns with a DESCRIBE table command.</p>\n\n<p>Pseudo-code:</p>\n\n<p><pre><code>\nforeach $column ($cols) {\n query(\"SELECT count(*) FROM table WHERE $column IS NOT NULL\")\n if($result is zero) {\n # $column contains only null values\"\n push @onlyNullColumns, $column;\n } else {\n # $column contains non-null values\n }\n}\nreturn @onlyNullColumns;\n</pre></code></p>\n\n<p>I know this seems a little counterintuitive but SQL does not provide a native method of selecting columns, only rows.</p>\n" }, { "answer_id": 63552, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 2, "selected": false, "text": "<p>You can do: </p>\n\n<pre><code>select \n count(&lt;columnName&gt;)\nfrom\n &lt;tableName&gt;\n</code></pre>\n\n<p>If the count returns 0 that means that all rows in that column all NULL (or there is no rows at all in the table)</p>\n\n<p>can be changed to </p>\n\n<pre><code>select \n case(count(&lt;columnName&gt;)) when 0 then 'Nulls Only' else 'Some Values' end\nfrom \n &lt;tableName&gt;\n</code></pre>\n\n<p>If you want to automate it you can use system tables to iterate the column names in the table you are interested in</p>\n" }, { "answer_id": 63565, "author": "squadette", "author_id": 7754, "author_profile": "https://Stackoverflow.com/users/7754", "pm_score": 0, "selected": false, "text": "<p>I would also recommend to search for fields which all have the same value, not just NULL.</p>\n\n<p>That is, for each column in each table do the query:</p>\n\n<pre><code>SELECT COUNT(DISTINCT field) FROM tableName\n</code></pre>\n\n<p>and concentrate on those which return 1 as a result.</p>\n" }, { "answer_id": 63641, "author": "MobyDX", "author_id": 3923, "author_profile": "https://Stackoverflow.com/users/3923", "pm_score": 3, "selected": false, "text": "<p>This should give you a list of all columns in the table \"Person\" that has only NULL-values. You will get the results as multiple result-sets, which are either empty or contains the name of a single column. You need to replace \"Person\" in two places to use it with another table.</p>\n\n<pre><code>DECLARE crs CURSOR LOCAL FAST_FORWARD FOR SELECT name FROM syscolumns WHERE id=OBJECT_ID('Person')\nOPEN crs\nDECLARE @name sysname\nFETCH NEXT FROM crs INTO @name\nWHILE @@FETCH_STATUS = 0\nBEGIN\n EXEC('SELECT ''' + @name + ''' WHERE NOT EXISTS (SELECT * FROM Person WHERE ' + @name + ' IS NOT NULL)')\n FETCH NEXT FROM crs INTO @name\nEND\nCLOSE crs\nDEALLOCATE crs\n</code></pre>\n" }, { "answer_id": 63772, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 7, "selected": true, "text": "<p>Here is the sql 2005 or later version: Replace ADDR_Address with your tablename.</p>\n\n<pre><code>declare @col varchar(255), @cmd varchar(max)\n\nDECLARE getinfo cursor for\nSELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID\nWHERE t.Name = 'ADDR_Address'\n\nOPEN getinfo\n\nFETCH NEXT FROM getinfo into @col\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM ADDR_Address WHERE [' + @col + '] IS NOT NULL) BEGIN print ''' + @col + ''' end'\n EXEC(@cmd)\n\n FETCH NEXT FROM getinfo into @col\nEND\n\nCLOSE getinfo\nDEALLOCATE getinfo\n</code></pre>\n" }, { "answer_id": 63868, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you need to list all rows where all the column values are <code>NULL</code>, then i'd use the <code>COLLATE</code> function. This takes a list of values and returns the first non-null value. If you add all the column names to the list, then use <code>IS NULL</code>, you should get all the rows containing only nulls.</p>\n\n<pre><code>SELECT * FROM MyTable WHERE COLLATE(Col1, Col2, Col3, Col4......) IS NULL\n</code></pre>\n\n<p>You shouldn't really have any tables with ALL the <code>columns</code> null, as this means you don't have a <code>primary key</code> (not allowed to be <code>null</code>). Not having a primary key is something to be avoided; this breaks the first normal form.</p>\n" }, { "answer_id": 16550333, "author": "Jasmina Shevchenko", "author_id": 2370941, "author_profile": "https://Stackoverflow.com/users/2370941", "pm_score": 1, "selected": false, "text": "<p>Try this -</p>\n\n<pre><code>DECLARE @table VARCHAR(100) = 'dbo.table'\n\nDECLARE @sql NVARCHAR(MAX) = ''\n\nSELECT @sql = @sql + 'IF NOT EXISTS(SELECT 1 FROM ' + @table + ' WHERE ' + c.name + ' IS NOT NULL) PRINT ''' + c.name + ''''\nFROM sys.objects o\nJOIN sys.columns c ON o.[object_id] = c.[object_id]\nWHERE o.[type] = 'U'\n AND o.[object_id] = OBJECT_ID(@table)\n AND c.is_nullable = 1\n\nEXEC(@sql)\n</code></pre>\n" }, { "answer_id": 24685175, "author": "user2466387", "author_id": 2466387, "author_profile": "https://Stackoverflow.com/users/2466387", "pm_score": 3, "selected": false, "text": "<p>Here is an updated version of Bryan's query for 2008 and later. It uses INFORMATION_SCHEMA.COLUMNS, adds variables for the table schema and table name. The column data type was added to the output. Including the column data type helps when looking for a column of a particular data type. I didn't added the column widths or anything.</p>\n\n<p>For output the RAISERROR ... WITH NOWAIT is used so text will display immediately instead of all at once (for the most part) at the end like PRINT does.</p>\n\n<pre><code>SET NOCOUNT ON;\n\nDECLARE\n @ColumnName sysname\n,@DataType nvarchar(128)\n,@cmd nvarchar(max)\n,@TableSchema nvarchar(128) = 'dbo'\n,@TableName sysname = 'TableName';\n\nDECLARE getinfo CURSOR FOR\nSELECT\n c.COLUMN_NAME\n ,c.DATA_TYPE\nFROM\n INFORMATION_SCHEMA.COLUMNS AS c\nWHERE\n c.TABLE_SCHEMA = @TableSchema\n AND c.TABLE_NAME = @TableName;\n\nOPEN getinfo;\n\nFETCH NEXT FROM getinfo INTO @ColumnName, @DataType;\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n SET @cmd = N'IF NOT EXISTS (SELECT * FROM ' + @TableSchema + N'.' + @TableName + N' WHERE [' + @ColumnName + N'] IS NOT NULL) RAISERROR(''' + @ColumnName + N' (' + @DataType + N')'', 0, 0) WITH NOWAIT;';\n EXECUTE (@cmd);\n\n FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;\nEND;\n\nCLOSE getinfo;\nDEALLOCATE getinfo;\n</code></pre>\n\n<p></p>\n" }, { "answer_id": 24685590, "author": "user3827049", "author_id": 3827049, "author_profile": "https://Stackoverflow.com/users/3827049", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT t.column_name\nFROM user_tab_columns t\nWHERE t.nullable = 'Y' AND t.table_name = 'table name here' AND t.num_distinct = 0;\n</code></pre>\n" }, { "answer_id": 43806546, "author": "Sylvain Bruyere", "author_id": 7969179, "author_profile": "https://Stackoverflow.com/users/7969179", "pm_score": 0, "selected": false, "text": "<p>An updated version of 'user2466387' version, with an additional small test which can improve performance, because it's useless to test non nullable columns:</p>\n\n<pre><code>AND IS_NULLABLE = 'YES'\n</code></pre>\n\n<p>The full code:</p>\n\n<pre><code>SET NOCOUNT ON;\n\nDECLARE\n @ColumnName sysname\n,@DataType nvarchar(128)\n,@cmd nvarchar(max)\n,@TableSchema nvarchar(128) = 'dbo'\n,@TableName sysname = 'TableName';\n\nDECLARE getinfo CURSOR FOR\nSELECT\n c.COLUMN_NAME\n ,c.DATA_TYPE\nFROM\n INFORMATION_SCHEMA.COLUMNS AS c\nWHERE\n c.TABLE_SCHEMA = @TableSchema\n AND c.TABLE_NAME = @TableName\n AND IS_NULLABLE = 'YES';\n\nOPEN getinfo;\n\nFETCH NEXT FROM getinfo INTO @ColumnName, @DataType;\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n SET @cmd = N'IF NOT EXISTS (SELECT * FROM ' + @TableSchema + N'.' + @TableName + N' WHERE [' + @ColumnName + N'] IS NOT NULL) RAISERROR(''' + @ColumnName + N' (' + @DataType + N')'', 0, 0) WITH NOWAIT;';\n EXECUTE (@cmd);\n\n FETCH NEXT FROM getinfo INTO @ColumnName, @DataType;\nEND;\n\nCLOSE getinfo;\nDEALLOCATE getinfo;\n</code></pre>\n" }, { "answer_id": 44392513, "author": "user8120267", "author_id": 8120267, "author_profile": "https://Stackoverflow.com/users/8120267", "pm_score": 1, "selected": false, "text": "<p>Not actually sure about 2005, but 2008 ate it:</p>\n\n<pre><code>USE [DATABASE_NAME] -- !\nGO\n\nDECLARE @SQL NVARCHAR(MAX)\nDECLARE @TableName VARCHAR(255)\n\nSET @TableName = 'TABLE_NAME' -- !\n\nSELECT @SQL = \n(\n SELECT \n CHAR(10)\n +'DELETE FROM ['+t1.TABLE_CATALOG+'].['+t1.TABLE_SCHEMA+'].['+t1.TABLE_NAME+'] WHERE '\n +(\n SELECT \n CASE t2.ORDINAL_POSITION \n WHEN (SELECT MIN(t3.ORDINAL_POSITION) FROM INFORMATION_SCHEMA.COLUMNS t3 WHERE t3.TABLE_NAME=t2.TABLE_NAME) THEN ''\n ELSE 'AND '\n END\n +'['+COLUMN_NAME+'] IS NULL' AS 'data()'\n FROM INFORMATION_SCHEMA.COLUMNS t2 WHERE t2.TABLE_NAME=t1.TABLE_NAME FOR XML PATH('')\n ) AS 'data()'\n FROM INFORMATION_SCHEMA.TABLES t1 WHERE t1.TABLE_NAME = @TableName FOR XML PATH('')\n)\n\nSELECT @SQL -- EXEC(@SQL)\n</code></pre>\n" }, { "answer_id": 57849043, "author": "Akila Viduranga Liyanaarachchi", "author_id": 6885539, "author_profile": "https://Stackoverflow.com/users/6885539", "pm_score": 1, "selected": false, "text": "<p>Here I have created a script for any kind of SQL table. please copy this stored procedure and create this on your Environment and run this stored procedure with your Table.</p>\n\n<pre><code>exec [dbo].[SP_RemoveNullValues] 'Your_Table_Name'\n</code></pre>\n\n<p>stored procedure</p>\n\n<pre><code>GO\n/****** Object: StoredProcedure [dbo].[SP_RemoveNullValues] Script Date: 09/09/2019 11:26:53 AM ******/\nSET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n-- akila liyanaarachchi\nCreate procedure [dbo].[SP_RemoveNullValues](@PTableName Varchar(50) ) as \nbegin\n\n\nDECLARE Cussor CURSOR FOR \nSELECT COLUMN_NAME,TABLE_NAME,DATA_TYPE\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME = @PTableName \n\nOPEN Cussor;\n\nDeclare @ColumnName Varchar(50)\nDeclare @TableName Varchar(50)\nDeclare @DataType Varchar(50)\nDeclare @Flage int \n\nFETCH NEXT FROM Cussor INTO @ColumnName,@TableName,@DataType\nWHILE @@FETCH_STATUS = 0\nBEGIN\n\nset @Flage=0\n\n\nIf(@DataType in('bigint','numeric','bit','smallint','decimal','smallmoney','int','tinyint','money','float','real'))\nbegin\nset @Flage=1\nend \nIf(@DataType in('date','atetimeoffset','datetime2','smalldatetime','datetime','time'))\nbegin\nset @Flage=2\nend \nIf(@DataType in('char','varchar','text','nchar','nvarchar','ntext'))\nbegin\nset @Flage=3\nend \n\nIf(@DataType in('binary','varbinary'))\nbegin\nset @Flage=4\nend \n\n\n\nDECLARE @SQL VARCHAR(MAX) \n\nif (@Flage in(1,4))\nbegin \n\nSET @SQL =' update ['+@TableName+'] set ['+@ColumnName+']=0 where ['+@ColumnName+'] is null'\nend \n\nif (@Flage =3)\nbegin \n\nSET @SQL =' update ['+@TableName+'] set ['+@ColumnName+'] = '''' where ['+@ColumnName+'] is null '\nend \n\nif (@Flage =2)\nbegin \n\nSET @SQL =' update ['+@TableName+'] set ['+@ColumnName+'] ='+'''1901-01-01 00:00:00.000'''+' where ['+@ColumnName+'] is null '\nend \n\n\nEXEC(@SQL)\n\n\n\nFETCH NEXT FROM Cussor INTO @ColumnName,@TableName,@DataType\nEND\n\nCLOSE Cussor\nDEALLOCATE Cussor\n\nEND\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ]
How do I select all the columns in a table that only contain NULL values for all the rows? I'm using **MS SQL Server 2005**. I'm trying to find out which columns are not used in the table so I can delete them.
Here is the sql 2005 or later version: Replace ADDR\_Address with your tablename. ``` declare @col varchar(255), @cmd varchar(max) DECLARE getinfo cursor for SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID WHERE t.Name = 'ADDR_Address' OPEN getinfo FETCH NEXT FROM getinfo into @col WHILE @@FETCH_STATUS = 0 BEGIN SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM ADDR_Address WHERE [' + @col + '] IS NOT NULL) BEGIN print ''' + @col + ''' end' EXEC(@cmd) FETCH NEXT FROM getinfo into @col END CLOSE getinfo DEALLOCATE getinfo ```
63,295
<p>I have Sun webserver iws6 (iplanet 6) proxying my bea cluster. My cluster is under /portal/yadda. I want anyone who goes to </p> <pre><code>http://the.domain.com/ </code></pre> <p>to be quickly redirected to </p> <pre><code>http://the.domain.com/portal/ </code></pre> <p>I have and index.html that does a post and redirect, but the user sometimes sees it. Does anyone have a better way?</p> <p>Aaron</p> <p>I have tried the 3 replies below. None of them worked for me. Back to the drawing board. A</p>
[ { "answer_id": 63362, "author": "wolak", "author_id": 7717, "author_profile": "https://Stackoverflow.com/users/7717", "pm_score": 0, "selected": false, "text": "<p>Does this help?\n<a href=\"http://docs.sun.com/source/816-5691-10/essearch.htm#25618\" rel=\"nofollow noreferrer\">http://docs.sun.com/source/816-5691-10/essearch.htm#25618</a></p>\n\n<hr>\n\n<p>To map a URL, perform the following steps:</p>\n\n<p>Open the Class Manager and select the server instance from the drop-down list.</p>\n\n<p>Choose the Content Mgmt tab.</p>\n\n<p>Click the Additional Document Directories link.\nThe web server displays the Additional Document Directories page.\n(Optional) Add another directory by entering one of the following.</p>\n\n<p>URL prefix.\nFor example: plans.\nAbsolute physical path of the directory you want the URL mapped to.\nFor example:\nC:/iPlanet/Servers/docs/marketing/plans\nClick OK.</p>\n\n<p>Click Apply.</p>\n\n<p>Edit one of the current additional directories listed by selecting one of the following:\nEdit</p>\n\n<p>Remove\nIf editing, select edit next to the listed directory you wish to change.</p>\n\n<p>Enter a new prefix using ASCII format.</p>\n\n<p>(Optional) Select a style in the Apply Style drop-down list if you want to apply a style to the directory:\nFor more information about styles, see Applying Configuration Styles.\nClick OK to add the new document directory.</p>\n\n<p>Click Apply.</p>\n\n<p>Choose Apply Changes to hard start /restart your server.</p>\n" }, { "answer_id": 63398, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": -1, "selected": false, "text": "<p>You should be able to configure the webserver to do a header redirect (301 or 302 depending on your situation) so it redirects without ever loading an HTML page. This can be done in PHP as well:</p>\n\n<pre><code>&lt;?php\nheader(\"Location: http://www.example.com/\"); /* Redirect browser */\n\n/* Make sure that code below does not get executed when we redirect. */\nexit;\n?&gt;\n</code></pre>\n\n<p>If you don't want to modify your server configuration.</p>\n\n<p>If your server uses the .htaccess file, insert a line similar to the following:</p>\n\n<pre><code>Redirect 301 /oldpage.html http://www.example.com/newpage.html\n</code></pre>\n\n<p>-Adam</p>\n" }, { "answer_id": 63575, "author": "Jahangir", "author_id": 6927, "author_profile": "https://Stackoverflow.com/users/6927", "pm_score": 0, "selected": false, "text": "<p>You could also just add the below line in the .htaccess file</p>\n\n<p>Redirect permanent /oldpage.html <a href=\"http://www.example.com/newpage.html\" rel=\"nofollow noreferrer\">http://www.example.com/newpage.html</a></p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7659/" ]
I have Sun webserver iws6 (iplanet 6) proxying my bea cluster. My cluster is under /portal/yadda. I want anyone who goes to ``` http://the.domain.com/ ``` to be quickly redirected to ``` http://the.domain.com/portal/ ``` I have and index.html that does a post and redirect, but the user sometimes sees it. Does anyone have a better way? Aaron I have tried the 3 replies below. None of them worked for me. Back to the drawing board. A
Does this help? <http://docs.sun.com/source/816-5691-10/essearch.htm#25618> --- To map a URL, perform the following steps: Open the Class Manager and select the server instance from the drop-down list. Choose the Content Mgmt tab. Click the Additional Document Directories link. The web server displays the Additional Document Directories page. (Optional) Add another directory by entering one of the following. URL prefix. For example: plans. Absolute physical path of the directory you want the URL mapped to. For example: C:/iPlanet/Servers/docs/marketing/plans Click OK. Click Apply. Edit one of the current additional directories listed by selecting one of the following: Edit Remove If editing, select edit next to the listed directory you wish to change. Enter a new prefix using ASCII format. (Optional) Select a style in the Apply Style drop-down list if you want to apply a style to the directory: For more information about styles, see Applying Configuration Styles. Click OK to add the new document directory. Click Apply. Choose Apply Changes to hard start /restart your server.
63,303
<p>I have a System.Diagnostics.Process object in a program targeted at the .Net framework 3.5</p> <p>I have redirected both <code>StandardOutput</code> and <code>StandardError</code> pipes and I'm receiving data from them asynchronously. I've also set an event handler for the Exited event.</p> <p>Once I call <code>Process.Start()</code> I want to go off and do other work whilst I wait for events to be raised.</p> <p>Unfortunately it appears that, for a process which returns a large amount of information, the Exited event is fired before the last <code>OutputDataReceived</code> event.</p> <p>How do I know when the last <code>OutputDataReceived</code> has been received? Ideally I would like the <code>Exited</code> event to be the last event I receive.</p> <p>Here is an example program:</p> <pre><code>using System; using System.Diagnostics; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string command = "output.exe"; string arguments = " whatever"; ProcessStartInfo info = new ProcessStartInfo(command, arguments); // Redirect the standard output of the process. info.RedirectStandardOutput = true; info.RedirectStandardError = true; // Set UseShellExecute to false for redirection info.UseShellExecute = false; Process proc = new Process(); proc.StartInfo = info; proc.EnableRaisingEvents = true; // Set our event handler to asynchronously read the sort output. proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived); proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived); proc.Exited += new EventHandler(proc_Exited); proc.Start(); // Start the asynchronous read of the sort output stream. Note this line! proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.WaitForExit(); Console.WriteLine("Exited (Main)"); } static void proc_Exited(object sender, EventArgs e) { Console.WriteLine("Exited (Event)"); } static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine("Error: {0}", e.Data); } static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine("Output data: {0}", e.Data); } } } </code></pre> <p>When running this program you will notice that "Exited (Event)" appears in a completely variable location within the output. You may need to run it a few times and, obviously, you will need to replace "output.exe" with a program of your choice that produces a suitably large amount of output.</p> <p>So, the question again: How do I know when the last <code>OutputDataReceived</code> has been received? Ideally I would like the <code>Exited</code> event to be the last event I receive.</p>
[ { "answer_id": 1423665, "author": "csharptest.net", "author_id": 164392, "author_profile": "https://Stackoverflow.com/users/164392", "pm_score": 5, "selected": false, "text": "<p>The answer to this is that <a href=\"https://msdn.microsoft.com/en-us/library/system.diagnostics.datareceivedeventhandler%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>e.Data</code> will be set to <code>null</code></a>:</p>\n\n<pre><code>static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)\n{\n if( e.Data == null ) _exited.Set();\n}\n</code></pre>\n" }, { "answer_id": 63083735, "author": "user2763329", "author_id": 2763329, "author_profile": "https://Stackoverflow.com/users/2763329", "pm_score": 1, "selected": false, "text": "<p>It will be more comfortable if e.Data set to null, but actually, the value will be an empty string. Please note the first value also could be Empty string. The real answer is once you receive some value other than Empty string, then look for next Empty string. I am using Visual Studio 2019.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a System.Diagnostics.Process object in a program targeted at the .Net framework 3.5 I have redirected both `StandardOutput` and `StandardError` pipes and I'm receiving data from them asynchronously. I've also set an event handler for the Exited event. Once I call `Process.Start()` I want to go off and do other work whilst I wait for events to be raised. Unfortunately it appears that, for a process which returns a large amount of information, the Exited event is fired before the last `OutputDataReceived` event. How do I know when the last `OutputDataReceived` has been received? Ideally I would like the `Exited` event to be the last event I receive. Here is an example program: ``` using System; using System.Diagnostics; using System.Threading; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string command = "output.exe"; string arguments = " whatever"; ProcessStartInfo info = new ProcessStartInfo(command, arguments); // Redirect the standard output of the process. info.RedirectStandardOutput = true; info.RedirectStandardError = true; // Set UseShellExecute to false for redirection info.UseShellExecute = false; Process proc = new Process(); proc.StartInfo = info; proc.EnableRaisingEvents = true; // Set our event handler to asynchronously read the sort output. proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived); proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived); proc.Exited += new EventHandler(proc_Exited); proc.Start(); // Start the asynchronous read of the sort output stream. Note this line! proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.WaitForExit(); Console.WriteLine("Exited (Main)"); } static void proc_Exited(object sender, EventArgs e) { Console.WriteLine("Exited (Event)"); } static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine("Error: {0}", e.Data); } static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine("Output data: {0}", e.Data); } } } ``` When running this program you will notice that "Exited (Event)" appears in a completely variable location within the output. You may need to run it a few times and, obviously, you will need to replace "output.exe" with a program of your choice that produces a suitably large amount of output. So, the question again: How do I know when the last `OutputDataReceived` has been received? Ideally I would like the `Exited` event to be the last event I receive.
The answer to this is that [`e.Data` will be set to `null`](https://msdn.microsoft.com/en-us/library/system.diagnostics.datareceivedeventhandler%28v=vs.110%29.aspx): ``` static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e) { if( e.Data == null ) _exited.Set(); } ```
63,399
<p>I need to do a dump of a table on a remote server, but I can't access the server directly. The only access I have is through PHP scripts.</p> <p>Is there some way in which MySQL will return an </p> <pre><code>INSERT INTO `table_name` (`field1`, `field2`) VALUES ('a', 'b'), ('c', 'd') </code></pre> <p>statement, like what <code>mysqldump</code> will return?</p> <p>I don't have access to phpMyAdmin, and I preferably don't want to use <code>exec</code>, <code>system</code> or <code>passthru</code>.</p> <p>See <a href="https://stackoverflow.com/questions/81934/easy-way-to-export-a-sql-table-without-access-to-the-server-or-phpmyadmin">this question</a> for another export method</p>
[ { "answer_id": 63405, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 4, "selected": true, "text": "<p>1) can you run mysqldump from exec or passthru<br />\n2) take a look at this: <a href=\"http://www.php-mysql-tutorial.com/perform-mysql-backup-php.php\" rel=\"noreferrer\">http://www.php-mysql-tutorial.com/perform-mysql-backup-php.php</a></p>\n" }, { "answer_id": 63419, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>If you can use php-scripts on the server i would recommend <a href=\"http://www.phpmyadmin.net/home_page/index.php\" rel=\"nofollow noreferrer\">phpmyadmin</a>. Then you can do this from the web-interface.</p>\n" }, { "answer_id": 63420, "author": "Astra", "author_id": 5862, "author_profile": "https://Stackoverflow.com/users/5862", "pm_score": 0, "selected": false, "text": "<p>You should check out <a href=\"http://phpmyadmin.sourceforge.net\" rel=\"nofollow noreferrer\">PHPMyAdmin</a>, it is a php based MySQL administration tool. It supports backups and recovery for the database as well as a 'GUI' to the database server. It works very well.</p>\n" }, { "answer_id": 63424, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 0, "selected": false, "text": "<p>I'm pretty sure <a href=\"http://www.phpmyadmin.net/\" rel=\"nofollow noreferrer\">phpMyAdmin</a> will <a href=\"http://www.phpmyadmin.net/documentation/#faqexport\" rel=\"nofollow noreferrer\">do this for you</a>.</p>\n" }, { "answer_id": 63431, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 0, "selected": false, "text": "<p>This</p>\n\n<pre><code>select 'insert into table table_name (field1, field2) values'\n || table_name.field1 || ', ' || table_field2 || ');'\nfrom table_name\n</code></pre>\n\n<p>should get you started. Replace || with the string concatenation operator for your db flavour. If field1 or field2 are strings you will have to come up with some trick for quoting/escaping.</p>\n" }, { "answer_id": 63468, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Here is one approach generating a lot of separate query statements. You can also use implode to more efficiently combine the strings, but this is easier to read for starters and derived from this you can come up with a million other approaches.</p>\n\n<pre><code>$results = mysql_query(\"SELECT * FROM `table_name`\");\nwhile($row = mysql_fetch_assoc($results)) {\n\n $query = \"INSERT INTO `table_name` \";\n $fields = '(';\n $values = '('; \n\n foreach($row as $field=&gt;$value) {\n $fields .= \"'\".$field.\"',\";\n $values .= \"'\".mysql_escape_string($value).\"',\";\n }\n\n //drop the last comma off\n $fields = substr($fields,0,-1);\n $values = substr($values,0,-1);\n\n $query .= $fields . \" VALUES \" . $values;\n\n //your final result\n echo $query;\n}\n</code></pre>\n\n<p>See if that gets you started </p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
I need to do a dump of a table on a remote server, but I can't access the server directly. The only access I have is through PHP scripts. Is there some way in which MySQL will return an ``` INSERT INTO `table_name` (`field1`, `field2`) VALUES ('a', 'b'), ('c', 'd') ``` statement, like what `mysqldump` will return? I don't have access to phpMyAdmin, and I preferably don't want to use `exec`, `system` or `passthru`. See [this question](https://stackoverflow.com/questions/81934/easy-way-to-export-a-sql-table-without-access-to-the-server-or-phpmyadmin) for another export method
1) can you run mysqldump from exec or passthru 2) take a look at this: <http://www.php-mysql-tutorial.com/perform-mysql-backup-php.php>
63,447
<p>How do I perform an <code>IF...THEN</code> in an <code>SQL SELECT</code> statement?</p> <p>For example:</p> <pre><code>SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product </code></pre>
[ { "answer_id": 63474, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 6, "selected": false, "text": "<pre><code>SELECT \n(CASE \n WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'\n ELSE 'NO' \n END) as Salable\n, * \nFROM Product\n</code></pre>\n" }, { "answer_id": 63476, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 6, "selected": false, "text": "<p>Use CASE. Something like this.</p>\n\n<pre><code>SELECT Salable =\n CASE Obsolete\n WHEN 'N' THEN 1\n ELSE 0\n END\n</code></pre>\n" }, { "answer_id": 63477, "author": "Santiago Cepas", "author_id": 6547, "author_profile": "https://Stackoverflow.com/users/6547", "pm_score": 6, "selected": false, "text": "<pre><code> SELECT\n CASE \n WHEN OBSOLETE = 'N' or InStock = 'Y' THEN 'TRUE' \n ELSE 'FALSE' \n END AS Salable,\n * \nFROM PRODUCT\n</code></pre>\n" }, { "answer_id": 63480, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 12, "selected": true, "text": "<p>The <code>CASE</code> statement is the closest to IF in SQL and is supported on all versions of SQL Server.</p>\n<pre><code>SELECT CAST(\n CASE\n WHEN Obsolete = 'N' or InStock = 'Y'\n THEN 1\n ELSE 0\n END AS bit) as Saleable, *\nFROM Product\n</code></pre>\n<p>You only need to use the <code>CAST</code> operator if you want the result as a Boolean value. If you are happy with an <code>int</code>, this works:</p>\n<pre><code>SELECT CASE\n WHEN Obsolete = 'N' or InStock = 'Y'\n THEN 1\n ELSE 0\n END as Saleable, *\nFROM Product\n</code></pre>\n<p><code>CASE</code> statements can be embedded in other <code>CASE</code> statements and even included in aggregates.</p>\n<p>SQL Server Denali (SQL Server 2012) adds the <a href=\"http://msdn.microsoft.com/en-us/library/hh213574%28v=sql.110%29.aspx\" rel=\"noreferrer\">IIF</a> statement which is also available in <a href=\"http://www.techonthenet.com/access/functions/advanced/iif.php\" rel=\"noreferrer\">access</a> (pointed out by <a href=\"https://stackoverflow.com/questions/63447/how-do-you-perform-an-if-then-in-an-sql-select/6769805#6769805\">Martin Smith</a>):</p>\n<pre><code>SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product\n</code></pre>\n" }, { "answer_id": 63498, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 7, "selected": false, "text": "<p>You can find some nice examples in <em><a href=\"https://web.archive.org/web/20210728081626/https://www.4guysfromrolla.com/webtech/102704-1.shtml\" rel=\"nofollow noreferrer\">The Power of SQL CASE Statements</a></em>, and I think the statement that you can use will be something like this (from <a href=\"https://web.archive.org/web/20211020202742/https://www.4guysfromrolla.com\" rel=\"nofollow noreferrer\">4guysfromrolla</a>):</p>\n<pre><code>SELECT\n FirstName, LastName,\n Salary, DOB,\n CASE Gender\n WHEN 'M' THEN 'Male'\n WHEN 'F' THEN 'Female'\n END\nFROM Employees\n</code></pre>\n" }, { "answer_id": 63500, "author": "user7658", "author_id": 7658, "author_profile": "https://Stackoverflow.com/users/7658", "pm_score": 6, "selected": false, "text": "<p>Microsoft SQL Server (T-SQL)</p>\n\n<p>In a <code>select</code>, use:</p>\n\n<pre><code>select case when Obsolete = 'N' or InStock = 'Y' then 'YES' else 'NO' end\n</code></pre>\n\n<p>In a <code>where</code> clause, use:</p>\n\n<pre><code>where 1 = case when Obsolete = 'N' or InStock = 'Y' then 1 else 0 end\n</code></pre>\n" }, { "answer_id": 63504, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Use a CASE statement:</p>\n\n<pre><code>SELECT CASE\n WHEN (Obsolete = 'N' OR InStock = 'Y')\n THEN 'Y'\n ELSE 'N'\nEND as Available\n\netc...\n</code></pre>\n" }, { "answer_id": 63777, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 8, "selected": false, "text": "<p>The case statement is your friend in this situation, and takes one of two forms:</p>\n\n<p>The simple case:</p>\n\n<pre><code>SELECT CASE &lt;variable&gt; WHEN &lt;value&gt; THEN &lt;returnvalue&gt;\n WHEN &lt;othervalue&gt; THEN &lt;returnthis&gt;\n ELSE &lt;returndefaultcase&gt;\n END AS &lt;newcolumnname&gt;\nFROM &lt;table&gt;\n</code></pre>\n\n<p>The extended case:</p>\n\n<pre><code>SELECT CASE WHEN &lt;test&gt; THEN &lt;returnvalue&gt;\n WHEN &lt;othertest&gt; THEN &lt;returnthis&gt;\n ELSE &lt;returndefaultcase&gt;\n END AS &lt;newcolumnname&gt;\nFROM &lt;table&gt;\n</code></pre>\n\n<p>You can even put case statements in an order by clause for really fancy ordering.</p>\n" }, { "answer_id": 2010311, "author": "Ken", "author_id": 244385, "author_profile": "https://Stackoverflow.com/users/244385", "pm_score": 6, "selected": false, "text": "<p>From <a href=\"http://www.databasejournal.com/features/mssql/article.php/3087431/T-SQL-Programming-Part-1---Defining-Variables-and-IFELSE-logic.htm\" rel=\"noreferrer\">this link</a>, we can understand <code>IF THEN ELSE</code> in T-SQL:</p>\n\n<pre><code>IF EXISTS(SELECT *\n FROM Northwind.dbo.Customers\n WHERE CustomerId = 'ALFKI')\n PRINT 'Need to update Customer Record ALFKI'\nELSE\n PRINT 'Need to add Customer Record ALFKI'\n\nIF EXISTS(SELECT *\n FROM Northwind.dbo.Customers\n WHERE CustomerId = 'LARSE')\n PRINT 'Need to update Customer Record LARSE'\nELSE\n PRINT 'Need to add Customer Record LARSE' \n</code></pre>\n\n<p>Isn't this good enough for T-SQL?</p>\n" }, { "answer_id": 6769805, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 8, "selected": false, "text": "<p>From SQL Server 2012 you can use the <a href=\"http://msdn.microsoft.com/en-us/library/hh213574(v=sql.110).aspx\" rel=\"noreferrer\"><strong><code>IIF</code></strong> function</a> for this.</p>\n\n<pre><code>SELECT IIF(Obsolete = 'N' OR InStock = 'Y', 1, 0) AS Salable, *\nFROM Product\n</code></pre>\n\n<p>This is effectively just a shorthand (albeit not standard SQL) way of writing <code>CASE</code>.</p>\n\n<p>I prefer the conciseness when compared with the expanded <code>CASE</code> version.</p>\n\n<p>Both <code>IIF()</code> and <code>CASE</code> resolve as expressions within a SQL statement and can only be used in well-defined places.</p>\n\n<blockquote>\n <p>The CASE expression cannot be used to control the flow of execution of\n Transact-SQL statements, statement blocks, user-defined functions, and\n stored procedures.</p>\n</blockquote>\n\n<p>If your needs can not be satisfied by these limitations (for example, a need to return differently shaped result sets dependent on some condition) then SQL Server does also have a procedural <a href=\"http://msdn.microsoft.com/en-gb/library/ms182717.aspx\" rel=\"noreferrer\"><code>IF</code></a> keyword.</p>\n\n<pre><code>IF @IncludeExtendedInformation = 1\n BEGIN\n SELECT A,B,C,X,Y,Z\n FROM T\n END\nELSE\n BEGIN\n SELECT A,B,C\n FROM T\n END\n</code></pre>\n\n<p><a href=\"https://dba.stackexchange.com/a/9874/3690\">Care must sometimes be taken to avoid parameter sniffing issues with this approach however</a>.</p>\n" }, { "answer_id": 13089905, "author": "Robert B. Grossman", "author_id": 1777537, "author_profile": "https://Stackoverflow.com/users/1777537", "pm_score": 4, "selected": false, "text": "<p>If you're inserting results into a table for the first time, rather than transferring results from one table to another, this works in <a href=\"https://en.wikipedia.org/wiki/Oracle_Database#Releases_and_versions\" rel=\"nofollow noreferrer\">Oracle 11.2g</a>:</p>\n<pre><code>INSERT INTO customers (last_name, first_name, city)\n SELECT 'Doe', 'John', 'Chicago' FROM dual\n WHERE NOT EXISTS\n (SELECT '1' from customers\n where last_name = 'Doe'\n and first_name = 'John'\n and city = 'Chicago');\n</code></pre>\n" }, { "answer_id": 17004447, "author": "Tomasito", "author_id": 1296687, "author_profile": "https://Stackoverflow.com/users/1296687", "pm_score": 5, "selected": false, "text": "<p>Use pure bit logic:</p>\n\n<pre><code>DECLARE @Product TABLE (\n id INT PRIMARY KEY IDENTITY NOT NULL\n ,Obsolote CHAR(1)\n ,Instock CHAR(1)\n)\n\nINSERT INTO @Product ([Obsolote], [Instock])\n VALUES ('N', 'N'), ('N', 'Y'), ('Y', 'Y'), ('Y', 'N')\n\n;\nWITH cte\nAS\n(\n SELECT\n 'CheckIfInstock' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Instock], 'Y'), 1), 'N'), 0) AS BIT)\n ,'CheckIfObsolote' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Obsolote], 'N'), 0), 'Y'), 1) AS BIT)\n ,*\n FROM\n @Product AS p\n)\nSELECT\n 'Salable' = c.[CheckIfInstock] &amp; ~c.[CheckIfObsolote]\n ,*\nFROM\n [cte] c\n</code></pre>\n\n<p>See <a href=\"http://sqlfiddle.com/#!3/0b900/3/0\" rel=\"nofollow noreferrer\">working demo: if then without <code>case</code> in SQL&nbsp;Server</a>.</p>\n\n<p>For start, you need to work out the value of <code>true</code> and <code>false</code> for selected conditions. Here comes two <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/language-elements/nullif-transact-sql?view=sql-server-2017\" rel=\"nofollow noreferrer\">NULLIF</a>:</p>\n\n<pre><code>for true: ISNULL(NULLIF(p.[Instock], 'Y'), 1)\nfor false: ISNULL(NULLIF(p.[Instock], 'N'), 0)\n</code></pre>\n\n<p>combined together gives 1 or 0. Next use <a href=\"http://msdn.microsoft.com/en-us/library/ms176122.aspx\" rel=\"nofollow noreferrer\">bitwise operators</a>.</p>\n\n<p>It's the most <a href=\"http://en.wikipedia.org/wiki/WYSIWYG\" rel=\"nofollow noreferrer\">WYSIWYG</a> method.</p>\n" }, { "answer_id": 20992729, "author": "Dibin", "author_id": 1915236, "author_profile": "https://Stackoverflow.com/users/1915236", "pm_score": 3, "selected": false, "text": "<p>For those who uses SQL Server 2012, IIF is a feature that has been added and works as an alternative to Case statements.</p>\n\n<pre><code>SELECT IIF(Obsolete = 'N' OR InStock = 'Y', 1, 0) AS Salable, *\nFROM Product \n</code></pre>\n" }, { "answer_id": 32200662, "author": "Mohammad Atiour Islam", "author_id": 1077346, "author_profile": "https://Stackoverflow.com/users/1077346", "pm_score": 4, "selected": false, "text": "<pre><code>SELECT CASE WHEN profile.nrefillno = 0 THEN 'N' ELSE 'R'END as newref\nFrom profile\n</code></pre>\n" }, { "answer_id": 34178590, "author": "Chanukya", "author_id": 5093602, "author_profile": "https://Stackoverflow.com/users/5093602", "pm_score": 4, "selected": false, "text": "<pre><code>case statement some what similar to if in SQL server\n\nSELECT CASE \n WHEN Obsolete = 'N' or InStock = 'Y' \n THEN 1 \n ELSE 0 \n END as Saleable, * \nFROM Product\n</code></pre>\n" }, { "answer_id": 34340652, "author": "Ravi Anand", "author_id": 2444505, "author_profile": "https://Stackoverflow.com/users/2444505", "pm_score": 5, "selected": false, "text": "<p>Simple if-else statement in SQL&nbsp;Server:</p>\n\n<pre><code>DECLARE @val INT;\nSET @val = 15;\n\nIF @val &lt; 25\nPRINT 'Hi Ravi Anand';\nELSE\nPRINT 'By Ravi Anand.';\n\nGO\n</code></pre>\n\n<p>Nested If...else statement in SQL&nbsp;Server -</p>\n\n<pre><code>DECLARE @val INT;\nSET @val = 15;\n\nIF @val &lt; 25\nPRINT 'Hi Ravi Anand.';\nELSE\nBEGIN\nIF @val &lt; 50\n PRINT 'what''s up?';\nELSE\n PRINT 'Bye Ravi Anand.';\nEND;\n\nGO\n</code></pre>\n" }, { "answer_id": 35350520, "author": "JustJohn", "author_id": 564810, "author_profile": "https://Stackoverflow.com/users/564810", "pm_score": 4, "selected": false, "text": "<p>This isn't an answer, just an example of a CASE statement in use where I work. It has a nested CASE statement. Now you know why my eyes are crossed. </p>\n\n<pre><code> CASE orweb2.dbo.Inventory.RegulatingAgencyName\n WHEN 'Region 1'\n THEN orweb2.dbo.CountyStateAgContactInfo.ContactState\n WHEN 'Region 2'\n THEN orweb2.dbo.CountyStateAgContactInfo.ContactState\n WHEN 'Region 3'\n THEN orweb2.dbo.CountyStateAgContactInfo.ContactState\n WHEN 'DEPT OF AGRICULTURE'\n THEN orweb2.dbo.CountyStateAgContactInfo.ContactAg\n ELSE (\n CASE orweb2.dbo.CountyStateAgContactInfo.IsContract\n WHEN 1\n THEN orweb2.dbo.CountyStateAgContactInfo.ContactCounty\n ELSE orweb2.dbo.CountyStateAgContactInfo.ContactState\n END\n )\n END AS [County Contact Name]\n</code></pre>\n" }, { "answer_id": 36868923, "author": "sandeep rawat", "author_id": 6085803, "author_profile": "https://Stackoverflow.com/users/6085803", "pm_score": 5, "selected": false, "text": "<p>A new feature, <a href=\"https://msdn.microsoft.com/en-IN/library/hh213574.aspx\" rel=\"noreferrer\">IIF</a> (that we can simply use), was added in SQL Server 2012:</p>\n\n<pre><code>SELECT IIF ( (Obsolete = 'N' OR InStock = 'Y'), 1, 0) AS Saleable, * FROM Product\n</code></pre>\n" }, { "answer_id": 37167739, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 4, "selected": false, "text": "<pre><code>SELECT 1 AS Saleable, *\n FROM @Product\n WHERE ( Obsolete = 'N' OR InStock = 'Y' )\nUNION\nSELECT 0 AS Saleable, *\n FROM @Product\n WHERE NOT ( Obsolete = 'N' OR InStock = 'Y' )\n</code></pre>\n" }, { "answer_id": 40886727, "author": "SURJEET SINGH Bisht", "author_id": 5081921, "author_profile": "https://Stackoverflow.com/users/5081921", "pm_score": 3, "selected": false, "text": "<pre><code> SELECT IIF(Obsolete = 'N' OR InStock = 'Y',1,0) AS Saleable, * FROM Product\n</code></pre>\n" }, { "answer_id": 45578381, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1 ELSE 0 \n END AS Saleable, * \nFROM Product\n</code></pre>\n" }, { "answer_id": 48541127, "author": "Serkan Arslan", "author_id": 8500110, "author_profile": "https://Stackoverflow.com/users/8500110", "pm_score": 3, "selected": false, "text": "<p>As an alternative solution to the <code>CASE</code> statement, a table-driven approach can be used:</p>\n<pre><code>DECLARE @Product TABLE (ID INT, Obsolete VARCHAR(10), InStock VARCHAR(10))\nINSERT INTO @Product VALUES\n(1,'N','Y'),\n(2,'A','B'),\n(3,'N','B'),\n(4,'A','Y')\n\nSELECT P.* , ISNULL(Stmt.Saleable,0) Saleable\nFROM\n @Product P\n LEFT JOIN\n ( VALUES\n ( 'N', 'Y', 1 )\n ) Stmt (Obsolete, InStock, Saleable)\n ON P.InStock = Stmt.InStock OR P.Obsolete = Stmt.Obsolete\n</code></pre>\n<p>Result:</p>\n<pre class=\"lang-none prettyprint-override\"><code>ID Obsolete InStock Saleable\n----------- ---------- ---------- -----------\n1 N Y 1\n2 A B 0\n3 N B 1\n4 A Y 1\n</code></pre>\n" }, { "answer_id": 52696617, "author": "laplace", "author_id": 9822422, "author_profile": "https://Stackoverflow.com/users/9822422", "pm_score": 2, "selected": false, "text": "<pre><code>SELECT \n CAST(\n CASE WHEN Obsolete = 'N' \n or InStock = 'Y' THEN ELSE 0 END AS bit\n ) as Saleable, * \nFROM \n Product\n</code></pre>\n" }, { "answer_id": 53121744, "author": "David Cohn", "author_id": 10588302, "author_profile": "https://Stackoverflow.com/users/10588302", "pm_score": 3, "selected": false, "text": "<p>Question:</p>\n\n<pre><code>SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product\n</code></pre>\n\n<p>ANSI:</p>\n\n<pre><code>Select \n case when p.Obsolete = 'N' \n or p.InStock = 'Y' then 1 else 0 end as Saleable, \n p.* \nFROM \n Product p;\n</code></pre>\n\n<p>Using aliases -- <code>p</code> in this case -- will help prevent issues.</p>\n" }, { "answer_id": 54932658, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You can have two choices for this to actually implement:</p>\n\n<ol>\n<li><p>Using IIF, which got introduced from SQL Server 2012:</p>\n\n<pre><code>SELECT IIF ( (Obsolete = 'N' OR InStock = 'Y'), 1, 0) AS Saleable, * FROM Product\n</code></pre></li>\n<li><p>Using <code>Select Case</code>:</p>\n\n<pre><code>SELECT CASE\n WHEN Obsolete = 'N' or InStock = 'Y'\n THEN 1\n ELSE 0\n END as Saleable, *\n FROM Product\n</code></pre></li>\n</ol>\n" }, { "answer_id": 58643023, "author": "Muhammad Awais", "author_id": 3901944, "author_profile": "https://Stackoverflow.com/users/3901944", "pm_score": 2, "selected": false, "text": "<p>It will be something like that:</p>\n\n<pre><code>SELECT OrderID, Quantity,\nCASE\n WHEN Quantity &gt; 30 THEN \"The quantity is greater than 30\"\n WHEN Quantity = 30 THEN \"The quantity is 30\"\n ELSE \"The quantity is under 30\"\nEND AS QuantityText\nFROM OrderDetails;\n</code></pre>\n" }, { "answer_id": 59086460, "author": "Salman A", "author_id": 87015, "author_profile": "https://Stackoverflow.com/users/87015", "pm_score": 2, "selected": false, "text": "<p>For the sake of completeness, I would add that SQL uses three-valued logic. The expression:</p>\n\n<pre><code>obsolete = 'N' OR instock = 'Y'\n</code></pre>\n\n<p>Could produce three distinct results:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>| obsolete | instock | saleable |\n|----------|---------|----------|\n| Y | Y | true |\n| Y | N | false |\n| Y | null | null |\n| N | Y | true |\n| N | N | true |\n| N | null | true |\n| null | Y | true |\n| null | N | null |\n| null | null | null |\n</code></pre>\n\n<p>So for example if a product is obsolete but you dont know if product is instock then you dont know if product is saleable. You can write this three-valued logic as follows:</p>\n\n<pre><code>SELECT CASE\n WHEN obsolete = 'N' OR instock = 'Y' THEN 'true'\n WHEN NOT (obsolete = 'N' OR instock = 'Y') THEN 'false'\n ELSE NULL\n END AS saleable\n</code></pre>\n\n<p>Once you figure out how it works, you can convert three results to two results by deciding the behavior of null. E.g. this would treat null as not saleable:</p>\n\n<pre><code>SELECT CASE\n WHEN obsolete = 'N' OR instock = 'Y' THEN 'true'\n ELSE 'false' -- either false or null\n END AS saleable\n</code></pre>\n" }, { "answer_id": 60278997, "author": "Tharuka Madumal", "author_id": 12910157, "author_profile": "https://Stackoverflow.com/users/12910157", "pm_score": 3, "selected": false, "text": "<p>Using SQL CASE is just like normal If / Else statements.\nIn the below query, if obsolete value = 'N' or if InStock value = 'Y' then the output will be 1. Otherwise the output will be 0.\nThen we put that 0 or 1 value under the Salable Column.</p>\n<pre><code>SELECT\n CASE\n WHEN obsolete = 'N' OR InStock = 'Y'\n THEN 1\n ELSE 0\n END AS Salable\n , *\nFROM PRODUCT\n</code></pre>\n" }, { "answer_id": 61112581, "author": "Prashant Marathay", "author_id": 12046787, "author_profile": "https://Stackoverflow.com/users/12046787", "pm_score": 2, "selected": false, "text": "<p>I like the use of the CASE statements, but the question asked for an IF statement in the SQL Select. What I've used in the past has been:</p>\n<pre><code>SELECT\n\n if(GENDER = &quot;M&quot;,&quot;Male&quot;,&quot;Female&quot;) as Gender\n\nFROM ...\n</code></pre>\n<p>It's like the Excel or sheets IF statements where there is a conditional followed by the true condition and then the false condition:</p>\n<pre><code>if(condition, true, false)\n</code></pre>\n<p>Furthermore, you can nest the <em>if</em> statements (but then use should use a CASE :-)</p>\n<p>(Note: this works in <a href=\"https://en.wikipedia.org/wiki/MySQL_Workbench\" rel=\"nofollow noreferrer\">MySQL Workbench</a>, but it may not work on other platforms)</p>\n" }, { "answer_id": 61941630, "author": "The AG", "author_id": 8692957, "author_profile": "https://Stackoverflow.com/users/8692957", "pm_score": 2, "selected": false, "text": "<p>You can use a <em>case</em> statement:</p>\n<pre><code>Select\nCase WHEN (Obsolete = 'N' or InStock = 'Y') THEN 1 ELSE 0 END Saleable,\nProduct.*\nfrom Product\n</code></pre>\n" }, { "answer_id": 65006288, "author": "yusuf hayırsever", "author_id": 10238086, "author_profile": "https://Stackoverflow.com/users/10238086", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT\nif((obsolete = 'N' OR instock = 'Y'), 1, 0) AS saleable, *\nFROM\nproduct;\n</code></pre>\n" }, { "answer_id": 71934110, "author": "durlove roy", "author_id": 1549783, "author_profile": "https://Stackoverflow.com/users/1549783", "pm_score": 1, "selected": false, "text": "<p>There are multiple conditions.</p>\n<pre><code>SELECT\n\n(CASE\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1001' THEN 'DM'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1002' THEN 'GS'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1003' THEN 'MB'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1004' THEN 'MP'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1005' THEN 'PL'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1008' THEN 'DM-27'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1011' THEN 'PB'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1012' THEN 'UT-2'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1013' THEN 'JGC'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1014' THEN 'SB'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1015' THEN 'IR'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1016' THEN 'UT-3'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1017' THEN 'UT-4'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1019' THEN 'KR'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1020' THEN 'SYB-SB'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1021' THEN 'GR'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1022' THEN 'SYB-KP'\nWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1026' THEN 'BNS'\n\n ELSE ''\nEND) AS OUTLET\n\nFROM matrixcrm.Transact\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6522/" ]
How do I perform an `IF...THEN` in an `SQL SELECT` statement? For example: ``` SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product ```
The `CASE` statement is the closest to IF in SQL and is supported on all versions of SQL Server. ``` SELECT CAST( CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1 ELSE 0 END AS bit) as Saleable, * FROM Product ``` You only need to use the `CAST` operator if you want the result as a Boolean value. If you are happy with an `int`, this works: ``` SELECT CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1 ELSE 0 END as Saleable, * FROM Product ``` `CASE` statements can be embedded in other `CASE` statements and even included in aggregates. SQL Server Denali (SQL Server 2012) adds the [IIF](http://msdn.microsoft.com/en-us/library/hh213574%28v=sql.110%29.aspx) statement which is also available in [access](http://www.techonthenet.com/access/functions/advanced/iif.php) (pointed out by [Martin Smith](https://stackoverflow.com/questions/63447/how-do-you-perform-an-if-then-in-an-sql-select/6769805#6769805)): ``` SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product ```
63,556
<p>I have a class with a bunch of properties that look like this:</p> <pre><code>public string Name { get { return _name; } set { IsDirty = true; _name = value; } } </code></pre> <p>It would be a lot easier if I could rely on C# 3.0 to generate the backing store for these, but is there any way to factor out the IsDirty=true; so that I can write my properties something like this and still get the same behaviour:</p> <pre><code>[MakesDirty] public string Name { get; set; } </code></pre>
[ { "answer_id": 63564, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>You could try setting up a code snippet to make it easy to create those.</p>\n" }, { "answer_id": 63600, "author": "LepardUK", "author_id": 44247, "author_profile": "https://Stackoverflow.com/users/44247", "pm_score": 0, "selected": false, "text": "<p>The other alternative might be a code generator such as codesmith to automate creating the properties. This would be especially useful if the properties you are creating are columns in a database table</p>\n" }, { "answer_id": 63623, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>ContextBound object. If you create a class that extends context bound object and you create a ContextAttribute you can intercept the calls made to such a property and set the IsDirty. .NET will create a proxy to your class so all calls go over something like a remoting sink.</p>\n\n<p>The problem with such an approach though is that your proxy will only be invoked when called externally. I'll give you an example.</p>\n\n<pre><code>class A\n{\n [Foo]\n public int Property1{get; set;}\n public int Property2{get {return variable;} set{ Property1 = value; variable = value; }\n}\n</code></pre>\n\n<p>When property1 is called from another class, your proxy would be invoked. But if another class calls property2, even though the set of property2 will call into property1 no proxy will be invoked, (a proxy isn't necessary when you're in the class itself).</p>\n\n<p>There is a lot of sample code out there of using ContextBoundObjects, look into it.</p>\n" }, { "answer_id": 63628, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 4, "selected": true, "text": "<p><strong>No. Not without writing considerably more (arcane?) code than the original version</strong> (You'd have to use reflection to check for the attribute on the property and what not.. did I mention it being 'slower').. This is the kind of duplication I can live with.</p>\n\n<p>MS has the same need for <a href=\"http://msdn.microsoft.com/en-us/library/ms229614.aspx\" rel=\"nofollow noreferrer\">raising events when a property is changed</a>. INotifyPropertyChanged that is a vital interface for change notifications. Every implementation I've seen yet\ndoes</p>\n\n<pre><code>set\n{ \n _name = value; \n NotifyPropertyChanged(\"Name\"); \n}\n</code></pre>\n\n<p>If it was possible, I'd figure those smart guys at MS would already have something like that in place.. </p>\n" }, { "answer_id": 63647, "author": "JRoppert", "author_id": 6777, "author_profile": "https://Stackoverflow.com/users/6777", "pm_score": 0, "selected": false, "text": "<p>I can recommend to use <a href=\"http://www.codeplex.com/entlib\" rel=\"nofollow noreferrer\">Enterprise Library</a> for that purpose. Policy Application Block delivers the infrastructure to do \"something\" (something = you can code that on your own) whenever you enter/exit a method for example. You can control the behavior with attributes. Take that as a hint an go into detail with the documentation of enterprise library.</p>\n" }, { "answer_id": 63670, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 0, "selected": false, "text": "<p>There's a DefaultValueAttribute that can be assigned to a property, this is mainly used by the designer tools so they can indicate when a property has been changed, but, it might be a \"tidy\" way of describing what the default value for a property is, and thus being able to identify if it's changed.</p>\n\n<p>You'd need to use Reflection to identify property changes - which isn't actually <em>that</em> expensive unless you're doing lots of it!</p>\n\n<p>Caveat: You wouldn't be able to tell if a property had been changed BACK from a non-default value to the default one.</p>\n" }, { "answer_id": 63677, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": false, "text": "<p>No, when you use automatic properties you don't have any control over the implementation. The best option is to use a templating tool, code snippets or create a private SetValue<code>&lt;T</code>>(ref T backingField, T value) which encapsulates the setter logic.</p>\n\n<pre><code>private void SetValue&lt;T&gt;(ref T backingField, T value)\n{\n if (backingField != value)\n {\n backingField = value;\n IsDirty = true;\n }\n}\n\npublic string Name\n{\n get\n {\n return _name;\n }\n set\n {\n SetValue(ref _name, value);\n }\n}\n</code></pre>\n" }, { "answer_id": 63703, "author": "Thomas Lundström", "author_id": 3985, "author_profile": "https://Stackoverflow.com/users/3985", "pm_score": 0, "selected": false, "text": "<p>I'd say that the best way of solving this is to use Aspect-Oriented Programming (AOP). Mats Helander did a <a href=\"http://www.infoq.com/articles/aspects-of-domain-model-mgmt\" rel=\"nofollow noreferrer\">write up on this on InfoQ</a>. The article is a bit messy, but it's possible to follow. \nThere are a number of different products that does AOP in the .NET space, i recommend PostSharp.</p>\n" }, { "answer_id": 63745, "author": "Sean Hanley", "author_id": 7290, "author_profile": "https://Stackoverflow.com/users/7290", "pm_score": 0, "selected": false, "text": "<p>If you do go with Attributes, I'm fairly certain you'll have to <a href=\"http://www.csharphelp.com/archives/archive119.html\" rel=\"nofollow noreferrer\">roll your own logic</a> to deduce what they mean and what to do about them. Whatever is using your custom class objects will have to have a way of performing these attribute actions/checks, preferably at instantiation.</p>\n\n<p>Otherwise, you're looking at using maybe events. You'd still have to add the event to every set method, but the benefit there would be you're not hard-coding what to do about dirty sets on every property and can control, in one place, what is to be done. That would, at the very least, introduce a bit more code re-use.</p>\n" }, { "answer_id": 63798, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 2, "selected": false, "text": "<p>If you really want to go that way, to modify what the code does using an attribute, there are some ways to do it and they all are related to AOP (Aspect oriented programming). Check out <a href=\"http://www.postsharp.org/\" rel=\"nofollow noreferrer\">PostSharp</a>, which is an aftercompiler that can modify your code in a after compilation step. For example you could set up one custom attribute for your properties (or aspect, how it is called in AOP) that injects code inside property setters, that marks your objects as dirty. If you want some examples of how this is achieved you can check out their <a href=\"http://www.postsharp.org/about/getting-started/\" rel=\"nofollow noreferrer\">tutorials</a>. </p>\n\n<p><em>But be careful with AOP and because you can just as easily create more problems using it that you're trying to solve if not used right.</em></p>\n\n<p>There are more AOP frameworks out there some using post compilation and some using method interception mechanisms that are present in .Net, the later have some performance drawbacks compared to the first.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1404/" ]
I have a class with a bunch of properties that look like this: ``` public string Name { get { return _name; } set { IsDirty = true; _name = value; } } ``` It would be a lot easier if I could rely on C# 3.0 to generate the backing store for these, but is there any way to factor out the IsDirty=true; so that I can write my properties something like this and still get the same behaviour: ``` [MakesDirty] public string Name { get; set; } ```
**No. Not without writing considerably more (arcane?) code than the original version** (You'd have to use reflection to check for the attribute on the property and what not.. did I mention it being 'slower').. This is the kind of duplication I can live with. MS has the same need for [raising events when a property is changed](http://msdn.microsoft.com/en-us/library/ms229614.aspx). INotifyPropertyChanged that is a vital interface for change notifications. Every implementation I've seen yet does ``` set { _name = value; NotifyPropertyChanged("Name"); } ``` If it was possible, I'd figure those smart guys at MS would already have something like that in place..
63,581
<p>I'm using <a href="http://www.c6software.com/Products/PopBox/" rel="nofollow noreferrer">PopBox</a> for magnifying thumbnails on my page. But I want my website to work even for users which turned javascript off.</p> <p>I tried to use the following HTML code:</p> <pre><code>&lt;a href="image.jpg"&gt; &lt;img src="thumbnail.jpg" pbsrc="image.jpg" onclick="Pop(...);"/&gt; &lt;/a&gt; </code></pre> <p>Now i need to disable the a-Tag using javascript, otherwise my PopBox won't work.</p> <p>How do I do that?</p>
[ { "answer_id": 63612, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": 2, "selected": false, "text": "<p>Put the onclick event onto the link itself, and return false from the handler if you don't want the default behavior to be executed (the link to be followed)</p>\n" }, { "answer_id": 63626, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 3, "selected": true, "text": "<p>Just put the onclick on the a-tag:</p>\n\n<pre><code>&lt;a href=\"image.jpg onclick=\"Pop()\"; return false;\"&gt;&lt;img ...&gt;&lt;/a&gt;\n</code></pre>\n\n<p>Make sure to return <code>false</code> either at the end of the function (here <code>Pop</code>) or inline like in the above example. This prevents the user from being redirected to the link by the <code>&lt;a&gt;</code>'s default behaviour.</p>\n" }, { "answer_id": 63638, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 1, "selected": false, "text": "<p>You could give all your fallback anchor tags a particular classname, like \"simple\"</p>\n\n<p>Using <a href=\"http://www.prototypejs.org/api/utility/dollar-dollar\" rel=\"nofollow noreferrer\">prototype</a>, you can get an array of all tags using that class using a CSS selector, e.g.</p>\n\n<pre><code>var anchors=$$('a.simple')\n</code></pre>\n\n<p>Now you can iterate over that array and clear the href attributes, or install an onclick handler to override the normal behaviour, etc...</p>\n\n<p>(Edited to add that the other methods listed above are much simpler, this just came from a background of doing lots of unobtrusive javascript, where your JS kicks in and goes and augments a functioning HTML page with extra stuff!)</p>\n" }, { "answer_id": 538993, "author": "system PAUSE", "author_id": 52963, "author_profile": "https://Stackoverflow.com/users/52963", "pm_score": 0, "selected": false, "text": "<p>The <code>href</code> attribute is not required for anchors (<code>&lt;a&gt;</code> tags), so get rid of it...</p>\n\n<pre><code> &lt;a id=\"apic001\" href=\"pic001.png\">&lt;img src=\"tn_pic001.png\">&lt;/a>\n\n &lt;script type=\"text/javascript\">\n document.getElementById(\"apic001\").removeAttribute(\"href\");\n &lt;/script>\n</code></pre>\n\n<p>This method will avoid library contention for <code>onclick</code>.</p>\n\n<p>Tested in IE6/FF3/Chrome. Side benefit: You can link directly to the portion of the page containing that thumbnail, using the id as a URI fragment: <code><a href=\"http://whatever/gallery.html\" rel=\"nofollow noreferrer\">http://whatever/gallery.html</a><strong>#apic001</strong></code>.</p>\n\n<p>For maximum browser compatibility, add a <code>name=\"apic001\"</code> attribute to the anchor tag in your markup ('name' and 'id' values must be identical).</p>\n\n<p>Using jQuery, dojo, Prototype, etc. you should be able to do the removeAttribute on multiple, similar anchors without needing the id.</p>\n" }, { "answer_id": 814735, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You should be able to mix and match the return false from Chris's idea with your own code:</p>\n\n<pre><code>&lt;a href=\"image.jpg\" onclick=\"return false;\"&gt;\n &lt;img src=\"thumbnail.jpg\" pbsrc=\"image.jpg\" onclick=\"Pop(...);\"&gt;\n&lt;/a&gt;\n</code></pre>\n\n<p>If someone has Javascript disabled, then their browser ignores the onclick statement in both elements and follows the link; if they have Javascript enabled, then their browser follows both OnClick statements -- the first one tells them not to follow the <code>&lt;a&gt;</code> link. ^_^</p>\n" }, { "answer_id": 2995911, "author": "Igor Zinov'yev", "author_id": 123564, "author_profile": "https://Stackoverflow.com/users/123564", "pm_score": 1, "selected": false, "text": "<p>May I suggest, in my opinion, the best solution? This is using jQuery 1.4+.</p>\n\n<p>Here you have a container with all your photos. Notice the added classes.</p>\n\n<pre><code>&lt;div id=\"photo-container\"&gt;\n &lt;a href=\"image1.jpg\"&gt;\n &lt;img class=\"popup-image\" src=\"thumbnail1.jpg\" pbsrc=\"image1.jpg\" /&gt;\n &lt;/a&gt;\n &lt;a href=\"image2.jpg\"&gt;\n &lt;img class=\"popup-image\" src=\"thumbnail2.jpg\" pbsrc=\"image2.jpg\" /&gt;\n &lt;/a&gt;\n &lt;a href=\"image3.jpg\"&gt;\n &lt;img class=\"popup-image\" src=\"thumbnail3.jpg\" pbsrc=\"image3.jpg\"/&gt;\n &lt;/a&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>An then you make a single event handler this way:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n$(document).ready(function(){\n var container = $('#photo-container');\n\n // let's bind our event handler\n container.bind('click', function(event){\n // thus we find (if any) the image the user has clicked on\n var target = $(event.target).closest('img.popup-image');\n\n // If the user has not hit any image, we do not handle the click\n if (!target.length) return;\n\n event.preventDefault(); // instead of return false;\n\n // And here you can do what you want to your image\n // which you can get from target\n Pop(target.get(0));\n });\n});\n&lt;/script&gt;\n</code></pre>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4186/" ]
I'm using [PopBox](http://www.c6software.com/Products/PopBox/) for magnifying thumbnails on my page. But I want my website to work even for users which turned javascript off. I tried to use the following HTML code: ``` <a href="image.jpg"> <img src="thumbnail.jpg" pbsrc="image.jpg" onclick="Pop(...);"/> </a> ``` Now i need to disable the a-Tag using javascript, otherwise my PopBox won't work. How do I do that?
Just put the onclick on the a-tag: ``` <a href="image.jpg onclick="Pop()"; return false;"><img ...></a> ``` Make sure to return `false` either at the end of the function (here `Pop`) or inline like in the above example. This prevents the user from being redirected to the link by the `<a>`'s default behaviour.
63,599
<p>We have an issue using the <code>PEAR</code> libraries on <code>Windows</code> from <code>PHP</code>.</p> <p>Pear contains many classes, we are making use of a fair few, one of which is the Mail class found in <code>Mail.php</code>. We use PEAR on the path, rather than providing the full explicit path to individual PEAR files:</p> <pre><code>require_once('Mail.php'); </code></pre> <p>Rather than:</p> <pre><code>require_once('/path/to/pear/Mail.php'); </code></pre> <p>This causes issues in the administration module of the site, where there is a <code>mail.php</code> file (used to send mails to users). If we are in an administrative screen that sends an email (such as the user administration screen that can generate and email new random passwords to users when they are approved from the moderation queue) and we attempt to include <code>Mail.php</code> we "accidentally" include mail.php.</p> <p>Without changing to prepend the full path to the PEAR install explicitly requiring the PEAR modules (non-standard, typically you install PEAR to your path...) is there a way to enforce PHP on Windows to require files case-sensitively?</p> <p>We are adding the PEAR path to the include path ourselves, so have control over the path order. We also recognize that we should avoid using filenames that clash with PEAR names regardless of case, and in the future will do so. This page however (which is not an include file, but a controller), has been in the repository for some years, and plugins specifically generate URLS to provide links/redirects to this page in their processing.</p> <blockquote> <p>(We support Apache, Microsoft IIS, LightHTTPD and Zeus, using PHP 4.3 or later (including PHP5))</p> </blockquote>
[ { "answer_id": 63627, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 2, "selected": false, "text": "<p>As it's an OS level thing, I don't believe there's an easy way of doing this.</p>\n\n<p>You could try changing your include from <code>include('Mail.php');</code> to <code>include('./Mail.php');</code>, but I'm not certain if that'll work on a Windows box (not having one with PHP to test on).</p>\n" }, { "answer_id": 63652, "author": "Jan Hančič", "author_id": 185527, "author_profile": "https://Stackoverflow.com/users/185527", "pm_score": 0, "selected": false, "text": "<p>If you are using PHP 4, you can take advantage of <a href=\"http://bugs.php.net/bug.php?id=43821\" rel=\"nofollow noreferrer\">this</a> bug. Off course that is a messy solution...</p>\n\n<p>Or you could just rename your mail.php file to something else...</p>\n" }, { "answer_id": 65937, "author": "farzad", "author_id": 9394, "author_profile": "https://Stackoverflow.com/users/9394", "pm_score": 2, "selected": true, "text": "<p>having 2 files with the same name in the include path is not a good idea, rename your files so the files that you wrote have different names from third party libraries. anyway for your current situation I think by changing the order of paths in your include path, you can fix this.\nPHP searches for the files in the include paths, one by one. when the required file is found in the include path, PHP will stop searching for the file. so in the administration section of your application, if you want to include the PEAR Mail file, instead of the mail.php that you wrote, change your include path so the PEAR path is before the current directory.\ndo something like this:</p>\n\n<pre><code>&lt;?php\n $path_to_pear = '/usr/share/php/pear';\n set_include_path( $path_to_pear . PATH_SEPARATOR . get_include_path() );\n?&gt;\n</code></pre>\n" }, { "answer_id": 82131, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 0, "selected": false, "text": "<p>I'm fairly certain this problem is caused by the NTFS code in the Win32 subsystem. If you use an Ext2 Installable File System (IFS), you should get case sensitivity on that drive.</p>\n" } ]
2008/09/15
[ "https://Stackoverflow.com/questions/63599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7106/" ]
We have an issue using the `PEAR` libraries on `Windows` from `PHP`. Pear contains many classes, we are making use of a fair few, one of which is the Mail class found in `Mail.php`. We use PEAR on the path, rather than providing the full explicit path to individual PEAR files: ``` require_once('Mail.php'); ``` Rather than: ``` require_once('/path/to/pear/Mail.php'); ``` This causes issues in the administration module of the site, where there is a `mail.php` file (used to send mails to users). If we are in an administrative screen that sends an email (such as the user administration screen that can generate and email new random passwords to users when they are approved from the moderation queue) and we attempt to include `Mail.php` we "accidentally" include mail.php. Without changing to prepend the full path to the PEAR install explicitly requiring the PEAR modules (non-standard, typically you install PEAR to your path...) is there a way to enforce PHP on Windows to require files case-sensitively? We are adding the PEAR path to the include path ourselves, so have control over the path order. We also recognize that we should avoid using filenames that clash with PEAR names regardless of case, and in the future will do so. This page however (which is not an include file, but a controller), has been in the repository for some years, and plugins specifically generate URLS to provide links/redirects to this page in their processing. > > (We support Apache, Microsoft IIS, LightHTTPD and Zeus, using PHP 4.3 or later (including PHP5)) > > >
having 2 files with the same name in the include path is not a good idea, rename your files so the files that you wrote have different names from third party libraries. anyway for your current situation I think by changing the order of paths in your include path, you can fix this. PHP searches for the files in the include paths, one by one. when the required file is found in the include path, PHP will stop searching for the file. so in the administration section of your application, if you want to include the PEAR Mail file, instead of the mail.php that you wrote, change your include path so the PEAR path is before the current directory. do something like this: ``` <?php $path_to_pear = '/usr/share/php/pear'; set_include_path( $path_to_pear . PATH_SEPARATOR . get_include_path() ); ?> ```